PackageManagerService.java revision 4f7883ce61aa8781f8781104fbee18d8ba1feb81
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 60import static android.content.pm.PackageManager.MATCH_ALL; 61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 65import static android.content.pm.PackageManager.PERMISSION_DENIED; 66import static android.content.pm.PackageManager.PERMISSION_GRANTED; 67import static android.content.pm.PackageParser.isApkFile; 68import static android.os.Process.PACKAGE_INFO_GID; 69import static android.os.Process.SYSTEM_UID; 70import static android.system.OsConstants.O_CREAT; 71import static android.system.OsConstants.O_RDWR; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 76import static com.android.internal.util.ArrayUtils.appendInt; 77import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 80import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 81import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 85 86import android.Manifest; 87import android.app.ActivityManager; 88import android.app.ActivityManagerNative; 89import android.app.AppGlobals; 90import android.app.IActivityManager; 91import android.app.admin.IDevicePolicyManager; 92import android.app.backup.IBackupManager; 93import android.app.usage.UsageStats; 94import android.app.usage.UsageStatsManager; 95import android.content.BroadcastReceiver; 96import android.content.ComponentName; 97import android.content.Context; 98import android.content.IIntentReceiver; 99import android.content.Intent; 100import android.content.IntentFilter; 101import android.content.IntentSender; 102import android.content.IntentSender.SendIntentException; 103import android.content.ServiceConnection; 104import android.content.pm.ActivityInfo; 105import android.content.pm.ApplicationInfo; 106import android.content.pm.FeatureInfo; 107import android.content.pm.IOnPermissionsChangeListener; 108import android.content.pm.IPackageDataObserver; 109import android.content.pm.IPackageDeleteObserver; 110import android.content.pm.IPackageDeleteObserver2; 111import android.content.pm.IPackageInstallObserver2; 112import android.content.pm.IPackageInstaller; 113import android.content.pm.IPackageManager; 114import android.content.pm.IPackageMoveObserver; 115import android.content.pm.IPackageStatsObserver; 116import android.content.pm.InstrumentationInfo; 117import android.content.pm.IntentFilterVerificationInfo; 118import android.content.pm.KeySet; 119import android.content.pm.ManifestDigest; 120import android.content.pm.PackageCleanItem; 121import android.content.pm.PackageInfo; 122import android.content.pm.PackageInfoLite; 123import android.content.pm.PackageInstaller; 124import android.content.pm.PackageManager; 125import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 126import android.content.pm.PackageManagerInternal; 127import android.content.pm.PackageParser; 128import android.content.pm.PackageParser.ActivityIntentInfo; 129import android.content.pm.PackageParser.PackageLite; 130import android.content.pm.PackageParser.PackageParserException; 131import android.content.pm.PackageStats; 132import android.content.pm.PackageUserState; 133import android.content.pm.ParceledListSlice; 134import android.content.pm.PermissionGroupInfo; 135import android.content.pm.PermissionInfo; 136import android.content.pm.ProviderInfo; 137import android.content.pm.ResolveInfo; 138import android.content.pm.ServiceInfo; 139import android.content.pm.Signature; 140import android.content.pm.UserInfo; 141import android.content.pm.VerificationParams; 142import android.content.pm.VerifierDeviceIdentity; 143import android.content.pm.VerifierInfo; 144import android.content.res.Resources; 145import android.hardware.display.DisplayManager; 146import android.net.Uri; 147import android.os.Debug; 148import android.os.Binder; 149import android.os.Build; 150import android.os.Bundle; 151import android.os.Environment; 152import android.os.Environment.UserEnvironment; 153import android.os.FileUtils; 154import android.os.Handler; 155import android.os.IBinder; 156import android.os.Looper; 157import android.os.Message; 158import android.os.Parcel; 159import android.os.ParcelFileDescriptor; 160import android.os.Process; 161import android.os.RemoteCallbackList; 162import android.os.RemoteException; 163import android.os.SELinux; 164import android.os.ServiceManager; 165import android.os.SystemClock; 166import android.os.SystemProperties; 167import android.os.UserHandle; 168import android.os.UserManager; 169import android.os.storage.IMountService; 170import android.os.storage.MountServiceInternal; 171import android.os.storage.StorageEventListener; 172import android.os.storage.StorageManager; 173import android.os.storage.VolumeInfo; 174import android.os.storage.VolumeRecord; 175import android.security.KeyStore; 176import android.security.SystemKeyStore; 177import android.system.ErrnoException; 178import android.system.Os; 179import android.system.StructStat; 180import android.text.TextUtils; 181import android.text.format.DateUtils; 182import android.util.ArrayMap; 183import android.util.ArraySet; 184import android.util.AtomicFile; 185import android.util.DisplayMetrics; 186import android.util.EventLog; 187import android.util.ExceptionUtils; 188import android.util.Log; 189import android.util.LogPrinter; 190import android.util.MathUtils; 191import android.util.PrintStreamPrinter; 192import android.util.Slog; 193import android.util.SparseArray; 194import android.util.SparseBooleanArray; 195import android.util.SparseIntArray; 196import android.util.Xml; 197import android.view.Display; 198 199import dalvik.system.DexFile; 200import dalvik.system.VMRuntime; 201 202import libcore.io.IoUtils; 203import libcore.util.EmptyArray; 204 205import com.android.internal.R; 206import com.android.internal.annotations.GuardedBy; 207import com.android.internal.app.IMediaContainerService; 208import com.android.internal.app.ResolverActivity; 209import com.android.internal.content.NativeLibraryHelper; 210import com.android.internal.content.PackageHelper; 211import com.android.internal.os.IParcelFileDescriptorFactory; 212import com.android.internal.os.SomeArgs; 213import com.android.internal.os.Zygote; 214import com.android.internal.util.ArrayUtils; 215import com.android.internal.util.FastPrintWriter; 216import com.android.internal.util.FastXmlSerializer; 217import com.android.internal.util.IndentingPrintWriter; 218import com.android.internal.util.Preconditions; 219import com.android.server.EventLogTags; 220import com.android.server.FgThread; 221import com.android.server.IntentResolver; 222import com.android.server.LocalServices; 223import com.android.server.ServiceThread; 224import com.android.server.SystemConfig; 225import com.android.server.Watchdog; 226import com.android.server.pm.PermissionsState.PermissionState; 227import com.android.server.pm.Settings.DatabaseVersion; 228import com.android.server.pm.Settings.VersionInfo; 229import com.android.server.storage.DeviceStorageMonitorInternal; 230 231import org.xmlpull.v1.XmlPullParser; 232import org.xmlpull.v1.XmlPullParserException; 233import org.xmlpull.v1.XmlSerializer; 234 235import java.io.BufferedInputStream; 236import java.io.BufferedOutputStream; 237import java.io.BufferedReader; 238import java.io.ByteArrayInputStream; 239import java.io.ByteArrayOutputStream; 240import java.io.File; 241import java.io.FileDescriptor; 242import java.io.FileNotFoundException; 243import java.io.FileOutputStream; 244import java.io.FileReader; 245import java.io.FilenameFilter; 246import java.io.IOException; 247import java.io.InputStream; 248import java.io.PrintWriter; 249import java.nio.charset.StandardCharsets; 250import java.security.NoSuchAlgorithmException; 251import java.security.PublicKey; 252import java.security.cert.CertificateEncodingException; 253import java.security.cert.CertificateException; 254import java.text.SimpleDateFormat; 255import java.util.ArrayList; 256import java.util.Arrays; 257import java.util.Collection; 258import java.util.Collections; 259import java.util.Comparator; 260import java.util.Date; 261import java.util.Iterator; 262import java.util.List; 263import java.util.Map; 264import java.util.Objects; 265import java.util.Set; 266import java.util.concurrent.CountDownLatch; 267import java.util.concurrent.TimeUnit; 268import java.util.concurrent.atomic.AtomicBoolean; 269import java.util.concurrent.atomic.AtomicInteger; 270import java.util.concurrent.atomic.AtomicLong; 271 272/** 273 * Keep track of all those .apks everywhere. 274 * 275 * This is very central to the platform's security; please run the unit 276 * tests whenever making modifications here: 277 * 278mmm frameworks/base/tests/AndroidTests 279adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 280adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 281 * 282 * {@hide} 283 */ 284public class PackageManagerService extends IPackageManager.Stub { 285 static final String TAG = "PackageManager"; 286 static final boolean DEBUG_SETTINGS = false; 287 static final boolean DEBUG_PREFERRED = false; 288 static final boolean DEBUG_UPGRADE = false; 289 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 290 private static final boolean DEBUG_BACKUP = false; 291 private static final boolean DEBUG_INSTALL = false; 292 private static final boolean DEBUG_REMOVE = false; 293 private static final boolean DEBUG_BROADCASTS = false; 294 private static final boolean DEBUG_SHOW_INFO = false; 295 private static final boolean DEBUG_PACKAGE_INFO = false; 296 private static final boolean DEBUG_INTENT_MATCHING = false; 297 private static final boolean DEBUG_PACKAGE_SCANNING = false; 298 private static final boolean DEBUG_VERIFY = false; 299 private static final boolean DEBUG_DEXOPT = false; 300 private static final boolean DEBUG_ABI_SELECTION = false; 301 302 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 303 304 private static final int RADIO_UID = Process.PHONE_UID; 305 private static final int LOG_UID = Process.LOG_UID; 306 private static final int NFC_UID = Process.NFC_UID; 307 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 308 private static final int SHELL_UID = Process.SHELL_UID; 309 310 // Cap the size of permission trees that 3rd party apps can define 311 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 312 313 // Suffix used during package installation when copying/moving 314 // package apks to install directory. 315 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 316 317 static final int SCAN_NO_DEX = 1<<1; 318 static final int SCAN_FORCE_DEX = 1<<2; 319 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 320 static final int SCAN_NEW_INSTALL = 1<<4; 321 static final int SCAN_NO_PATHS = 1<<5; 322 static final int SCAN_UPDATE_TIME = 1<<6; 323 static final int SCAN_DEFER_DEX = 1<<7; 324 static final int SCAN_BOOTING = 1<<8; 325 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 326 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 327 static final int SCAN_REPLACING = 1<<11; 328 static final int SCAN_REQUIRE_KNOWN = 1<<12; 329 static final int SCAN_MOVE = 1<<13; 330 static final int SCAN_INITIAL = 1<<14; 331 332 static final int REMOVE_CHATTY = 1<<16; 333 334 private static final int[] EMPTY_INT_ARRAY = new int[0]; 335 336 /** 337 * Timeout (in milliseconds) after which the watchdog should declare that 338 * our handler thread is wedged. The usual default for such things is one 339 * minute but we sometimes do very lengthy I/O operations on this thread, 340 * such as installing multi-gigabyte applications, so ours needs to be longer. 341 */ 342 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 343 344 /** 345 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 346 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 347 * settings entry if available, otherwise we use the hardcoded default. If it's been 348 * more than this long since the last fstrim, we force one during the boot sequence. 349 * 350 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 351 * one gets run at the next available charging+idle time. This final mandatory 352 * no-fstrim check kicks in only of the other scheduling criteria is never met. 353 */ 354 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 355 356 /** 357 * Whether verification is enabled by default. 358 */ 359 private static final boolean DEFAULT_VERIFY_ENABLE = true; 360 361 /** 362 * The default maximum time to wait for the verification agent to return in 363 * milliseconds. 364 */ 365 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 366 367 /** 368 * The default response for package verification timeout. 369 * 370 * This can be either PackageManager.VERIFICATION_ALLOW or 371 * PackageManager.VERIFICATION_REJECT. 372 */ 373 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 374 375 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 376 377 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 378 DEFAULT_CONTAINER_PACKAGE, 379 "com.android.defcontainer.DefaultContainerService"); 380 381 private static final String KILL_APP_REASON_GIDS_CHANGED = 382 "permission grant or revoke changed gids"; 383 384 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 385 "permissions revoked"; 386 387 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 388 389 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 390 391 /** Permission grant: not grant the permission. */ 392 private static final int GRANT_DENIED = 1; 393 394 /** Permission grant: grant the permission as an install permission. */ 395 private static final int GRANT_INSTALL = 2; 396 397 /** Permission grant: grant the permission as an install permission for a legacy app. */ 398 private static final int GRANT_INSTALL_LEGACY = 3; 399 400 /** Permission grant: grant the permission as a runtime one. */ 401 private static final int GRANT_RUNTIME = 4; 402 403 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 404 private static final int GRANT_UPGRADE = 5; 405 406 /** Canonical intent used to identify what counts as a "web browser" app */ 407 private static final Intent sBrowserIntent; 408 static { 409 sBrowserIntent = new Intent(); 410 sBrowserIntent.setAction(Intent.ACTION_VIEW); 411 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 412 sBrowserIntent.setData(Uri.parse("http:")); 413 } 414 415 final ServiceThread mHandlerThread; 416 417 final PackageHandler mHandler; 418 419 /** 420 * Messages for {@link #mHandler} that need to wait for system ready before 421 * being dispatched. 422 */ 423 private ArrayList<Message> mPostSystemReadyMessages; 424 425 final int mSdkVersion = Build.VERSION.SDK_INT; 426 427 final Context mContext; 428 final boolean mFactoryTest; 429 final boolean mOnlyCore; 430 final boolean mLazyDexOpt; 431 final long mDexOptLRUThresholdInMills; 432 final DisplayMetrics mMetrics; 433 final int mDefParseFlags; 434 final String[] mSeparateProcesses; 435 final boolean mIsUpgrade; 436 437 // This is where all application persistent data goes. 438 final File mAppDataDir; 439 440 // This is where all application persistent data goes for secondary users. 441 final File mUserAppDataDir; 442 443 /** The location for ASEC container files on internal storage. */ 444 final String mAsecInternalPath; 445 446 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 447 // LOCK HELD. Can be called with mInstallLock held. 448 @GuardedBy("mInstallLock") 449 final Installer mInstaller; 450 451 /** Directory where installed third-party apps stored */ 452 final File mAppInstallDir; 453 454 /** 455 * Directory to which applications installed internally have their 456 * 32 bit native libraries copied. 457 */ 458 private File mAppLib32InstallDir; 459 460 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 461 // apps. 462 final File mDrmAppPrivateInstallDir; 463 464 // ---------------------------------------------------------------- 465 466 // Lock for state used when installing and doing other long running 467 // operations. Methods that must be called with this lock held have 468 // the suffix "LI". 469 final Object mInstallLock = new Object(); 470 471 // ---------------------------------------------------------------- 472 473 // Keys are String (package name), values are Package. This also serves 474 // as the lock for the global state. Methods that must be called with 475 // this lock held have the prefix "LP". 476 @GuardedBy("mPackages") 477 final ArrayMap<String, PackageParser.Package> mPackages = 478 new ArrayMap<String, PackageParser.Package>(); 479 480 // Tracks available target package names -> overlay package paths. 481 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 482 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 483 484 /** 485 * Tracks new system packages [received in an OTA] that we expect to 486 * find updated user-installed versions. Keys are package name, values 487 * are package location. 488 */ 489 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 490 491 /** 492 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 493 */ 494 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 495 /** 496 * Whether or not system app permissions should be promoted from install to runtime. 497 */ 498 boolean mPromoteSystemApps; 499 500 final Settings mSettings; 501 boolean mRestoredSettings; 502 503 // System configuration read by SystemConfig. 504 final int[] mGlobalGids; 505 final SparseArray<ArraySet<String>> mSystemPermissions; 506 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 507 508 // If mac_permissions.xml was found for seinfo labeling. 509 boolean mFoundPolicyFile; 510 511 // If a recursive restorecon of /data/data/<pkg> is needed. 512 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 513 514 public static final class SharedLibraryEntry { 515 public final String path; 516 public final String apk; 517 518 SharedLibraryEntry(String _path, String _apk) { 519 path = _path; 520 apk = _apk; 521 } 522 } 523 524 // Currently known shared libraries. 525 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 526 new ArrayMap<String, SharedLibraryEntry>(); 527 528 // All available activities, for your resolving pleasure. 529 final ActivityIntentResolver mActivities = 530 new ActivityIntentResolver(); 531 532 // All available receivers, for your resolving pleasure. 533 final ActivityIntentResolver mReceivers = 534 new ActivityIntentResolver(); 535 536 // All available services, for your resolving pleasure. 537 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 538 539 // All available providers, for your resolving pleasure. 540 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 541 542 // Mapping from provider base names (first directory in content URI codePath) 543 // to the provider information. 544 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 545 new ArrayMap<String, PackageParser.Provider>(); 546 547 // Mapping from instrumentation class names to info about them. 548 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 549 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 550 551 // Mapping from permission names to info about them. 552 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 553 new ArrayMap<String, PackageParser.PermissionGroup>(); 554 555 // Packages whose data we have transfered into another package, thus 556 // should no longer exist. 557 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 558 559 // Broadcast actions that are only available to the system. 560 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 561 562 /** List of packages waiting for verification. */ 563 final SparseArray<PackageVerificationState> mPendingVerification 564 = new SparseArray<PackageVerificationState>(); 565 566 /** Set of packages associated with each app op permission. */ 567 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 568 569 final PackageInstallerService mInstallerService; 570 571 private final PackageDexOptimizer mPackageDexOptimizer; 572 573 private AtomicInteger mNextMoveId = new AtomicInteger(); 574 private final MoveCallbacks mMoveCallbacks; 575 576 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 577 578 // Cache of users who need badging. 579 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 580 581 /** Token for keys in mPendingVerification. */ 582 private int mPendingVerificationToken = 0; 583 584 volatile boolean mSystemReady; 585 volatile boolean mSafeMode; 586 volatile boolean mHasSystemUidErrors; 587 588 ApplicationInfo mAndroidApplication; 589 final ActivityInfo mResolveActivity = new ActivityInfo(); 590 final ResolveInfo mResolveInfo = new ResolveInfo(); 591 ComponentName mResolveComponentName; 592 PackageParser.Package mPlatformPackage; 593 ComponentName mCustomResolverComponentName; 594 595 boolean mResolverReplaced = false; 596 597 private final ComponentName mIntentFilterVerifierComponent; 598 private int mIntentFilterVerificationToken = 0; 599 600 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 601 = new SparseArray<IntentFilterVerificationState>(); 602 603 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 604 new DefaultPermissionGrantPolicy(this); 605 606 private static class IFVerificationParams { 607 PackageParser.Package pkg; 608 boolean replacing; 609 int userId; 610 int verifierUid; 611 612 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 613 int _userId, int _verifierUid) { 614 pkg = _pkg; 615 replacing = _replacing; 616 userId = _userId; 617 replacing = _replacing; 618 verifierUid = _verifierUid; 619 } 620 } 621 622 private interface IntentFilterVerifier<T extends IntentFilter> { 623 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 624 T filter, String packageName); 625 void startVerifications(int userId); 626 void receiveVerificationResponse(int verificationId); 627 } 628 629 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 630 private Context mContext; 631 private ComponentName mIntentFilterVerifierComponent; 632 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 633 634 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 635 mContext = context; 636 mIntentFilterVerifierComponent = verifierComponent; 637 } 638 639 private String getDefaultScheme() { 640 return IntentFilter.SCHEME_HTTPS; 641 } 642 643 @Override 644 public void startVerifications(int userId) { 645 // Launch verifications requests 646 int count = mCurrentIntentFilterVerifications.size(); 647 for (int n=0; n<count; n++) { 648 int verificationId = mCurrentIntentFilterVerifications.get(n); 649 final IntentFilterVerificationState ivs = 650 mIntentFilterVerificationStates.get(verificationId); 651 652 String packageName = ivs.getPackageName(); 653 654 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 655 final int filterCount = filters.size(); 656 ArraySet<String> domainsSet = new ArraySet<>(); 657 for (int m=0; m<filterCount; m++) { 658 PackageParser.ActivityIntentInfo filter = filters.get(m); 659 domainsSet.addAll(filter.getHostsList()); 660 } 661 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 662 synchronized (mPackages) { 663 if (mSettings.createIntentFilterVerificationIfNeededLPw( 664 packageName, domainsList) != null) { 665 scheduleWriteSettingsLocked(); 666 } 667 } 668 sendVerificationRequest(userId, verificationId, ivs); 669 } 670 mCurrentIntentFilterVerifications.clear(); 671 } 672 673 private void sendVerificationRequest(int userId, int verificationId, 674 IntentFilterVerificationState ivs) { 675 676 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 677 verificationIntent.putExtra( 678 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 679 verificationId); 680 verificationIntent.putExtra( 681 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 682 getDefaultScheme()); 683 verificationIntent.putExtra( 684 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 685 ivs.getHostsString()); 686 verificationIntent.putExtra( 687 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 688 ivs.getPackageName()); 689 verificationIntent.setComponent(mIntentFilterVerifierComponent); 690 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 691 692 UserHandle user = new UserHandle(userId); 693 mContext.sendBroadcastAsUser(verificationIntent, user); 694 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 695 "Sending IntentFilter verification broadcast"); 696 } 697 698 public void receiveVerificationResponse(int verificationId) { 699 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 700 701 final boolean verified = ivs.isVerified(); 702 703 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 704 final int count = filters.size(); 705 if (DEBUG_DOMAIN_VERIFICATION) { 706 Slog.i(TAG, "Received verification response " + verificationId 707 + " for " + count + " filters, verified=" + verified); 708 } 709 for (int n=0; n<count; n++) { 710 PackageParser.ActivityIntentInfo filter = filters.get(n); 711 filter.setVerified(verified); 712 713 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 714 + " verified with result:" + verified + " and hosts:" 715 + ivs.getHostsString()); 716 } 717 718 mIntentFilterVerificationStates.remove(verificationId); 719 720 final String packageName = ivs.getPackageName(); 721 IntentFilterVerificationInfo ivi = null; 722 723 synchronized (mPackages) { 724 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 725 } 726 if (ivi == null) { 727 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 728 + verificationId + " packageName:" + packageName); 729 return; 730 } 731 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 732 "Updating IntentFilterVerificationInfo for package " + packageName 733 +" verificationId:" + verificationId); 734 735 synchronized (mPackages) { 736 if (verified) { 737 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 738 } else { 739 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 740 } 741 scheduleWriteSettingsLocked(); 742 743 final int userId = ivs.getUserId(); 744 if (userId != UserHandle.USER_ALL) { 745 final int userStatus = 746 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 747 748 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 749 boolean needUpdate = false; 750 751 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 752 // already been set by the User thru the Disambiguation dialog 753 switch (userStatus) { 754 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 755 if (verified) { 756 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 757 } else { 758 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 759 } 760 needUpdate = true; 761 break; 762 763 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 764 if (verified) { 765 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 766 needUpdate = true; 767 } 768 break; 769 770 default: 771 // Nothing to do 772 } 773 774 if (needUpdate) { 775 mSettings.updateIntentFilterVerificationStatusLPw( 776 packageName, updatedStatus, userId); 777 scheduleWritePackageRestrictionsLocked(userId); 778 } 779 } 780 } 781 } 782 783 @Override 784 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 785 ActivityIntentInfo filter, String packageName) { 786 if (!hasValidDomains(filter)) { 787 return false; 788 } 789 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 790 if (ivs == null) { 791 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 792 packageName); 793 } 794 if (DEBUG_DOMAIN_VERIFICATION) { 795 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 796 } 797 ivs.addFilter(filter); 798 return true; 799 } 800 801 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 802 int userId, int verificationId, String packageName) { 803 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 804 verifierUid, userId, packageName); 805 ivs.setPendingState(); 806 synchronized (mPackages) { 807 mIntentFilterVerificationStates.append(verificationId, ivs); 808 mCurrentIntentFilterVerifications.add(verificationId); 809 } 810 return ivs; 811 } 812 } 813 814 private static boolean hasValidDomains(ActivityIntentInfo filter) { 815 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 816 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 817 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 818 } 819 820 private IntentFilterVerifier mIntentFilterVerifier; 821 822 // Set of pending broadcasts for aggregating enable/disable of components. 823 static class PendingPackageBroadcasts { 824 // for each user id, a map of <package name -> components within that package> 825 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 826 827 public PendingPackageBroadcasts() { 828 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 829 } 830 831 public ArrayList<String> get(int userId, String packageName) { 832 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 833 return packages.get(packageName); 834 } 835 836 public void put(int userId, String packageName, ArrayList<String> components) { 837 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 838 packages.put(packageName, components); 839 } 840 841 public void remove(int userId, String packageName) { 842 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 843 if (packages != null) { 844 packages.remove(packageName); 845 } 846 } 847 848 public void remove(int userId) { 849 mUidMap.remove(userId); 850 } 851 852 public int userIdCount() { 853 return mUidMap.size(); 854 } 855 856 public int userIdAt(int n) { 857 return mUidMap.keyAt(n); 858 } 859 860 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 861 return mUidMap.get(userId); 862 } 863 864 public int size() { 865 // total number of pending broadcast entries across all userIds 866 int num = 0; 867 for (int i = 0; i< mUidMap.size(); i++) { 868 num += mUidMap.valueAt(i).size(); 869 } 870 return num; 871 } 872 873 public void clear() { 874 mUidMap.clear(); 875 } 876 877 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 878 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 879 if (map == null) { 880 map = new ArrayMap<String, ArrayList<String>>(); 881 mUidMap.put(userId, map); 882 } 883 return map; 884 } 885 } 886 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 887 888 // Service Connection to remote media container service to copy 889 // package uri's from external media onto secure containers 890 // or internal storage. 891 private IMediaContainerService mContainerService = null; 892 893 static final int SEND_PENDING_BROADCAST = 1; 894 static final int MCS_BOUND = 3; 895 static final int END_COPY = 4; 896 static final int INIT_COPY = 5; 897 static final int MCS_UNBIND = 6; 898 static final int START_CLEANING_PACKAGE = 7; 899 static final int FIND_INSTALL_LOC = 8; 900 static final int POST_INSTALL = 9; 901 static final int MCS_RECONNECT = 10; 902 static final int MCS_GIVE_UP = 11; 903 static final int UPDATED_MEDIA_STATUS = 12; 904 static final int WRITE_SETTINGS = 13; 905 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 906 static final int PACKAGE_VERIFIED = 15; 907 static final int CHECK_PENDING_VERIFICATION = 16; 908 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 909 static final int INTENT_FILTER_VERIFIED = 18; 910 911 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 912 913 // Delay time in millisecs 914 static final int BROADCAST_DELAY = 10 * 1000; 915 916 static UserManagerService sUserManager; 917 918 // Stores a list of users whose package restrictions file needs to be updated 919 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 920 921 final private DefaultContainerConnection mDefContainerConn = 922 new DefaultContainerConnection(); 923 class DefaultContainerConnection implements ServiceConnection { 924 public void onServiceConnected(ComponentName name, IBinder service) { 925 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 926 IMediaContainerService imcs = 927 IMediaContainerService.Stub.asInterface(service); 928 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 929 } 930 931 public void onServiceDisconnected(ComponentName name) { 932 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 933 } 934 } 935 936 // Recordkeeping of restore-after-install operations that are currently in flight 937 // between the Package Manager and the Backup Manager 938 class PostInstallData { 939 public InstallArgs args; 940 public PackageInstalledInfo res; 941 942 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 943 args = _a; 944 res = _r; 945 } 946 } 947 948 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 949 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 950 951 // XML tags for backup/restore of various bits of state 952 private static final String TAG_PREFERRED_BACKUP = "pa"; 953 private static final String TAG_DEFAULT_APPS = "da"; 954 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 955 956 final String mRequiredVerifierPackage; 957 final String mRequiredInstallerPackage; 958 959 private final PackageUsage mPackageUsage = new PackageUsage(); 960 961 private class PackageUsage { 962 private static final int WRITE_INTERVAL 963 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 964 965 private final Object mFileLock = new Object(); 966 private final AtomicLong mLastWritten = new AtomicLong(0); 967 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 968 969 private boolean mIsHistoricalPackageUsageAvailable = true; 970 971 boolean isHistoricalPackageUsageAvailable() { 972 return mIsHistoricalPackageUsageAvailable; 973 } 974 975 void write(boolean force) { 976 if (force) { 977 writeInternal(); 978 return; 979 } 980 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 981 && !DEBUG_DEXOPT) { 982 return; 983 } 984 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 985 new Thread("PackageUsage_DiskWriter") { 986 @Override 987 public void run() { 988 try { 989 writeInternal(); 990 } finally { 991 mBackgroundWriteRunning.set(false); 992 } 993 } 994 }.start(); 995 } 996 } 997 998 private void writeInternal() { 999 synchronized (mPackages) { 1000 synchronized (mFileLock) { 1001 AtomicFile file = getFile(); 1002 FileOutputStream f = null; 1003 try { 1004 f = file.startWrite(); 1005 BufferedOutputStream out = new BufferedOutputStream(f); 1006 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1007 StringBuilder sb = new StringBuilder(); 1008 for (PackageParser.Package pkg : mPackages.values()) { 1009 if (pkg.mLastPackageUsageTimeInMills == 0) { 1010 continue; 1011 } 1012 sb.setLength(0); 1013 sb.append(pkg.packageName); 1014 sb.append(' '); 1015 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1016 sb.append('\n'); 1017 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1018 } 1019 out.flush(); 1020 file.finishWrite(f); 1021 } catch (IOException e) { 1022 if (f != null) { 1023 file.failWrite(f); 1024 } 1025 Log.e(TAG, "Failed to write package usage times", e); 1026 } 1027 } 1028 } 1029 mLastWritten.set(SystemClock.elapsedRealtime()); 1030 } 1031 1032 void readLP() { 1033 synchronized (mFileLock) { 1034 AtomicFile file = getFile(); 1035 BufferedInputStream in = null; 1036 try { 1037 in = new BufferedInputStream(file.openRead()); 1038 StringBuffer sb = new StringBuffer(); 1039 while (true) { 1040 String packageName = readToken(in, sb, ' '); 1041 if (packageName == null) { 1042 break; 1043 } 1044 String timeInMillisString = readToken(in, sb, '\n'); 1045 if (timeInMillisString == null) { 1046 throw new IOException("Failed to find last usage time for package " 1047 + packageName); 1048 } 1049 PackageParser.Package pkg = mPackages.get(packageName); 1050 if (pkg == null) { 1051 continue; 1052 } 1053 long timeInMillis; 1054 try { 1055 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1056 } catch (NumberFormatException e) { 1057 throw new IOException("Failed to parse " + timeInMillisString 1058 + " as a long.", e); 1059 } 1060 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1061 } 1062 } catch (FileNotFoundException expected) { 1063 mIsHistoricalPackageUsageAvailable = false; 1064 } catch (IOException e) { 1065 Log.w(TAG, "Failed to read package usage times", e); 1066 } finally { 1067 IoUtils.closeQuietly(in); 1068 } 1069 } 1070 mLastWritten.set(SystemClock.elapsedRealtime()); 1071 } 1072 1073 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1074 throws IOException { 1075 sb.setLength(0); 1076 while (true) { 1077 int ch = in.read(); 1078 if (ch == -1) { 1079 if (sb.length() == 0) { 1080 return null; 1081 } 1082 throw new IOException("Unexpected EOF"); 1083 } 1084 if (ch == endOfToken) { 1085 return sb.toString(); 1086 } 1087 sb.append((char)ch); 1088 } 1089 } 1090 1091 private AtomicFile getFile() { 1092 File dataDir = Environment.getDataDirectory(); 1093 File systemDir = new File(dataDir, "system"); 1094 File fname = new File(systemDir, "package-usage.list"); 1095 return new AtomicFile(fname); 1096 } 1097 } 1098 1099 class PackageHandler extends Handler { 1100 private boolean mBound = false; 1101 final ArrayList<HandlerParams> mPendingInstalls = 1102 new ArrayList<HandlerParams>(); 1103 1104 private boolean connectToService() { 1105 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1106 " DefaultContainerService"); 1107 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1108 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1109 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1110 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1112 mBound = true; 1113 return true; 1114 } 1115 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1116 return false; 1117 } 1118 1119 private void disconnectService() { 1120 mContainerService = null; 1121 mBound = false; 1122 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1123 mContext.unbindService(mDefContainerConn); 1124 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1125 } 1126 1127 PackageHandler(Looper looper) { 1128 super(looper); 1129 } 1130 1131 public void handleMessage(Message msg) { 1132 try { 1133 doHandleMessage(msg); 1134 } finally { 1135 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1136 } 1137 } 1138 1139 void doHandleMessage(Message msg) { 1140 switch (msg.what) { 1141 case INIT_COPY: { 1142 HandlerParams params = (HandlerParams) msg.obj; 1143 int idx = mPendingInstalls.size(); 1144 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1145 // If a bind was already initiated we dont really 1146 // need to do anything. The pending install 1147 // will be processed later on. 1148 if (!mBound) { 1149 // If this is the only one pending we might 1150 // have to bind to the service again. 1151 if (!connectToService()) { 1152 Slog.e(TAG, "Failed to bind to media container service"); 1153 params.serviceError(); 1154 return; 1155 } else { 1156 // Once we bind to the service, the first 1157 // pending request will be processed. 1158 mPendingInstalls.add(idx, params); 1159 } 1160 } else { 1161 mPendingInstalls.add(idx, params); 1162 // Already bound to the service. Just make 1163 // sure we trigger off processing the first request. 1164 if (idx == 0) { 1165 mHandler.sendEmptyMessage(MCS_BOUND); 1166 } 1167 } 1168 break; 1169 } 1170 case MCS_BOUND: { 1171 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1172 if (msg.obj != null) { 1173 mContainerService = (IMediaContainerService) msg.obj; 1174 } 1175 if (mContainerService == null) { 1176 if (!mBound) { 1177 // Something seriously wrong since we are not bound and we are not 1178 // waiting for connection. Bail out. 1179 Slog.e(TAG, "Cannot bind to media container service"); 1180 for (HandlerParams params : mPendingInstalls) { 1181 // Indicate service bind error 1182 params.serviceError(); 1183 } 1184 mPendingInstalls.clear(); 1185 } else { 1186 Slog.w(TAG, "Waiting to connect to media container service"); 1187 } 1188 } else if (mPendingInstalls.size() > 0) { 1189 HandlerParams params = mPendingInstalls.get(0); 1190 if (params != null) { 1191 if (params.startCopy()) { 1192 // We are done... look for more work or to 1193 // go idle. 1194 if (DEBUG_SD_INSTALL) Log.i(TAG, 1195 "Checking for more work or unbind..."); 1196 // Delete pending install 1197 if (mPendingInstalls.size() > 0) { 1198 mPendingInstalls.remove(0); 1199 } 1200 if (mPendingInstalls.size() == 0) { 1201 if (mBound) { 1202 if (DEBUG_SD_INSTALL) Log.i(TAG, 1203 "Posting delayed MCS_UNBIND"); 1204 removeMessages(MCS_UNBIND); 1205 Message ubmsg = obtainMessage(MCS_UNBIND); 1206 // Unbind after a little delay, to avoid 1207 // continual thrashing. 1208 sendMessageDelayed(ubmsg, 10000); 1209 } 1210 } else { 1211 // There are more pending requests in queue. 1212 // Just post MCS_BOUND message to trigger processing 1213 // of next pending install. 1214 if (DEBUG_SD_INSTALL) Log.i(TAG, 1215 "Posting MCS_BOUND for next work"); 1216 mHandler.sendEmptyMessage(MCS_BOUND); 1217 } 1218 } 1219 } 1220 } else { 1221 // Should never happen ideally. 1222 Slog.w(TAG, "Empty queue"); 1223 } 1224 break; 1225 } 1226 case MCS_RECONNECT: { 1227 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1228 if (mPendingInstalls.size() > 0) { 1229 if (mBound) { 1230 disconnectService(); 1231 } 1232 if (!connectToService()) { 1233 Slog.e(TAG, "Failed to bind to media container service"); 1234 for (HandlerParams params : mPendingInstalls) { 1235 // Indicate service bind error 1236 params.serviceError(); 1237 } 1238 mPendingInstalls.clear(); 1239 } 1240 } 1241 break; 1242 } 1243 case MCS_UNBIND: { 1244 // If there is no actual work left, then time to unbind. 1245 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1246 1247 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1248 if (mBound) { 1249 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1250 1251 disconnectService(); 1252 } 1253 } else if (mPendingInstalls.size() > 0) { 1254 // There are more pending requests in queue. 1255 // Just post MCS_BOUND message to trigger processing 1256 // of next pending install. 1257 mHandler.sendEmptyMessage(MCS_BOUND); 1258 } 1259 1260 break; 1261 } 1262 case MCS_GIVE_UP: { 1263 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1264 mPendingInstalls.remove(0); 1265 break; 1266 } 1267 case SEND_PENDING_BROADCAST: { 1268 String packages[]; 1269 ArrayList<String> components[]; 1270 int size = 0; 1271 int uids[]; 1272 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1273 synchronized (mPackages) { 1274 if (mPendingBroadcasts == null) { 1275 return; 1276 } 1277 size = mPendingBroadcasts.size(); 1278 if (size <= 0) { 1279 // Nothing to be done. Just return 1280 return; 1281 } 1282 packages = new String[size]; 1283 components = new ArrayList[size]; 1284 uids = new int[size]; 1285 int i = 0; // filling out the above arrays 1286 1287 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1288 int packageUserId = mPendingBroadcasts.userIdAt(n); 1289 Iterator<Map.Entry<String, ArrayList<String>>> it 1290 = mPendingBroadcasts.packagesForUserId(packageUserId) 1291 .entrySet().iterator(); 1292 while (it.hasNext() && i < size) { 1293 Map.Entry<String, ArrayList<String>> ent = it.next(); 1294 packages[i] = ent.getKey(); 1295 components[i] = ent.getValue(); 1296 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1297 uids[i] = (ps != null) 1298 ? UserHandle.getUid(packageUserId, ps.appId) 1299 : -1; 1300 i++; 1301 } 1302 } 1303 size = i; 1304 mPendingBroadcasts.clear(); 1305 } 1306 // Send broadcasts 1307 for (int i = 0; i < size; i++) { 1308 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1309 } 1310 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1311 break; 1312 } 1313 case START_CLEANING_PACKAGE: { 1314 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1315 final String packageName = (String)msg.obj; 1316 final int userId = msg.arg1; 1317 final boolean andCode = msg.arg2 != 0; 1318 synchronized (mPackages) { 1319 if (userId == UserHandle.USER_ALL) { 1320 int[] users = sUserManager.getUserIds(); 1321 for (int user : users) { 1322 mSettings.addPackageToCleanLPw( 1323 new PackageCleanItem(user, packageName, andCode)); 1324 } 1325 } else { 1326 mSettings.addPackageToCleanLPw( 1327 new PackageCleanItem(userId, packageName, andCode)); 1328 } 1329 } 1330 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1331 startCleaningPackages(); 1332 } break; 1333 case POST_INSTALL: { 1334 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1335 PostInstallData data = mRunningInstalls.get(msg.arg1); 1336 mRunningInstalls.delete(msg.arg1); 1337 boolean deleteOld = false; 1338 1339 if (data != null) { 1340 InstallArgs args = data.args; 1341 PackageInstalledInfo res = data.res; 1342 1343 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1344 final String packageName = res.pkg.applicationInfo.packageName; 1345 res.removedInfo.sendBroadcast(false, true, false); 1346 Bundle extras = new Bundle(1); 1347 extras.putInt(Intent.EXTRA_UID, res.uid); 1348 1349 // Now that we successfully installed the package, grant runtime 1350 // permissions if requested before broadcasting the install. 1351 if ((args.installFlags 1352 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1353 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1354 args.installGrantPermissions); 1355 } 1356 1357 // Determine the set of users who are adding this 1358 // package for the first time vs. those who are seeing 1359 // an update. 1360 int[] firstUsers; 1361 int[] updateUsers = new int[0]; 1362 if (res.origUsers == null || res.origUsers.length == 0) { 1363 firstUsers = res.newUsers; 1364 } else { 1365 firstUsers = new int[0]; 1366 for (int i=0; i<res.newUsers.length; i++) { 1367 int user = res.newUsers[i]; 1368 boolean isNew = true; 1369 for (int j=0; j<res.origUsers.length; j++) { 1370 if (res.origUsers[j] == user) { 1371 isNew = false; 1372 break; 1373 } 1374 } 1375 if (isNew) { 1376 int[] newFirst = new int[firstUsers.length+1]; 1377 System.arraycopy(firstUsers, 0, newFirst, 0, 1378 firstUsers.length); 1379 newFirst[firstUsers.length] = user; 1380 firstUsers = newFirst; 1381 } else { 1382 int[] newUpdate = new int[updateUsers.length+1]; 1383 System.arraycopy(updateUsers, 0, newUpdate, 0, 1384 updateUsers.length); 1385 newUpdate[updateUsers.length] = user; 1386 updateUsers = newUpdate; 1387 } 1388 } 1389 } 1390 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1391 packageName, extras, null, null, firstUsers); 1392 final boolean update = res.removedInfo.removedPackage != null; 1393 if (update) { 1394 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1395 } 1396 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1397 packageName, extras, null, null, updateUsers); 1398 if (update) { 1399 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1400 packageName, extras, null, null, updateUsers); 1401 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1402 null, null, packageName, null, updateUsers); 1403 1404 // treat asec-hosted packages like removable media on upgrade 1405 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1406 if (DEBUG_INSTALL) { 1407 Slog.i(TAG, "upgrading pkg " + res.pkg 1408 + " is ASEC-hosted -> AVAILABLE"); 1409 } 1410 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1411 ArrayList<String> pkgList = new ArrayList<String>(1); 1412 pkgList.add(packageName); 1413 sendResourcesChangedBroadcast(true, true, 1414 pkgList,uidArray, null); 1415 } 1416 } 1417 if (res.removedInfo.args != null) { 1418 // Remove the replaced package's older resources safely now 1419 deleteOld = true; 1420 } 1421 1422 // If this app is a browser and it's newly-installed for some 1423 // users, clear any default-browser state in those users 1424 if (firstUsers.length > 0) { 1425 // the app's nature doesn't depend on the user, so we can just 1426 // check its browser nature in any user and generalize. 1427 if (packageIsBrowser(packageName, firstUsers[0])) { 1428 synchronized (mPackages) { 1429 for (int userId : firstUsers) { 1430 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1431 } 1432 } 1433 } 1434 } 1435 // Log current value of "unknown sources" setting 1436 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1437 getUnknownSourcesSettings()); 1438 } 1439 // Force a gc to clear up things 1440 Runtime.getRuntime().gc(); 1441 // We delete after a gc for applications on sdcard. 1442 if (deleteOld) { 1443 synchronized (mInstallLock) { 1444 res.removedInfo.args.doPostDeleteLI(true); 1445 } 1446 } 1447 if (args.observer != null) { 1448 try { 1449 Bundle extras = extrasForInstallResult(res); 1450 args.observer.onPackageInstalled(res.name, res.returnCode, 1451 res.returnMsg, extras); 1452 } catch (RemoteException e) { 1453 Slog.i(TAG, "Observer no longer exists."); 1454 } 1455 } 1456 } else { 1457 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1458 } 1459 } break; 1460 case UPDATED_MEDIA_STATUS: { 1461 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1462 boolean reportStatus = msg.arg1 == 1; 1463 boolean doGc = msg.arg2 == 1; 1464 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1465 if (doGc) { 1466 // Force a gc to clear up stale containers. 1467 Runtime.getRuntime().gc(); 1468 } 1469 if (msg.obj != null) { 1470 @SuppressWarnings("unchecked") 1471 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1472 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1473 // Unload containers 1474 unloadAllContainers(args); 1475 } 1476 if (reportStatus) { 1477 try { 1478 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1479 PackageHelper.getMountService().finishMediaUpdate(); 1480 } catch (RemoteException e) { 1481 Log.e(TAG, "MountService not running?"); 1482 } 1483 } 1484 } break; 1485 case WRITE_SETTINGS: { 1486 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1487 synchronized (mPackages) { 1488 removeMessages(WRITE_SETTINGS); 1489 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1490 mSettings.writeLPr(); 1491 mDirtyUsers.clear(); 1492 } 1493 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1494 } break; 1495 case WRITE_PACKAGE_RESTRICTIONS: { 1496 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1497 synchronized (mPackages) { 1498 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1499 for (int userId : mDirtyUsers) { 1500 mSettings.writePackageRestrictionsLPr(userId); 1501 } 1502 mDirtyUsers.clear(); 1503 } 1504 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1505 } break; 1506 case CHECK_PENDING_VERIFICATION: { 1507 final int verificationId = msg.arg1; 1508 final PackageVerificationState state = mPendingVerification.get(verificationId); 1509 1510 if ((state != null) && !state.timeoutExtended()) { 1511 final InstallArgs args = state.getInstallArgs(); 1512 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1513 1514 Slog.i(TAG, "Verification timed out for " + originUri); 1515 mPendingVerification.remove(verificationId); 1516 1517 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1518 1519 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1520 Slog.i(TAG, "Continuing with installation of " + originUri); 1521 state.setVerifierResponse(Binder.getCallingUid(), 1522 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1523 broadcastPackageVerified(verificationId, originUri, 1524 PackageManager.VERIFICATION_ALLOW, 1525 state.getInstallArgs().getUser()); 1526 try { 1527 ret = args.copyApk(mContainerService, true); 1528 } catch (RemoteException e) { 1529 Slog.e(TAG, "Could not contact the ContainerService"); 1530 } 1531 } else { 1532 broadcastPackageVerified(verificationId, originUri, 1533 PackageManager.VERIFICATION_REJECT, 1534 state.getInstallArgs().getUser()); 1535 } 1536 1537 processPendingInstall(args, ret); 1538 mHandler.sendEmptyMessage(MCS_UNBIND); 1539 } 1540 break; 1541 } 1542 case PACKAGE_VERIFIED: { 1543 final int verificationId = msg.arg1; 1544 1545 final PackageVerificationState state = mPendingVerification.get(verificationId); 1546 if (state == null) { 1547 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1548 break; 1549 } 1550 1551 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1552 1553 state.setVerifierResponse(response.callerUid, response.code); 1554 1555 if (state.isVerificationComplete()) { 1556 mPendingVerification.remove(verificationId); 1557 1558 final InstallArgs args = state.getInstallArgs(); 1559 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1560 1561 int ret; 1562 if (state.isInstallAllowed()) { 1563 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1564 broadcastPackageVerified(verificationId, originUri, 1565 response.code, state.getInstallArgs().getUser()); 1566 try { 1567 ret = args.copyApk(mContainerService, true); 1568 } catch (RemoteException e) { 1569 Slog.e(TAG, "Could not contact the ContainerService"); 1570 } 1571 } else { 1572 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1573 } 1574 1575 processPendingInstall(args, ret); 1576 1577 mHandler.sendEmptyMessage(MCS_UNBIND); 1578 } 1579 1580 break; 1581 } 1582 case START_INTENT_FILTER_VERIFICATIONS: { 1583 IFVerificationParams params = (IFVerificationParams) msg.obj; 1584 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1585 params.replacing, params.pkg); 1586 break; 1587 } 1588 case INTENT_FILTER_VERIFIED: { 1589 final int verificationId = msg.arg1; 1590 1591 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1592 verificationId); 1593 if (state == null) { 1594 Slog.w(TAG, "Invalid IntentFilter verification token " 1595 + verificationId + " received"); 1596 break; 1597 } 1598 1599 final int userId = state.getUserId(); 1600 1601 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1602 "Processing IntentFilter verification with token:" 1603 + verificationId + " and userId:" + userId); 1604 1605 final IntentFilterVerificationResponse response = 1606 (IntentFilterVerificationResponse) msg.obj; 1607 1608 state.setVerifierResponse(response.callerUid, response.code); 1609 1610 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1611 "IntentFilter verification with token:" + verificationId 1612 + " and userId:" + userId 1613 + " is settings verifier response with response code:" 1614 + response.code); 1615 1616 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1617 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1618 + response.getFailedDomainsString()); 1619 } 1620 1621 if (state.isVerificationComplete()) { 1622 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1623 } else { 1624 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1625 "IntentFilter verification with token:" + verificationId 1626 + " was not said to be complete"); 1627 } 1628 1629 break; 1630 } 1631 } 1632 } 1633 } 1634 1635 private StorageEventListener mStorageListener = new StorageEventListener() { 1636 @Override 1637 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1638 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1639 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1640 final String volumeUuid = vol.getFsUuid(); 1641 1642 // Clean up any users or apps that were removed or recreated 1643 // while this volume was missing 1644 reconcileUsers(volumeUuid); 1645 reconcileApps(volumeUuid); 1646 1647 // Clean up any install sessions that expired or were 1648 // cancelled while this volume was missing 1649 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1650 1651 loadPrivatePackages(vol); 1652 1653 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1654 unloadPrivatePackages(vol); 1655 } 1656 } 1657 1658 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1659 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1660 updateExternalMediaStatus(true, false); 1661 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1662 updateExternalMediaStatus(false, false); 1663 } 1664 } 1665 } 1666 1667 @Override 1668 public void onVolumeForgotten(String fsUuid) { 1669 if (TextUtils.isEmpty(fsUuid)) { 1670 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1671 return; 1672 } 1673 1674 // Remove any apps installed on the forgotten volume 1675 synchronized (mPackages) { 1676 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1677 for (PackageSetting ps : packages) { 1678 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1679 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1680 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1681 } 1682 1683 mSettings.onVolumeForgotten(fsUuid); 1684 mSettings.writeLPr(); 1685 } 1686 } 1687 }; 1688 1689 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1690 String[] grantedPermissions) { 1691 if (userId >= UserHandle.USER_OWNER) { 1692 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1693 } else if (userId == UserHandle.USER_ALL) { 1694 final int[] userIds; 1695 synchronized (mPackages) { 1696 userIds = UserManagerService.getInstance().getUserIds(); 1697 } 1698 for (int someUserId : userIds) { 1699 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1700 } 1701 } 1702 1703 // We could have touched GID membership, so flush out packages.list 1704 synchronized (mPackages) { 1705 mSettings.writePackageListLPr(); 1706 } 1707 } 1708 1709 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1710 String[] grantedPermissions) { 1711 SettingBase sb = (SettingBase) pkg.mExtras; 1712 if (sb == null) { 1713 return; 1714 } 1715 1716 synchronized (mPackages) { 1717 for (String permission : pkg.requestedPermissions) { 1718 BasePermission bp = mSettings.mPermissions.get(permission); 1719 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1720 && (grantedPermissions == null 1721 || ArrayUtils.contains(grantedPermissions, permission)) 1722 && (getPermissionFlags(permission, pkg.packageName, userId) 1723 & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) == 0) { 1724 grantRuntimePermission(pkg.packageName, permission, userId); 1725 } 1726 } 1727 } 1728 } 1729 1730 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1731 Bundle extras = null; 1732 switch (res.returnCode) { 1733 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1734 extras = new Bundle(); 1735 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1736 res.origPermission); 1737 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1738 res.origPackage); 1739 break; 1740 } 1741 case PackageManager.INSTALL_SUCCEEDED: { 1742 extras = new Bundle(); 1743 extras.putBoolean(Intent.EXTRA_REPLACING, 1744 res.removedInfo != null && res.removedInfo.removedPackage != null); 1745 break; 1746 } 1747 } 1748 return extras; 1749 } 1750 1751 void scheduleWriteSettingsLocked() { 1752 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1753 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1754 } 1755 } 1756 1757 void scheduleWritePackageRestrictionsLocked(int userId) { 1758 if (!sUserManager.exists(userId)) return; 1759 mDirtyUsers.add(userId); 1760 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1761 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1762 } 1763 } 1764 1765 public static PackageManagerService main(Context context, Installer installer, 1766 boolean factoryTest, boolean onlyCore) { 1767 PackageManagerService m = new PackageManagerService(context, installer, 1768 factoryTest, onlyCore); 1769 ServiceManager.addService("package", m); 1770 return m; 1771 } 1772 1773 static String[] splitString(String str, char sep) { 1774 int count = 1; 1775 int i = 0; 1776 while ((i=str.indexOf(sep, i)) >= 0) { 1777 count++; 1778 i++; 1779 } 1780 1781 String[] res = new String[count]; 1782 i=0; 1783 count = 0; 1784 int lastI=0; 1785 while ((i=str.indexOf(sep, i)) >= 0) { 1786 res[count] = str.substring(lastI, i); 1787 count++; 1788 i++; 1789 lastI = i; 1790 } 1791 res[count] = str.substring(lastI, str.length()); 1792 return res; 1793 } 1794 1795 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1796 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1797 Context.DISPLAY_SERVICE); 1798 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1799 } 1800 1801 public PackageManagerService(Context context, Installer installer, 1802 boolean factoryTest, boolean onlyCore) { 1803 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1804 SystemClock.uptimeMillis()); 1805 1806 if (mSdkVersion <= 0) { 1807 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1808 } 1809 1810 mContext = context; 1811 mFactoryTest = factoryTest; 1812 mOnlyCore = onlyCore; 1813 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1814 mMetrics = new DisplayMetrics(); 1815 mSettings = new Settings(mPackages); 1816 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1817 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1818 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1819 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1820 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1821 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1822 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1823 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1824 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1825 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1826 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1827 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1828 1829 // TODO: add a property to control this? 1830 long dexOptLRUThresholdInMinutes; 1831 if (mLazyDexOpt) { 1832 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1833 } else { 1834 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1835 } 1836 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1837 1838 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1839 if (separateProcesses != null && separateProcesses.length() > 0) { 1840 if ("*".equals(separateProcesses)) { 1841 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1842 mSeparateProcesses = null; 1843 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1844 } else { 1845 mDefParseFlags = 0; 1846 mSeparateProcesses = separateProcesses.split(","); 1847 Slog.w(TAG, "Running with debug.separate_processes: " 1848 + separateProcesses); 1849 } 1850 } else { 1851 mDefParseFlags = 0; 1852 mSeparateProcesses = null; 1853 } 1854 1855 mInstaller = installer; 1856 mPackageDexOptimizer = new PackageDexOptimizer(this); 1857 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1858 1859 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1860 FgThread.get().getLooper()); 1861 1862 getDefaultDisplayMetrics(context, mMetrics); 1863 1864 SystemConfig systemConfig = SystemConfig.getInstance(); 1865 mGlobalGids = systemConfig.getGlobalGids(); 1866 mSystemPermissions = systemConfig.getSystemPermissions(); 1867 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1868 1869 synchronized (mInstallLock) { 1870 // writer 1871 synchronized (mPackages) { 1872 mHandlerThread = new ServiceThread(TAG, 1873 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1874 mHandlerThread.start(); 1875 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1876 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1877 1878 File dataDir = Environment.getDataDirectory(); 1879 mAppDataDir = new File(dataDir, "data"); 1880 mAppInstallDir = new File(dataDir, "app"); 1881 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1882 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1883 mUserAppDataDir = new File(dataDir, "user"); 1884 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1885 1886 sUserManager = new UserManagerService(context, this, 1887 mInstallLock, mPackages); 1888 1889 // Propagate permission configuration in to package manager. 1890 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1891 = systemConfig.getPermissions(); 1892 for (int i=0; i<permConfig.size(); i++) { 1893 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1894 BasePermission bp = mSettings.mPermissions.get(perm.name); 1895 if (bp == null) { 1896 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1897 mSettings.mPermissions.put(perm.name, bp); 1898 } 1899 if (perm.gids != null) { 1900 bp.setGids(perm.gids, perm.perUser); 1901 } 1902 } 1903 1904 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1905 for (int i=0; i<libConfig.size(); i++) { 1906 mSharedLibraries.put(libConfig.keyAt(i), 1907 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1908 } 1909 1910 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1911 1912 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1913 mSdkVersion, mOnlyCore); 1914 1915 String customResolverActivity = Resources.getSystem().getString( 1916 R.string.config_customResolverActivity); 1917 if (TextUtils.isEmpty(customResolverActivity)) { 1918 customResolverActivity = null; 1919 } else { 1920 mCustomResolverComponentName = ComponentName.unflattenFromString( 1921 customResolverActivity); 1922 } 1923 1924 long startTime = SystemClock.uptimeMillis(); 1925 1926 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1927 startTime); 1928 1929 // Set flag to monitor and not change apk file paths when 1930 // scanning install directories. 1931 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1932 1933 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1934 1935 /** 1936 * Add everything in the in the boot class path to the 1937 * list of process files because dexopt will have been run 1938 * if necessary during zygote startup. 1939 */ 1940 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1941 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1942 1943 if (bootClassPath != null) { 1944 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1945 for (String element : bootClassPathElements) { 1946 alreadyDexOpted.add(element); 1947 } 1948 } else { 1949 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1950 } 1951 1952 if (systemServerClassPath != null) { 1953 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1954 for (String element : systemServerClassPathElements) { 1955 alreadyDexOpted.add(element); 1956 } 1957 } else { 1958 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1959 } 1960 1961 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1962 final String[] dexCodeInstructionSets = 1963 getDexCodeInstructionSets( 1964 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1965 1966 /** 1967 * Ensure all external libraries have had dexopt run on them. 1968 */ 1969 if (mSharedLibraries.size() > 0) { 1970 // NOTE: For now, we're compiling these system "shared libraries" 1971 // (and framework jars) into all available architectures. It's possible 1972 // to compile them only when we come across an app that uses them (there's 1973 // already logic for that in scanPackageLI) but that adds some complexity. 1974 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1975 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1976 final String lib = libEntry.path; 1977 if (lib == null) { 1978 continue; 1979 } 1980 1981 try { 1982 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1983 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1984 alreadyDexOpted.add(lib); 1985 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded, false); 1986 } 1987 } catch (FileNotFoundException e) { 1988 Slog.w(TAG, "Library not found: " + lib); 1989 } catch (IOException e) { 1990 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1991 + e.getMessage()); 1992 } 1993 } 1994 } 1995 } 1996 1997 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1998 1999 // Gross hack for now: we know this file doesn't contain any 2000 // code, so don't dexopt it to avoid the resulting log spew. 2001 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2002 2003 // Gross hack for now: we know this file is only part of 2004 // the boot class path for art, so don't dexopt it to 2005 // avoid the resulting log spew. 2006 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2007 2008 /** 2009 * There are a number of commands implemented in Java, which 2010 * we currently need to do the dexopt on so that they can be 2011 * run from a non-root shell. 2012 */ 2013 String[] frameworkFiles = frameworkDir.list(); 2014 if (frameworkFiles != null) { 2015 // TODO: We could compile these only for the most preferred ABI. We should 2016 // first double check that the dex files for these commands are not referenced 2017 // by other system apps. 2018 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2019 for (int i=0; i<frameworkFiles.length; i++) { 2020 File libPath = new File(frameworkDir, frameworkFiles[i]); 2021 String path = libPath.getPath(); 2022 // Skip the file if we already did it. 2023 if (alreadyDexOpted.contains(path)) { 2024 continue; 2025 } 2026 // Skip the file if it is not a type we want to dexopt. 2027 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2028 continue; 2029 } 2030 try { 2031 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2032 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2033 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded, false); 2034 } 2035 } catch (FileNotFoundException e) { 2036 Slog.w(TAG, "Jar not found: " + path); 2037 } catch (IOException e) { 2038 Slog.w(TAG, "Exception reading jar: " + path, e); 2039 } 2040 } 2041 } 2042 } 2043 2044 final VersionInfo ver = mSettings.getInternalVersion(); 2045 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2046 // when upgrading from pre-M, promote system app permissions from install to runtime 2047 mPromoteSystemApps = 2048 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2049 2050 // save off the names of pre-existing system packages prior to scanning; we don't 2051 // want to automatically grant runtime permissions for new system apps 2052 if (mPromoteSystemApps) { 2053 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2054 while (pkgSettingIter.hasNext()) { 2055 PackageSetting ps = pkgSettingIter.next(); 2056 if (isSystemApp(ps)) { 2057 mExistingSystemPackages.add(ps.name); 2058 } 2059 } 2060 } 2061 2062 // Collect vendor overlay packages. 2063 // (Do this before scanning any apps.) 2064 // For security and version matching reason, only consider 2065 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2066 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2067 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2068 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2069 2070 // Find base frameworks (resource packages without code). 2071 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2072 | PackageParser.PARSE_IS_SYSTEM_DIR 2073 | PackageParser.PARSE_IS_PRIVILEGED, 2074 scanFlags | SCAN_NO_DEX, 0); 2075 2076 // Collected privileged system packages. 2077 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2078 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2079 | PackageParser.PARSE_IS_SYSTEM_DIR 2080 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2081 2082 // Collect ordinary system packages. 2083 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2084 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2085 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2086 2087 // Collect all vendor packages. 2088 File vendorAppDir = new File("/vendor/app"); 2089 try { 2090 vendorAppDir = vendorAppDir.getCanonicalFile(); 2091 } catch (IOException e) { 2092 // failed to look up canonical path, continue with original one 2093 } 2094 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2095 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2096 2097 // Collect all OEM packages. 2098 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2099 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2100 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2101 2102 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2103 mInstaller.moveFiles(); 2104 2105 // Prune any system packages that no longer exist. 2106 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2107 if (!mOnlyCore) { 2108 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2109 while (psit.hasNext()) { 2110 PackageSetting ps = psit.next(); 2111 2112 /* 2113 * If this is not a system app, it can't be a 2114 * disable system app. 2115 */ 2116 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2117 continue; 2118 } 2119 2120 /* 2121 * If the package is scanned, it's not erased. 2122 */ 2123 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2124 if (scannedPkg != null) { 2125 /* 2126 * If the system app is both scanned and in the 2127 * disabled packages list, then it must have been 2128 * added via OTA. Remove it from the currently 2129 * scanned package so the previously user-installed 2130 * application can be scanned. 2131 */ 2132 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2133 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2134 + ps.name + "; removing system app. Last known codePath=" 2135 + ps.codePathString + ", installStatus=" + ps.installStatus 2136 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2137 + scannedPkg.mVersionCode); 2138 removePackageLI(ps, true); 2139 mExpectingBetter.put(ps.name, ps.codePath); 2140 } 2141 2142 continue; 2143 } 2144 2145 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2146 psit.remove(); 2147 logCriticalInfo(Log.WARN, "System package " + ps.name 2148 + " no longer exists; wiping its data"); 2149 removeDataDirsLI(null, ps.name); 2150 } else { 2151 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2152 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2153 possiblyDeletedUpdatedSystemApps.add(ps.name); 2154 } 2155 } 2156 } 2157 } 2158 2159 //look for any incomplete package installations 2160 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2161 //clean up list 2162 for(int i = 0; i < deletePkgsList.size(); i++) { 2163 //clean up here 2164 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2165 } 2166 //delete tmp files 2167 deleteTempPackageFiles(); 2168 2169 // Remove any shared userIDs that have no associated packages 2170 mSettings.pruneSharedUsersLPw(); 2171 2172 if (!mOnlyCore) { 2173 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2174 SystemClock.uptimeMillis()); 2175 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2176 2177 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2178 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2179 2180 /** 2181 * Remove disable package settings for any updated system 2182 * apps that were removed via an OTA. If they're not a 2183 * previously-updated app, remove them completely. 2184 * Otherwise, just revoke their system-level permissions. 2185 */ 2186 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2187 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2188 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2189 2190 String msg; 2191 if (deletedPkg == null) { 2192 msg = "Updated system package " + deletedAppName 2193 + " no longer exists; wiping its data"; 2194 removeDataDirsLI(null, deletedAppName); 2195 } else { 2196 msg = "Updated system app + " + deletedAppName 2197 + " no longer present; removing system privileges for " 2198 + deletedAppName; 2199 2200 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2201 2202 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2203 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2204 } 2205 logCriticalInfo(Log.WARN, msg); 2206 } 2207 2208 /** 2209 * Make sure all system apps that we expected to appear on 2210 * the userdata partition actually showed up. If they never 2211 * appeared, crawl back and revive the system version. 2212 */ 2213 for (int i = 0; i < mExpectingBetter.size(); i++) { 2214 final String packageName = mExpectingBetter.keyAt(i); 2215 if (!mPackages.containsKey(packageName)) { 2216 final File scanFile = mExpectingBetter.valueAt(i); 2217 2218 logCriticalInfo(Log.WARN, "Expected better " + packageName 2219 + " but never showed up; reverting to system"); 2220 2221 final int reparseFlags; 2222 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2223 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2224 | PackageParser.PARSE_IS_SYSTEM_DIR 2225 | PackageParser.PARSE_IS_PRIVILEGED; 2226 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2227 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2228 | PackageParser.PARSE_IS_SYSTEM_DIR; 2229 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2230 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2231 | PackageParser.PARSE_IS_SYSTEM_DIR; 2232 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2233 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2234 | PackageParser.PARSE_IS_SYSTEM_DIR; 2235 } else { 2236 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2237 continue; 2238 } 2239 2240 mSettings.enableSystemPackageLPw(packageName); 2241 2242 try { 2243 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2244 } catch (PackageManagerException e) { 2245 Slog.e(TAG, "Failed to parse original system package: " 2246 + e.getMessage()); 2247 } 2248 } 2249 } 2250 } 2251 mExpectingBetter.clear(); 2252 2253 // Now that we know all of the shared libraries, update all clients to have 2254 // the correct library paths. 2255 updateAllSharedLibrariesLPw(); 2256 2257 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2258 // NOTE: We ignore potential failures here during a system scan (like 2259 // the rest of the commands above) because there's precious little we 2260 // can do about it. A settings error is reported, though. 2261 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2262 false /* force dexopt */, false /* defer dexopt */, 2263 false /* boot complete */); 2264 } 2265 2266 // Now that we know all the packages we are keeping, 2267 // read and update their last usage times. 2268 mPackageUsage.readLP(); 2269 2270 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2271 SystemClock.uptimeMillis()); 2272 Slog.i(TAG, "Time to scan packages: " 2273 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2274 + " seconds"); 2275 2276 // If the platform SDK has changed since the last time we booted, 2277 // we need to re-grant app permission to catch any new ones that 2278 // appear. This is really a hack, and means that apps can in some 2279 // cases get permissions that the user didn't initially explicitly 2280 // allow... it would be nice to have some better way to handle 2281 // this situation. 2282 int updateFlags = UPDATE_PERMISSIONS_ALL; 2283 if (ver.sdkVersion != mSdkVersion) { 2284 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2285 + mSdkVersion + "; regranting permissions for internal storage"); 2286 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2287 } 2288 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2289 ver.sdkVersion = mSdkVersion; 2290 2291 // If this is the first boot or an update from pre-M, and it is a normal 2292 // boot, then we need to initialize the default preferred apps across 2293 // all defined users. 2294 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2295 for (UserInfo user : sUserManager.getUsers(true)) { 2296 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2297 applyFactoryDefaultBrowserLPw(user.id); 2298 primeDomainVerificationsLPw(user.id); 2299 } 2300 } 2301 2302 // If this is first boot after an OTA, and a normal boot, then 2303 // we need to clear code cache directories. 2304 if (mIsUpgrade && !onlyCore) { 2305 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2306 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2307 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2308 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2309 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2310 } 2311 } 2312 ver.fingerprint = Build.FINGERPRINT; 2313 } 2314 2315 checkDefaultBrowser(); 2316 2317 // clear only after permissions and other defaults have been updated 2318 mExistingSystemPackages.clear(); 2319 mPromoteSystemApps = false; 2320 2321 // All the changes are done during package scanning. 2322 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2323 2324 // can downgrade to reader 2325 mSettings.writeLPr(); 2326 2327 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2328 SystemClock.uptimeMillis()); 2329 2330 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2331 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2332 2333 mInstallerService = new PackageInstallerService(context, this); 2334 2335 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2336 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2337 mIntentFilterVerifierComponent); 2338 2339 } // synchronized (mPackages) 2340 } // synchronized (mInstallLock) 2341 2342 // Now after opening every single application zip, make sure they 2343 // are all flushed. Not really needed, but keeps things nice and 2344 // tidy. 2345 Runtime.getRuntime().gc(); 2346 2347 // Expose private service for system components to use. 2348 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2349 } 2350 2351 @Override 2352 public boolean isFirstBoot() { 2353 return !mRestoredSettings; 2354 } 2355 2356 @Override 2357 public boolean isOnlyCoreApps() { 2358 return mOnlyCore; 2359 } 2360 2361 @Override 2362 public boolean isUpgrade() { 2363 return mIsUpgrade; 2364 } 2365 2366 private String getRequiredVerifierLPr() { 2367 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2368 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2369 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2370 2371 String requiredVerifier = null; 2372 2373 final int N = receivers.size(); 2374 for (int i = 0; i < N; i++) { 2375 final ResolveInfo info = receivers.get(i); 2376 2377 if (info.activityInfo == null) { 2378 continue; 2379 } 2380 2381 final String packageName = info.activityInfo.packageName; 2382 2383 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2384 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2385 continue; 2386 } 2387 2388 if (requiredVerifier != null) { 2389 throw new RuntimeException("There can be only one required verifier"); 2390 } 2391 2392 requiredVerifier = packageName; 2393 } 2394 2395 return requiredVerifier; 2396 } 2397 2398 private String getRequiredInstallerLPr() { 2399 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2400 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2401 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2402 2403 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2404 PACKAGE_MIME_TYPE, 0, 0); 2405 2406 String requiredInstaller = null; 2407 2408 final int N = installers.size(); 2409 for (int i = 0; i < N; i++) { 2410 final ResolveInfo info = installers.get(i); 2411 final String packageName = info.activityInfo.packageName; 2412 2413 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2414 continue; 2415 } 2416 2417 if (requiredInstaller != null) { 2418 throw new RuntimeException("There must be one required installer"); 2419 } 2420 2421 requiredInstaller = packageName; 2422 } 2423 2424 if (requiredInstaller == null) { 2425 throw new RuntimeException("There must be one required installer"); 2426 } 2427 2428 return requiredInstaller; 2429 } 2430 2431 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2432 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2433 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2434 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2435 2436 ComponentName verifierComponentName = null; 2437 2438 int priority = -1000; 2439 final int N = receivers.size(); 2440 for (int i = 0; i < N; i++) { 2441 final ResolveInfo info = receivers.get(i); 2442 2443 if (info.activityInfo == null) { 2444 continue; 2445 } 2446 2447 final String packageName = info.activityInfo.packageName; 2448 2449 final PackageSetting ps = mSettings.mPackages.get(packageName); 2450 if (ps == null) { 2451 continue; 2452 } 2453 2454 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2455 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2456 continue; 2457 } 2458 2459 // Select the IntentFilterVerifier with the highest priority 2460 if (priority < info.priority) { 2461 priority = info.priority; 2462 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2463 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2464 + verifierComponentName + " with priority: " + info.priority); 2465 } 2466 } 2467 2468 return verifierComponentName; 2469 } 2470 2471 private void primeDomainVerificationsLPw(int userId) { 2472 if (DEBUG_DOMAIN_VERIFICATION) { 2473 Slog.d(TAG, "Priming domain verifications in user " + userId); 2474 } 2475 2476 SystemConfig systemConfig = SystemConfig.getInstance(); 2477 ArraySet<String> packages = systemConfig.getLinkedApps(); 2478 ArraySet<String> domains = new ArraySet<String>(); 2479 2480 for (String packageName : packages) { 2481 PackageParser.Package pkg = mPackages.get(packageName); 2482 if (pkg != null) { 2483 if (!pkg.isSystemApp()) { 2484 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2485 continue; 2486 } 2487 2488 domains.clear(); 2489 for (PackageParser.Activity a : pkg.activities) { 2490 for (ActivityIntentInfo filter : a.intents) { 2491 if (hasValidDomains(filter)) { 2492 domains.addAll(filter.getHostsList()); 2493 } 2494 } 2495 } 2496 2497 if (domains.size() > 0) { 2498 if (DEBUG_DOMAIN_VERIFICATION) { 2499 Slog.v(TAG, " + " + packageName); 2500 } 2501 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2502 // state w.r.t. the formal app-linkage "no verification attempted" state; 2503 // and then 'always' in the per-user state actually used for intent resolution. 2504 final IntentFilterVerificationInfo ivi; 2505 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2506 new ArrayList<String>(domains)); 2507 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2508 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2509 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2510 } else { 2511 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2512 + "' does not handle web links"); 2513 } 2514 } else { 2515 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2516 } 2517 } 2518 2519 scheduleWritePackageRestrictionsLocked(userId); 2520 scheduleWriteSettingsLocked(); 2521 } 2522 2523 private void applyFactoryDefaultBrowserLPw(int userId) { 2524 // The default browser app's package name is stored in a string resource, 2525 // with a product-specific overlay used for vendor customization. 2526 String browserPkg = mContext.getResources().getString( 2527 com.android.internal.R.string.default_browser); 2528 if (!TextUtils.isEmpty(browserPkg)) { 2529 // non-empty string => required to be a known package 2530 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2531 if (ps == null) { 2532 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2533 browserPkg = null; 2534 } else { 2535 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2536 } 2537 } 2538 2539 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2540 // default. If there's more than one, just leave everything alone. 2541 if (browserPkg == null) { 2542 calculateDefaultBrowserLPw(userId); 2543 } 2544 } 2545 2546 private void calculateDefaultBrowserLPw(int userId) { 2547 List<String> allBrowsers = resolveAllBrowserApps(userId); 2548 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2549 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2550 } 2551 2552 private List<String> resolveAllBrowserApps(int userId) { 2553 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2554 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2555 PackageManager.MATCH_ALL, userId); 2556 2557 final int count = list.size(); 2558 List<String> result = new ArrayList<String>(count); 2559 for (int i=0; i<count; i++) { 2560 ResolveInfo info = list.get(i); 2561 if (info.activityInfo == null 2562 || !info.handleAllWebDataURI 2563 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2564 || result.contains(info.activityInfo.packageName)) { 2565 continue; 2566 } 2567 result.add(info.activityInfo.packageName); 2568 } 2569 2570 return result; 2571 } 2572 2573 private boolean packageIsBrowser(String packageName, int userId) { 2574 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2575 PackageManager.MATCH_ALL, userId); 2576 final int N = list.size(); 2577 for (int i = 0; i < N; i++) { 2578 ResolveInfo info = list.get(i); 2579 if (packageName.equals(info.activityInfo.packageName)) { 2580 return true; 2581 } 2582 } 2583 return false; 2584 } 2585 2586 private void checkDefaultBrowser() { 2587 final int myUserId = UserHandle.myUserId(); 2588 final String packageName = getDefaultBrowserPackageName(myUserId); 2589 if (packageName != null) { 2590 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2591 if (info == null) { 2592 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2593 synchronized (mPackages) { 2594 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2595 } 2596 } 2597 } 2598 } 2599 2600 @Override 2601 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2602 throws RemoteException { 2603 try { 2604 return super.onTransact(code, data, reply, flags); 2605 } catch (RuntimeException e) { 2606 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2607 Slog.wtf(TAG, "Package Manager Crash", e); 2608 } 2609 throw e; 2610 } 2611 } 2612 2613 void cleanupInstallFailedPackage(PackageSetting ps) { 2614 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2615 2616 removeDataDirsLI(ps.volumeUuid, ps.name); 2617 if (ps.codePath != null) { 2618 if (ps.codePath.isDirectory()) { 2619 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2620 } else { 2621 ps.codePath.delete(); 2622 } 2623 } 2624 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2625 if (ps.resourcePath.isDirectory()) { 2626 FileUtils.deleteContents(ps.resourcePath); 2627 } 2628 ps.resourcePath.delete(); 2629 } 2630 mSettings.removePackageLPw(ps.name); 2631 } 2632 2633 static int[] appendInts(int[] cur, int[] add) { 2634 if (add == null) return cur; 2635 if (cur == null) return add; 2636 final int N = add.length; 2637 for (int i=0; i<N; i++) { 2638 cur = appendInt(cur, add[i]); 2639 } 2640 return cur; 2641 } 2642 2643 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2644 if (!sUserManager.exists(userId)) return null; 2645 final PackageSetting ps = (PackageSetting) p.mExtras; 2646 if (ps == null) { 2647 return null; 2648 } 2649 2650 final PermissionsState permissionsState = ps.getPermissionsState(); 2651 2652 final int[] gids = permissionsState.computeGids(userId); 2653 final Set<String> permissions = permissionsState.getPermissions(userId); 2654 final PackageUserState state = ps.readUserState(userId); 2655 2656 return PackageParser.generatePackageInfo(p, gids, flags, 2657 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2658 } 2659 2660 @Override 2661 public boolean isPackageFrozen(String packageName) { 2662 synchronized (mPackages) { 2663 final PackageSetting ps = mSettings.mPackages.get(packageName); 2664 if (ps != null) { 2665 return ps.frozen; 2666 } 2667 } 2668 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2669 return true; 2670 } 2671 2672 @Override 2673 public boolean isPackageAvailable(String packageName, int userId) { 2674 if (!sUserManager.exists(userId)) return false; 2675 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2676 synchronized (mPackages) { 2677 PackageParser.Package p = mPackages.get(packageName); 2678 if (p != null) { 2679 final PackageSetting ps = (PackageSetting) p.mExtras; 2680 if (ps != null) { 2681 final PackageUserState state = ps.readUserState(userId); 2682 if (state != null) { 2683 return PackageParser.isAvailable(state); 2684 } 2685 } 2686 } 2687 } 2688 return false; 2689 } 2690 2691 @Override 2692 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2693 if (!sUserManager.exists(userId)) return null; 2694 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2695 // reader 2696 synchronized (mPackages) { 2697 PackageParser.Package p = mPackages.get(packageName); 2698 if (DEBUG_PACKAGE_INFO) 2699 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2700 if (p != null) { 2701 return generatePackageInfo(p, flags, userId); 2702 } 2703 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2704 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2705 } 2706 } 2707 return null; 2708 } 2709 2710 @Override 2711 public String[] currentToCanonicalPackageNames(String[] names) { 2712 String[] out = new String[names.length]; 2713 // reader 2714 synchronized (mPackages) { 2715 for (int i=names.length-1; i>=0; i--) { 2716 PackageSetting ps = mSettings.mPackages.get(names[i]); 2717 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2718 } 2719 } 2720 return out; 2721 } 2722 2723 @Override 2724 public String[] canonicalToCurrentPackageNames(String[] names) { 2725 String[] out = new String[names.length]; 2726 // reader 2727 synchronized (mPackages) { 2728 for (int i=names.length-1; i>=0; i--) { 2729 String cur = mSettings.mRenamedPackages.get(names[i]); 2730 out[i] = cur != null ? cur : names[i]; 2731 } 2732 } 2733 return out; 2734 } 2735 2736 @Override 2737 public int getPackageUid(String packageName, int userId) { 2738 return getPackageUidEtc(packageName, 0, userId); 2739 } 2740 2741 @Override 2742 public int getPackageUidEtc(String packageName, int flags, int userId) { 2743 if (!sUserManager.exists(userId)) return -1; 2744 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2745 2746 // reader 2747 synchronized (mPackages) { 2748 final PackageParser.Package p = mPackages.get(packageName); 2749 if (p != null) { 2750 return UserHandle.getUid(userId, p.applicationInfo.uid); 2751 } 2752 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2753 final PackageSetting ps = mSettings.mPackages.get(packageName); 2754 if (ps != null) { 2755 return UserHandle.getUid(userId, ps.appId); 2756 } 2757 } 2758 } 2759 2760 return -1; 2761 } 2762 2763 @Override 2764 public int[] getPackageGids(String packageName, int userId) { 2765 return getPackageGidsEtc(packageName, 0, userId); 2766 } 2767 2768 @Override 2769 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2770 if (!sUserManager.exists(userId)) { 2771 return null; 2772 } 2773 2774 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2775 "getPackageGids"); 2776 2777 // reader 2778 synchronized (mPackages) { 2779 final PackageParser.Package p = mPackages.get(packageName); 2780 if (p != null) { 2781 PackageSetting ps = (PackageSetting) p.mExtras; 2782 return ps.getPermissionsState().computeGids(userId); 2783 } 2784 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2785 final PackageSetting ps = mSettings.mPackages.get(packageName); 2786 if (ps != null) { 2787 return ps.getPermissionsState().computeGids(userId); 2788 } 2789 } 2790 } 2791 2792 return null; 2793 } 2794 2795 static PermissionInfo generatePermissionInfo( 2796 BasePermission bp, int flags) { 2797 if (bp.perm != null) { 2798 return PackageParser.generatePermissionInfo(bp.perm, flags); 2799 } 2800 PermissionInfo pi = new PermissionInfo(); 2801 pi.name = bp.name; 2802 pi.packageName = bp.sourcePackage; 2803 pi.nonLocalizedLabel = bp.name; 2804 pi.protectionLevel = bp.protectionLevel; 2805 return pi; 2806 } 2807 2808 @Override 2809 public PermissionInfo getPermissionInfo(String name, int flags) { 2810 // reader 2811 synchronized (mPackages) { 2812 final BasePermission p = mSettings.mPermissions.get(name); 2813 if (p != null) { 2814 return generatePermissionInfo(p, flags); 2815 } 2816 return null; 2817 } 2818 } 2819 2820 @Override 2821 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2822 // reader 2823 synchronized (mPackages) { 2824 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2825 for (BasePermission p : mSettings.mPermissions.values()) { 2826 if (group == null) { 2827 if (p.perm == null || p.perm.info.group == null) { 2828 out.add(generatePermissionInfo(p, flags)); 2829 } 2830 } else { 2831 if (p.perm != null && group.equals(p.perm.info.group)) { 2832 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2833 } 2834 } 2835 } 2836 2837 if (out.size() > 0) { 2838 return out; 2839 } 2840 return mPermissionGroups.containsKey(group) ? out : null; 2841 } 2842 } 2843 2844 @Override 2845 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2846 // reader 2847 synchronized (mPackages) { 2848 return PackageParser.generatePermissionGroupInfo( 2849 mPermissionGroups.get(name), flags); 2850 } 2851 } 2852 2853 @Override 2854 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2855 // reader 2856 synchronized (mPackages) { 2857 final int N = mPermissionGroups.size(); 2858 ArrayList<PermissionGroupInfo> out 2859 = new ArrayList<PermissionGroupInfo>(N); 2860 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2861 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2862 } 2863 return out; 2864 } 2865 } 2866 2867 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2868 int userId) { 2869 if (!sUserManager.exists(userId)) return null; 2870 PackageSetting ps = mSettings.mPackages.get(packageName); 2871 if (ps != null) { 2872 if (ps.pkg == null) { 2873 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2874 flags, userId); 2875 if (pInfo != null) { 2876 return pInfo.applicationInfo; 2877 } 2878 return null; 2879 } 2880 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2881 ps.readUserState(userId), userId); 2882 } 2883 return null; 2884 } 2885 2886 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2887 int userId) { 2888 if (!sUserManager.exists(userId)) return null; 2889 PackageSetting ps = mSettings.mPackages.get(packageName); 2890 if (ps != null) { 2891 PackageParser.Package pkg = ps.pkg; 2892 if (pkg == null) { 2893 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2894 return null; 2895 } 2896 // Only data remains, so we aren't worried about code paths 2897 pkg = new PackageParser.Package(packageName); 2898 pkg.applicationInfo.packageName = packageName; 2899 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2900 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2901 pkg.applicationInfo.dataDir = Environment 2902 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2903 .getAbsolutePath(); 2904 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2905 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2906 } 2907 return generatePackageInfo(pkg, flags, userId); 2908 } 2909 return null; 2910 } 2911 2912 @Override 2913 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2914 if (!sUserManager.exists(userId)) return null; 2915 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2916 // writer 2917 synchronized (mPackages) { 2918 PackageParser.Package p = mPackages.get(packageName); 2919 if (DEBUG_PACKAGE_INFO) Log.v( 2920 TAG, "getApplicationInfo " + packageName 2921 + ": " + p); 2922 if (p != null) { 2923 PackageSetting ps = mSettings.mPackages.get(packageName); 2924 if (ps == null) return null; 2925 // Note: isEnabledLP() does not apply here - always return info 2926 return PackageParser.generateApplicationInfo( 2927 p, flags, ps.readUserState(userId), userId); 2928 } 2929 if ("android".equals(packageName)||"system".equals(packageName)) { 2930 return mAndroidApplication; 2931 } 2932 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2933 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2934 } 2935 } 2936 return null; 2937 } 2938 2939 @Override 2940 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2941 final IPackageDataObserver observer) { 2942 mContext.enforceCallingOrSelfPermission( 2943 android.Manifest.permission.CLEAR_APP_CACHE, null); 2944 // Queue up an async operation since clearing cache may take a little while. 2945 mHandler.post(new Runnable() { 2946 public void run() { 2947 mHandler.removeCallbacks(this); 2948 int retCode = -1; 2949 synchronized (mInstallLock) { 2950 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2951 if (retCode < 0) { 2952 Slog.w(TAG, "Couldn't clear application caches"); 2953 } 2954 } 2955 if (observer != null) { 2956 try { 2957 observer.onRemoveCompleted(null, (retCode >= 0)); 2958 } catch (RemoteException e) { 2959 Slog.w(TAG, "RemoveException when invoking call back"); 2960 } 2961 } 2962 } 2963 }); 2964 } 2965 2966 @Override 2967 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2968 final IntentSender pi) { 2969 mContext.enforceCallingOrSelfPermission( 2970 android.Manifest.permission.CLEAR_APP_CACHE, null); 2971 // Queue up an async operation since clearing cache may take a little while. 2972 mHandler.post(new Runnable() { 2973 public void run() { 2974 mHandler.removeCallbacks(this); 2975 int retCode = -1; 2976 synchronized (mInstallLock) { 2977 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2978 if (retCode < 0) { 2979 Slog.w(TAG, "Couldn't clear application caches"); 2980 } 2981 } 2982 if(pi != null) { 2983 try { 2984 // Callback via pending intent 2985 int code = (retCode >= 0) ? 1 : 0; 2986 pi.sendIntent(null, code, null, 2987 null, null); 2988 } catch (SendIntentException e1) { 2989 Slog.i(TAG, "Failed to send pending intent"); 2990 } 2991 } 2992 } 2993 }); 2994 } 2995 2996 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2997 synchronized (mInstallLock) { 2998 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2999 throw new IOException("Failed to free enough space"); 3000 } 3001 } 3002 } 3003 3004 @Override 3005 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3006 if (!sUserManager.exists(userId)) return null; 3007 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3008 synchronized (mPackages) { 3009 PackageParser.Activity a = mActivities.mActivities.get(component); 3010 3011 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3012 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3013 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3014 if (ps == null) return null; 3015 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3016 userId); 3017 } 3018 if (mResolveComponentName.equals(component)) { 3019 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3020 new PackageUserState(), userId); 3021 } 3022 } 3023 return null; 3024 } 3025 3026 @Override 3027 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3028 String resolvedType) { 3029 synchronized (mPackages) { 3030 if (component.equals(mResolveComponentName)) { 3031 // The resolver supports EVERYTHING! 3032 return true; 3033 } 3034 PackageParser.Activity a = mActivities.mActivities.get(component); 3035 if (a == null) { 3036 return false; 3037 } 3038 for (int i=0; i<a.intents.size(); i++) { 3039 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3040 intent.getData(), intent.getCategories(), TAG) >= 0) { 3041 return true; 3042 } 3043 } 3044 return false; 3045 } 3046 } 3047 3048 @Override 3049 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3050 if (!sUserManager.exists(userId)) return null; 3051 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3052 synchronized (mPackages) { 3053 PackageParser.Activity a = mReceivers.mActivities.get(component); 3054 if (DEBUG_PACKAGE_INFO) Log.v( 3055 TAG, "getReceiverInfo " + component + ": " + a); 3056 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3057 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3058 if (ps == null) return null; 3059 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3060 userId); 3061 } 3062 } 3063 return null; 3064 } 3065 3066 @Override 3067 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3068 if (!sUserManager.exists(userId)) return null; 3069 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3070 synchronized (mPackages) { 3071 PackageParser.Service s = mServices.mServices.get(component); 3072 if (DEBUG_PACKAGE_INFO) Log.v( 3073 TAG, "getServiceInfo " + component + ": " + s); 3074 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3075 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3076 if (ps == null) return null; 3077 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3078 userId); 3079 } 3080 } 3081 return null; 3082 } 3083 3084 @Override 3085 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3086 if (!sUserManager.exists(userId)) return null; 3087 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3088 synchronized (mPackages) { 3089 PackageParser.Provider p = mProviders.mProviders.get(component); 3090 if (DEBUG_PACKAGE_INFO) Log.v( 3091 TAG, "getProviderInfo " + component + ": " + p); 3092 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3093 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3094 if (ps == null) return null; 3095 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3096 userId); 3097 } 3098 } 3099 return null; 3100 } 3101 3102 @Override 3103 public String[] getSystemSharedLibraryNames() { 3104 Set<String> libSet; 3105 synchronized (mPackages) { 3106 libSet = mSharedLibraries.keySet(); 3107 int size = libSet.size(); 3108 if (size > 0) { 3109 String[] libs = new String[size]; 3110 libSet.toArray(libs); 3111 return libs; 3112 } 3113 } 3114 return null; 3115 } 3116 3117 /** 3118 * @hide 3119 */ 3120 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3121 synchronized (mPackages) { 3122 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3123 if (lib != null && lib.apk != null) { 3124 return mPackages.get(lib.apk); 3125 } 3126 } 3127 return null; 3128 } 3129 3130 @Override 3131 public FeatureInfo[] getSystemAvailableFeatures() { 3132 Collection<FeatureInfo> featSet; 3133 synchronized (mPackages) { 3134 featSet = mAvailableFeatures.values(); 3135 int size = featSet.size(); 3136 if (size > 0) { 3137 FeatureInfo[] features = new FeatureInfo[size+1]; 3138 featSet.toArray(features); 3139 FeatureInfo fi = new FeatureInfo(); 3140 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3141 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3142 features[size] = fi; 3143 return features; 3144 } 3145 } 3146 return null; 3147 } 3148 3149 @Override 3150 public boolean hasSystemFeature(String name) { 3151 synchronized (mPackages) { 3152 return mAvailableFeatures.containsKey(name); 3153 } 3154 } 3155 3156 private void checkValidCaller(int uid, int userId) { 3157 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3158 return; 3159 3160 throw new SecurityException("Caller uid=" + uid 3161 + " is not privileged to communicate with user=" + userId); 3162 } 3163 3164 @Override 3165 public int checkPermission(String permName, String pkgName, int userId) { 3166 if (!sUserManager.exists(userId)) { 3167 return PackageManager.PERMISSION_DENIED; 3168 } 3169 3170 synchronized (mPackages) { 3171 final PackageParser.Package p = mPackages.get(pkgName); 3172 if (p != null && p.mExtras != null) { 3173 final PackageSetting ps = (PackageSetting) p.mExtras; 3174 final PermissionsState permissionsState = ps.getPermissionsState(); 3175 if (permissionsState.hasPermission(permName, userId)) { 3176 return PackageManager.PERMISSION_GRANTED; 3177 } 3178 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3179 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3180 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3181 return PackageManager.PERMISSION_GRANTED; 3182 } 3183 } 3184 } 3185 3186 return PackageManager.PERMISSION_DENIED; 3187 } 3188 3189 @Override 3190 public int checkUidPermission(String permName, int uid) { 3191 final int userId = UserHandle.getUserId(uid); 3192 3193 if (!sUserManager.exists(userId)) { 3194 return PackageManager.PERMISSION_DENIED; 3195 } 3196 3197 synchronized (mPackages) { 3198 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3199 if (obj != null) { 3200 final SettingBase ps = (SettingBase) obj; 3201 final PermissionsState permissionsState = ps.getPermissionsState(); 3202 if (permissionsState.hasPermission(permName, userId)) { 3203 return PackageManager.PERMISSION_GRANTED; 3204 } 3205 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3206 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3207 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3208 return PackageManager.PERMISSION_GRANTED; 3209 } 3210 } else { 3211 ArraySet<String> perms = mSystemPermissions.get(uid); 3212 if (perms != null) { 3213 if (perms.contains(permName)) { 3214 return PackageManager.PERMISSION_GRANTED; 3215 } 3216 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3217 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3218 return PackageManager.PERMISSION_GRANTED; 3219 } 3220 } 3221 } 3222 } 3223 3224 return PackageManager.PERMISSION_DENIED; 3225 } 3226 3227 @Override 3228 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3229 if (UserHandle.getCallingUserId() != userId) { 3230 mContext.enforceCallingPermission( 3231 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3232 "isPermissionRevokedByPolicy for user " + userId); 3233 } 3234 3235 if (checkPermission(permission, packageName, userId) 3236 == PackageManager.PERMISSION_GRANTED) { 3237 return false; 3238 } 3239 3240 final long identity = Binder.clearCallingIdentity(); 3241 try { 3242 final int flags = getPermissionFlags(permission, packageName, userId); 3243 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3244 } finally { 3245 Binder.restoreCallingIdentity(identity); 3246 } 3247 } 3248 3249 @Override 3250 public String getPermissionControllerPackageName() { 3251 synchronized (mPackages) { 3252 return mRequiredInstallerPackage; 3253 } 3254 } 3255 3256 /** 3257 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3258 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3259 * @param checkShell TODO(yamasani): 3260 * @param message the message to log on security exception 3261 */ 3262 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3263 boolean checkShell, String message) { 3264 if (userId < 0) { 3265 throw new IllegalArgumentException("Invalid userId " + userId); 3266 } 3267 if (checkShell) { 3268 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3269 } 3270 if (userId == UserHandle.getUserId(callingUid)) return; 3271 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3272 if (requireFullPermission) { 3273 mContext.enforceCallingOrSelfPermission( 3274 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3275 } else { 3276 try { 3277 mContext.enforceCallingOrSelfPermission( 3278 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3279 } catch (SecurityException se) { 3280 mContext.enforceCallingOrSelfPermission( 3281 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3282 } 3283 } 3284 } 3285 } 3286 3287 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3288 if (callingUid == Process.SHELL_UID) { 3289 if (userHandle >= 0 3290 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3291 throw new SecurityException("Shell does not have permission to access user " 3292 + userHandle); 3293 } else if (userHandle < 0) { 3294 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3295 + Debug.getCallers(3)); 3296 } 3297 } 3298 } 3299 3300 private BasePermission findPermissionTreeLP(String permName) { 3301 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3302 if (permName.startsWith(bp.name) && 3303 permName.length() > bp.name.length() && 3304 permName.charAt(bp.name.length()) == '.') { 3305 return bp; 3306 } 3307 } 3308 return null; 3309 } 3310 3311 private BasePermission checkPermissionTreeLP(String permName) { 3312 if (permName != null) { 3313 BasePermission bp = findPermissionTreeLP(permName); 3314 if (bp != null) { 3315 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3316 return bp; 3317 } 3318 throw new SecurityException("Calling uid " 3319 + Binder.getCallingUid() 3320 + " is not allowed to add to permission tree " 3321 + bp.name + " owned by uid " + bp.uid); 3322 } 3323 } 3324 throw new SecurityException("No permission tree found for " + permName); 3325 } 3326 3327 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3328 if (s1 == null) { 3329 return s2 == null; 3330 } 3331 if (s2 == null) { 3332 return false; 3333 } 3334 if (s1.getClass() != s2.getClass()) { 3335 return false; 3336 } 3337 return s1.equals(s2); 3338 } 3339 3340 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3341 if (pi1.icon != pi2.icon) return false; 3342 if (pi1.logo != pi2.logo) return false; 3343 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3344 if (!compareStrings(pi1.name, pi2.name)) return false; 3345 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3346 // We'll take care of setting this one. 3347 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3348 // These are not currently stored in settings. 3349 //if (!compareStrings(pi1.group, pi2.group)) return false; 3350 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3351 //if (pi1.labelRes != pi2.labelRes) return false; 3352 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3353 return true; 3354 } 3355 3356 int permissionInfoFootprint(PermissionInfo info) { 3357 int size = info.name.length(); 3358 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3359 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3360 return size; 3361 } 3362 3363 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3364 int size = 0; 3365 for (BasePermission perm : mSettings.mPermissions.values()) { 3366 if (perm.uid == tree.uid) { 3367 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3368 } 3369 } 3370 return size; 3371 } 3372 3373 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3374 // We calculate the max size of permissions defined by this uid and throw 3375 // if that plus the size of 'info' would exceed our stated maximum. 3376 if (tree.uid != Process.SYSTEM_UID) { 3377 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3378 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3379 throw new SecurityException("Permission tree size cap exceeded"); 3380 } 3381 } 3382 } 3383 3384 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3385 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3386 throw new SecurityException("Label must be specified in permission"); 3387 } 3388 BasePermission tree = checkPermissionTreeLP(info.name); 3389 BasePermission bp = mSettings.mPermissions.get(info.name); 3390 boolean added = bp == null; 3391 boolean changed = true; 3392 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3393 if (added) { 3394 enforcePermissionCapLocked(info, tree); 3395 bp = new BasePermission(info.name, tree.sourcePackage, 3396 BasePermission.TYPE_DYNAMIC); 3397 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3398 throw new SecurityException( 3399 "Not allowed to modify non-dynamic permission " 3400 + info.name); 3401 } else { 3402 if (bp.protectionLevel == fixedLevel 3403 && bp.perm.owner.equals(tree.perm.owner) 3404 && bp.uid == tree.uid 3405 && comparePermissionInfos(bp.perm.info, info)) { 3406 changed = false; 3407 } 3408 } 3409 bp.protectionLevel = fixedLevel; 3410 info = new PermissionInfo(info); 3411 info.protectionLevel = fixedLevel; 3412 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3413 bp.perm.info.packageName = tree.perm.info.packageName; 3414 bp.uid = tree.uid; 3415 if (added) { 3416 mSettings.mPermissions.put(info.name, bp); 3417 } 3418 if (changed) { 3419 if (!async) { 3420 mSettings.writeLPr(); 3421 } else { 3422 scheduleWriteSettingsLocked(); 3423 } 3424 } 3425 return added; 3426 } 3427 3428 @Override 3429 public boolean addPermission(PermissionInfo info) { 3430 synchronized (mPackages) { 3431 return addPermissionLocked(info, false); 3432 } 3433 } 3434 3435 @Override 3436 public boolean addPermissionAsync(PermissionInfo info) { 3437 synchronized (mPackages) { 3438 return addPermissionLocked(info, true); 3439 } 3440 } 3441 3442 @Override 3443 public void removePermission(String name) { 3444 synchronized (mPackages) { 3445 checkPermissionTreeLP(name); 3446 BasePermission bp = mSettings.mPermissions.get(name); 3447 if (bp != null) { 3448 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3449 throw new SecurityException( 3450 "Not allowed to modify non-dynamic permission " 3451 + name); 3452 } 3453 mSettings.mPermissions.remove(name); 3454 mSettings.writeLPr(); 3455 } 3456 } 3457 } 3458 3459 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3460 BasePermission bp) { 3461 int index = pkg.requestedPermissions.indexOf(bp.name); 3462 if (index == -1) { 3463 throw new SecurityException("Package " + pkg.packageName 3464 + " has not requested permission " + bp.name); 3465 } 3466 if (!bp.isRuntime() && !bp.isDevelopment()) { 3467 throw new SecurityException("Permission " + bp.name 3468 + " is not a changeable permission type"); 3469 } 3470 } 3471 3472 @Override 3473 public void grantRuntimePermission(String packageName, String name, final int userId) { 3474 if (!sUserManager.exists(userId)) { 3475 Log.e(TAG, "No such user:" + userId); 3476 return; 3477 } 3478 3479 mContext.enforceCallingOrSelfPermission( 3480 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3481 "grantRuntimePermission"); 3482 3483 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3484 "grantRuntimePermission"); 3485 3486 final int uid; 3487 final SettingBase sb; 3488 3489 synchronized (mPackages) { 3490 final PackageParser.Package pkg = mPackages.get(packageName); 3491 if (pkg == null) { 3492 throw new IllegalArgumentException("Unknown package: " + packageName); 3493 } 3494 3495 final BasePermission bp = mSettings.mPermissions.get(name); 3496 if (bp == null) { 3497 throw new IllegalArgumentException("Unknown permission: " + name); 3498 } 3499 3500 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3501 3502 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3503 sb = (SettingBase) pkg.mExtras; 3504 if (sb == null) { 3505 throw new IllegalArgumentException("Unknown package: " + packageName); 3506 } 3507 3508 final PermissionsState permissionsState = sb.getPermissionsState(); 3509 3510 final int flags = permissionsState.getPermissionFlags(name, userId); 3511 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3512 throw new SecurityException("Cannot grant system fixed permission: " 3513 + name + " for package: " + packageName); 3514 } 3515 3516 if (bp.isDevelopment()) { 3517 // Development permissions must be handled specially, since they are not 3518 // normal runtime permissions. For now they apply to all users. 3519 if (permissionsState.grantInstallPermission(bp) != 3520 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3521 scheduleWriteSettingsLocked(); 3522 } 3523 return; 3524 } 3525 3526 final int result = permissionsState.grantRuntimePermission(bp, userId); 3527 switch (result) { 3528 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3529 return; 3530 } 3531 3532 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3533 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3534 mHandler.post(new Runnable() { 3535 @Override 3536 public void run() { 3537 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3538 } 3539 }); 3540 } 3541 break; 3542 } 3543 3544 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3545 3546 // Not critical if that is lost - app has to request again. 3547 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3548 } 3549 3550 // Only need to do this if user is initialized. Otherwise it's a new user 3551 // and there are no processes running as the user yet and there's no need 3552 // to make an expensive call to remount processes for the changed permissions. 3553 if (READ_EXTERNAL_STORAGE.equals(name) 3554 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3555 final long token = Binder.clearCallingIdentity(); 3556 try { 3557 if (sUserManager.isInitialized(userId)) { 3558 MountServiceInternal mountServiceInternal = LocalServices.getService( 3559 MountServiceInternal.class); 3560 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3561 } 3562 } finally { 3563 Binder.restoreCallingIdentity(token); 3564 } 3565 } 3566 } 3567 3568 @Override 3569 public void revokeRuntimePermission(String packageName, String name, int userId) { 3570 if (!sUserManager.exists(userId)) { 3571 Log.e(TAG, "No such user:" + userId); 3572 return; 3573 } 3574 3575 mContext.enforceCallingOrSelfPermission( 3576 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3577 "revokeRuntimePermission"); 3578 3579 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3580 "revokeRuntimePermission"); 3581 3582 final int appId; 3583 3584 synchronized (mPackages) { 3585 final PackageParser.Package pkg = mPackages.get(packageName); 3586 if (pkg == null) { 3587 throw new IllegalArgumentException("Unknown package: " + packageName); 3588 } 3589 3590 final BasePermission bp = mSettings.mPermissions.get(name); 3591 if (bp == null) { 3592 throw new IllegalArgumentException("Unknown permission: " + name); 3593 } 3594 3595 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3596 3597 SettingBase sb = (SettingBase) pkg.mExtras; 3598 if (sb == null) { 3599 throw new IllegalArgumentException("Unknown package: " + packageName); 3600 } 3601 3602 final PermissionsState permissionsState = sb.getPermissionsState(); 3603 3604 final int flags = permissionsState.getPermissionFlags(name, userId); 3605 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3606 throw new SecurityException("Cannot revoke system fixed permission: " 3607 + name + " for package: " + packageName); 3608 } 3609 3610 if (bp.isDevelopment()) { 3611 // Development permissions must be handled specially, since they are not 3612 // normal runtime permissions. For now they apply to all users. 3613 if (permissionsState.revokeInstallPermission(bp) != 3614 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3615 scheduleWriteSettingsLocked(); 3616 } 3617 return; 3618 } 3619 3620 if (permissionsState.revokeRuntimePermission(bp, userId) == 3621 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3622 return; 3623 } 3624 3625 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3626 3627 // Critical, after this call app should never have the permission. 3628 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3629 3630 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3631 } 3632 3633 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3634 } 3635 3636 @Override 3637 public void resetRuntimePermissions() { 3638 mContext.enforceCallingOrSelfPermission( 3639 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3640 "revokeRuntimePermission"); 3641 3642 int callingUid = Binder.getCallingUid(); 3643 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3644 mContext.enforceCallingOrSelfPermission( 3645 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3646 "resetRuntimePermissions"); 3647 } 3648 3649 synchronized (mPackages) { 3650 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3651 for (int userId : UserManagerService.getInstance().getUserIds()) { 3652 final int packageCount = mPackages.size(); 3653 for (int i = 0; i < packageCount; i++) { 3654 PackageParser.Package pkg = mPackages.valueAt(i); 3655 if (!(pkg.mExtras instanceof PackageSetting)) { 3656 continue; 3657 } 3658 PackageSetting ps = (PackageSetting) pkg.mExtras; 3659 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3660 } 3661 } 3662 } 3663 } 3664 3665 @Override 3666 public int getPermissionFlags(String name, String packageName, int userId) { 3667 if (!sUserManager.exists(userId)) { 3668 return 0; 3669 } 3670 3671 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3672 3673 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3674 "getPermissionFlags"); 3675 3676 synchronized (mPackages) { 3677 final PackageParser.Package pkg = mPackages.get(packageName); 3678 if (pkg == null) { 3679 throw new IllegalArgumentException("Unknown package: " + packageName); 3680 } 3681 3682 final BasePermission bp = mSettings.mPermissions.get(name); 3683 if (bp == null) { 3684 throw new IllegalArgumentException("Unknown permission: " + name); 3685 } 3686 3687 SettingBase sb = (SettingBase) pkg.mExtras; 3688 if (sb == null) { 3689 throw new IllegalArgumentException("Unknown package: " + packageName); 3690 } 3691 3692 PermissionsState permissionsState = sb.getPermissionsState(); 3693 return permissionsState.getPermissionFlags(name, userId); 3694 } 3695 } 3696 3697 @Override 3698 public void updatePermissionFlags(String name, String packageName, int flagMask, 3699 int flagValues, int userId) { 3700 if (!sUserManager.exists(userId)) { 3701 return; 3702 } 3703 3704 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3705 3706 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3707 "updatePermissionFlags"); 3708 3709 // Only the system can change these flags and nothing else. 3710 if (getCallingUid() != Process.SYSTEM_UID) { 3711 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3712 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3713 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3714 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3715 } 3716 3717 synchronized (mPackages) { 3718 final PackageParser.Package pkg = mPackages.get(packageName); 3719 if (pkg == null) { 3720 throw new IllegalArgumentException("Unknown package: " + packageName); 3721 } 3722 3723 final BasePermission bp = mSettings.mPermissions.get(name); 3724 if (bp == null) { 3725 throw new IllegalArgumentException("Unknown permission: " + name); 3726 } 3727 3728 SettingBase sb = (SettingBase) pkg.mExtras; 3729 if (sb == null) { 3730 throw new IllegalArgumentException("Unknown package: " + packageName); 3731 } 3732 3733 PermissionsState permissionsState = sb.getPermissionsState(); 3734 3735 // Only the package manager can change flags for system component permissions. 3736 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3737 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3738 return; 3739 } 3740 3741 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3742 3743 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3744 // Install and runtime permissions are stored in different places, 3745 // so figure out what permission changed and persist the change. 3746 if (permissionsState.getInstallPermissionState(name) != null) { 3747 scheduleWriteSettingsLocked(); 3748 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3749 || hadState) { 3750 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3751 } 3752 } 3753 } 3754 } 3755 3756 /** 3757 * Update the permission flags for all packages and runtime permissions of a user in order 3758 * to allow device or profile owner to remove POLICY_FIXED. 3759 */ 3760 @Override 3761 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3762 if (!sUserManager.exists(userId)) { 3763 return; 3764 } 3765 3766 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3767 3768 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3769 "updatePermissionFlagsForAllApps"); 3770 3771 // Only the system can change system fixed flags. 3772 if (getCallingUid() != Process.SYSTEM_UID) { 3773 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3774 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3775 } 3776 3777 synchronized (mPackages) { 3778 boolean changed = false; 3779 final int packageCount = mPackages.size(); 3780 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3781 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3782 SettingBase sb = (SettingBase) pkg.mExtras; 3783 if (sb == null) { 3784 continue; 3785 } 3786 PermissionsState permissionsState = sb.getPermissionsState(); 3787 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3788 userId, flagMask, flagValues); 3789 } 3790 if (changed) { 3791 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3792 } 3793 } 3794 } 3795 3796 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3797 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3798 != PackageManager.PERMISSION_GRANTED 3799 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3800 != PackageManager.PERMISSION_GRANTED) { 3801 throw new SecurityException(message + " requires " 3802 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3803 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3804 } 3805 } 3806 3807 @Override 3808 public boolean shouldShowRequestPermissionRationale(String permissionName, 3809 String packageName, int userId) { 3810 if (UserHandle.getCallingUserId() != userId) { 3811 mContext.enforceCallingPermission( 3812 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3813 "canShowRequestPermissionRationale for user " + userId); 3814 } 3815 3816 final int uid = getPackageUid(packageName, userId); 3817 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3818 return false; 3819 } 3820 3821 if (checkPermission(permissionName, packageName, userId) 3822 == PackageManager.PERMISSION_GRANTED) { 3823 return false; 3824 } 3825 3826 final int flags; 3827 3828 final long identity = Binder.clearCallingIdentity(); 3829 try { 3830 flags = getPermissionFlags(permissionName, 3831 packageName, userId); 3832 } finally { 3833 Binder.restoreCallingIdentity(identity); 3834 } 3835 3836 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3837 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3838 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3839 3840 if ((flags & fixedFlags) != 0) { 3841 return false; 3842 } 3843 3844 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3845 } 3846 3847 @Override 3848 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3849 mContext.enforceCallingOrSelfPermission( 3850 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3851 "addOnPermissionsChangeListener"); 3852 3853 synchronized (mPackages) { 3854 mOnPermissionChangeListeners.addListenerLocked(listener); 3855 } 3856 } 3857 3858 @Override 3859 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3860 synchronized (mPackages) { 3861 mOnPermissionChangeListeners.removeListenerLocked(listener); 3862 } 3863 } 3864 3865 @Override 3866 public boolean isProtectedBroadcast(String actionName) { 3867 synchronized (mPackages) { 3868 return mProtectedBroadcasts.contains(actionName); 3869 } 3870 } 3871 3872 @Override 3873 public int checkSignatures(String pkg1, String pkg2) { 3874 synchronized (mPackages) { 3875 final PackageParser.Package p1 = mPackages.get(pkg1); 3876 final PackageParser.Package p2 = mPackages.get(pkg2); 3877 if (p1 == null || p1.mExtras == null 3878 || p2 == null || p2.mExtras == null) { 3879 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3880 } 3881 return compareSignatures(p1.mSignatures, p2.mSignatures); 3882 } 3883 } 3884 3885 @Override 3886 public int checkUidSignatures(int uid1, int uid2) { 3887 // Map to base uids. 3888 uid1 = UserHandle.getAppId(uid1); 3889 uid2 = UserHandle.getAppId(uid2); 3890 // reader 3891 synchronized (mPackages) { 3892 Signature[] s1; 3893 Signature[] s2; 3894 Object obj = mSettings.getUserIdLPr(uid1); 3895 if (obj != null) { 3896 if (obj instanceof SharedUserSetting) { 3897 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3898 } else if (obj instanceof PackageSetting) { 3899 s1 = ((PackageSetting)obj).signatures.mSignatures; 3900 } else { 3901 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3902 } 3903 } else { 3904 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3905 } 3906 obj = mSettings.getUserIdLPr(uid2); 3907 if (obj != null) { 3908 if (obj instanceof SharedUserSetting) { 3909 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3910 } else if (obj instanceof PackageSetting) { 3911 s2 = ((PackageSetting)obj).signatures.mSignatures; 3912 } else { 3913 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3914 } 3915 } else { 3916 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3917 } 3918 return compareSignatures(s1, s2); 3919 } 3920 } 3921 3922 private void killUid(int appId, int userId, String reason) { 3923 final long identity = Binder.clearCallingIdentity(); 3924 try { 3925 IActivityManager am = ActivityManagerNative.getDefault(); 3926 if (am != null) { 3927 try { 3928 am.killUid(appId, userId, reason); 3929 } catch (RemoteException e) { 3930 /* ignore - same process */ 3931 } 3932 } 3933 } finally { 3934 Binder.restoreCallingIdentity(identity); 3935 } 3936 } 3937 3938 /** 3939 * Compares two sets of signatures. Returns: 3940 * <br /> 3941 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3942 * <br /> 3943 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3944 * <br /> 3945 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3946 * <br /> 3947 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3948 * <br /> 3949 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3950 */ 3951 static int compareSignatures(Signature[] s1, Signature[] s2) { 3952 if (s1 == null) { 3953 return s2 == null 3954 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3955 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3956 } 3957 3958 if (s2 == null) { 3959 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3960 } 3961 3962 if (s1.length != s2.length) { 3963 return PackageManager.SIGNATURE_NO_MATCH; 3964 } 3965 3966 // Since both signature sets are of size 1, we can compare without HashSets. 3967 if (s1.length == 1) { 3968 return s1[0].equals(s2[0]) ? 3969 PackageManager.SIGNATURE_MATCH : 3970 PackageManager.SIGNATURE_NO_MATCH; 3971 } 3972 3973 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3974 for (Signature sig : s1) { 3975 set1.add(sig); 3976 } 3977 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3978 for (Signature sig : s2) { 3979 set2.add(sig); 3980 } 3981 // Make sure s2 contains all signatures in s1. 3982 if (set1.equals(set2)) { 3983 return PackageManager.SIGNATURE_MATCH; 3984 } 3985 return PackageManager.SIGNATURE_NO_MATCH; 3986 } 3987 3988 /** 3989 * If the database version for this type of package (internal storage or 3990 * external storage) is less than the version where package signatures 3991 * were updated, return true. 3992 */ 3993 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3994 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3995 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3996 } 3997 3998 /** 3999 * Used for backward compatibility to make sure any packages with 4000 * certificate chains get upgraded to the new style. {@code existingSigs} 4001 * will be in the old format (since they were stored on disk from before the 4002 * system upgrade) and {@code scannedSigs} will be in the newer format. 4003 */ 4004 private int compareSignaturesCompat(PackageSignatures existingSigs, 4005 PackageParser.Package scannedPkg) { 4006 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4007 return PackageManager.SIGNATURE_NO_MATCH; 4008 } 4009 4010 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4011 for (Signature sig : existingSigs.mSignatures) { 4012 existingSet.add(sig); 4013 } 4014 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4015 for (Signature sig : scannedPkg.mSignatures) { 4016 try { 4017 Signature[] chainSignatures = sig.getChainSignatures(); 4018 for (Signature chainSig : chainSignatures) { 4019 scannedCompatSet.add(chainSig); 4020 } 4021 } catch (CertificateEncodingException e) { 4022 scannedCompatSet.add(sig); 4023 } 4024 } 4025 /* 4026 * Make sure the expanded scanned set contains all signatures in the 4027 * existing one. 4028 */ 4029 if (scannedCompatSet.equals(existingSet)) { 4030 // Migrate the old signatures to the new scheme. 4031 existingSigs.assignSignatures(scannedPkg.mSignatures); 4032 // The new KeySets will be re-added later in the scanning process. 4033 synchronized (mPackages) { 4034 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4035 } 4036 return PackageManager.SIGNATURE_MATCH; 4037 } 4038 return PackageManager.SIGNATURE_NO_MATCH; 4039 } 4040 4041 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4042 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4043 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4044 } 4045 4046 private int compareSignaturesRecover(PackageSignatures existingSigs, 4047 PackageParser.Package scannedPkg) { 4048 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4049 return PackageManager.SIGNATURE_NO_MATCH; 4050 } 4051 4052 String msg = null; 4053 try { 4054 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4055 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4056 + scannedPkg.packageName); 4057 return PackageManager.SIGNATURE_MATCH; 4058 } 4059 } catch (CertificateException e) { 4060 msg = e.getMessage(); 4061 } 4062 4063 logCriticalInfo(Log.INFO, 4064 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4065 return PackageManager.SIGNATURE_NO_MATCH; 4066 } 4067 4068 @Override 4069 public String[] getPackagesForUid(int uid) { 4070 uid = UserHandle.getAppId(uid); 4071 // reader 4072 synchronized (mPackages) { 4073 Object obj = mSettings.getUserIdLPr(uid); 4074 if (obj instanceof SharedUserSetting) { 4075 final SharedUserSetting sus = (SharedUserSetting) obj; 4076 final int N = sus.packages.size(); 4077 final String[] res = new String[N]; 4078 final Iterator<PackageSetting> it = sus.packages.iterator(); 4079 int i = 0; 4080 while (it.hasNext()) { 4081 res[i++] = it.next().name; 4082 } 4083 return res; 4084 } else if (obj instanceof PackageSetting) { 4085 final PackageSetting ps = (PackageSetting) obj; 4086 return new String[] { ps.name }; 4087 } 4088 } 4089 return null; 4090 } 4091 4092 @Override 4093 public String getNameForUid(int uid) { 4094 // reader 4095 synchronized (mPackages) { 4096 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4097 if (obj instanceof SharedUserSetting) { 4098 final SharedUserSetting sus = (SharedUserSetting) obj; 4099 return sus.name + ":" + sus.userId; 4100 } else if (obj instanceof PackageSetting) { 4101 final PackageSetting ps = (PackageSetting) obj; 4102 return ps.name; 4103 } 4104 } 4105 return null; 4106 } 4107 4108 @Override 4109 public int getUidForSharedUser(String sharedUserName) { 4110 if(sharedUserName == null) { 4111 return -1; 4112 } 4113 // reader 4114 synchronized (mPackages) { 4115 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4116 if (suid == null) { 4117 return -1; 4118 } 4119 return suid.userId; 4120 } 4121 } 4122 4123 @Override 4124 public int getFlagsForUid(int uid) { 4125 synchronized (mPackages) { 4126 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4127 if (obj instanceof SharedUserSetting) { 4128 final SharedUserSetting sus = (SharedUserSetting) obj; 4129 return sus.pkgFlags; 4130 } else if (obj instanceof PackageSetting) { 4131 final PackageSetting ps = (PackageSetting) obj; 4132 return ps.pkgFlags; 4133 } 4134 } 4135 return 0; 4136 } 4137 4138 @Override 4139 public int getPrivateFlagsForUid(int uid) { 4140 synchronized (mPackages) { 4141 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4142 if (obj instanceof SharedUserSetting) { 4143 final SharedUserSetting sus = (SharedUserSetting) obj; 4144 return sus.pkgPrivateFlags; 4145 } else if (obj instanceof PackageSetting) { 4146 final PackageSetting ps = (PackageSetting) obj; 4147 return ps.pkgPrivateFlags; 4148 } 4149 } 4150 return 0; 4151 } 4152 4153 @Override 4154 public boolean isUidPrivileged(int uid) { 4155 uid = UserHandle.getAppId(uid); 4156 // reader 4157 synchronized (mPackages) { 4158 Object obj = mSettings.getUserIdLPr(uid); 4159 if (obj instanceof SharedUserSetting) { 4160 final SharedUserSetting sus = (SharedUserSetting) obj; 4161 final Iterator<PackageSetting> it = sus.packages.iterator(); 4162 while (it.hasNext()) { 4163 if (it.next().isPrivileged()) { 4164 return true; 4165 } 4166 } 4167 } else if (obj instanceof PackageSetting) { 4168 final PackageSetting ps = (PackageSetting) obj; 4169 return ps.isPrivileged(); 4170 } 4171 } 4172 return false; 4173 } 4174 4175 @Override 4176 public String[] getAppOpPermissionPackages(String permissionName) { 4177 synchronized (mPackages) { 4178 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4179 if (pkgs == null) { 4180 return null; 4181 } 4182 return pkgs.toArray(new String[pkgs.size()]); 4183 } 4184 } 4185 4186 @Override 4187 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4188 int flags, int userId) { 4189 if (!sUserManager.exists(userId)) return null; 4190 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4191 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4192 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4193 } 4194 4195 @Override 4196 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4197 IntentFilter filter, int match, ComponentName activity) { 4198 final int userId = UserHandle.getCallingUserId(); 4199 if (DEBUG_PREFERRED) { 4200 Log.v(TAG, "setLastChosenActivity intent=" + intent 4201 + " resolvedType=" + resolvedType 4202 + " flags=" + flags 4203 + " filter=" + filter 4204 + " match=" + match 4205 + " activity=" + activity); 4206 filter.dump(new PrintStreamPrinter(System.out), " "); 4207 } 4208 intent.setComponent(null); 4209 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4210 // Find any earlier preferred or last chosen entries and nuke them 4211 findPreferredActivity(intent, resolvedType, 4212 flags, query, 0, false, true, false, userId); 4213 // Add the new activity as the last chosen for this filter 4214 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4215 "Setting last chosen"); 4216 } 4217 4218 @Override 4219 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4220 final int userId = UserHandle.getCallingUserId(); 4221 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4222 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4223 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4224 false, false, false, userId); 4225 } 4226 4227 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4228 int flags, List<ResolveInfo> query, int userId) { 4229 if (query != null) { 4230 final int N = query.size(); 4231 if (N == 1) { 4232 return query.get(0); 4233 } else if (N > 1) { 4234 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4235 // If there is more than one activity with the same priority, 4236 // then let the user decide between them. 4237 ResolveInfo r0 = query.get(0); 4238 ResolveInfo r1 = query.get(1); 4239 if (DEBUG_INTENT_MATCHING || debug) { 4240 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4241 + r1.activityInfo.name + "=" + r1.priority); 4242 } 4243 // If the first activity has a higher priority, or a different 4244 // default, then it is always desireable to pick it. 4245 if (r0.priority != r1.priority 4246 || r0.preferredOrder != r1.preferredOrder 4247 || r0.isDefault != r1.isDefault) { 4248 return query.get(0); 4249 } 4250 // If we have saved a preference for a preferred activity for 4251 // this Intent, use that. 4252 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4253 flags, query, r0.priority, true, false, debug, userId); 4254 if (ri != null) { 4255 return ri; 4256 } 4257 ri = new ResolveInfo(mResolveInfo); 4258 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4259 ri.activityInfo.applicationInfo = new ApplicationInfo( 4260 ri.activityInfo.applicationInfo); 4261 if (userId != 0) { 4262 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4263 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4264 } 4265 // Make sure that the resolver is displayable in car mode 4266 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4267 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4268 return ri; 4269 } 4270 } 4271 return null; 4272 } 4273 4274 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4275 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4276 final int N = query.size(); 4277 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4278 .get(userId); 4279 // Get the list of persistent preferred activities that handle the intent 4280 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4281 List<PersistentPreferredActivity> pprefs = ppir != null 4282 ? ppir.queryIntent(intent, resolvedType, 4283 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4284 : null; 4285 if (pprefs != null && pprefs.size() > 0) { 4286 final int M = pprefs.size(); 4287 for (int i=0; i<M; i++) { 4288 final PersistentPreferredActivity ppa = pprefs.get(i); 4289 if (DEBUG_PREFERRED || debug) { 4290 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4291 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4292 + "\n component=" + ppa.mComponent); 4293 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4294 } 4295 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4296 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4297 if (DEBUG_PREFERRED || debug) { 4298 Slog.v(TAG, "Found persistent preferred activity:"); 4299 if (ai != null) { 4300 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4301 } else { 4302 Slog.v(TAG, " null"); 4303 } 4304 } 4305 if (ai == null) { 4306 // This previously registered persistent preferred activity 4307 // component is no longer known. Ignore it and do NOT remove it. 4308 continue; 4309 } 4310 for (int j=0; j<N; j++) { 4311 final ResolveInfo ri = query.get(j); 4312 if (!ri.activityInfo.applicationInfo.packageName 4313 .equals(ai.applicationInfo.packageName)) { 4314 continue; 4315 } 4316 if (!ri.activityInfo.name.equals(ai.name)) { 4317 continue; 4318 } 4319 // Found a persistent preference that can handle the intent. 4320 if (DEBUG_PREFERRED || debug) { 4321 Slog.v(TAG, "Returning persistent preferred activity: " + 4322 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4323 } 4324 return ri; 4325 } 4326 } 4327 } 4328 return null; 4329 } 4330 4331 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4332 List<ResolveInfo> query, int priority, boolean always, 4333 boolean removeMatches, boolean debug, int userId) { 4334 if (!sUserManager.exists(userId)) return null; 4335 // writer 4336 synchronized (mPackages) { 4337 if (intent.getSelector() != null) { 4338 intent = intent.getSelector(); 4339 } 4340 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4341 4342 // Try to find a matching persistent preferred activity. 4343 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4344 debug, userId); 4345 4346 // If a persistent preferred activity matched, use it. 4347 if (pri != null) { 4348 return pri; 4349 } 4350 4351 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4352 // Get the list of preferred activities that handle the intent 4353 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4354 List<PreferredActivity> prefs = pir != null 4355 ? pir.queryIntent(intent, resolvedType, 4356 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4357 : null; 4358 if (prefs != null && prefs.size() > 0) { 4359 boolean changed = false; 4360 try { 4361 // First figure out how good the original match set is. 4362 // We will only allow preferred activities that came 4363 // from the same match quality. 4364 int match = 0; 4365 4366 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4367 4368 final int N = query.size(); 4369 for (int j=0; j<N; j++) { 4370 final ResolveInfo ri = query.get(j); 4371 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4372 + ": 0x" + Integer.toHexString(match)); 4373 if (ri.match > match) { 4374 match = ri.match; 4375 } 4376 } 4377 4378 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4379 + Integer.toHexString(match)); 4380 4381 match &= IntentFilter.MATCH_CATEGORY_MASK; 4382 final int M = prefs.size(); 4383 for (int i=0; i<M; i++) { 4384 final PreferredActivity pa = prefs.get(i); 4385 if (DEBUG_PREFERRED || debug) { 4386 Slog.v(TAG, "Checking PreferredActivity ds=" 4387 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4388 + "\n component=" + pa.mPref.mComponent); 4389 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4390 } 4391 if (pa.mPref.mMatch != match) { 4392 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4393 + Integer.toHexString(pa.mPref.mMatch)); 4394 continue; 4395 } 4396 // If it's not an "always" type preferred activity and that's what we're 4397 // looking for, skip it. 4398 if (always && !pa.mPref.mAlways) { 4399 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4400 continue; 4401 } 4402 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4403 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4404 if (DEBUG_PREFERRED || debug) { 4405 Slog.v(TAG, "Found preferred activity:"); 4406 if (ai != null) { 4407 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4408 } else { 4409 Slog.v(TAG, " null"); 4410 } 4411 } 4412 if (ai == null) { 4413 // This previously registered preferred activity 4414 // component is no longer known. Most likely an update 4415 // to the app was installed and in the new version this 4416 // component no longer exists. Clean it up by removing 4417 // it from the preferred activities list, and skip it. 4418 Slog.w(TAG, "Removing dangling preferred activity: " 4419 + pa.mPref.mComponent); 4420 pir.removeFilter(pa); 4421 changed = true; 4422 continue; 4423 } 4424 for (int j=0; j<N; j++) { 4425 final ResolveInfo ri = query.get(j); 4426 if (!ri.activityInfo.applicationInfo.packageName 4427 .equals(ai.applicationInfo.packageName)) { 4428 continue; 4429 } 4430 if (!ri.activityInfo.name.equals(ai.name)) { 4431 continue; 4432 } 4433 4434 if (removeMatches) { 4435 pir.removeFilter(pa); 4436 changed = true; 4437 if (DEBUG_PREFERRED) { 4438 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4439 } 4440 break; 4441 } 4442 4443 // Okay we found a previously set preferred or last chosen app. 4444 // If the result set is different from when this 4445 // was created, we need to clear it and re-ask the 4446 // user their preference, if we're looking for an "always" type entry. 4447 if (always && !pa.mPref.sameSet(query)) { 4448 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4449 + intent + " type " + resolvedType); 4450 if (DEBUG_PREFERRED) { 4451 Slog.v(TAG, "Removing preferred activity since set changed " 4452 + pa.mPref.mComponent); 4453 } 4454 pir.removeFilter(pa); 4455 // Re-add the filter as a "last chosen" entry (!always) 4456 PreferredActivity lastChosen = new PreferredActivity( 4457 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4458 pir.addFilter(lastChosen); 4459 changed = true; 4460 return null; 4461 } 4462 4463 // Yay! Either the set matched or we're looking for the last chosen 4464 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4465 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4466 return ri; 4467 } 4468 } 4469 } finally { 4470 if (changed) { 4471 if (DEBUG_PREFERRED) { 4472 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4473 } 4474 scheduleWritePackageRestrictionsLocked(userId); 4475 } 4476 } 4477 } 4478 } 4479 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4480 return null; 4481 } 4482 4483 /* 4484 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4485 */ 4486 @Override 4487 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4488 int targetUserId) { 4489 mContext.enforceCallingOrSelfPermission( 4490 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4491 List<CrossProfileIntentFilter> matches = 4492 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4493 if (matches != null) { 4494 int size = matches.size(); 4495 for (int i = 0; i < size; i++) { 4496 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4497 } 4498 } 4499 if (hasWebURI(intent)) { 4500 // cross-profile app linking works only towards the parent. 4501 final UserInfo parent = getProfileParent(sourceUserId); 4502 synchronized(mPackages) { 4503 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4504 intent, resolvedType, 0, sourceUserId, parent.id); 4505 return xpDomainInfo != null; 4506 } 4507 } 4508 return false; 4509 } 4510 4511 private UserInfo getProfileParent(int userId) { 4512 final long identity = Binder.clearCallingIdentity(); 4513 try { 4514 return sUserManager.getProfileParent(userId); 4515 } finally { 4516 Binder.restoreCallingIdentity(identity); 4517 } 4518 } 4519 4520 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4521 String resolvedType, int userId) { 4522 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4523 if (resolver != null) { 4524 return resolver.queryIntent(intent, resolvedType, false, userId); 4525 } 4526 return null; 4527 } 4528 4529 @Override 4530 public List<ResolveInfo> queryIntentActivities(Intent intent, 4531 String resolvedType, int flags, int userId) { 4532 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4533 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4534 ComponentName comp = intent.getComponent(); 4535 if (comp == null) { 4536 if (intent.getSelector() != null) { 4537 intent = intent.getSelector(); 4538 comp = intent.getComponent(); 4539 } 4540 } 4541 4542 if (comp != null) { 4543 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4544 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4545 if (ai != null) { 4546 final ResolveInfo ri = new ResolveInfo(); 4547 ri.activityInfo = ai; 4548 list.add(ri); 4549 } 4550 return list; 4551 } 4552 4553 // reader 4554 synchronized (mPackages) { 4555 final String pkgName = intent.getPackage(); 4556 if (pkgName == null) { 4557 List<CrossProfileIntentFilter> matchingFilters = 4558 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4559 // Check for results that need to skip the current profile. 4560 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4561 resolvedType, flags, userId); 4562 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4563 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4564 result.add(xpResolveInfo); 4565 return filterIfNotPrimaryUser(result, userId); 4566 } 4567 4568 // Check for results in the current profile. 4569 List<ResolveInfo> result = mActivities.queryIntent( 4570 intent, resolvedType, flags, userId); 4571 4572 // Check for cross profile results. 4573 xpResolveInfo = queryCrossProfileIntents( 4574 matchingFilters, intent, resolvedType, flags, userId); 4575 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4576 result.add(xpResolveInfo); 4577 Collections.sort(result, mResolvePrioritySorter); 4578 } 4579 result = filterIfNotPrimaryUser(result, userId); 4580 if (hasWebURI(intent)) { 4581 CrossProfileDomainInfo xpDomainInfo = null; 4582 final UserInfo parent = getProfileParent(userId); 4583 if (parent != null) { 4584 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4585 flags, userId, parent.id); 4586 } 4587 if (xpDomainInfo != null) { 4588 if (xpResolveInfo != null) { 4589 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4590 // in the result. 4591 result.remove(xpResolveInfo); 4592 } 4593 if (result.size() == 0) { 4594 result.add(xpDomainInfo.resolveInfo); 4595 return result; 4596 } 4597 } else if (result.size() <= 1) { 4598 return result; 4599 } 4600 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4601 xpDomainInfo, userId); 4602 Collections.sort(result, mResolvePrioritySorter); 4603 } 4604 return result; 4605 } 4606 final PackageParser.Package pkg = mPackages.get(pkgName); 4607 if (pkg != null) { 4608 return filterIfNotPrimaryUser( 4609 mActivities.queryIntentForPackage( 4610 intent, resolvedType, flags, pkg.activities, userId), 4611 userId); 4612 } 4613 return new ArrayList<ResolveInfo>(); 4614 } 4615 } 4616 4617 private static class CrossProfileDomainInfo { 4618 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4619 ResolveInfo resolveInfo; 4620 /* Best domain verification status of the activities found in the other profile */ 4621 int bestDomainVerificationStatus; 4622 } 4623 4624 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4625 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4626 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4627 sourceUserId)) { 4628 return null; 4629 } 4630 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4631 resolvedType, flags, parentUserId); 4632 4633 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4634 return null; 4635 } 4636 CrossProfileDomainInfo result = null; 4637 int size = resultTargetUser.size(); 4638 for (int i = 0; i < size; i++) { 4639 ResolveInfo riTargetUser = resultTargetUser.get(i); 4640 // Intent filter verification is only for filters that specify a host. So don't return 4641 // those that handle all web uris. 4642 if (riTargetUser.handleAllWebDataURI) { 4643 continue; 4644 } 4645 String packageName = riTargetUser.activityInfo.packageName; 4646 PackageSetting ps = mSettings.mPackages.get(packageName); 4647 if (ps == null) { 4648 continue; 4649 } 4650 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4651 int status = (int)(verificationState >> 32); 4652 if (result == null) { 4653 result = new CrossProfileDomainInfo(); 4654 result.resolveInfo = 4655 createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId); 4656 result.bestDomainVerificationStatus = status; 4657 } else { 4658 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4659 result.bestDomainVerificationStatus); 4660 } 4661 } 4662 // Don't consider matches with status NEVER across profiles. 4663 if (result != null && result.bestDomainVerificationStatus 4664 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4665 return null; 4666 } 4667 return result; 4668 } 4669 4670 /** 4671 * Verification statuses are ordered from the worse to the best, except for 4672 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4673 */ 4674 private int bestDomainVerificationStatus(int status1, int status2) { 4675 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4676 return status2; 4677 } 4678 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4679 return status1; 4680 } 4681 return (int) MathUtils.max(status1, status2); 4682 } 4683 4684 private boolean isUserEnabled(int userId) { 4685 long callingId = Binder.clearCallingIdentity(); 4686 try { 4687 UserInfo userInfo = sUserManager.getUserInfo(userId); 4688 return userInfo != null && userInfo.isEnabled(); 4689 } finally { 4690 Binder.restoreCallingIdentity(callingId); 4691 } 4692 } 4693 4694 /** 4695 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4696 * 4697 * @return filtered list 4698 */ 4699 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4700 if (userId == UserHandle.USER_OWNER) { 4701 return resolveInfos; 4702 } 4703 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4704 ResolveInfo info = resolveInfos.get(i); 4705 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4706 resolveInfos.remove(i); 4707 } 4708 } 4709 return resolveInfos; 4710 } 4711 4712 private static boolean hasWebURI(Intent intent) { 4713 if (intent.getData() == null) { 4714 return false; 4715 } 4716 final String scheme = intent.getScheme(); 4717 if (TextUtils.isEmpty(scheme)) { 4718 return false; 4719 } 4720 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4721 } 4722 4723 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4724 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4725 int userId) { 4726 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4727 4728 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4729 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4730 candidates.size()); 4731 } 4732 4733 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4734 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4735 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4736 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4737 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4738 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4739 4740 synchronized (mPackages) { 4741 final int count = candidates.size(); 4742 // First, try to use linked apps. Partition the candidates into four lists: 4743 // one for the final results, one for the "do not use ever", one for "undefined status" 4744 // and finally one for "browser app type". 4745 for (int n=0; n<count; n++) { 4746 ResolveInfo info = candidates.get(n); 4747 String packageName = info.activityInfo.packageName; 4748 PackageSetting ps = mSettings.mPackages.get(packageName); 4749 if (ps != null) { 4750 // Add to the special match all list (Browser use case) 4751 if (info.handleAllWebDataURI) { 4752 matchAllList.add(info); 4753 continue; 4754 } 4755 // Try to get the status from User settings first 4756 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4757 int status = (int)(packedStatus >> 32); 4758 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4759 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4760 if (DEBUG_DOMAIN_VERIFICATION) { 4761 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4762 + " : linkgen=" + linkGeneration); 4763 } 4764 // Use link-enabled generation as preferredOrder, i.e. 4765 // prefer newly-enabled over earlier-enabled. 4766 info.preferredOrder = linkGeneration; 4767 alwaysList.add(info); 4768 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4769 if (DEBUG_DOMAIN_VERIFICATION) { 4770 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4771 } 4772 neverList.add(info); 4773 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4774 if (DEBUG_DOMAIN_VERIFICATION) { 4775 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4776 } 4777 alwaysAskList.add(info); 4778 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4779 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4780 if (DEBUG_DOMAIN_VERIFICATION) { 4781 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4782 } 4783 undefinedList.add(info); 4784 } 4785 } 4786 } 4787 4788 // We'll want to include browser possibilities in a few cases 4789 boolean includeBrowser = false; 4790 4791 // First try to add the "always" resolution(s) for the current user, if any 4792 if (alwaysList.size() > 0) { 4793 result.addAll(alwaysList); 4794 } else { 4795 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4796 result.addAll(undefinedList); 4797 // Maybe add one for the other profile. 4798 if (xpDomainInfo != null && ( 4799 xpDomainInfo.bestDomainVerificationStatus 4800 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 4801 result.add(xpDomainInfo.resolveInfo); 4802 } 4803 includeBrowser = true; 4804 } 4805 4806 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4807 // If there were 'always' entries their preferred order has been set, so we also 4808 // back that off to make the alternatives equivalent 4809 if (alwaysAskList.size() > 0) { 4810 for (ResolveInfo i : result) { 4811 i.preferredOrder = 0; 4812 } 4813 result.addAll(alwaysAskList); 4814 includeBrowser = true; 4815 } 4816 4817 if (includeBrowser) { 4818 // Also add browsers (all of them or only the default one) 4819 if (DEBUG_DOMAIN_VERIFICATION) { 4820 Slog.v(TAG, " ...including browsers in candidate set"); 4821 } 4822 if ((matchFlags & MATCH_ALL) != 0) { 4823 result.addAll(matchAllList); 4824 } else { 4825 // Browser/generic handling case. If there's a default browser, go straight 4826 // to that (but only if there is no other higher-priority match). 4827 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4828 int maxMatchPrio = 0; 4829 ResolveInfo defaultBrowserMatch = null; 4830 final int numCandidates = matchAllList.size(); 4831 for (int n = 0; n < numCandidates; n++) { 4832 ResolveInfo info = matchAllList.get(n); 4833 // track the highest overall match priority... 4834 if (info.priority > maxMatchPrio) { 4835 maxMatchPrio = info.priority; 4836 } 4837 // ...and the highest-priority default browser match 4838 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4839 if (defaultBrowserMatch == null 4840 || (defaultBrowserMatch.priority < info.priority)) { 4841 if (debug) { 4842 Slog.v(TAG, "Considering default browser match " + info); 4843 } 4844 defaultBrowserMatch = info; 4845 } 4846 } 4847 } 4848 if (defaultBrowserMatch != null 4849 && defaultBrowserMatch.priority >= maxMatchPrio 4850 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4851 { 4852 if (debug) { 4853 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4854 } 4855 result.add(defaultBrowserMatch); 4856 } else { 4857 result.addAll(matchAllList); 4858 } 4859 } 4860 4861 // If there is nothing selected, add all candidates and remove the ones that the user 4862 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4863 if (result.size() == 0) { 4864 result.addAll(candidates); 4865 result.removeAll(neverList); 4866 } 4867 } 4868 } 4869 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4870 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4871 result.size()); 4872 for (ResolveInfo info : result) { 4873 Slog.v(TAG, " + " + info.activityInfo); 4874 } 4875 } 4876 return result; 4877 } 4878 4879 // Returns a packed value as a long: 4880 // 4881 // high 'int'-sized word: link status: undefined/ask/never/always. 4882 // low 'int'-sized word: relative priority among 'always' results. 4883 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4884 long result = ps.getDomainVerificationStatusForUser(userId); 4885 // if none available, get the master status 4886 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4887 if (ps.getIntentFilterVerificationInfo() != null) { 4888 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4889 } 4890 } 4891 return result; 4892 } 4893 4894 private ResolveInfo querySkipCurrentProfileIntents( 4895 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4896 int flags, int sourceUserId) { 4897 if (matchingFilters != null) { 4898 int size = matchingFilters.size(); 4899 for (int i = 0; i < size; i ++) { 4900 CrossProfileIntentFilter filter = matchingFilters.get(i); 4901 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4902 // Checking if there are activities in the target user that can handle the 4903 // intent. 4904 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4905 flags, sourceUserId); 4906 if (resolveInfo != null) { 4907 return resolveInfo; 4908 } 4909 } 4910 } 4911 } 4912 return null; 4913 } 4914 4915 // Return matching ResolveInfo if any for skip current profile intent filters. 4916 private ResolveInfo queryCrossProfileIntents( 4917 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4918 int flags, int sourceUserId) { 4919 if (matchingFilters != null) { 4920 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4921 // match the same intent. For performance reasons, it is better not to 4922 // run queryIntent twice for the same userId 4923 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4924 int size = matchingFilters.size(); 4925 for (int i = 0; i < size; i++) { 4926 CrossProfileIntentFilter filter = matchingFilters.get(i); 4927 int targetUserId = filter.getTargetUserId(); 4928 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4929 && !alreadyTriedUserIds.get(targetUserId)) { 4930 // Checking if there are activities in the target user that can handle the 4931 // intent. 4932 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4933 flags, sourceUserId); 4934 if (resolveInfo != null) return resolveInfo; 4935 alreadyTriedUserIds.put(targetUserId, true); 4936 } 4937 } 4938 } 4939 return null; 4940 } 4941 4942 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4943 String resolvedType, int flags, int sourceUserId) { 4944 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4945 resolvedType, flags, filter.getTargetUserId()); 4946 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4947 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4948 } 4949 return null; 4950 } 4951 4952 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4953 int sourceUserId, int targetUserId) { 4954 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4955 String className; 4956 if (targetUserId == UserHandle.USER_OWNER) { 4957 className = FORWARD_INTENT_TO_USER_OWNER; 4958 } else { 4959 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4960 } 4961 ComponentName forwardingActivityComponentName = new ComponentName( 4962 mAndroidApplication.packageName, className); 4963 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4964 sourceUserId); 4965 if (targetUserId == UserHandle.USER_OWNER) { 4966 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4967 forwardingResolveInfo.noResourceId = true; 4968 } 4969 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4970 forwardingResolveInfo.priority = 0; 4971 forwardingResolveInfo.preferredOrder = 0; 4972 forwardingResolveInfo.match = 0; 4973 forwardingResolveInfo.isDefault = true; 4974 forwardingResolveInfo.filter = filter; 4975 forwardingResolveInfo.targetUserId = targetUserId; 4976 return forwardingResolveInfo; 4977 } 4978 4979 @Override 4980 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4981 Intent[] specifics, String[] specificTypes, Intent intent, 4982 String resolvedType, int flags, int userId) { 4983 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4984 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4985 false, "query intent activity options"); 4986 final String resultsAction = intent.getAction(); 4987 4988 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4989 | PackageManager.GET_RESOLVED_FILTER, userId); 4990 4991 if (DEBUG_INTENT_MATCHING) { 4992 Log.v(TAG, "Query " + intent + ": " + results); 4993 } 4994 4995 int specificsPos = 0; 4996 int N; 4997 4998 // todo: note that the algorithm used here is O(N^2). This 4999 // isn't a problem in our current environment, but if we start running 5000 // into situations where we have more than 5 or 10 matches then this 5001 // should probably be changed to something smarter... 5002 5003 // First we go through and resolve each of the specific items 5004 // that were supplied, taking care of removing any corresponding 5005 // duplicate items in the generic resolve list. 5006 if (specifics != null) { 5007 for (int i=0; i<specifics.length; i++) { 5008 final Intent sintent = specifics[i]; 5009 if (sintent == null) { 5010 continue; 5011 } 5012 5013 if (DEBUG_INTENT_MATCHING) { 5014 Log.v(TAG, "Specific #" + i + ": " + sintent); 5015 } 5016 5017 String action = sintent.getAction(); 5018 if (resultsAction != null && resultsAction.equals(action)) { 5019 // If this action was explicitly requested, then don't 5020 // remove things that have it. 5021 action = null; 5022 } 5023 5024 ResolveInfo ri = null; 5025 ActivityInfo ai = null; 5026 5027 ComponentName comp = sintent.getComponent(); 5028 if (comp == null) { 5029 ri = resolveIntent( 5030 sintent, 5031 specificTypes != null ? specificTypes[i] : null, 5032 flags, userId); 5033 if (ri == null) { 5034 continue; 5035 } 5036 if (ri == mResolveInfo) { 5037 // ACK! Must do something better with this. 5038 } 5039 ai = ri.activityInfo; 5040 comp = new ComponentName(ai.applicationInfo.packageName, 5041 ai.name); 5042 } else { 5043 ai = getActivityInfo(comp, flags, userId); 5044 if (ai == null) { 5045 continue; 5046 } 5047 } 5048 5049 // Look for any generic query activities that are duplicates 5050 // of this specific one, and remove them from the results. 5051 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5052 N = results.size(); 5053 int j; 5054 for (j=specificsPos; j<N; j++) { 5055 ResolveInfo sri = results.get(j); 5056 if ((sri.activityInfo.name.equals(comp.getClassName()) 5057 && sri.activityInfo.applicationInfo.packageName.equals( 5058 comp.getPackageName())) 5059 || (action != null && sri.filter.matchAction(action))) { 5060 results.remove(j); 5061 if (DEBUG_INTENT_MATCHING) Log.v( 5062 TAG, "Removing duplicate item from " + j 5063 + " due to specific " + specificsPos); 5064 if (ri == null) { 5065 ri = sri; 5066 } 5067 j--; 5068 N--; 5069 } 5070 } 5071 5072 // Add this specific item to its proper place. 5073 if (ri == null) { 5074 ri = new ResolveInfo(); 5075 ri.activityInfo = ai; 5076 } 5077 results.add(specificsPos, ri); 5078 ri.specificIndex = i; 5079 specificsPos++; 5080 } 5081 } 5082 5083 // Now we go through the remaining generic results and remove any 5084 // duplicate actions that are found here. 5085 N = results.size(); 5086 for (int i=specificsPos; i<N-1; i++) { 5087 final ResolveInfo rii = results.get(i); 5088 if (rii.filter == null) { 5089 continue; 5090 } 5091 5092 // Iterate over all of the actions of this result's intent 5093 // filter... typically this should be just one. 5094 final Iterator<String> it = rii.filter.actionsIterator(); 5095 if (it == null) { 5096 continue; 5097 } 5098 while (it.hasNext()) { 5099 final String action = it.next(); 5100 if (resultsAction != null && resultsAction.equals(action)) { 5101 // If this action was explicitly requested, then don't 5102 // remove things that have it. 5103 continue; 5104 } 5105 for (int j=i+1; j<N; j++) { 5106 final ResolveInfo rij = results.get(j); 5107 if (rij.filter != null && rij.filter.hasAction(action)) { 5108 results.remove(j); 5109 if (DEBUG_INTENT_MATCHING) Log.v( 5110 TAG, "Removing duplicate item from " + j 5111 + " due to action " + action + " at " + i); 5112 j--; 5113 N--; 5114 } 5115 } 5116 } 5117 5118 // If the caller didn't request filter information, drop it now 5119 // so we don't have to marshall/unmarshall it. 5120 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5121 rii.filter = null; 5122 } 5123 } 5124 5125 // Filter out the caller activity if so requested. 5126 if (caller != null) { 5127 N = results.size(); 5128 for (int i=0; i<N; i++) { 5129 ActivityInfo ainfo = results.get(i).activityInfo; 5130 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5131 && caller.getClassName().equals(ainfo.name)) { 5132 results.remove(i); 5133 break; 5134 } 5135 } 5136 } 5137 5138 // If the caller didn't request filter information, 5139 // drop them now so we don't have to 5140 // marshall/unmarshall it. 5141 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5142 N = results.size(); 5143 for (int i=0; i<N; i++) { 5144 results.get(i).filter = null; 5145 } 5146 } 5147 5148 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5149 return results; 5150 } 5151 5152 @Override 5153 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5154 int userId) { 5155 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5156 ComponentName comp = intent.getComponent(); 5157 if (comp == null) { 5158 if (intent.getSelector() != null) { 5159 intent = intent.getSelector(); 5160 comp = intent.getComponent(); 5161 } 5162 } 5163 if (comp != null) { 5164 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5165 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5166 if (ai != null) { 5167 ResolveInfo ri = new ResolveInfo(); 5168 ri.activityInfo = ai; 5169 list.add(ri); 5170 } 5171 return list; 5172 } 5173 5174 // reader 5175 synchronized (mPackages) { 5176 String pkgName = intent.getPackage(); 5177 if (pkgName == null) { 5178 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5179 } 5180 final PackageParser.Package pkg = mPackages.get(pkgName); 5181 if (pkg != null) { 5182 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5183 userId); 5184 } 5185 return null; 5186 } 5187 } 5188 5189 @Override 5190 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5191 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5192 if (!sUserManager.exists(userId)) return null; 5193 if (query != null) { 5194 if (query.size() >= 1) { 5195 // If there is more than one service with the same priority, 5196 // just arbitrarily pick the first one. 5197 return query.get(0); 5198 } 5199 } 5200 return null; 5201 } 5202 5203 @Override 5204 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5205 int userId) { 5206 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5207 ComponentName comp = intent.getComponent(); 5208 if (comp == null) { 5209 if (intent.getSelector() != null) { 5210 intent = intent.getSelector(); 5211 comp = intent.getComponent(); 5212 } 5213 } 5214 if (comp != null) { 5215 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5216 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5217 if (si != null) { 5218 final ResolveInfo ri = new ResolveInfo(); 5219 ri.serviceInfo = si; 5220 list.add(ri); 5221 } 5222 return list; 5223 } 5224 5225 // reader 5226 synchronized (mPackages) { 5227 String pkgName = intent.getPackage(); 5228 if (pkgName == null) { 5229 return mServices.queryIntent(intent, resolvedType, flags, userId); 5230 } 5231 final PackageParser.Package pkg = mPackages.get(pkgName); 5232 if (pkg != null) { 5233 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5234 userId); 5235 } 5236 return null; 5237 } 5238 } 5239 5240 @Override 5241 public List<ResolveInfo> queryIntentContentProviders( 5242 Intent intent, String resolvedType, int flags, int userId) { 5243 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5244 ComponentName comp = intent.getComponent(); 5245 if (comp == null) { 5246 if (intent.getSelector() != null) { 5247 intent = intent.getSelector(); 5248 comp = intent.getComponent(); 5249 } 5250 } 5251 if (comp != null) { 5252 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5253 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5254 if (pi != null) { 5255 final ResolveInfo ri = new ResolveInfo(); 5256 ri.providerInfo = pi; 5257 list.add(ri); 5258 } 5259 return list; 5260 } 5261 5262 // reader 5263 synchronized (mPackages) { 5264 String pkgName = intent.getPackage(); 5265 if (pkgName == null) { 5266 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5267 } 5268 final PackageParser.Package pkg = mPackages.get(pkgName); 5269 if (pkg != null) { 5270 return mProviders.queryIntentForPackage( 5271 intent, resolvedType, flags, pkg.providers, userId); 5272 } 5273 return null; 5274 } 5275 } 5276 5277 @Override 5278 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5279 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5280 5281 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5282 5283 // writer 5284 synchronized (mPackages) { 5285 ArrayList<PackageInfo> list; 5286 if (listUninstalled) { 5287 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5288 for (PackageSetting ps : mSettings.mPackages.values()) { 5289 PackageInfo pi; 5290 if (ps.pkg != null) { 5291 pi = generatePackageInfo(ps.pkg, flags, userId); 5292 } else { 5293 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5294 } 5295 if (pi != null) { 5296 list.add(pi); 5297 } 5298 } 5299 } else { 5300 list = new ArrayList<PackageInfo>(mPackages.size()); 5301 for (PackageParser.Package p : mPackages.values()) { 5302 PackageInfo pi = generatePackageInfo(p, flags, userId); 5303 if (pi != null) { 5304 list.add(pi); 5305 } 5306 } 5307 } 5308 5309 return new ParceledListSlice<PackageInfo>(list); 5310 } 5311 } 5312 5313 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5314 String[] permissions, boolean[] tmp, int flags, int userId) { 5315 int numMatch = 0; 5316 final PermissionsState permissionsState = ps.getPermissionsState(); 5317 for (int i=0; i<permissions.length; i++) { 5318 final String permission = permissions[i]; 5319 if (permissionsState.hasPermission(permission, userId)) { 5320 tmp[i] = true; 5321 numMatch++; 5322 } else { 5323 tmp[i] = false; 5324 } 5325 } 5326 if (numMatch == 0) { 5327 return; 5328 } 5329 PackageInfo pi; 5330 if (ps.pkg != null) { 5331 pi = generatePackageInfo(ps.pkg, flags, userId); 5332 } else { 5333 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5334 } 5335 // The above might return null in cases of uninstalled apps or install-state 5336 // skew across users/profiles. 5337 if (pi != null) { 5338 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5339 if (numMatch == permissions.length) { 5340 pi.requestedPermissions = permissions; 5341 } else { 5342 pi.requestedPermissions = new String[numMatch]; 5343 numMatch = 0; 5344 for (int i=0; i<permissions.length; i++) { 5345 if (tmp[i]) { 5346 pi.requestedPermissions[numMatch] = permissions[i]; 5347 numMatch++; 5348 } 5349 } 5350 } 5351 } 5352 list.add(pi); 5353 } 5354 } 5355 5356 @Override 5357 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5358 String[] permissions, int flags, int userId) { 5359 if (!sUserManager.exists(userId)) return null; 5360 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5361 5362 // writer 5363 synchronized (mPackages) { 5364 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5365 boolean[] tmpBools = new boolean[permissions.length]; 5366 if (listUninstalled) { 5367 for (PackageSetting ps : mSettings.mPackages.values()) { 5368 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5369 } 5370 } else { 5371 for (PackageParser.Package pkg : mPackages.values()) { 5372 PackageSetting ps = (PackageSetting)pkg.mExtras; 5373 if (ps != null) { 5374 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5375 userId); 5376 } 5377 } 5378 } 5379 5380 return new ParceledListSlice<PackageInfo>(list); 5381 } 5382 } 5383 5384 @Override 5385 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5386 if (!sUserManager.exists(userId)) return null; 5387 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5388 5389 // writer 5390 synchronized (mPackages) { 5391 ArrayList<ApplicationInfo> list; 5392 if (listUninstalled) { 5393 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5394 for (PackageSetting ps : mSettings.mPackages.values()) { 5395 ApplicationInfo ai; 5396 if (ps.pkg != null) { 5397 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5398 ps.readUserState(userId), userId); 5399 } else { 5400 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5401 } 5402 if (ai != null) { 5403 list.add(ai); 5404 } 5405 } 5406 } else { 5407 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5408 for (PackageParser.Package p : mPackages.values()) { 5409 if (p.mExtras != null) { 5410 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5411 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5412 if (ai != null) { 5413 list.add(ai); 5414 } 5415 } 5416 } 5417 } 5418 5419 return new ParceledListSlice<ApplicationInfo>(list); 5420 } 5421 } 5422 5423 public List<ApplicationInfo> getPersistentApplications(int flags) { 5424 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5425 5426 // reader 5427 synchronized (mPackages) { 5428 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5429 final int userId = UserHandle.getCallingUserId(); 5430 while (i.hasNext()) { 5431 final PackageParser.Package p = i.next(); 5432 if (p.applicationInfo != null 5433 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5434 && (!mSafeMode || isSystemApp(p))) { 5435 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5436 if (ps != null) { 5437 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5438 ps.readUserState(userId), userId); 5439 if (ai != null) { 5440 finalList.add(ai); 5441 } 5442 } 5443 } 5444 } 5445 } 5446 5447 return finalList; 5448 } 5449 5450 @Override 5451 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5452 if (!sUserManager.exists(userId)) return null; 5453 // reader 5454 synchronized (mPackages) { 5455 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5456 PackageSetting ps = provider != null 5457 ? mSettings.mPackages.get(provider.owner.packageName) 5458 : null; 5459 return ps != null 5460 && mSettings.isEnabledLPr(provider.info, flags, userId) 5461 && (!mSafeMode || (provider.info.applicationInfo.flags 5462 &ApplicationInfo.FLAG_SYSTEM) != 0) 5463 ? PackageParser.generateProviderInfo(provider, flags, 5464 ps.readUserState(userId), userId) 5465 : null; 5466 } 5467 } 5468 5469 /** 5470 * @deprecated 5471 */ 5472 @Deprecated 5473 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5474 // reader 5475 synchronized (mPackages) { 5476 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5477 .entrySet().iterator(); 5478 final int userId = UserHandle.getCallingUserId(); 5479 while (i.hasNext()) { 5480 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5481 PackageParser.Provider p = entry.getValue(); 5482 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5483 5484 if (ps != null && p.syncable 5485 && (!mSafeMode || (p.info.applicationInfo.flags 5486 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5487 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5488 ps.readUserState(userId), userId); 5489 if (info != null) { 5490 outNames.add(entry.getKey()); 5491 outInfo.add(info); 5492 } 5493 } 5494 } 5495 } 5496 } 5497 5498 @Override 5499 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5500 int uid, int flags) { 5501 ArrayList<ProviderInfo> finalList = null; 5502 // reader 5503 synchronized (mPackages) { 5504 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5505 final int userId = processName != null ? 5506 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5507 while (i.hasNext()) { 5508 final PackageParser.Provider p = i.next(); 5509 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5510 if (ps != null && p.info.authority != null 5511 && (processName == null 5512 || (p.info.processName.equals(processName) 5513 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5514 && mSettings.isEnabledLPr(p.info, flags, userId) 5515 && (!mSafeMode 5516 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5517 if (finalList == null) { 5518 finalList = new ArrayList<ProviderInfo>(3); 5519 } 5520 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5521 ps.readUserState(userId), userId); 5522 if (info != null) { 5523 finalList.add(info); 5524 } 5525 } 5526 } 5527 } 5528 5529 if (finalList != null) { 5530 Collections.sort(finalList, mProviderInitOrderSorter); 5531 return new ParceledListSlice<ProviderInfo>(finalList); 5532 } 5533 5534 return null; 5535 } 5536 5537 @Override 5538 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5539 int flags) { 5540 // reader 5541 synchronized (mPackages) { 5542 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5543 return PackageParser.generateInstrumentationInfo(i, flags); 5544 } 5545 } 5546 5547 @Override 5548 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5549 int flags) { 5550 ArrayList<InstrumentationInfo> finalList = 5551 new ArrayList<InstrumentationInfo>(); 5552 5553 // reader 5554 synchronized (mPackages) { 5555 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5556 while (i.hasNext()) { 5557 final PackageParser.Instrumentation p = i.next(); 5558 if (targetPackage == null 5559 || targetPackage.equals(p.info.targetPackage)) { 5560 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5561 flags); 5562 if (ii != null) { 5563 finalList.add(ii); 5564 } 5565 } 5566 } 5567 } 5568 5569 return finalList; 5570 } 5571 5572 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5573 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5574 if (overlays == null) { 5575 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5576 return; 5577 } 5578 for (PackageParser.Package opkg : overlays.values()) { 5579 // Not much to do if idmap fails: we already logged the error 5580 // and we certainly don't want to abort installation of pkg simply 5581 // because an overlay didn't fit properly. For these reasons, 5582 // ignore the return value of createIdmapForPackagePairLI. 5583 createIdmapForPackagePairLI(pkg, opkg); 5584 } 5585 } 5586 5587 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5588 PackageParser.Package opkg) { 5589 if (!opkg.mTrustedOverlay) { 5590 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5591 opkg.baseCodePath + ": overlay not trusted"); 5592 return false; 5593 } 5594 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5595 if (overlaySet == null) { 5596 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5597 opkg.baseCodePath + " but target package has no known overlays"); 5598 return false; 5599 } 5600 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5601 // TODO: generate idmap for split APKs 5602 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5603 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5604 + opkg.baseCodePath); 5605 return false; 5606 } 5607 PackageParser.Package[] overlayArray = 5608 overlaySet.values().toArray(new PackageParser.Package[0]); 5609 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5610 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5611 return p1.mOverlayPriority - p2.mOverlayPriority; 5612 } 5613 }; 5614 Arrays.sort(overlayArray, cmp); 5615 5616 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5617 int i = 0; 5618 for (PackageParser.Package p : overlayArray) { 5619 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5620 } 5621 return true; 5622 } 5623 5624 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5625 final File[] files = dir.listFiles(); 5626 if (ArrayUtils.isEmpty(files)) { 5627 Log.d(TAG, "No files in app dir " + dir); 5628 return; 5629 } 5630 5631 if (DEBUG_PACKAGE_SCANNING) { 5632 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5633 + " flags=0x" + Integer.toHexString(parseFlags)); 5634 } 5635 5636 for (File file : files) { 5637 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5638 && !PackageInstallerService.isStageName(file.getName()); 5639 if (!isPackage) { 5640 // Ignore entries which are not packages 5641 continue; 5642 } 5643 try { 5644 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5645 scanFlags, currentTime, null); 5646 } catch (PackageManagerException e) { 5647 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5648 5649 // Delete invalid userdata apps 5650 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5651 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5652 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5653 if (file.isDirectory()) { 5654 mInstaller.rmPackageDir(file.getAbsolutePath()); 5655 } else { 5656 file.delete(); 5657 } 5658 } 5659 } 5660 } 5661 } 5662 5663 private static File getSettingsProblemFile() { 5664 File dataDir = Environment.getDataDirectory(); 5665 File systemDir = new File(dataDir, "system"); 5666 File fname = new File(systemDir, "uiderrors.txt"); 5667 return fname; 5668 } 5669 5670 static void reportSettingsProblem(int priority, String msg) { 5671 logCriticalInfo(priority, msg); 5672 } 5673 5674 static void logCriticalInfo(int priority, String msg) { 5675 Slog.println(priority, TAG, msg); 5676 EventLogTags.writePmCriticalInfo(msg); 5677 try { 5678 File fname = getSettingsProblemFile(); 5679 FileOutputStream out = new FileOutputStream(fname, true); 5680 PrintWriter pw = new FastPrintWriter(out); 5681 SimpleDateFormat formatter = new SimpleDateFormat(); 5682 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5683 pw.println(dateString + ": " + msg); 5684 pw.close(); 5685 FileUtils.setPermissions( 5686 fname.toString(), 5687 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5688 -1, -1); 5689 } catch (java.io.IOException e) { 5690 } 5691 } 5692 5693 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5694 PackageParser.Package pkg, File srcFile, int parseFlags) 5695 throws PackageManagerException { 5696 if (ps != null 5697 && ps.codePath.equals(srcFile) 5698 && ps.timeStamp == srcFile.lastModified() 5699 && !isCompatSignatureUpdateNeeded(pkg) 5700 && !isRecoverSignatureUpdateNeeded(pkg)) { 5701 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5702 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5703 ArraySet<PublicKey> signingKs; 5704 synchronized (mPackages) { 5705 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5706 } 5707 if (ps.signatures.mSignatures != null 5708 && ps.signatures.mSignatures.length != 0 5709 && signingKs != null) { 5710 // Optimization: reuse the existing cached certificates 5711 // if the package appears to be unchanged. 5712 pkg.mSignatures = ps.signatures.mSignatures; 5713 pkg.mSigningKeys = signingKs; 5714 return; 5715 } 5716 5717 Slog.w(TAG, "PackageSetting for " + ps.name 5718 + " is missing signatures. Collecting certs again to recover them."); 5719 } else { 5720 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5721 } 5722 5723 try { 5724 pp.collectCertificates(pkg, parseFlags); 5725 pp.collectManifestDigest(pkg); 5726 } catch (PackageParserException e) { 5727 throw PackageManagerException.from(e); 5728 } 5729 } 5730 5731 /* 5732 * Scan a package and return the newly parsed package. 5733 * Returns null in case of errors and the error code is stored in mLastScanError 5734 */ 5735 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5736 long currentTime, UserHandle user) throws PackageManagerException { 5737 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5738 parseFlags |= mDefParseFlags; 5739 PackageParser pp = new PackageParser(); 5740 pp.setSeparateProcesses(mSeparateProcesses); 5741 pp.setOnlyCoreApps(mOnlyCore); 5742 pp.setDisplayMetrics(mMetrics); 5743 5744 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5745 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5746 } 5747 5748 final PackageParser.Package pkg; 5749 try { 5750 pkg = pp.parsePackage(scanFile, parseFlags); 5751 } catch (PackageParserException e) { 5752 throw PackageManagerException.from(e); 5753 } 5754 5755 PackageSetting ps = null; 5756 PackageSetting updatedPkg; 5757 // reader 5758 synchronized (mPackages) { 5759 // Look to see if we already know about this package. 5760 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5761 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5762 // This package has been renamed to its original name. Let's 5763 // use that. 5764 ps = mSettings.peekPackageLPr(oldName); 5765 } 5766 // If there was no original package, see one for the real package name. 5767 if (ps == null) { 5768 ps = mSettings.peekPackageLPr(pkg.packageName); 5769 } 5770 // Check to see if this package could be hiding/updating a system 5771 // package. Must look for it either under the original or real 5772 // package name depending on our state. 5773 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5774 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5775 } 5776 boolean updatedPkgBetter = false; 5777 // First check if this is a system package that may involve an update 5778 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5779 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5780 // it needs to drop FLAG_PRIVILEGED. 5781 if (locationIsPrivileged(scanFile)) { 5782 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5783 } else { 5784 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5785 } 5786 5787 if (ps != null && !ps.codePath.equals(scanFile)) { 5788 // The path has changed from what was last scanned... check the 5789 // version of the new path against what we have stored to determine 5790 // what to do. 5791 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5792 if (pkg.mVersionCode <= ps.versionCode) { 5793 // The system package has been updated and the code path does not match 5794 // Ignore entry. Skip it. 5795 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5796 + " ignored: updated version " + ps.versionCode 5797 + " better than this " + pkg.mVersionCode); 5798 if (!updatedPkg.codePath.equals(scanFile)) { 5799 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5800 + ps.name + " changing from " + updatedPkg.codePathString 5801 + " to " + scanFile); 5802 updatedPkg.codePath = scanFile; 5803 updatedPkg.codePathString = scanFile.toString(); 5804 updatedPkg.resourcePath = scanFile; 5805 updatedPkg.resourcePathString = scanFile.toString(); 5806 } 5807 updatedPkg.pkg = pkg; 5808 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5809 "Package " + ps.name + " at " + scanFile 5810 + " ignored: updated version " + ps.versionCode 5811 + " better than this " + pkg.mVersionCode); 5812 } else { 5813 // The current app on the system partition is better than 5814 // what we have updated to on the data partition; switch 5815 // back to the system partition version. 5816 // At this point, its safely assumed that package installation for 5817 // apps in system partition will go through. If not there won't be a working 5818 // version of the app 5819 // writer 5820 synchronized (mPackages) { 5821 // Just remove the loaded entries from package lists. 5822 mPackages.remove(ps.name); 5823 } 5824 5825 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5826 + " reverting from " + ps.codePathString 5827 + ": new version " + pkg.mVersionCode 5828 + " better than installed " + ps.versionCode); 5829 5830 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5831 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5832 synchronized (mInstallLock) { 5833 args.cleanUpResourcesLI(); 5834 } 5835 synchronized (mPackages) { 5836 mSettings.enableSystemPackageLPw(ps.name); 5837 } 5838 updatedPkgBetter = true; 5839 } 5840 } 5841 } 5842 5843 if (updatedPkg != null) { 5844 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5845 // initially 5846 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5847 5848 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5849 // flag set initially 5850 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5851 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5852 } 5853 } 5854 5855 // Verify certificates against what was last scanned 5856 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5857 5858 /* 5859 * A new system app appeared, but we already had a non-system one of the 5860 * same name installed earlier. 5861 */ 5862 boolean shouldHideSystemApp = false; 5863 if (updatedPkg == null && ps != null 5864 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5865 /* 5866 * Check to make sure the signatures match first. If they don't, 5867 * wipe the installed application and its data. 5868 */ 5869 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5870 != PackageManager.SIGNATURE_MATCH) { 5871 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5872 + " signatures don't match existing userdata copy; removing"); 5873 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5874 ps = null; 5875 } else { 5876 /* 5877 * If the newly-added system app is an older version than the 5878 * already installed version, hide it. It will be scanned later 5879 * and re-added like an update. 5880 */ 5881 if (pkg.mVersionCode <= ps.versionCode) { 5882 shouldHideSystemApp = true; 5883 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5884 + " but new version " + pkg.mVersionCode + " better than installed " 5885 + ps.versionCode + "; hiding system"); 5886 } else { 5887 /* 5888 * The newly found system app is a newer version that the 5889 * one previously installed. Simply remove the 5890 * already-installed application and replace it with our own 5891 * while keeping the application data. 5892 */ 5893 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5894 + " reverting from " + ps.codePathString + ": new version " 5895 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5896 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5897 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5898 synchronized (mInstallLock) { 5899 args.cleanUpResourcesLI(); 5900 } 5901 } 5902 } 5903 } 5904 5905 // The apk is forward locked (not public) if its code and resources 5906 // are kept in different files. (except for app in either system or 5907 // vendor path). 5908 // TODO grab this value from PackageSettings 5909 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5910 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5911 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5912 } 5913 } 5914 5915 // TODO: extend to support forward-locked splits 5916 String resourcePath = null; 5917 String baseResourcePath = null; 5918 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5919 if (ps != null && ps.resourcePathString != null) { 5920 resourcePath = ps.resourcePathString; 5921 baseResourcePath = ps.resourcePathString; 5922 } else { 5923 // Should not happen at all. Just log an error. 5924 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5925 } 5926 } else { 5927 resourcePath = pkg.codePath; 5928 baseResourcePath = pkg.baseCodePath; 5929 } 5930 5931 // Set application objects path explicitly. 5932 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5933 pkg.applicationInfo.setCodePath(pkg.codePath); 5934 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5935 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5936 pkg.applicationInfo.setResourcePath(resourcePath); 5937 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5938 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5939 5940 // Note that we invoke the following method only if we are about to unpack an application 5941 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5942 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5943 5944 /* 5945 * If the system app should be overridden by a previously installed 5946 * data, hide the system app now and let the /data/app scan pick it up 5947 * again. 5948 */ 5949 if (shouldHideSystemApp) { 5950 synchronized (mPackages) { 5951 mSettings.disableSystemPackageLPw(pkg.packageName); 5952 } 5953 } 5954 5955 return scannedPkg; 5956 } 5957 5958 private static String fixProcessName(String defProcessName, 5959 String processName, int uid) { 5960 if (processName == null) { 5961 return defProcessName; 5962 } 5963 return processName; 5964 } 5965 5966 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5967 throws PackageManagerException { 5968 if (pkgSetting.signatures.mSignatures != null) { 5969 // Already existing package. Make sure signatures match 5970 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5971 == PackageManager.SIGNATURE_MATCH; 5972 if (!match) { 5973 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5974 == PackageManager.SIGNATURE_MATCH; 5975 } 5976 if (!match) { 5977 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5978 == PackageManager.SIGNATURE_MATCH; 5979 } 5980 if (!match) { 5981 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5982 + pkg.packageName + " signatures do not match the " 5983 + "previously installed version; ignoring!"); 5984 } 5985 } 5986 5987 // Check for shared user signatures 5988 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5989 // Already existing package. Make sure signatures match 5990 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5991 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5992 if (!match) { 5993 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5994 == PackageManager.SIGNATURE_MATCH; 5995 } 5996 if (!match) { 5997 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5998 == PackageManager.SIGNATURE_MATCH; 5999 } 6000 if (!match) { 6001 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6002 "Package " + pkg.packageName 6003 + " has no signatures that match those in shared user " 6004 + pkgSetting.sharedUser.name + "; ignoring!"); 6005 } 6006 } 6007 } 6008 6009 /** 6010 * Enforces that only the system UID or root's UID can call a method exposed 6011 * via Binder. 6012 * 6013 * @param message used as message if SecurityException is thrown 6014 * @throws SecurityException if the caller is not system or root 6015 */ 6016 private static final void enforceSystemOrRoot(String message) { 6017 final int uid = Binder.getCallingUid(); 6018 if (uid != Process.SYSTEM_UID && uid != 0) { 6019 throw new SecurityException(message); 6020 } 6021 } 6022 6023 @Override 6024 public void performBootDexOpt() { 6025 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6026 6027 // Before everything else, see whether we need to fstrim. 6028 try { 6029 IMountService ms = PackageHelper.getMountService(); 6030 if (ms != null) { 6031 final boolean isUpgrade = isUpgrade(); 6032 boolean doTrim = isUpgrade; 6033 if (doTrim) { 6034 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6035 } else { 6036 final long interval = android.provider.Settings.Global.getLong( 6037 mContext.getContentResolver(), 6038 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6039 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6040 if (interval > 0) { 6041 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6042 if (timeSinceLast > interval) { 6043 doTrim = true; 6044 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6045 + "; running immediately"); 6046 } 6047 } 6048 } 6049 if (doTrim) { 6050 if (!isFirstBoot()) { 6051 try { 6052 ActivityManagerNative.getDefault().showBootMessage( 6053 mContext.getResources().getString( 6054 R.string.android_upgrading_fstrim), true); 6055 } catch (RemoteException e) { 6056 } 6057 } 6058 ms.runMaintenance(); 6059 } 6060 } else { 6061 Slog.e(TAG, "Mount service unavailable!"); 6062 } 6063 } catch (RemoteException e) { 6064 // Can't happen; MountService is local 6065 } 6066 6067 final ArraySet<PackageParser.Package> pkgs; 6068 synchronized (mPackages) { 6069 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6070 } 6071 6072 if (pkgs != null) { 6073 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6074 // in case the device runs out of space. 6075 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6076 // Give priority to core apps. 6077 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6078 PackageParser.Package pkg = it.next(); 6079 if (pkg.coreApp) { 6080 if (DEBUG_DEXOPT) { 6081 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6082 } 6083 sortedPkgs.add(pkg); 6084 it.remove(); 6085 } 6086 } 6087 // Give priority to system apps that listen for pre boot complete. 6088 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6089 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6090 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6091 PackageParser.Package pkg = it.next(); 6092 if (pkgNames.contains(pkg.packageName)) { 6093 if (DEBUG_DEXOPT) { 6094 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6095 } 6096 sortedPkgs.add(pkg); 6097 it.remove(); 6098 } 6099 } 6100 // Filter out packages that aren't recently used. 6101 filterRecentlyUsedApps(pkgs); 6102 // Add all remaining apps. 6103 for (PackageParser.Package pkg : pkgs) { 6104 if (DEBUG_DEXOPT) { 6105 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6106 } 6107 sortedPkgs.add(pkg); 6108 } 6109 6110 // If we want to be lazy, filter everything that wasn't recently used. 6111 if (mLazyDexOpt) { 6112 filterRecentlyUsedApps(sortedPkgs); 6113 } 6114 6115 int i = 0; 6116 int total = sortedPkgs.size(); 6117 File dataDir = Environment.getDataDirectory(); 6118 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6119 if (lowThreshold == 0) { 6120 throw new IllegalStateException("Invalid low memory threshold"); 6121 } 6122 for (PackageParser.Package pkg : sortedPkgs) { 6123 long usableSpace = dataDir.getUsableSpace(); 6124 if (usableSpace < lowThreshold) { 6125 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6126 break; 6127 } 6128 performBootDexOpt(pkg, ++i, total); 6129 } 6130 } 6131 } 6132 6133 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6134 // Filter out packages that aren't recently used. 6135 // 6136 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6137 // should do a full dexopt. 6138 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6139 int total = pkgs.size(); 6140 int skipped = 0; 6141 long now = System.currentTimeMillis(); 6142 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6143 PackageParser.Package pkg = i.next(); 6144 long then = pkg.mLastPackageUsageTimeInMills; 6145 if (then + mDexOptLRUThresholdInMills < now) { 6146 if (DEBUG_DEXOPT) { 6147 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6148 ((then == 0) ? "never" : new Date(then))); 6149 } 6150 i.remove(); 6151 skipped++; 6152 } 6153 } 6154 if (DEBUG_DEXOPT) { 6155 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6156 } 6157 } 6158 } 6159 6160 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6161 List<ResolveInfo> ris = null; 6162 try { 6163 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6164 intent, null, 0, UserHandle.USER_OWNER); 6165 } catch (RemoteException e) { 6166 } 6167 ArraySet<String> pkgNames = new ArraySet<String>(); 6168 if (ris != null) { 6169 for (ResolveInfo ri : ris) { 6170 pkgNames.add(ri.activityInfo.packageName); 6171 } 6172 } 6173 return pkgNames; 6174 } 6175 6176 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6177 if (DEBUG_DEXOPT) { 6178 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6179 } 6180 if (!isFirstBoot()) { 6181 try { 6182 ActivityManagerNative.getDefault().showBootMessage( 6183 mContext.getResources().getString(R.string.android_upgrading_apk, 6184 curr, total), true); 6185 } catch (RemoteException e) { 6186 } 6187 } 6188 PackageParser.Package p = pkg; 6189 synchronized (mInstallLock) { 6190 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6191 false /* force dex */, false /* defer */, true /* include dependencies */, 6192 false /* boot complete */); 6193 } 6194 } 6195 6196 @Override 6197 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6198 return performDexOpt(packageName, instructionSet, false); 6199 } 6200 6201 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6202 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6203 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6204 if (!dexopt && !updateUsage) { 6205 // We aren't going to dexopt or update usage, so bail early. 6206 return false; 6207 } 6208 PackageParser.Package p; 6209 final String targetInstructionSet; 6210 synchronized (mPackages) { 6211 p = mPackages.get(packageName); 6212 if (p == null) { 6213 return false; 6214 } 6215 if (updateUsage) { 6216 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6217 } 6218 mPackageUsage.write(false); 6219 if (!dexopt) { 6220 // We aren't going to dexopt, so bail early. 6221 return false; 6222 } 6223 6224 targetInstructionSet = instructionSet != null ? instructionSet : 6225 getPrimaryInstructionSet(p.applicationInfo); 6226 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6227 return false; 6228 } 6229 } 6230 long callingId = Binder.clearCallingIdentity(); 6231 try { 6232 synchronized (mInstallLock) { 6233 final String[] instructionSets = new String[] { targetInstructionSet }; 6234 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6235 false /* forceDex */, false /* defer */, true /* inclDependencies */, 6236 true /* boot complete */); 6237 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6238 } 6239 } finally { 6240 Binder.restoreCallingIdentity(callingId); 6241 } 6242 } 6243 6244 public ArraySet<String> getPackagesThatNeedDexOpt() { 6245 ArraySet<String> pkgs = null; 6246 synchronized (mPackages) { 6247 for (PackageParser.Package p : mPackages.values()) { 6248 if (DEBUG_DEXOPT) { 6249 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6250 } 6251 if (!p.mDexOptPerformed.isEmpty()) { 6252 continue; 6253 } 6254 if (pkgs == null) { 6255 pkgs = new ArraySet<String>(); 6256 } 6257 pkgs.add(p.packageName); 6258 } 6259 } 6260 return pkgs; 6261 } 6262 6263 public void shutdown() { 6264 mPackageUsage.write(true); 6265 } 6266 6267 @Override 6268 public void forceDexOpt(String packageName) { 6269 enforceSystemOrRoot("forceDexOpt"); 6270 6271 PackageParser.Package pkg; 6272 synchronized (mPackages) { 6273 pkg = mPackages.get(packageName); 6274 if (pkg == null) { 6275 throw new IllegalArgumentException("Missing package: " + packageName); 6276 } 6277 } 6278 6279 synchronized (mInstallLock) { 6280 final String[] instructionSets = new String[] { 6281 getPrimaryInstructionSet(pkg.applicationInfo) }; 6282 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6283 true /*forceDex*/, false /* defer */, true /* inclDependencies */, 6284 true /* boot complete */); 6285 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6286 throw new IllegalStateException("Failed to dexopt: " + res); 6287 } 6288 } 6289 } 6290 6291 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6292 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6293 Slog.w(TAG, "Unable to update from " + oldPkg.name 6294 + " to " + newPkg.packageName 6295 + ": old package not in system partition"); 6296 return false; 6297 } else if (mPackages.get(oldPkg.name) != null) { 6298 Slog.w(TAG, "Unable to update from " + oldPkg.name 6299 + " to " + newPkg.packageName 6300 + ": old package still exists"); 6301 return false; 6302 } 6303 return true; 6304 } 6305 6306 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6307 int[] users = sUserManager.getUserIds(); 6308 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6309 if (res < 0) { 6310 return res; 6311 } 6312 for (int user : users) { 6313 if (user != 0) { 6314 res = mInstaller.createUserData(volumeUuid, packageName, 6315 UserHandle.getUid(user, uid), user, seinfo); 6316 if (res < 0) { 6317 return res; 6318 } 6319 } 6320 } 6321 return res; 6322 } 6323 6324 private int removeDataDirsLI(String volumeUuid, String packageName) { 6325 int[] users = sUserManager.getUserIds(); 6326 int res = 0; 6327 for (int user : users) { 6328 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6329 if (resInner < 0) { 6330 res = resInner; 6331 } 6332 } 6333 6334 return res; 6335 } 6336 6337 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6338 int[] users = sUserManager.getUserIds(); 6339 int res = 0; 6340 for (int user : users) { 6341 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6342 if (resInner < 0) { 6343 res = resInner; 6344 } 6345 } 6346 return res; 6347 } 6348 6349 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6350 PackageParser.Package changingLib) { 6351 if (file.path != null) { 6352 usesLibraryFiles.add(file.path); 6353 return; 6354 } 6355 PackageParser.Package p = mPackages.get(file.apk); 6356 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6357 // If we are doing this while in the middle of updating a library apk, 6358 // then we need to make sure to use that new apk for determining the 6359 // dependencies here. (We haven't yet finished committing the new apk 6360 // to the package manager state.) 6361 if (p == null || p.packageName.equals(changingLib.packageName)) { 6362 p = changingLib; 6363 } 6364 } 6365 if (p != null) { 6366 usesLibraryFiles.addAll(p.getAllCodePaths()); 6367 } 6368 } 6369 6370 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6371 PackageParser.Package changingLib) throws PackageManagerException { 6372 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6373 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6374 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6375 for (int i=0; i<N; i++) { 6376 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6377 if (file == null) { 6378 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6379 "Package " + pkg.packageName + " requires unavailable shared library " 6380 + pkg.usesLibraries.get(i) + "; failing!"); 6381 } 6382 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6383 } 6384 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6385 for (int i=0; i<N; i++) { 6386 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6387 if (file == null) { 6388 Slog.w(TAG, "Package " + pkg.packageName 6389 + " desires unavailable shared library " 6390 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6391 } else { 6392 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6393 } 6394 } 6395 N = usesLibraryFiles.size(); 6396 if (N > 0) { 6397 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6398 } else { 6399 pkg.usesLibraryFiles = null; 6400 } 6401 } 6402 } 6403 6404 private static boolean hasString(List<String> list, List<String> which) { 6405 if (list == null) { 6406 return false; 6407 } 6408 for (int i=list.size()-1; i>=0; i--) { 6409 for (int j=which.size()-1; j>=0; j--) { 6410 if (which.get(j).equals(list.get(i))) { 6411 return true; 6412 } 6413 } 6414 } 6415 return false; 6416 } 6417 6418 private void updateAllSharedLibrariesLPw() { 6419 for (PackageParser.Package pkg : mPackages.values()) { 6420 try { 6421 updateSharedLibrariesLPw(pkg, null); 6422 } catch (PackageManagerException e) { 6423 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6424 } 6425 } 6426 } 6427 6428 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6429 PackageParser.Package changingPkg) { 6430 ArrayList<PackageParser.Package> res = null; 6431 for (PackageParser.Package pkg : mPackages.values()) { 6432 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6433 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6434 if (res == null) { 6435 res = new ArrayList<PackageParser.Package>(); 6436 } 6437 res.add(pkg); 6438 try { 6439 updateSharedLibrariesLPw(pkg, changingPkg); 6440 } catch (PackageManagerException e) { 6441 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6442 } 6443 } 6444 } 6445 return res; 6446 } 6447 6448 /** 6449 * Derive the value of the {@code cpuAbiOverride} based on the provided 6450 * value and an optional stored value from the package settings. 6451 */ 6452 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6453 String cpuAbiOverride = null; 6454 6455 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6456 cpuAbiOverride = null; 6457 } else if (abiOverride != null) { 6458 cpuAbiOverride = abiOverride; 6459 } else if (settings != null) { 6460 cpuAbiOverride = settings.cpuAbiOverrideString; 6461 } 6462 6463 return cpuAbiOverride; 6464 } 6465 6466 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6467 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6468 boolean success = false; 6469 try { 6470 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6471 currentTime, user); 6472 success = true; 6473 return res; 6474 } finally { 6475 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6476 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6477 } 6478 } 6479 } 6480 6481 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6482 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6483 final File scanFile = new File(pkg.codePath); 6484 if (pkg.applicationInfo.getCodePath() == null || 6485 pkg.applicationInfo.getResourcePath() == null) { 6486 // Bail out. The resource and code paths haven't been set. 6487 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6488 "Code and resource paths haven't been set correctly"); 6489 } 6490 6491 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6492 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6493 } else { 6494 // Only allow system apps to be flagged as core apps. 6495 pkg.coreApp = false; 6496 } 6497 6498 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6499 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6500 } 6501 6502 if (mCustomResolverComponentName != null && 6503 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6504 setUpCustomResolverActivity(pkg); 6505 } 6506 6507 if (pkg.packageName.equals("android")) { 6508 synchronized (mPackages) { 6509 if (mAndroidApplication != null) { 6510 Slog.w(TAG, "*************************************************"); 6511 Slog.w(TAG, "Core android package being redefined. Skipping."); 6512 Slog.w(TAG, " file=" + scanFile); 6513 Slog.w(TAG, "*************************************************"); 6514 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6515 "Core android package being redefined. Skipping."); 6516 } 6517 6518 // Set up information for our fall-back user intent resolution activity. 6519 mPlatformPackage = pkg; 6520 pkg.mVersionCode = mSdkVersion; 6521 mAndroidApplication = pkg.applicationInfo; 6522 6523 if (!mResolverReplaced) { 6524 mResolveActivity.applicationInfo = mAndroidApplication; 6525 mResolveActivity.name = ResolverActivity.class.getName(); 6526 mResolveActivity.packageName = mAndroidApplication.packageName; 6527 mResolveActivity.processName = "system:ui"; 6528 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6529 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6530 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6531 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6532 mResolveActivity.exported = true; 6533 mResolveActivity.enabled = true; 6534 mResolveInfo.activityInfo = mResolveActivity; 6535 mResolveInfo.priority = 0; 6536 mResolveInfo.preferredOrder = 0; 6537 mResolveInfo.match = 0; 6538 mResolveComponentName = new ComponentName( 6539 mAndroidApplication.packageName, mResolveActivity.name); 6540 } 6541 } 6542 } 6543 6544 if (DEBUG_PACKAGE_SCANNING) { 6545 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6546 Log.d(TAG, "Scanning package " + pkg.packageName); 6547 } 6548 6549 if (mPackages.containsKey(pkg.packageName) 6550 || mSharedLibraries.containsKey(pkg.packageName)) { 6551 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6552 "Application package " + pkg.packageName 6553 + " already installed. Skipping duplicate."); 6554 } 6555 6556 // If we're only installing presumed-existing packages, require that the 6557 // scanned APK is both already known and at the path previously established 6558 // for it. Previously unknown packages we pick up normally, but if we have an 6559 // a priori expectation about this package's install presence, enforce it. 6560 // With a singular exception for new system packages. When an OTA contains 6561 // a new system package, we allow the codepath to change from a system location 6562 // to the user-installed location. If we don't allow this change, any newer, 6563 // user-installed version of the application will be ignored. 6564 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6565 if (mExpectingBetter.containsKey(pkg.packageName)) { 6566 logCriticalInfo(Log.WARN, 6567 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6568 } else { 6569 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6570 if (known != null) { 6571 if (DEBUG_PACKAGE_SCANNING) { 6572 Log.d(TAG, "Examining " + pkg.codePath 6573 + " and requiring known paths " + known.codePathString 6574 + " & " + known.resourcePathString); 6575 } 6576 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6577 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6578 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6579 "Application package " + pkg.packageName 6580 + " found at " + pkg.applicationInfo.getCodePath() 6581 + " but expected at " + known.codePathString + "; ignoring."); 6582 } 6583 } 6584 } 6585 } 6586 6587 // Initialize package source and resource directories 6588 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6589 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6590 6591 SharedUserSetting suid = null; 6592 PackageSetting pkgSetting = null; 6593 6594 if (!isSystemApp(pkg)) { 6595 // Only system apps can use these features. 6596 pkg.mOriginalPackages = null; 6597 pkg.mRealPackage = null; 6598 pkg.mAdoptPermissions = null; 6599 } 6600 6601 // writer 6602 synchronized (mPackages) { 6603 if (pkg.mSharedUserId != null) { 6604 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6605 if (suid == null) { 6606 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6607 "Creating application package " + pkg.packageName 6608 + " for shared user failed"); 6609 } 6610 if (DEBUG_PACKAGE_SCANNING) { 6611 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6612 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6613 + "): packages=" + suid.packages); 6614 } 6615 } 6616 6617 // Check if we are renaming from an original package name. 6618 PackageSetting origPackage = null; 6619 String realName = null; 6620 if (pkg.mOriginalPackages != null) { 6621 // This package may need to be renamed to a previously 6622 // installed name. Let's check on that... 6623 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6624 if (pkg.mOriginalPackages.contains(renamed)) { 6625 // This package had originally been installed as the 6626 // original name, and we have already taken care of 6627 // transitioning to the new one. Just update the new 6628 // one to continue using the old name. 6629 realName = pkg.mRealPackage; 6630 if (!pkg.packageName.equals(renamed)) { 6631 // Callers into this function may have already taken 6632 // care of renaming the package; only do it here if 6633 // it is not already done. 6634 pkg.setPackageName(renamed); 6635 } 6636 6637 } else { 6638 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6639 if ((origPackage = mSettings.peekPackageLPr( 6640 pkg.mOriginalPackages.get(i))) != null) { 6641 // We do have the package already installed under its 6642 // original name... should we use it? 6643 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6644 // New package is not compatible with original. 6645 origPackage = null; 6646 continue; 6647 } else if (origPackage.sharedUser != null) { 6648 // Make sure uid is compatible between packages. 6649 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6650 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6651 + " to " + pkg.packageName + ": old uid " 6652 + origPackage.sharedUser.name 6653 + " differs from " + pkg.mSharedUserId); 6654 origPackage = null; 6655 continue; 6656 } 6657 } else { 6658 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6659 + pkg.packageName + " to old name " + origPackage.name); 6660 } 6661 break; 6662 } 6663 } 6664 } 6665 } 6666 6667 if (mTransferedPackages.contains(pkg.packageName)) { 6668 Slog.w(TAG, "Package " + pkg.packageName 6669 + " was transferred to another, but its .apk remains"); 6670 } 6671 6672 // Just create the setting, don't add it yet. For already existing packages 6673 // the PkgSetting exists already and doesn't have to be created. 6674 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6675 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6676 pkg.applicationInfo.primaryCpuAbi, 6677 pkg.applicationInfo.secondaryCpuAbi, 6678 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6679 user, false); 6680 if (pkgSetting == null) { 6681 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6682 "Creating application package " + pkg.packageName + " failed"); 6683 } 6684 6685 if (pkgSetting.origPackage != null) { 6686 // If we are first transitioning from an original package, 6687 // fix up the new package's name now. We need to do this after 6688 // looking up the package under its new name, so getPackageLP 6689 // can take care of fiddling things correctly. 6690 pkg.setPackageName(origPackage.name); 6691 6692 // File a report about this. 6693 String msg = "New package " + pkgSetting.realName 6694 + " renamed to replace old package " + pkgSetting.name; 6695 reportSettingsProblem(Log.WARN, msg); 6696 6697 // Make a note of it. 6698 mTransferedPackages.add(origPackage.name); 6699 6700 // No longer need to retain this. 6701 pkgSetting.origPackage = null; 6702 } 6703 6704 if (realName != null) { 6705 // Make a note of it. 6706 mTransferedPackages.add(pkg.packageName); 6707 } 6708 6709 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6710 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6711 } 6712 6713 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6714 // Check all shared libraries and map to their actual file path. 6715 // We only do this here for apps not on a system dir, because those 6716 // are the only ones that can fail an install due to this. We 6717 // will take care of the system apps by updating all of their 6718 // library paths after the scan is done. 6719 updateSharedLibrariesLPw(pkg, null); 6720 } 6721 6722 if (mFoundPolicyFile) { 6723 SELinuxMMAC.assignSeinfoValue(pkg); 6724 } 6725 6726 pkg.applicationInfo.uid = pkgSetting.appId; 6727 pkg.mExtras = pkgSetting; 6728 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6729 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6730 // We just determined the app is signed correctly, so bring 6731 // over the latest parsed certs. 6732 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6733 } else { 6734 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6735 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6736 "Package " + pkg.packageName + " upgrade keys do not match the " 6737 + "previously installed version"); 6738 } else { 6739 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6740 String msg = "System package " + pkg.packageName 6741 + " signature changed; retaining data."; 6742 reportSettingsProblem(Log.WARN, msg); 6743 } 6744 } 6745 } else { 6746 try { 6747 verifySignaturesLP(pkgSetting, pkg); 6748 // We just determined the app is signed correctly, so bring 6749 // over the latest parsed certs. 6750 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6751 } catch (PackageManagerException e) { 6752 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6753 throw e; 6754 } 6755 // The signature has changed, but this package is in the system 6756 // image... let's recover! 6757 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6758 // However... if this package is part of a shared user, but it 6759 // doesn't match the signature of the shared user, let's fail. 6760 // What this means is that you can't change the signatures 6761 // associated with an overall shared user, which doesn't seem all 6762 // that unreasonable. 6763 if (pkgSetting.sharedUser != null) { 6764 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6765 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6766 throw new PackageManagerException( 6767 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6768 "Signature mismatch for shared user : " 6769 + pkgSetting.sharedUser); 6770 } 6771 } 6772 // File a report about this. 6773 String msg = "System package " + pkg.packageName 6774 + " signature changed; retaining data."; 6775 reportSettingsProblem(Log.WARN, msg); 6776 } 6777 } 6778 // Verify that this new package doesn't have any content providers 6779 // that conflict with existing packages. Only do this if the 6780 // package isn't already installed, since we don't want to break 6781 // things that are installed. 6782 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6783 final int N = pkg.providers.size(); 6784 int i; 6785 for (i=0; i<N; i++) { 6786 PackageParser.Provider p = pkg.providers.get(i); 6787 if (p.info.authority != null) { 6788 String names[] = p.info.authority.split(";"); 6789 for (int j = 0; j < names.length; j++) { 6790 if (mProvidersByAuthority.containsKey(names[j])) { 6791 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6792 final String otherPackageName = 6793 ((other != null && other.getComponentName() != null) ? 6794 other.getComponentName().getPackageName() : "?"); 6795 throw new PackageManagerException( 6796 INSTALL_FAILED_CONFLICTING_PROVIDER, 6797 "Can't install because provider name " + names[j] 6798 + " (in package " + pkg.applicationInfo.packageName 6799 + ") is already used by " + otherPackageName); 6800 } 6801 } 6802 } 6803 } 6804 } 6805 6806 if (pkg.mAdoptPermissions != null) { 6807 // This package wants to adopt ownership of permissions from 6808 // another package. 6809 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6810 final String origName = pkg.mAdoptPermissions.get(i); 6811 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6812 if (orig != null) { 6813 if (verifyPackageUpdateLPr(orig, pkg)) { 6814 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6815 + pkg.packageName); 6816 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6817 } 6818 } 6819 } 6820 } 6821 } 6822 6823 final String pkgName = pkg.packageName; 6824 6825 final long scanFileTime = scanFile.lastModified(); 6826 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6827 pkg.applicationInfo.processName = fixProcessName( 6828 pkg.applicationInfo.packageName, 6829 pkg.applicationInfo.processName, 6830 pkg.applicationInfo.uid); 6831 6832 File dataPath; 6833 if (mPlatformPackage == pkg) { 6834 // The system package is special. 6835 dataPath = new File(Environment.getDataDirectory(), "system"); 6836 6837 pkg.applicationInfo.dataDir = dataPath.getPath(); 6838 6839 } else { 6840 // This is a normal package, need to make its data directory. 6841 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6842 UserHandle.USER_OWNER, pkg.packageName); 6843 6844 boolean uidError = false; 6845 if (dataPath.exists()) { 6846 int currentUid = 0; 6847 try { 6848 StructStat stat = Os.stat(dataPath.getPath()); 6849 currentUid = stat.st_uid; 6850 } catch (ErrnoException e) { 6851 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6852 } 6853 6854 // If we have mismatched owners for the data path, we have a problem. 6855 if (currentUid != pkg.applicationInfo.uid) { 6856 boolean recovered = false; 6857 if (currentUid == 0) { 6858 // The directory somehow became owned by root. Wow. 6859 // This is probably because the system was stopped while 6860 // installd was in the middle of messing with its libs 6861 // directory. Ask installd to fix that. 6862 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6863 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6864 if (ret >= 0) { 6865 recovered = true; 6866 String msg = "Package " + pkg.packageName 6867 + " unexpectedly changed to uid 0; recovered to " + 6868 + pkg.applicationInfo.uid; 6869 reportSettingsProblem(Log.WARN, msg); 6870 } 6871 } 6872 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6873 || (scanFlags&SCAN_BOOTING) != 0)) { 6874 // If this is a system app, we can at least delete its 6875 // current data so the application will still work. 6876 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6877 if (ret >= 0) { 6878 // TODO: Kill the processes first 6879 // Old data gone! 6880 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6881 ? "System package " : "Third party package "; 6882 String msg = prefix + pkg.packageName 6883 + " has changed from uid: " 6884 + currentUid + " to " 6885 + pkg.applicationInfo.uid + "; old data erased"; 6886 reportSettingsProblem(Log.WARN, msg); 6887 recovered = true; 6888 6889 // And now re-install the app. 6890 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6891 pkg.applicationInfo.seinfo); 6892 if (ret == -1) { 6893 // Ack should not happen! 6894 msg = prefix + pkg.packageName 6895 + " could not have data directory re-created after delete."; 6896 reportSettingsProblem(Log.WARN, msg); 6897 throw new PackageManagerException( 6898 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6899 } 6900 } 6901 if (!recovered) { 6902 mHasSystemUidErrors = true; 6903 } 6904 } else if (!recovered) { 6905 // If we allow this install to proceed, we will be broken. 6906 // Abort, abort! 6907 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6908 "scanPackageLI"); 6909 } 6910 if (!recovered) { 6911 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6912 + pkg.applicationInfo.uid + "/fs_" 6913 + currentUid; 6914 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6915 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6916 String msg = "Package " + pkg.packageName 6917 + " has mismatched uid: " 6918 + currentUid + " on disk, " 6919 + pkg.applicationInfo.uid + " in settings"; 6920 // writer 6921 synchronized (mPackages) { 6922 mSettings.mReadMessages.append(msg); 6923 mSettings.mReadMessages.append('\n'); 6924 uidError = true; 6925 if (!pkgSetting.uidError) { 6926 reportSettingsProblem(Log.ERROR, msg); 6927 } 6928 } 6929 } 6930 } 6931 pkg.applicationInfo.dataDir = dataPath.getPath(); 6932 if (mShouldRestoreconData) { 6933 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6934 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6935 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6936 } 6937 } else { 6938 if (DEBUG_PACKAGE_SCANNING) { 6939 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6940 Log.v(TAG, "Want this data dir: " + dataPath); 6941 } 6942 //invoke installer to do the actual installation 6943 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6944 pkg.applicationInfo.seinfo); 6945 if (ret < 0) { 6946 // Error from installer 6947 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6948 "Unable to create data dirs [errorCode=" + ret + "]"); 6949 } 6950 6951 if (dataPath.exists()) { 6952 pkg.applicationInfo.dataDir = dataPath.getPath(); 6953 } else { 6954 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6955 pkg.applicationInfo.dataDir = null; 6956 } 6957 } 6958 6959 pkgSetting.uidError = uidError; 6960 } 6961 6962 final String path = scanFile.getPath(); 6963 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6964 6965 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6966 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6967 6968 // Some system apps still use directory structure for native libraries 6969 // in which case we might end up not detecting abi solely based on apk 6970 // structure. Try to detect abi based on directory structure. 6971 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6972 pkg.applicationInfo.primaryCpuAbi == null) { 6973 setBundledAppAbisAndRoots(pkg, pkgSetting); 6974 setNativeLibraryPaths(pkg); 6975 } 6976 6977 } else { 6978 if ((scanFlags & SCAN_MOVE) != 0) { 6979 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6980 // but we already have this packages package info in the PackageSetting. We just 6981 // use that and derive the native library path based on the new codepath. 6982 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6983 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6984 } 6985 6986 // Set native library paths again. For moves, the path will be updated based on the 6987 // ABIs we've determined above. For non-moves, the path will be updated based on the 6988 // ABIs we determined during compilation, but the path will depend on the final 6989 // package path (after the rename away from the stage path). 6990 setNativeLibraryPaths(pkg); 6991 } 6992 6993 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6994 final int[] userIds = sUserManager.getUserIds(); 6995 synchronized (mInstallLock) { 6996 // Make sure all user data directories are ready to roll; we're okay 6997 // if they already exist 6998 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6999 for (int userId : userIds) { 7000 if (userId != 0) { 7001 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7002 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7003 pkg.applicationInfo.seinfo); 7004 } 7005 } 7006 } 7007 7008 // Create a native library symlink only if we have native libraries 7009 // and if the native libraries are 32 bit libraries. We do not provide 7010 // this symlink for 64 bit libraries. 7011 if (pkg.applicationInfo.primaryCpuAbi != null && 7012 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7013 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7014 for (int userId : userIds) { 7015 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7016 nativeLibPath, userId) < 0) { 7017 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7018 "Failed linking native library dir (user=" + userId + ")"); 7019 } 7020 } 7021 } 7022 } 7023 7024 // This is a special case for the "system" package, where the ABI is 7025 // dictated by the zygote configuration (and init.rc). We should keep track 7026 // of this ABI so that we can deal with "normal" applications that run under 7027 // the same UID correctly. 7028 if (mPlatformPackage == pkg) { 7029 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7030 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7031 } 7032 7033 // If there's a mismatch between the abi-override in the package setting 7034 // and the abiOverride specified for the install. Warn about this because we 7035 // would've already compiled the app without taking the package setting into 7036 // account. 7037 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7038 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7039 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7040 " for package: " + pkg.packageName); 7041 } 7042 } 7043 7044 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7045 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7046 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7047 7048 // Copy the derived override back to the parsed package, so that we can 7049 // update the package settings accordingly. 7050 pkg.cpuAbiOverride = cpuAbiOverride; 7051 7052 if (DEBUG_ABI_SELECTION) { 7053 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7054 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7055 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7056 } 7057 7058 // Push the derived path down into PackageSettings so we know what to 7059 // clean up at uninstall time. 7060 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7061 7062 if (DEBUG_ABI_SELECTION) { 7063 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7064 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7065 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7066 } 7067 7068 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7069 // We don't do this here during boot because we can do it all 7070 // at once after scanning all existing packages. 7071 // 7072 // We also do this *before* we perform dexopt on this package, so that 7073 // we can avoid redundant dexopts, and also to make sure we've got the 7074 // code and package path correct. 7075 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7076 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */); 7077 } 7078 7079 if ((scanFlags & SCAN_NO_DEX) == 0) { 7080 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7081 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */, 7082 (scanFlags & SCAN_BOOTING) == 0); 7083 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7084 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7085 } 7086 } 7087 if (mFactoryTest && pkg.requestedPermissions.contains( 7088 android.Manifest.permission.FACTORY_TEST)) { 7089 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7090 } 7091 7092 ArrayList<PackageParser.Package> clientLibPkgs = null; 7093 7094 // writer 7095 synchronized (mPackages) { 7096 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7097 // Only system apps can add new shared libraries. 7098 if (pkg.libraryNames != null) { 7099 for (int i=0; i<pkg.libraryNames.size(); i++) { 7100 String name = pkg.libraryNames.get(i); 7101 boolean allowed = false; 7102 if (pkg.isUpdatedSystemApp()) { 7103 // New library entries can only be added through the 7104 // system image. This is important to get rid of a lot 7105 // of nasty edge cases: for example if we allowed a non- 7106 // system update of the app to add a library, then uninstalling 7107 // the update would make the library go away, and assumptions 7108 // we made such as through app install filtering would now 7109 // have allowed apps on the device which aren't compatible 7110 // with it. Better to just have the restriction here, be 7111 // conservative, and create many fewer cases that can negatively 7112 // impact the user experience. 7113 final PackageSetting sysPs = mSettings 7114 .getDisabledSystemPkgLPr(pkg.packageName); 7115 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7116 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7117 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7118 allowed = true; 7119 allowed = true; 7120 break; 7121 } 7122 } 7123 } 7124 } else { 7125 allowed = true; 7126 } 7127 if (allowed) { 7128 if (!mSharedLibraries.containsKey(name)) { 7129 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7130 } else if (!name.equals(pkg.packageName)) { 7131 Slog.w(TAG, "Package " + pkg.packageName + " library " 7132 + name + " already exists; skipping"); 7133 } 7134 } else { 7135 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7136 + name + " that is not declared on system image; skipping"); 7137 } 7138 } 7139 if ((scanFlags&SCAN_BOOTING) == 0) { 7140 // If we are not booting, we need to update any applications 7141 // that are clients of our shared library. If we are booting, 7142 // this will all be done once the scan is complete. 7143 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7144 } 7145 } 7146 } 7147 } 7148 7149 // We also need to dexopt any apps that are dependent on this library. Note that 7150 // if these fail, we should abort the install since installing the library will 7151 // result in some apps being broken. 7152 if (clientLibPkgs != null) { 7153 if ((scanFlags & SCAN_NO_DEX) == 0) { 7154 for (int i = 0; i < clientLibPkgs.size(); i++) { 7155 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7156 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7157 null /* instruction sets */, forceDex, 7158 (scanFlags & SCAN_DEFER_DEX) != 0, false, 7159 (scanFlags & SCAN_BOOTING) == 0); 7160 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7161 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7162 "scanPackageLI failed to dexopt clientLibPkgs"); 7163 } 7164 } 7165 } 7166 } 7167 7168 // Request the ActivityManager to kill the process(only for existing packages) 7169 // so that we do not end up in a confused state while the user is still using the older 7170 // version of the application while the new one gets installed. 7171 if ((scanFlags & SCAN_REPLACING) != 0) { 7172 killApplication(pkg.applicationInfo.packageName, 7173 pkg.applicationInfo.uid, "replace pkg"); 7174 } 7175 7176 // Also need to kill any apps that are dependent on the library. 7177 if (clientLibPkgs != null) { 7178 for (int i=0; i<clientLibPkgs.size(); i++) { 7179 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7180 killApplication(clientPkg.applicationInfo.packageName, 7181 clientPkg.applicationInfo.uid, "update lib"); 7182 } 7183 } 7184 7185 // Make sure we're not adding any bogus keyset info 7186 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7187 ksms.assertScannedPackageValid(pkg); 7188 7189 // writer 7190 synchronized (mPackages) { 7191 // We don't expect installation to fail beyond this point 7192 7193 // Add the new setting to mSettings 7194 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7195 // Add the new setting to mPackages 7196 mPackages.put(pkg.applicationInfo.packageName, pkg); 7197 // Make sure we don't accidentally delete its data. 7198 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7199 while (iter.hasNext()) { 7200 PackageCleanItem item = iter.next(); 7201 if (pkgName.equals(item.packageName)) { 7202 iter.remove(); 7203 } 7204 } 7205 7206 // Take care of first install / last update times. 7207 if (currentTime != 0) { 7208 if (pkgSetting.firstInstallTime == 0) { 7209 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7210 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7211 pkgSetting.lastUpdateTime = currentTime; 7212 } 7213 } else if (pkgSetting.firstInstallTime == 0) { 7214 // We need *something*. Take time time stamp of the file. 7215 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7216 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7217 if (scanFileTime != pkgSetting.timeStamp) { 7218 // A package on the system image has changed; consider this 7219 // to be an update. 7220 pkgSetting.lastUpdateTime = scanFileTime; 7221 } 7222 } 7223 7224 // Add the package's KeySets to the global KeySetManagerService 7225 ksms.addScannedPackageLPw(pkg); 7226 7227 int N = pkg.providers.size(); 7228 StringBuilder r = null; 7229 int i; 7230 for (i=0; i<N; i++) { 7231 PackageParser.Provider p = pkg.providers.get(i); 7232 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7233 p.info.processName, pkg.applicationInfo.uid); 7234 mProviders.addProvider(p); 7235 p.syncable = p.info.isSyncable; 7236 if (p.info.authority != null) { 7237 String names[] = p.info.authority.split(";"); 7238 p.info.authority = null; 7239 for (int j = 0; j < names.length; j++) { 7240 if (j == 1 && p.syncable) { 7241 // We only want the first authority for a provider to possibly be 7242 // syncable, so if we already added this provider using a different 7243 // authority clear the syncable flag. We copy the provider before 7244 // changing it because the mProviders object contains a reference 7245 // to a provider that we don't want to change. 7246 // Only do this for the second authority since the resulting provider 7247 // object can be the same for all future authorities for this provider. 7248 p = new PackageParser.Provider(p); 7249 p.syncable = false; 7250 } 7251 if (!mProvidersByAuthority.containsKey(names[j])) { 7252 mProvidersByAuthority.put(names[j], p); 7253 if (p.info.authority == null) { 7254 p.info.authority = names[j]; 7255 } else { 7256 p.info.authority = p.info.authority + ";" + names[j]; 7257 } 7258 if (DEBUG_PACKAGE_SCANNING) { 7259 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7260 Log.d(TAG, "Registered content provider: " + names[j] 7261 + ", className = " + p.info.name + ", isSyncable = " 7262 + p.info.isSyncable); 7263 } 7264 } else { 7265 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7266 Slog.w(TAG, "Skipping provider name " + names[j] + 7267 " (in package " + pkg.applicationInfo.packageName + 7268 "): name already used by " 7269 + ((other != null && other.getComponentName() != null) 7270 ? other.getComponentName().getPackageName() : "?")); 7271 } 7272 } 7273 } 7274 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7275 if (r == null) { 7276 r = new StringBuilder(256); 7277 } else { 7278 r.append(' '); 7279 } 7280 r.append(p.info.name); 7281 } 7282 } 7283 if (r != null) { 7284 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7285 } 7286 7287 N = pkg.services.size(); 7288 r = null; 7289 for (i=0; i<N; i++) { 7290 PackageParser.Service s = pkg.services.get(i); 7291 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7292 s.info.processName, pkg.applicationInfo.uid); 7293 mServices.addService(s); 7294 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7295 if (r == null) { 7296 r = new StringBuilder(256); 7297 } else { 7298 r.append(' '); 7299 } 7300 r.append(s.info.name); 7301 } 7302 } 7303 if (r != null) { 7304 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7305 } 7306 7307 N = pkg.receivers.size(); 7308 r = null; 7309 for (i=0; i<N; i++) { 7310 PackageParser.Activity a = pkg.receivers.get(i); 7311 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7312 a.info.processName, pkg.applicationInfo.uid); 7313 mReceivers.addActivity(a, "receiver"); 7314 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7315 if (r == null) { 7316 r = new StringBuilder(256); 7317 } else { 7318 r.append(' '); 7319 } 7320 r.append(a.info.name); 7321 } 7322 } 7323 if (r != null) { 7324 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7325 } 7326 7327 N = pkg.activities.size(); 7328 r = null; 7329 for (i=0; i<N; i++) { 7330 PackageParser.Activity a = pkg.activities.get(i); 7331 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7332 a.info.processName, pkg.applicationInfo.uid); 7333 mActivities.addActivity(a, "activity"); 7334 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7335 if (r == null) { 7336 r = new StringBuilder(256); 7337 } else { 7338 r.append(' '); 7339 } 7340 r.append(a.info.name); 7341 } 7342 } 7343 if (r != null) { 7344 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7345 } 7346 7347 N = pkg.permissionGroups.size(); 7348 r = null; 7349 for (i=0; i<N; i++) { 7350 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7351 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7352 if (cur == null) { 7353 mPermissionGroups.put(pg.info.name, pg); 7354 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7355 if (r == null) { 7356 r = new StringBuilder(256); 7357 } else { 7358 r.append(' '); 7359 } 7360 r.append(pg.info.name); 7361 } 7362 } else { 7363 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7364 + pg.info.packageName + " ignored: original from " 7365 + cur.info.packageName); 7366 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7367 if (r == null) { 7368 r = new StringBuilder(256); 7369 } else { 7370 r.append(' '); 7371 } 7372 r.append("DUP:"); 7373 r.append(pg.info.name); 7374 } 7375 } 7376 } 7377 if (r != null) { 7378 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7379 } 7380 7381 N = pkg.permissions.size(); 7382 r = null; 7383 for (i=0; i<N; i++) { 7384 PackageParser.Permission p = pkg.permissions.get(i); 7385 7386 // Assume by default that we did not install this permission into the system. 7387 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7388 7389 // Now that permission groups have a special meaning, we ignore permission 7390 // groups for legacy apps to prevent unexpected behavior. In particular, 7391 // permissions for one app being granted to someone just becuase they happen 7392 // to be in a group defined by another app (before this had no implications). 7393 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7394 p.group = mPermissionGroups.get(p.info.group); 7395 // Warn for a permission in an unknown group. 7396 if (p.info.group != null && p.group == null) { 7397 Slog.w(TAG, "Permission " + p.info.name + " from package " 7398 + p.info.packageName + " in an unknown group " + p.info.group); 7399 } 7400 } 7401 7402 ArrayMap<String, BasePermission> permissionMap = 7403 p.tree ? mSettings.mPermissionTrees 7404 : mSettings.mPermissions; 7405 BasePermission bp = permissionMap.get(p.info.name); 7406 7407 // Allow system apps to redefine non-system permissions 7408 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7409 final boolean currentOwnerIsSystem = (bp.perm != null 7410 && isSystemApp(bp.perm.owner)); 7411 if (isSystemApp(p.owner)) { 7412 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7413 // It's a built-in permission and no owner, take ownership now 7414 bp.packageSetting = pkgSetting; 7415 bp.perm = p; 7416 bp.uid = pkg.applicationInfo.uid; 7417 bp.sourcePackage = p.info.packageName; 7418 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7419 } else if (!currentOwnerIsSystem) { 7420 String msg = "New decl " + p.owner + " of permission " 7421 + p.info.name + " is system; overriding " + bp.sourcePackage; 7422 reportSettingsProblem(Log.WARN, msg); 7423 bp = null; 7424 } 7425 } 7426 } 7427 7428 if (bp == null) { 7429 bp = new BasePermission(p.info.name, p.info.packageName, 7430 BasePermission.TYPE_NORMAL); 7431 permissionMap.put(p.info.name, bp); 7432 } 7433 7434 if (bp.perm == null) { 7435 if (bp.sourcePackage == null 7436 || bp.sourcePackage.equals(p.info.packageName)) { 7437 BasePermission tree = findPermissionTreeLP(p.info.name); 7438 if (tree == null 7439 || tree.sourcePackage.equals(p.info.packageName)) { 7440 bp.packageSetting = pkgSetting; 7441 bp.perm = p; 7442 bp.uid = pkg.applicationInfo.uid; 7443 bp.sourcePackage = p.info.packageName; 7444 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7445 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7446 if (r == null) { 7447 r = new StringBuilder(256); 7448 } else { 7449 r.append(' '); 7450 } 7451 r.append(p.info.name); 7452 } 7453 } else { 7454 Slog.w(TAG, "Permission " + p.info.name + " from package " 7455 + p.info.packageName + " ignored: base tree " 7456 + tree.name + " is from package " 7457 + tree.sourcePackage); 7458 } 7459 } else { 7460 Slog.w(TAG, "Permission " + p.info.name + " from package " 7461 + p.info.packageName + " ignored: original from " 7462 + bp.sourcePackage); 7463 } 7464 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7465 if (r == null) { 7466 r = new StringBuilder(256); 7467 } else { 7468 r.append(' '); 7469 } 7470 r.append("DUP:"); 7471 r.append(p.info.name); 7472 } 7473 if (bp.perm == p) { 7474 bp.protectionLevel = p.info.protectionLevel; 7475 } 7476 } 7477 7478 if (r != null) { 7479 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7480 } 7481 7482 N = pkg.instrumentation.size(); 7483 r = null; 7484 for (i=0; i<N; i++) { 7485 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7486 a.info.packageName = pkg.applicationInfo.packageName; 7487 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7488 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7489 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7490 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7491 a.info.dataDir = pkg.applicationInfo.dataDir; 7492 7493 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7494 // need other information about the application, like the ABI and what not ? 7495 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7496 mInstrumentation.put(a.getComponentName(), a); 7497 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7498 if (r == null) { 7499 r = new StringBuilder(256); 7500 } else { 7501 r.append(' '); 7502 } 7503 r.append(a.info.name); 7504 } 7505 } 7506 if (r != null) { 7507 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7508 } 7509 7510 if (pkg.protectedBroadcasts != null) { 7511 N = pkg.protectedBroadcasts.size(); 7512 for (i=0; i<N; i++) { 7513 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7514 } 7515 } 7516 7517 pkgSetting.setTimeStamp(scanFileTime); 7518 7519 // Create idmap files for pairs of (packages, overlay packages). 7520 // Note: "android", ie framework-res.apk, is handled by native layers. 7521 if (pkg.mOverlayTarget != null) { 7522 // This is an overlay package. 7523 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7524 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7525 mOverlays.put(pkg.mOverlayTarget, 7526 new ArrayMap<String, PackageParser.Package>()); 7527 } 7528 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7529 map.put(pkg.packageName, pkg); 7530 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7531 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7532 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7533 "scanPackageLI failed to createIdmap"); 7534 } 7535 } 7536 } else if (mOverlays.containsKey(pkg.packageName) && 7537 !pkg.packageName.equals("android")) { 7538 // This is a regular package, with one or more known overlay packages. 7539 createIdmapsForPackageLI(pkg); 7540 } 7541 } 7542 7543 return pkg; 7544 } 7545 7546 /** 7547 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7548 * is derived purely on the basis of the contents of {@code scanFile} and 7549 * {@code cpuAbiOverride}. 7550 * 7551 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7552 */ 7553 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7554 String cpuAbiOverride, boolean extractLibs) 7555 throws PackageManagerException { 7556 // TODO: We can probably be smarter about this stuff. For installed apps, 7557 // we can calculate this information at install time once and for all. For 7558 // system apps, we can probably assume that this information doesn't change 7559 // after the first boot scan. As things stand, we do lots of unnecessary work. 7560 7561 // Give ourselves some initial paths; we'll come back for another 7562 // pass once we've determined ABI below. 7563 setNativeLibraryPaths(pkg); 7564 7565 // We would never need to extract libs for forward-locked and external packages, 7566 // since the container service will do it for us. We shouldn't attempt to 7567 // extract libs from system app when it was not updated. 7568 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7569 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7570 extractLibs = false; 7571 } 7572 7573 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7574 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7575 7576 NativeLibraryHelper.Handle handle = null; 7577 try { 7578 handle = NativeLibraryHelper.Handle.create(scanFile); 7579 // TODO(multiArch): This can be null for apps that didn't go through the 7580 // usual installation process. We can calculate it again, like we 7581 // do during install time. 7582 // 7583 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7584 // unnecessary. 7585 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7586 7587 // Null out the abis so that they can be recalculated. 7588 pkg.applicationInfo.primaryCpuAbi = null; 7589 pkg.applicationInfo.secondaryCpuAbi = null; 7590 if (isMultiArch(pkg.applicationInfo)) { 7591 // Warn if we've set an abiOverride for multi-lib packages.. 7592 // By definition, we need to copy both 32 and 64 bit libraries for 7593 // such packages. 7594 if (pkg.cpuAbiOverride != null 7595 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7596 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7597 } 7598 7599 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7600 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7601 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7602 if (extractLibs) { 7603 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7604 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7605 useIsaSpecificSubdirs); 7606 } else { 7607 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7608 } 7609 } 7610 7611 maybeThrowExceptionForMultiArchCopy( 7612 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7613 7614 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7615 if (extractLibs) { 7616 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7617 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7618 useIsaSpecificSubdirs); 7619 } else { 7620 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7621 } 7622 } 7623 7624 maybeThrowExceptionForMultiArchCopy( 7625 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7626 7627 if (abi64 >= 0) { 7628 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7629 } 7630 7631 if (abi32 >= 0) { 7632 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7633 if (abi64 >= 0) { 7634 pkg.applicationInfo.secondaryCpuAbi = abi; 7635 } else { 7636 pkg.applicationInfo.primaryCpuAbi = abi; 7637 } 7638 } 7639 } else { 7640 String[] abiList = (cpuAbiOverride != null) ? 7641 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7642 7643 // Enable gross and lame hacks for apps that are built with old 7644 // SDK tools. We must scan their APKs for renderscript bitcode and 7645 // not launch them if it's present. Don't bother checking on devices 7646 // that don't have 64 bit support. 7647 boolean needsRenderScriptOverride = false; 7648 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7649 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7650 abiList = Build.SUPPORTED_32_BIT_ABIS; 7651 needsRenderScriptOverride = true; 7652 } 7653 7654 final int copyRet; 7655 if (extractLibs) { 7656 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7657 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7658 } else { 7659 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7660 } 7661 7662 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7663 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7664 "Error unpackaging native libs for app, errorCode=" + copyRet); 7665 } 7666 7667 if (copyRet >= 0) { 7668 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7669 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7670 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7671 } else if (needsRenderScriptOverride) { 7672 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7673 } 7674 } 7675 } catch (IOException ioe) { 7676 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7677 } finally { 7678 IoUtils.closeQuietly(handle); 7679 } 7680 7681 // Now that we've calculated the ABIs and determined if it's an internal app, 7682 // we will go ahead and populate the nativeLibraryPath. 7683 setNativeLibraryPaths(pkg); 7684 } 7685 7686 /** 7687 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7688 * i.e, so that all packages can be run inside a single process if required. 7689 * 7690 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7691 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7692 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7693 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7694 * updating a package that belongs to a shared user. 7695 * 7696 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7697 * adds unnecessary complexity. 7698 */ 7699 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7700 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt, 7701 boolean bootComplete) { 7702 String requiredInstructionSet = null; 7703 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7704 requiredInstructionSet = VMRuntime.getInstructionSet( 7705 scannedPackage.applicationInfo.primaryCpuAbi); 7706 } 7707 7708 PackageSetting requirer = null; 7709 for (PackageSetting ps : packagesForUser) { 7710 // If packagesForUser contains scannedPackage, we skip it. This will happen 7711 // when scannedPackage is an update of an existing package. Without this check, 7712 // we will never be able to change the ABI of any package belonging to a shared 7713 // user, even if it's compatible with other packages. 7714 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7715 if (ps.primaryCpuAbiString == null) { 7716 continue; 7717 } 7718 7719 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7720 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7721 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7722 // this but there's not much we can do. 7723 String errorMessage = "Instruction set mismatch, " 7724 + ((requirer == null) ? "[caller]" : requirer) 7725 + " requires " + requiredInstructionSet + " whereas " + ps 7726 + " requires " + instructionSet; 7727 Slog.w(TAG, errorMessage); 7728 } 7729 7730 if (requiredInstructionSet == null) { 7731 requiredInstructionSet = instructionSet; 7732 requirer = ps; 7733 } 7734 } 7735 } 7736 7737 if (requiredInstructionSet != null) { 7738 String adjustedAbi; 7739 if (requirer != null) { 7740 // requirer != null implies that either scannedPackage was null or that scannedPackage 7741 // did not require an ABI, in which case we have to adjust scannedPackage to match 7742 // the ABI of the set (which is the same as requirer's ABI) 7743 adjustedAbi = requirer.primaryCpuAbiString; 7744 if (scannedPackage != null) { 7745 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7746 } 7747 } else { 7748 // requirer == null implies that we're updating all ABIs in the set to 7749 // match scannedPackage. 7750 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7751 } 7752 7753 for (PackageSetting ps : packagesForUser) { 7754 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7755 if (ps.primaryCpuAbiString != null) { 7756 continue; 7757 } 7758 7759 ps.primaryCpuAbiString = adjustedAbi; 7760 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7761 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7762 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7763 7764 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7765 null /* instruction sets */, forceDexOpt, deferDexOpt, true, 7766 bootComplete); 7767 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7768 ps.primaryCpuAbiString = null; 7769 ps.pkg.applicationInfo.primaryCpuAbi = null; 7770 return; 7771 } else { 7772 mInstaller.rmdex(ps.codePathString, 7773 getDexCodeInstructionSet(getPreferredInstructionSet())); 7774 } 7775 } 7776 } 7777 } 7778 } 7779 } 7780 7781 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7782 synchronized (mPackages) { 7783 mResolverReplaced = true; 7784 // Set up information for custom user intent resolution activity. 7785 mResolveActivity.applicationInfo = pkg.applicationInfo; 7786 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7787 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7788 mResolveActivity.processName = pkg.applicationInfo.packageName; 7789 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7790 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7791 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7792 mResolveActivity.theme = 0; 7793 mResolveActivity.exported = true; 7794 mResolveActivity.enabled = true; 7795 mResolveInfo.activityInfo = mResolveActivity; 7796 mResolveInfo.priority = 0; 7797 mResolveInfo.preferredOrder = 0; 7798 mResolveInfo.match = 0; 7799 mResolveComponentName = mCustomResolverComponentName; 7800 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7801 mResolveComponentName); 7802 } 7803 } 7804 7805 private static String calculateBundledApkRoot(final String codePathString) { 7806 final File codePath = new File(codePathString); 7807 final File codeRoot; 7808 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7809 codeRoot = Environment.getRootDirectory(); 7810 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7811 codeRoot = Environment.getOemDirectory(); 7812 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7813 codeRoot = Environment.getVendorDirectory(); 7814 } else { 7815 // Unrecognized code path; take its top real segment as the apk root: 7816 // e.g. /something/app/blah.apk => /something 7817 try { 7818 File f = codePath.getCanonicalFile(); 7819 File parent = f.getParentFile(); // non-null because codePath is a file 7820 File tmp; 7821 while ((tmp = parent.getParentFile()) != null) { 7822 f = parent; 7823 parent = tmp; 7824 } 7825 codeRoot = f; 7826 Slog.w(TAG, "Unrecognized code path " 7827 + codePath + " - using " + codeRoot); 7828 } catch (IOException e) { 7829 // Can't canonicalize the code path -- shenanigans? 7830 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7831 return Environment.getRootDirectory().getPath(); 7832 } 7833 } 7834 return codeRoot.getPath(); 7835 } 7836 7837 /** 7838 * Derive and set the location of native libraries for the given package, 7839 * which varies depending on where and how the package was installed. 7840 */ 7841 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7842 final ApplicationInfo info = pkg.applicationInfo; 7843 final String codePath = pkg.codePath; 7844 final File codeFile = new File(codePath); 7845 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7846 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 7847 7848 info.nativeLibraryRootDir = null; 7849 info.nativeLibraryRootRequiresIsa = false; 7850 info.nativeLibraryDir = null; 7851 info.secondaryNativeLibraryDir = null; 7852 7853 if (isApkFile(codeFile)) { 7854 // Monolithic install 7855 if (bundledApp) { 7856 // If "/system/lib64/apkname" exists, assume that is the per-package 7857 // native library directory to use; otherwise use "/system/lib/apkname". 7858 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7859 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7860 getPrimaryInstructionSet(info)); 7861 7862 // This is a bundled system app so choose the path based on the ABI. 7863 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7864 // is just the default path. 7865 final String apkName = deriveCodePathName(codePath); 7866 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7867 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7868 apkName).getAbsolutePath(); 7869 7870 if (info.secondaryCpuAbi != null) { 7871 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7872 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7873 secondaryLibDir, apkName).getAbsolutePath(); 7874 } 7875 } else if (asecApp) { 7876 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7877 .getAbsolutePath(); 7878 } else { 7879 final String apkName = deriveCodePathName(codePath); 7880 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7881 .getAbsolutePath(); 7882 } 7883 7884 info.nativeLibraryRootRequiresIsa = false; 7885 info.nativeLibraryDir = info.nativeLibraryRootDir; 7886 } else { 7887 // Cluster install 7888 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7889 info.nativeLibraryRootRequiresIsa = true; 7890 7891 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7892 getPrimaryInstructionSet(info)).getAbsolutePath(); 7893 7894 if (info.secondaryCpuAbi != null) { 7895 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7896 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7897 } 7898 } 7899 } 7900 7901 /** 7902 * Calculate the abis and roots for a bundled app. These can uniquely 7903 * be determined from the contents of the system partition, i.e whether 7904 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7905 * of this information, and instead assume that the system was built 7906 * sensibly. 7907 */ 7908 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7909 PackageSetting pkgSetting) { 7910 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7911 7912 // If "/system/lib64/apkname" exists, assume that is the per-package 7913 // native library directory to use; otherwise use "/system/lib/apkname". 7914 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7915 setBundledAppAbi(pkg, apkRoot, apkName); 7916 // pkgSetting might be null during rescan following uninstall of updates 7917 // to a bundled app, so accommodate that possibility. The settings in 7918 // that case will be established later from the parsed package. 7919 // 7920 // If the settings aren't null, sync them up with what we've just derived. 7921 // note that apkRoot isn't stored in the package settings. 7922 if (pkgSetting != null) { 7923 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7924 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7925 } 7926 } 7927 7928 /** 7929 * Deduces the ABI of a bundled app and sets the relevant fields on the 7930 * parsed pkg object. 7931 * 7932 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7933 * under which system libraries are installed. 7934 * @param apkName the name of the installed package. 7935 */ 7936 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7937 final File codeFile = new File(pkg.codePath); 7938 7939 final boolean has64BitLibs; 7940 final boolean has32BitLibs; 7941 if (isApkFile(codeFile)) { 7942 // Monolithic install 7943 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7944 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7945 } else { 7946 // Cluster install 7947 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7948 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7949 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7950 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7951 has64BitLibs = (new File(rootDir, isa)).exists(); 7952 } else { 7953 has64BitLibs = false; 7954 } 7955 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7956 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7957 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7958 has32BitLibs = (new File(rootDir, isa)).exists(); 7959 } else { 7960 has32BitLibs = false; 7961 } 7962 } 7963 7964 if (has64BitLibs && !has32BitLibs) { 7965 // The package has 64 bit libs, but not 32 bit libs. Its primary 7966 // ABI should be 64 bit. We can safely assume here that the bundled 7967 // native libraries correspond to the most preferred ABI in the list. 7968 7969 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7970 pkg.applicationInfo.secondaryCpuAbi = null; 7971 } else if (has32BitLibs && !has64BitLibs) { 7972 // The package has 32 bit libs but not 64 bit libs. Its primary 7973 // ABI should be 32 bit. 7974 7975 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7976 pkg.applicationInfo.secondaryCpuAbi = null; 7977 } else if (has32BitLibs && has64BitLibs) { 7978 // The application has both 64 and 32 bit bundled libraries. We check 7979 // here that the app declares multiArch support, and warn if it doesn't. 7980 // 7981 // We will be lenient here and record both ABIs. The primary will be the 7982 // ABI that's higher on the list, i.e, a device that's configured to prefer 7983 // 64 bit apps will see a 64 bit primary ABI, 7984 7985 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7986 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7987 } 7988 7989 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7990 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7991 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7992 } else { 7993 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7994 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7995 } 7996 } else { 7997 pkg.applicationInfo.primaryCpuAbi = null; 7998 pkg.applicationInfo.secondaryCpuAbi = null; 7999 } 8000 } 8001 8002 private void killApplication(String pkgName, int appId, String reason) { 8003 // Request the ActivityManager to kill the process(only for existing packages) 8004 // so that we do not end up in a confused state while the user is still using the older 8005 // version of the application while the new one gets installed. 8006 IActivityManager am = ActivityManagerNative.getDefault(); 8007 if (am != null) { 8008 try { 8009 am.killApplicationWithAppId(pkgName, appId, reason); 8010 } catch (RemoteException e) { 8011 } 8012 } 8013 } 8014 8015 void removePackageLI(PackageSetting ps, boolean chatty) { 8016 if (DEBUG_INSTALL) { 8017 if (chatty) 8018 Log.d(TAG, "Removing package " + ps.name); 8019 } 8020 8021 // writer 8022 synchronized (mPackages) { 8023 mPackages.remove(ps.name); 8024 final PackageParser.Package pkg = ps.pkg; 8025 if (pkg != null) { 8026 cleanPackageDataStructuresLILPw(pkg, chatty); 8027 } 8028 } 8029 } 8030 8031 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8032 if (DEBUG_INSTALL) { 8033 if (chatty) 8034 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8035 } 8036 8037 // writer 8038 synchronized (mPackages) { 8039 mPackages.remove(pkg.applicationInfo.packageName); 8040 cleanPackageDataStructuresLILPw(pkg, chatty); 8041 } 8042 } 8043 8044 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8045 int N = pkg.providers.size(); 8046 StringBuilder r = null; 8047 int i; 8048 for (i=0; i<N; i++) { 8049 PackageParser.Provider p = pkg.providers.get(i); 8050 mProviders.removeProvider(p); 8051 if (p.info.authority == null) { 8052 8053 /* There was another ContentProvider with this authority when 8054 * this app was installed so this authority is null, 8055 * Ignore it as we don't have to unregister the provider. 8056 */ 8057 continue; 8058 } 8059 String names[] = p.info.authority.split(";"); 8060 for (int j = 0; j < names.length; j++) { 8061 if (mProvidersByAuthority.get(names[j]) == p) { 8062 mProvidersByAuthority.remove(names[j]); 8063 if (DEBUG_REMOVE) { 8064 if (chatty) 8065 Log.d(TAG, "Unregistered content provider: " + names[j] 8066 + ", className = " + p.info.name + ", isSyncable = " 8067 + p.info.isSyncable); 8068 } 8069 } 8070 } 8071 if (DEBUG_REMOVE && chatty) { 8072 if (r == null) { 8073 r = new StringBuilder(256); 8074 } else { 8075 r.append(' '); 8076 } 8077 r.append(p.info.name); 8078 } 8079 } 8080 if (r != null) { 8081 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8082 } 8083 8084 N = pkg.services.size(); 8085 r = null; 8086 for (i=0; i<N; i++) { 8087 PackageParser.Service s = pkg.services.get(i); 8088 mServices.removeService(s); 8089 if (chatty) { 8090 if (r == null) { 8091 r = new StringBuilder(256); 8092 } else { 8093 r.append(' '); 8094 } 8095 r.append(s.info.name); 8096 } 8097 } 8098 if (r != null) { 8099 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8100 } 8101 8102 N = pkg.receivers.size(); 8103 r = null; 8104 for (i=0; i<N; i++) { 8105 PackageParser.Activity a = pkg.receivers.get(i); 8106 mReceivers.removeActivity(a, "receiver"); 8107 if (DEBUG_REMOVE && chatty) { 8108 if (r == null) { 8109 r = new StringBuilder(256); 8110 } else { 8111 r.append(' '); 8112 } 8113 r.append(a.info.name); 8114 } 8115 } 8116 if (r != null) { 8117 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8118 } 8119 8120 N = pkg.activities.size(); 8121 r = null; 8122 for (i=0; i<N; i++) { 8123 PackageParser.Activity a = pkg.activities.get(i); 8124 mActivities.removeActivity(a, "activity"); 8125 if (DEBUG_REMOVE && chatty) { 8126 if (r == null) { 8127 r = new StringBuilder(256); 8128 } else { 8129 r.append(' '); 8130 } 8131 r.append(a.info.name); 8132 } 8133 } 8134 if (r != null) { 8135 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8136 } 8137 8138 N = pkg.permissions.size(); 8139 r = null; 8140 for (i=0; i<N; i++) { 8141 PackageParser.Permission p = pkg.permissions.get(i); 8142 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8143 if (bp == null) { 8144 bp = mSettings.mPermissionTrees.get(p.info.name); 8145 } 8146 if (bp != null && bp.perm == p) { 8147 bp.perm = null; 8148 if (DEBUG_REMOVE && chatty) { 8149 if (r == null) { 8150 r = new StringBuilder(256); 8151 } else { 8152 r.append(' '); 8153 } 8154 r.append(p.info.name); 8155 } 8156 } 8157 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8158 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8159 if (appOpPerms != null) { 8160 appOpPerms.remove(pkg.packageName); 8161 } 8162 } 8163 } 8164 if (r != null) { 8165 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8166 } 8167 8168 N = pkg.requestedPermissions.size(); 8169 r = null; 8170 for (i=0; i<N; i++) { 8171 String perm = pkg.requestedPermissions.get(i); 8172 BasePermission bp = mSettings.mPermissions.get(perm); 8173 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8174 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8175 if (appOpPerms != null) { 8176 appOpPerms.remove(pkg.packageName); 8177 if (appOpPerms.isEmpty()) { 8178 mAppOpPermissionPackages.remove(perm); 8179 } 8180 } 8181 } 8182 } 8183 if (r != null) { 8184 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8185 } 8186 8187 N = pkg.instrumentation.size(); 8188 r = null; 8189 for (i=0; i<N; i++) { 8190 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8191 mInstrumentation.remove(a.getComponentName()); 8192 if (DEBUG_REMOVE && chatty) { 8193 if (r == null) { 8194 r = new StringBuilder(256); 8195 } else { 8196 r.append(' '); 8197 } 8198 r.append(a.info.name); 8199 } 8200 } 8201 if (r != null) { 8202 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8203 } 8204 8205 r = null; 8206 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8207 // Only system apps can hold shared libraries. 8208 if (pkg.libraryNames != null) { 8209 for (i=0; i<pkg.libraryNames.size(); i++) { 8210 String name = pkg.libraryNames.get(i); 8211 SharedLibraryEntry cur = mSharedLibraries.get(name); 8212 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8213 mSharedLibraries.remove(name); 8214 if (DEBUG_REMOVE && chatty) { 8215 if (r == null) { 8216 r = new StringBuilder(256); 8217 } else { 8218 r.append(' '); 8219 } 8220 r.append(name); 8221 } 8222 } 8223 } 8224 } 8225 } 8226 if (r != null) { 8227 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8228 } 8229 } 8230 8231 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8232 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8233 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8234 return true; 8235 } 8236 } 8237 return false; 8238 } 8239 8240 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8241 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8242 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8243 8244 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8245 int flags) { 8246 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8247 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8248 } 8249 8250 private void updatePermissionsLPw(String changingPkg, 8251 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8252 // Make sure there are no dangling permission trees. 8253 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8254 while (it.hasNext()) { 8255 final BasePermission bp = it.next(); 8256 if (bp.packageSetting == null) { 8257 // We may not yet have parsed the package, so just see if 8258 // we still know about its settings. 8259 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8260 } 8261 if (bp.packageSetting == null) { 8262 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8263 + " from package " + bp.sourcePackage); 8264 it.remove(); 8265 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8266 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8267 Slog.i(TAG, "Removing old permission tree: " + bp.name 8268 + " from package " + bp.sourcePackage); 8269 flags |= UPDATE_PERMISSIONS_ALL; 8270 it.remove(); 8271 } 8272 } 8273 } 8274 8275 // Make sure all dynamic permissions have been assigned to a package, 8276 // and make sure there are no dangling permissions. 8277 it = mSettings.mPermissions.values().iterator(); 8278 while (it.hasNext()) { 8279 final BasePermission bp = it.next(); 8280 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8281 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8282 + bp.name + " pkg=" + bp.sourcePackage 8283 + " info=" + bp.pendingInfo); 8284 if (bp.packageSetting == null && bp.pendingInfo != null) { 8285 final BasePermission tree = findPermissionTreeLP(bp.name); 8286 if (tree != null && tree.perm != null) { 8287 bp.packageSetting = tree.packageSetting; 8288 bp.perm = new PackageParser.Permission(tree.perm.owner, 8289 new PermissionInfo(bp.pendingInfo)); 8290 bp.perm.info.packageName = tree.perm.info.packageName; 8291 bp.perm.info.name = bp.name; 8292 bp.uid = tree.uid; 8293 } 8294 } 8295 } 8296 if (bp.packageSetting == null) { 8297 // We may not yet have parsed the package, so just see if 8298 // we still know about its settings. 8299 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8300 } 8301 if (bp.packageSetting == null) { 8302 Slog.w(TAG, "Removing dangling permission: " + bp.name 8303 + " from package " + bp.sourcePackage); 8304 it.remove(); 8305 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8306 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8307 Slog.i(TAG, "Removing old permission: " + bp.name 8308 + " from package " + bp.sourcePackage); 8309 flags |= UPDATE_PERMISSIONS_ALL; 8310 it.remove(); 8311 } 8312 } 8313 } 8314 8315 // Now update the permissions for all packages, in particular 8316 // replace the granted permissions of the system packages. 8317 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8318 for (PackageParser.Package pkg : mPackages.values()) { 8319 if (pkg != pkgInfo) { 8320 // Only replace for packages on requested volume 8321 final String volumeUuid = getVolumeUuidForPackage(pkg); 8322 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8323 && Objects.equals(replaceVolumeUuid, volumeUuid); 8324 grantPermissionsLPw(pkg, replace, changingPkg); 8325 } 8326 } 8327 } 8328 8329 if (pkgInfo != null) { 8330 // Only replace for packages on requested volume 8331 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8332 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8333 && Objects.equals(replaceVolumeUuid, volumeUuid); 8334 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8335 } 8336 } 8337 8338 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8339 String packageOfInterest) { 8340 // IMPORTANT: There are two types of permissions: install and runtime. 8341 // Install time permissions are granted when the app is installed to 8342 // all device users and users added in the future. Runtime permissions 8343 // are granted at runtime explicitly to specific users. Normal and signature 8344 // protected permissions are install time permissions. Dangerous permissions 8345 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8346 // otherwise they are runtime permissions. This function does not manage 8347 // runtime permissions except for the case an app targeting Lollipop MR1 8348 // being upgraded to target a newer SDK, in which case dangerous permissions 8349 // are transformed from install time to runtime ones. 8350 8351 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8352 if (ps == null) { 8353 return; 8354 } 8355 8356 PermissionsState permissionsState = ps.getPermissionsState(); 8357 PermissionsState origPermissions = permissionsState; 8358 8359 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8360 8361 boolean runtimePermissionsRevoked = false; 8362 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8363 8364 boolean changedInstallPermission = false; 8365 8366 if (replace) { 8367 ps.installPermissionsFixed = false; 8368 if (!ps.isSharedUser()) { 8369 origPermissions = new PermissionsState(permissionsState); 8370 permissionsState.reset(); 8371 } else { 8372 // We need to know only about runtime permission changes since the 8373 // calling code always writes the install permissions state but 8374 // the runtime ones are written only if changed. The only cases of 8375 // changed runtime permissions here are promotion of an install to 8376 // runtime and revocation of a runtime from a shared user. 8377 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8378 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8379 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8380 runtimePermissionsRevoked = true; 8381 } 8382 } 8383 } 8384 8385 permissionsState.setGlobalGids(mGlobalGids); 8386 8387 final int N = pkg.requestedPermissions.size(); 8388 for (int i=0; i<N; i++) { 8389 final String name = pkg.requestedPermissions.get(i); 8390 final BasePermission bp = mSettings.mPermissions.get(name); 8391 8392 if (DEBUG_INSTALL) { 8393 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8394 } 8395 8396 if (bp == null || bp.packageSetting == null) { 8397 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8398 Slog.w(TAG, "Unknown permission " + name 8399 + " in package " + pkg.packageName); 8400 } 8401 continue; 8402 } 8403 8404 final String perm = bp.name; 8405 boolean allowedSig = false; 8406 int grant = GRANT_DENIED; 8407 8408 // Keep track of app op permissions. 8409 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8410 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8411 if (pkgs == null) { 8412 pkgs = new ArraySet<>(); 8413 mAppOpPermissionPackages.put(bp.name, pkgs); 8414 } 8415 pkgs.add(pkg.packageName); 8416 } 8417 8418 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8419 switch (level) { 8420 case PermissionInfo.PROTECTION_NORMAL: { 8421 // For all apps normal permissions are install time ones. 8422 grant = GRANT_INSTALL; 8423 } break; 8424 8425 case PermissionInfo.PROTECTION_DANGEROUS: { 8426 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8427 // For legacy apps dangerous permissions are install time ones. 8428 grant = GRANT_INSTALL_LEGACY; 8429 } else if (origPermissions.hasInstallPermission(bp.name)) { 8430 // For legacy apps that became modern, install becomes runtime. 8431 grant = GRANT_UPGRADE; 8432 } else if (mPromoteSystemApps 8433 && isSystemApp(ps) 8434 && mExistingSystemPackages.contains(ps.name)) { 8435 // For legacy system apps, install becomes runtime. 8436 // We cannot check hasInstallPermission() for system apps since those 8437 // permissions were granted implicitly and not persisted pre-M. 8438 grant = GRANT_UPGRADE; 8439 } else { 8440 // For modern apps keep runtime permissions unchanged. 8441 grant = GRANT_RUNTIME; 8442 } 8443 } break; 8444 8445 case PermissionInfo.PROTECTION_SIGNATURE: { 8446 // For all apps signature permissions are install time ones. 8447 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8448 if (allowedSig) { 8449 grant = GRANT_INSTALL; 8450 } 8451 } break; 8452 } 8453 8454 if (DEBUG_INSTALL) { 8455 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8456 } 8457 8458 if (grant != GRANT_DENIED) { 8459 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8460 // If this is an existing, non-system package, then 8461 // we can't add any new permissions to it. 8462 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8463 // Except... if this is a permission that was added 8464 // to the platform (note: need to only do this when 8465 // updating the platform). 8466 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8467 grant = GRANT_DENIED; 8468 } 8469 } 8470 } 8471 8472 switch (grant) { 8473 case GRANT_INSTALL: { 8474 // Revoke this as runtime permission to handle the case of 8475 // a runtime permission being downgraded to an install one. 8476 for (int userId : UserManagerService.getInstance().getUserIds()) { 8477 if (origPermissions.getRuntimePermissionState( 8478 bp.name, userId) != null) { 8479 // Revoke the runtime permission and clear the flags. 8480 origPermissions.revokeRuntimePermission(bp, userId); 8481 origPermissions.updatePermissionFlags(bp, userId, 8482 PackageManager.MASK_PERMISSION_FLAGS, 0); 8483 // If we revoked a permission permission, we have to write. 8484 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8485 changedRuntimePermissionUserIds, userId); 8486 } 8487 } 8488 // Grant an install permission. 8489 if (permissionsState.grantInstallPermission(bp) != 8490 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8491 changedInstallPermission = true; 8492 } 8493 } break; 8494 8495 case GRANT_INSTALL_LEGACY: { 8496 // Grant an install permission. 8497 if (permissionsState.grantInstallPermission(bp) != 8498 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8499 changedInstallPermission = true; 8500 } 8501 } break; 8502 8503 case GRANT_RUNTIME: { 8504 // Grant previously granted runtime permissions. 8505 for (int userId : UserManagerService.getInstance().getUserIds()) { 8506 PermissionState permissionState = origPermissions 8507 .getRuntimePermissionState(bp.name, userId); 8508 final int flags = permissionState != null 8509 ? permissionState.getFlags() : 0; 8510 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8511 if (permissionsState.grantRuntimePermission(bp, userId) == 8512 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8513 // If we cannot put the permission as it was, we have to write. 8514 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8515 changedRuntimePermissionUserIds, userId); 8516 } 8517 } 8518 // Propagate the permission flags. 8519 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8520 } 8521 } break; 8522 8523 case GRANT_UPGRADE: { 8524 // Grant runtime permissions for a previously held install permission. 8525 PermissionState permissionState = origPermissions 8526 .getInstallPermissionState(bp.name); 8527 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8528 8529 if (origPermissions.revokeInstallPermission(bp) 8530 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8531 // We will be transferring the permission flags, so clear them. 8532 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8533 PackageManager.MASK_PERMISSION_FLAGS, 0); 8534 changedInstallPermission = true; 8535 } 8536 8537 // If the permission is not to be promoted to runtime we ignore it and 8538 // also its other flags as they are not applicable to install permissions. 8539 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8540 for (int userId : currentUserIds) { 8541 if (permissionsState.grantRuntimePermission(bp, userId) != 8542 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8543 // Transfer the permission flags. 8544 permissionsState.updatePermissionFlags(bp, userId, 8545 flags, flags); 8546 // If we granted the permission, we have to write. 8547 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8548 changedRuntimePermissionUserIds, userId); 8549 } 8550 } 8551 } 8552 } break; 8553 8554 default: { 8555 if (packageOfInterest == null 8556 || packageOfInterest.equals(pkg.packageName)) { 8557 Slog.w(TAG, "Not granting permission " + perm 8558 + " to package " + pkg.packageName 8559 + " because it was previously installed without"); 8560 } 8561 } break; 8562 } 8563 } else { 8564 if (permissionsState.revokeInstallPermission(bp) != 8565 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8566 // Also drop the permission flags. 8567 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8568 PackageManager.MASK_PERMISSION_FLAGS, 0); 8569 changedInstallPermission = true; 8570 Slog.i(TAG, "Un-granting permission " + perm 8571 + " from package " + pkg.packageName 8572 + " (protectionLevel=" + bp.protectionLevel 8573 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8574 + ")"); 8575 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8576 // Don't print warning for app op permissions, since it is fine for them 8577 // not to be granted, there is a UI for the user to decide. 8578 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8579 Slog.w(TAG, "Not granting permission " + perm 8580 + " to package " + pkg.packageName 8581 + " (protectionLevel=" + bp.protectionLevel 8582 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8583 + ")"); 8584 } 8585 } 8586 } 8587 } 8588 8589 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8590 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8591 // This is the first that we have heard about this package, so the 8592 // permissions we have now selected are fixed until explicitly 8593 // changed. 8594 ps.installPermissionsFixed = true; 8595 } 8596 8597 // Persist the runtime permissions state for users with changes. If permissions 8598 // were revoked because no app in the shared user declares them we have to 8599 // write synchronously to avoid losing runtime permissions state. 8600 for (int userId : changedRuntimePermissionUserIds) { 8601 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8602 } 8603 } 8604 8605 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8606 boolean allowed = false; 8607 final int NP = PackageParser.NEW_PERMISSIONS.length; 8608 for (int ip=0; ip<NP; ip++) { 8609 final PackageParser.NewPermissionInfo npi 8610 = PackageParser.NEW_PERMISSIONS[ip]; 8611 if (npi.name.equals(perm) 8612 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8613 allowed = true; 8614 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8615 + pkg.packageName); 8616 break; 8617 } 8618 } 8619 return allowed; 8620 } 8621 8622 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8623 BasePermission bp, PermissionsState origPermissions) { 8624 boolean allowed; 8625 allowed = (compareSignatures( 8626 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8627 == PackageManager.SIGNATURE_MATCH) 8628 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8629 == PackageManager.SIGNATURE_MATCH); 8630 if (!allowed && (bp.protectionLevel 8631 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8632 if (isSystemApp(pkg)) { 8633 // For updated system applications, a system permission 8634 // is granted only if it had been defined by the original application. 8635 if (pkg.isUpdatedSystemApp()) { 8636 final PackageSetting sysPs = mSettings 8637 .getDisabledSystemPkgLPr(pkg.packageName); 8638 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8639 // If the original was granted this permission, we take 8640 // that grant decision as read and propagate it to the 8641 // update. 8642 if (sysPs.isPrivileged()) { 8643 allowed = true; 8644 } 8645 } else { 8646 // The system apk may have been updated with an older 8647 // version of the one on the data partition, but which 8648 // granted a new system permission that it didn't have 8649 // before. In this case we do want to allow the app to 8650 // now get the new permission if the ancestral apk is 8651 // privileged to get it. 8652 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8653 for (int j=0; 8654 j<sysPs.pkg.requestedPermissions.size(); j++) { 8655 if (perm.equals( 8656 sysPs.pkg.requestedPermissions.get(j))) { 8657 allowed = true; 8658 break; 8659 } 8660 } 8661 } 8662 } 8663 } else { 8664 allowed = isPrivilegedApp(pkg); 8665 } 8666 } 8667 } 8668 if (!allowed) { 8669 if (!allowed && (bp.protectionLevel 8670 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8671 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8672 // If this was a previously normal/dangerous permission that got moved 8673 // to a system permission as part of the runtime permission redesign, then 8674 // we still want to blindly grant it to old apps. 8675 allowed = true; 8676 } 8677 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8678 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8679 // If this permission is to be granted to the system installer and 8680 // this app is an installer, then it gets the permission. 8681 allowed = true; 8682 } 8683 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8684 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8685 // If this permission is to be granted to the system verifier and 8686 // this app is a verifier, then it gets the permission. 8687 allowed = true; 8688 } 8689 if (!allowed && (bp.protectionLevel 8690 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8691 && isSystemApp(pkg)) { 8692 // Any pre-installed system app is allowed to get this permission. 8693 allowed = true; 8694 } 8695 if (!allowed && (bp.protectionLevel 8696 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8697 // For development permissions, a development permission 8698 // is granted only if it was already granted. 8699 allowed = origPermissions.hasInstallPermission(perm); 8700 } 8701 } 8702 return allowed; 8703 } 8704 8705 final class ActivityIntentResolver 8706 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8707 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8708 boolean defaultOnly, int userId) { 8709 if (!sUserManager.exists(userId)) return null; 8710 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8711 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8712 } 8713 8714 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8715 int userId) { 8716 if (!sUserManager.exists(userId)) return null; 8717 mFlags = flags; 8718 return super.queryIntent(intent, resolvedType, 8719 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8720 } 8721 8722 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8723 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8724 if (!sUserManager.exists(userId)) return null; 8725 if (packageActivities == null) { 8726 return null; 8727 } 8728 mFlags = flags; 8729 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8730 final int N = packageActivities.size(); 8731 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8732 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8733 8734 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8735 for (int i = 0; i < N; ++i) { 8736 intentFilters = packageActivities.get(i).intents; 8737 if (intentFilters != null && intentFilters.size() > 0) { 8738 PackageParser.ActivityIntentInfo[] array = 8739 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8740 intentFilters.toArray(array); 8741 listCut.add(array); 8742 } 8743 } 8744 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8745 } 8746 8747 public final void addActivity(PackageParser.Activity a, String type) { 8748 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8749 mActivities.put(a.getComponentName(), a); 8750 if (DEBUG_SHOW_INFO) 8751 Log.v( 8752 TAG, " " + type + " " + 8753 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8754 if (DEBUG_SHOW_INFO) 8755 Log.v(TAG, " Class=" + a.info.name); 8756 final int NI = a.intents.size(); 8757 for (int j=0; j<NI; j++) { 8758 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8759 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8760 intent.setPriority(0); 8761 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8762 + a.className + " with priority > 0, forcing to 0"); 8763 } 8764 if (DEBUG_SHOW_INFO) { 8765 Log.v(TAG, " IntentFilter:"); 8766 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8767 } 8768 if (!intent.debugCheck()) { 8769 Log.w(TAG, "==> For Activity " + a.info.name); 8770 } 8771 addFilter(intent); 8772 } 8773 } 8774 8775 public final void removeActivity(PackageParser.Activity a, String type) { 8776 mActivities.remove(a.getComponentName()); 8777 if (DEBUG_SHOW_INFO) { 8778 Log.v(TAG, " " + type + " " 8779 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8780 : a.info.name) + ":"); 8781 Log.v(TAG, " Class=" + a.info.name); 8782 } 8783 final int NI = a.intents.size(); 8784 for (int j=0; j<NI; j++) { 8785 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8786 if (DEBUG_SHOW_INFO) { 8787 Log.v(TAG, " IntentFilter:"); 8788 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8789 } 8790 removeFilter(intent); 8791 } 8792 } 8793 8794 @Override 8795 protected boolean allowFilterResult( 8796 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8797 ActivityInfo filterAi = filter.activity.info; 8798 for (int i=dest.size()-1; i>=0; i--) { 8799 ActivityInfo destAi = dest.get(i).activityInfo; 8800 if (destAi.name == filterAi.name 8801 && destAi.packageName == filterAi.packageName) { 8802 return false; 8803 } 8804 } 8805 return true; 8806 } 8807 8808 @Override 8809 protected ActivityIntentInfo[] newArray(int size) { 8810 return new ActivityIntentInfo[size]; 8811 } 8812 8813 @Override 8814 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8815 if (!sUserManager.exists(userId)) return true; 8816 PackageParser.Package p = filter.activity.owner; 8817 if (p != null) { 8818 PackageSetting ps = (PackageSetting)p.mExtras; 8819 if (ps != null) { 8820 // System apps are never considered stopped for purposes of 8821 // filtering, because there may be no way for the user to 8822 // actually re-launch them. 8823 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8824 && ps.getStopped(userId); 8825 } 8826 } 8827 return false; 8828 } 8829 8830 @Override 8831 protected boolean isPackageForFilter(String packageName, 8832 PackageParser.ActivityIntentInfo info) { 8833 return packageName.equals(info.activity.owner.packageName); 8834 } 8835 8836 @Override 8837 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8838 int match, int userId) { 8839 if (!sUserManager.exists(userId)) return null; 8840 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8841 return null; 8842 } 8843 final PackageParser.Activity activity = info.activity; 8844 if (mSafeMode && (activity.info.applicationInfo.flags 8845 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8846 return null; 8847 } 8848 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8849 if (ps == null) { 8850 return null; 8851 } 8852 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8853 ps.readUserState(userId), userId); 8854 if (ai == null) { 8855 return null; 8856 } 8857 final ResolveInfo res = new ResolveInfo(); 8858 res.activityInfo = ai; 8859 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8860 res.filter = info; 8861 } 8862 if (info != null) { 8863 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8864 } 8865 res.priority = info.getPriority(); 8866 res.preferredOrder = activity.owner.mPreferredOrder; 8867 //System.out.println("Result: " + res.activityInfo.className + 8868 // " = " + res.priority); 8869 res.match = match; 8870 res.isDefault = info.hasDefault; 8871 res.labelRes = info.labelRes; 8872 res.nonLocalizedLabel = info.nonLocalizedLabel; 8873 if (userNeedsBadging(userId)) { 8874 res.noResourceId = true; 8875 } else { 8876 res.icon = info.icon; 8877 } 8878 res.iconResourceId = info.icon; 8879 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8880 return res; 8881 } 8882 8883 @Override 8884 protected void sortResults(List<ResolveInfo> results) { 8885 Collections.sort(results, mResolvePrioritySorter); 8886 } 8887 8888 @Override 8889 protected void dumpFilter(PrintWriter out, String prefix, 8890 PackageParser.ActivityIntentInfo filter) { 8891 out.print(prefix); out.print( 8892 Integer.toHexString(System.identityHashCode(filter.activity))); 8893 out.print(' '); 8894 filter.activity.printComponentShortName(out); 8895 out.print(" filter "); 8896 out.println(Integer.toHexString(System.identityHashCode(filter))); 8897 } 8898 8899 @Override 8900 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8901 return filter.activity; 8902 } 8903 8904 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8905 PackageParser.Activity activity = (PackageParser.Activity)label; 8906 out.print(prefix); out.print( 8907 Integer.toHexString(System.identityHashCode(activity))); 8908 out.print(' '); 8909 activity.printComponentShortName(out); 8910 if (count > 1) { 8911 out.print(" ("); out.print(count); out.print(" filters)"); 8912 } 8913 out.println(); 8914 } 8915 8916// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8917// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8918// final List<ResolveInfo> retList = Lists.newArrayList(); 8919// while (i.hasNext()) { 8920// final ResolveInfo resolveInfo = i.next(); 8921// if (isEnabledLP(resolveInfo.activityInfo)) { 8922// retList.add(resolveInfo); 8923// } 8924// } 8925// return retList; 8926// } 8927 8928 // Keys are String (activity class name), values are Activity. 8929 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8930 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8931 private int mFlags; 8932 } 8933 8934 private final class ServiceIntentResolver 8935 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8936 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8937 boolean defaultOnly, int userId) { 8938 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8939 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8940 } 8941 8942 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8943 int userId) { 8944 if (!sUserManager.exists(userId)) return null; 8945 mFlags = flags; 8946 return super.queryIntent(intent, resolvedType, 8947 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8948 } 8949 8950 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8951 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8952 if (!sUserManager.exists(userId)) return null; 8953 if (packageServices == null) { 8954 return null; 8955 } 8956 mFlags = flags; 8957 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8958 final int N = packageServices.size(); 8959 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8960 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8961 8962 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8963 for (int i = 0; i < N; ++i) { 8964 intentFilters = packageServices.get(i).intents; 8965 if (intentFilters != null && intentFilters.size() > 0) { 8966 PackageParser.ServiceIntentInfo[] array = 8967 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8968 intentFilters.toArray(array); 8969 listCut.add(array); 8970 } 8971 } 8972 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8973 } 8974 8975 public final void addService(PackageParser.Service s) { 8976 mServices.put(s.getComponentName(), s); 8977 if (DEBUG_SHOW_INFO) { 8978 Log.v(TAG, " " 8979 + (s.info.nonLocalizedLabel != null 8980 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8981 Log.v(TAG, " Class=" + s.info.name); 8982 } 8983 final int NI = s.intents.size(); 8984 int j; 8985 for (j=0; j<NI; j++) { 8986 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8987 if (DEBUG_SHOW_INFO) { 8988 Log.v(TAG, " IntentFilter:"); 8989 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8990 } 8991 if (!intent.debugCheck()) { 8992 Log.w(TAG, "==> For Service " + s.info.name); 8993 } 8994 addFilter(intent); 8995 } 8996 } 8997 8998 public final void removeService(PackageParser.Service s) { 8999 mServices.remove(s.getComponentName()); 9000 if (DEBUG_SHOW_INFO) { 9001 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9002 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9003 Log.v(TAG, " Class=" + s.info.name); 9004 } 9005 final int NI = s.intents.size(); 9006 int j; 9007 for (j=0; j<NI; j++) { 9008 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9009 if (DEBUG_SHOW_INFO) { 9010 Log.v(TAG, " IntentFilter:"); 9011 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9012 } 9013 removeFilter(intent); 9014 } 9015 } 9016 9017 @Override 9018 protected boolean allowFilterResult( 9019 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9020 ServiceInfo filterSi = filter.service.info; 9021 for (int i=dest.size()-1; i>=0; i--) { 9022 ServiceInfo destAi = dest.get(i).serviceInfo; 9023 if (destAi.name == filterSi.name 9024 && destAi.packageName == filterSi.packageName) { 9025 return false; 9026 } 9027 } 9028 return true; 9029 } 9030 9031 @Override 9032 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9033 return new PackageParser.ServiceIntentInfo[size]; 9034 } 9035 9036 @Override 9037 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9038 if (!sUserManager.exists(userId)) return true; 9039 PackageParser.Package p = filter.service.owner; 9040 if (p != null) { 9041 PackageSetting ps = (PackageSetting)p.mExtras; 9042 if (ps != null) { 9043 // System apps are never considered stopped for purposes of 9044 // filtering, because there may be no way for the user to 9045 // actually re-launch them. 9046 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9047 && ps.getStopped(userId); 9048 } 9049 } 9050 return false; 9051 } 9052 9053 @Override 9054 protected boolean isPackageForFilter(String packageName, 9055 PackageParser.ServiceIntentInfo info) { 9056 return packageName.equals(info.service.owner.packageName); 9057 } 9058 9059 @Override 9060 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9061 int match, int userId) { 9062 if (!sUserManager.exists(userId)) return null; 9063 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9064 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9065 return null; 9066 } 9067 final PackageParser.Service service = info.service; 9068 if (mSafeMode && (service.info.applicationInfo.flags 9069 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9070 return null; 9071 } 9072 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9073 if (ps == null) { 9074 return null; 9075 } 9076 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9077 ps.readUserState(userId), userId); 9078 if (si == null) { 9079 return null; 9080 } 9081 final ResolveInfo res = new ResolveInfo(); 9082 res.serviceInfo = si; 9083 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9084 res.filter = filter; 9085 } 9086 res.priority = info.getPriority(); 9087 res.preferredOrder = service.owner.mPreferredOrder; 9088 res.match = match; 9089 res.isDefault = info.hasDefault; 9090 res.labelRes = info.labelRes; 9091 res.nonLocalizedLabel = info.nonLocalizedLabel; 9092 res.icon = info.icon; 9093 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9094 return res; 9095 } 9096 9097 @Override 9098 protected void sortResults(List<ResolveInfo> results) { 9099 Collections.sort(results, mResolvePrioritySorter); 9100 } 9101 9102 @Override 9103 protected void dumpFilter(PrintWriter out, String prefix, 9104 PackageParser.ServiceIntentInfo filter) { 9105 out.print(prefix); out.print( 9106 Integer.toHexString(System.identityHashCode(filter.service))); 9107 out.print(' '); 9108 filter.service.printComponentShortName(out); 9109 out.print(" filter "); 9110 out.println(Integer.toHexString(System.identityHashCode(filter))); 9111 } 9112 9113 @Override 9114 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9115 return filter.service; 9116 } 9117 9118 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9119 PackageParser.Service service = (PackageParser.Service)label; 9120 out.print(prefix); out.print( 9121 Integer.toHexString(System.identityHashCode(service))); 9122 out.print(' '); 9123 service.printComponentShortName(out); 9124 if (count > 1) { 9125 out.print(" ("); out.print(count); out.print(" filters)"); 9126 } 9127 out.println(); 9128 } 9129 9130// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9131// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9132// final List<ResolveInfo> retList = Lists.newArrayList(); 9133// while (i.hasNext()) { 9134// final ResolveInfo resolveInfo = (ResolveInfo) i; 9135// if (isEnabledLP(resolveInfo.serviceInfo)) { 9136// retList.add(resolveInfo); 9137// } 9138// } 9139// return retList; 9140// } 9141 9142 // Keys are String (activity class name), values are Activity. 9143 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9144 = new ArrayMap<ComponentName, PackageParser.Service>(); 9145 private int mFlags; 9146 }; 9147 9148 private final class ProviderIntentResolver 9149 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9150 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9151 boolean defaultOnly, int userId) { 9152 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9153 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9154 } 9155 9156 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9157 int userId) { 9158 if (!sUserManager.exists(userId)) 9159 return null; 9160 mFlags = flags; 9161 return super.queryIntent(intent, resolvedType, 9162 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9163 } 9164 9165 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9166 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9167 if (!sUserManager.exists(userId)) 9168 return null; 9169 if (packageProviders == null) { 9170 return null; 9171 } 9172 mFlags = flags; 9173 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9174 final int N = packageProviders.size(); 9175 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9176 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9177 9178 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9179 for (int i = 0; i < N; ++i) { 9180 intentFilters = packageProviders.get(i).intents; 9181 if (intentFilters != null && intentFilters.size() > 0) { 9182 PackageParser.ProviderIntentInfo[] array = 9183 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9184 intentFilters.toArray(array); 9185 listCut.add(array); 9186 } 9187 } 9188 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9189 } 9190 9191 public final void addProvider(PackageParser.Provider p) { 9192 if (mProviders.containsKey(p.getComponentName())) { 9193 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9194 return; 9195 } 9196 9197 mProviders.put(p.getComponentName(), p); 9198 if (DEBUG_SHOW_INFO) { 9199 Log.v(TAG, " " 9200 + (p.info.nonLocalizedLabel != null 9201 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9202 Log.v(TAG, " Class=" + p.info.name); 9203 } 9204 final int NI = p.intents.size(); 9205 int j; 9206 for (j = 0; j < NI; j++) { 9207 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9208 if (DEBUG_SHOW_INFO) { 9209 Log.v(TAG, " IntentFilter:"); 9210 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9211 } 9212 if (!intent.debugCheck()) { 9213 Log.w(TAG, "==> For Provider " + p.info.name); 9214 } 9215 addFilter(intent); 9216 } 9217 } 9218 9219 public final void removeProvider(PackageParser.Provider p) { 9220 mProviders.remove(p.getComponentName()); 9221 if (DEBUG_SHOW_INFO) { 9222 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9223 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9224 Log.v(TAG, " Class=" + p.info.name); 9225 } 9226 final int NI = p.intents.size(); 9227 int j; 9228 for (j = 0; j < NI; j++) { 9229 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9230 if (DEBUG_SHOW_INFO) { 9231 Log.v(TAG, " IntentFilter:"); 9232 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9233 } 9234 removeFilter(intent); 9235 } 9236 } 9237 9238 @Override 9239 protected boolean allowFilterResult( 9240 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9241 ProviderInfo filterPi = filter.provider.info; 9242 for (int i = dest.size() - 1; i >= 0; i--) { 9243 ProviderInfo destPi = dest.get(i).providerInfo; 9244 if (destPi.name == filterPi.name 9245 && destPi.packageName == filterPi.packageName) { 9246 return false; 9247 } 9248 } 9249 return true; 9250 } 9251 9252 @Override 9253 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9254 return new PackageParser.ProviderIntentInfo[size]; 9255 } 9256 9257 @Override 9258 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9259 if (!sUserManager.exists(userId)) 9260 return true; 9261 PackageParser.Package p = filter.provider.owner; 9262 if (p != null) { 9263 PackageSetting ps = (PackageSetting) p.mExtras; 9264 if (ps != null) { 9265 // System apps are never considered stopped for purposes of 9266 // filtering, because there may be no way for the user to 9267 // actually re-launch them. 9268 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9269 && ps.getStopped(userId); 9270 } 9271 } 9272 return false; 9273 } 9274 9275 @Override 9276 protected boolean isPackageForFilter(String packageName, 9277 PackageParser.ProviderIntentInfo info) { 9278 return packageName.equals(info.provider.owner.packageName); 9279 } 9280 9281 @Override 9282 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9283 int match, int userId) { 9284 if (!sUserManager.exists(userId)) 9285 return null; 9286 final PackageParser.ProviderIntentInfo info = filter; 9287 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9288 return null; 9289 } 9290 final PackageParser.Provider provider = info.provider; 9291 if (mSafeMode && (provider.info.applicationInfo.flags 9292 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9293 return null; 9294 } 9295 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9296 if (ps == null) { 9297 return null; 9298 } 9299 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9300 ps.readUserState(userId), userId); 9301 if (pi == null) { 9302 return null; 9303 } 9304 final ResolveInfo res = new ResolveInfo(); 9305 res.providerInfo = pi; 9306 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9307 res.filter = filter; 9308 } 9309 res.priority = info.getPriority(); 9310 res.preferredOrder = provider.owner.mPreferredOrder; 9311 res.match = match; 9312 res.isDefault = info.hasDefault; 9313 res.labelRes = info.labelRes; 9314 res.nonLocalizedLabel = info.nonLocalizedLabel; 9315 res.icon = info.icon; 9316 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9317 return res; 9318 } 9319 9320 @Override 9321 protected void sortResults(List<ResolveInfo> results) { 9322 Collections.sort(results, mResolvePrioritySorter); 9323 } 9324 9325 @Override 9326 protected void dumpFilter(PrintWriter out, String prefix, 9327 PackageParser.ProviderIntentInfo filter) { 9328 out.print(prefix); 9329 out.print( 9330 Integer.toHexString(System.identityHashCode(filter.provider))); 9331 out.print(' '); 9332 filter.provider.printComponentShortName(out); 9333 out.print(" filter "); 9334 out.println(Integer.toHexString(System.identityHashCode(filter))); 9335 } 9336 9337 @Override 9338 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9339 return filter.provider; 9340 } 9341 9342 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9343 PackageParser.Provider provider = (PackageParser.Provider)label; 9344 out.print(prefix); out.print( 9345 Integer.toHexString(System.identityHashCode(provider))); 9346 out.print(' '); 9347 provider.printComponentShortName(out); 9348 if (count > 1) { 9349 out.print(" ("); out.print(count); out.print(" filters)"); 9350 } 9351 out.println(); 9352 } 9353 9354 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9355 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9356 private int mFlags; 9357 }; 9358 9359 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9360 new Comparator<ResolveInfo>() { 9361 public int compare(ResolveInfo r1, ResolveInfo r2) { 9362 int v1 = r1.priority; 9363 int v2 = r2.priority; 9364 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9365 if (v1 != v2) { 9366 return (v1 > v2) ? -1 : 1; 9367 } 9368 v1 = r1.preferredOrder; 9369 v2 = r2.preferredOrder; 9370 if (v1 != v2) { 9371 return (v1 > v2) ? -1 : 1; 9372 } 9373 if (r1.isDefault != r2.isDefault) { 9374 return r1.isDefault ? -1 : 1; 9375 } 9376 v1 = r1.match; 9377 v2 = r2.match; 9378 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9379 if (v1 != v2) { 9380 return (v1 > v2) ? -1 : 1; 9381 } 9382 if (r1.system != r2.system) { 9383 return r1.system ? -1 : 1; 9384 } 9385 return 0; 9386 } 9387 }; 9388 9389 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9390 new Comparator<ProviderInfo>() { 9391 public int compare(ProviderInfo p1, ProviderInfo p2) { 9392 final int v1 = p1.initOrder; 9393 final int v2 = p2.initOrder; 9394 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9395 } 9396 }; 9397 9398 final void sendPackageBroadcast(final String action, final String pkg, 9399 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9400 final int[] userIds) { 9401 mHandler.post(new Runnable() { 9402 @Override 9403 public void run() { 9404 try { 9405 final IActivityManager am = ActivityManagerNative.getDefault(); 9406 if (am == null) return; 9407 final int[] resolvedUserIds; 9408 if (userIds == null) { 9409 resolvedUserIds = am.getRunningUserIds(); 9410 } else { 9411 resolvedUserIds = userIds; 9412 } 9413 for (int id : resolvedUserIds) { 9414 final Intent intent = new Intent(action, 9415 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9416 if (extras != null) { 9417 intent.putExtras(extras); 9418 } 9419 if (targetPkg != null) { 9420 intent.setPackage(targetPkg); 9421 } 9422 // Modify the UID when posting to other users 9423 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9424 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9425 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9426 intent.putExtra(Intent.EXTRA_UID, uid); 9427 } 9428 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9429 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9430 if (DEBUG_BROADCASTS) { 9431 RuntimeException here = new RuntimeException("here"); 9432 here.fillInStackTrace(); 9433 Slog.d(TAG, "Sending to user " + id + ": " 9434 + intent.toShortString(false, true, false, false) 9435 + " " + intent.getExtras(), here); 9436 } 9437 am.broadcastIntent(null, intent, null, finishedReceiver, 9438 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9439 null, finishedReceiver != null, false, id); 9440 } 9441 } catch (RemoteException ex) { 9442 } 9443 } 9444 }); 9445 } 9446 9447 /** 9448 * Check if the external storage media is available. This is true if there 9449 * is a mounted external storage medium or if the external storage is 9450 * emulated. 9451 */ 9452 private boolean isExternalMediaAvailable() { 9453 return mMediaMounted || Environment.isExternalStorageEmulated(); 9454 } 9455 9456 @Override 9457 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9458 // writer 9459 synchronized (mPackages) { 9460 if (!isExternalMediaAvailable()) { 9461 // If the external storage is no longer mounted at this point, 9462 // the caller may not have been able to delete all of this 9463 // packages files and can not delete any more. Bail. 9464 return null; 9465 } 9466 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9467 if (lastPackage != null) { 9468 pkgs.remove(lastPackage); 9469 } 9470 if (pkgs.size() > 0) { 9471 return pkgs.get(0); 9472 } 9473 } 9474 return null; 9475 } 9476 9477 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9478 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9479 userId, andCode ? 1 : 0, packageName); 9480 if (mSystemReady) { 9481 msg.sendToTarget(); 9482 } else { 9483 if (mPostSystemReadyMessages == null) { 9484 mPostSystemReadyMessages = new ArrayList<>(); 9485 } 9486 mPostSystemReadyMessages.add(msg); 9487 } 9488 } 9489 9490 void startCleaningPackages() { 9491 // reader 9492 synchronized (mPackages) { 9493 if (!isExternalMediaAvailable()) { 9494 return; 9495 } 9496 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9497 return; 9498 } 9499 } 9500 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9501 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9502 IActivityManager am = ActivityManagerNative.getDefault(); 9503 if (am != null) { 9504 try { 9505 am.startService(null, intent, null, mContext.getOpPackageName(), 9506 UserHandle.USER_OWNER); 9507 } catch (RemoteException e) { 9508 } 9509 } 9510 } 9511 9512 @Override 9513 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9514 int installFlags, String installerPackageName, VerificationParams verificationParams, 9515 String packageAbiOverride) { 9516 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9517 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9518 } 9519 9520 @Override 9521 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9522 int installFlags, String installerPackageName, VerificationParams verificationParams, 9523 String packageAbiOverride, int userId) { 9524 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9525 9526 final int callingUid = Binder.getCallingUid(); 9527 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9528 9529 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9530 try { 9531 if (observer != null) { 9532 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9533 } 9534 } catch (RemoteException re) { 9535 } 9536 return; 9537 } 9538 9539 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9540 installFlags |= PackageManager.INSTALL_FROM_ADB; 9541 9542 } else { 9543 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9544 // about installerPackageName. 9545 9546 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9547 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9548 } 9549 9550 UserHandle user; 9551 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9552 user = UserHandle.ALL; 9553 } else { 9554 user = new UserHandle(userId); 9555 } 9556 9557 // Only system components can circumvent runtime permissions when installing. 9558 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9559 && mContext.checkCallingOrSelfPermission(Manifest.permission 9560 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9561 throw new SecurityException("You need the " 9562 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9563 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9564 } 9565 9566 verificationParams.setInstallerUid(callingUid); 9567 9568 final File originFile = new File(originPath); 9569 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9570 9571 final Message msg = mHandler.obtainMessage(INIT_COPY); 9572 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9573 null, verificationParams, user, packageAbiOverride, null); 9574 mHandler.sendMessage(msg); 9575 } 9576 9577 void installStage(String packageName, File stagedDir, String stagedCid, 9578 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9579 String installerPackageName, int installerUid, UserHandle user) { 9580 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9581 params.referrerUri, installerUid, null); 9582 verifParams.setInstallerUid(installerUid); 9583 9584 final OriginInfo origin; 9585 if (stagedDir != null) { 9586 origin = OriginInfo.fromStagedFile(stagedDir); 9587 } else { 9588 origin = OriginInfo.fromStagedContainer(stagedCid); 9589 } 9590 9591 final Message msg = mHandler.obtainMessage(INIT_COPY); 9592 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9593 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9594 params.grantedRuntimePermissions); 9595 mHandler.sendMessage(msg); 9596 } 9597 9598 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9599 Bundle extras = new Bundle(1); 9600 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9601 9602 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9603 packageName, extras, null, null, new int[] {userId}); 9604 try { 9605 IActivityManager am = ActivityManagerNative.getDefault(); 9606 final boolean isSystem = 9607 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9608 if (isSystem && am.isUserRunning(userId, false)) { 9609 // The just-installed/enabled app is bundled on the system, so presumed 9610 // to be able to run automatically without needing an explicit launch. 9611 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9612 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9613 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9614 .setPackage(packageName); 9615 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9616 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9617 } 9618 } catch (RemoteException e) { 9619 // shouldn't happen 9620 Slog.w(TAG, "Unable to bootstrap installed package", e); 9621 } 9622 } 9623 9624 @Override 9625 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9626 int userId) { 9627 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9628 PackageSetting pkgSetting; 9629 final int uid = Binder.getCallingUid(); 9630 enforceCrossUserPermission(uid, userId, true, true, 9631 "setApplicationHiddenSetting for user " + userId); 9632 9633 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9634 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9635 return false; 9636 } 9637 9638 long callingId = Binder.clearCallingIdentity(); 9639 try { 9640 boolean sendAdded = false; 9641 boolean sendRemoved = false; 9642 // writer 9643 synchronized (mPackages) { 9644 pkgSetting = mSettings.mPackages.get(packageName); 9645 if (pkgSetting == null) { 9646 return false; 9647 } 9648 if (pkgSetting.getHidden(userId) != hidden) { 9649 pkgSetting.setHidden(hidden, userId); 9650 mSettings.writePackageRestrictionsLPr(userId); 9651 if (hidden) { 9652 sendRemoved = true; 9653 } else { 9654 sendAdded = true; 9655 } 9656 } 9657 } 9658 if (sendAdded) { 9659 sendPackageAddedForUser(packageName, pkgSetting, userId); 9660 return true; 9661 } 9662 if (sendRemoved) { 9663 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9664 "hiding pkg"); 9665 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9666 return true; 9667 } 9668 } finally { 9669 Binder.restoreCallingIdentity(callingId); 9670 } 9671 return false; 9672 } 9673 9674 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9675 int userId) { 9676 final PackageRemovedInfo info = new PackageRemovedInfo(); 9677 info.removedPackage = packageName; 9678 info.removedUsers = new int[] {userId}; 9679 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9680 info.sendBroadcast(false, false, false); 9681 } 9682 9683 /** 9684 * Returns true if application is not found or there was an error. Otherwise it returns 9685 * the hidden state of the package for the given user. 9686 */ 9687 @Override 9688 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9689 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9690 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9691 false, "getApplicationHidden for user " + userId); 9692 PackageSetting pkgSetting; 9693 long callingId = Binder.clearCallingIdentity(); 9694 try { 9695 // writer 9696 synchronized (mPackages) { 9697 pkgSetting = mSettings.mPackages.get(packageName); 9698 if (pkgSetting == null) { 9699 return true; 9700 } 9701 return pkgSetting.getHidden(userId); 9702 } 9703 } finally { 9704 Binder.restoreCallingIdentity(callingId); 9705 } 9706 } 9707 9708 /** 9709 * @hide 9710 */ 9711 @Override 9712 public int installExistingPackageAsUser(String packageName, int userId) { 9713 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9714 null); 9715 PackageSetting pkgSetting; 9716 final int uid = Binder.getCallingUid(); 9717 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9718 + userId); 9719 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9720 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9721 } 9722 9723 long callingId = Binder.clearCallingIdentity(); 9724 try { 9725 boolean sendAdded = false; 9726 9727 // writer 9728 synchronized (mPackages) { 9729 pkgSetting = mSettings.mPackages.get(packageName); 9730 if (pkgSetting == null) { 9731 return PackageManager.INSTALL_FAILED_INVALID_URI; 9732 } 9733 if (!pkgSetting.getInstalled(userId)) { 9734 pkgSetting.setInstalled(true, userId); 9735 pkgSetting.setHidden(false, userId); 9736 mSettings.writePackageRestrictionsLPr(userId); 9737 sendAdded = true; 9738 } 9739 } 9740 9741 if (sendAdded) { 9742 sendPackageAddedForUser(packageName, pkgSetting, userId); 9743 } 9744 } finally { 9745 Binder.restoreCallingIdentity(callingId); 9746 } 9747 9748 return PackageManager.INSTALL_SUCCEEDED; 9749 } 9750 9751 boolean isUserRestricted(int userId, String restrictionKey) { 9752 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9753 if (restrictions.getBoolean(restrictionKey, false)) { 9754 Log.w(TAG, "User is restricted: " + restrictionKey); 9755 return true; 9756 } 9757 return false; 9758 } 9759 9760 @Override 9761 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9762 mContext.enforceCallingOrSelfPermission( 9763 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9764 "Only package verification agents can verify applications"); 9765 9766 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9767 final PackageVerificationResponse response = new PackageVerificationResponse( 9768 verificationCode, Binder.getCallingUid()); 9769 msg.arg1 = id; 9770 msg.obj = response; 9771 mHandler.sendMessage(msg); 9772 } 9773 9774 @Override 9775 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9776 long millisecondsToDelay) { 9777 mContext.enforceCallingOrSelfPermission( 9778 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9779 "Only package verification agents can extend verification timeouts"); 9780 9781 final PackageVerificationState state = mPendingVerification.get(id); 9782 final PackageVerificationResponse response = new PackageVerificationResponse( 9783 verificationCodeAtTimeout, Binder.getCallingUid()); 9784 9785 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9786 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9787 } 9788 if (millisecondsToDelay < 0) { 9789 millisecondsToDelay = 0; 9790 } 9791 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9792 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9793 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9794 } 9795 9796 if ((state != null) && !state.timeoutExtended()) { 9797 state.extendTimeout(); 9798 9799 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9800 msg.arg1 = id; 9801 msg.obj = response; 9802 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9803 } 9804 } 9805 9806 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9807 int verificationCode, UserHandle user) { 9808 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9809 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9810 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9811 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9812 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9813 9814 mContext.sendBroadcastAsUser(intent, user, 9815 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9816 } 9817 9818 private ComponentName matchComponentForVerifier(String packageName, 9819 List<ResolveInfo> receivers) { 9820 ActivityInfo targetReceiver = null; 9821 9822 final int NR = receivers.size(); 9823 for (int i = 0; i < NR; i++) { 9824 final ResolveInfo info = receivers.get(i); 9825 if (info.activityInfo == null) { 9826 continue; 9827 } 9828 9829 if (packageName.equals(info.activityInfo.packageName)) { 9830 targetReceiver = info.activityInfo; 9831 break; 9832 } 9833 } 9834 9835 if (targetReceiver == null) { 9836 return null; 9837 } 9838 9839 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9840 } 9841 9842 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9843 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9844 if (pkgInfo.verifiers.length == 0) { 9845 return null; 9846 } 9847 9848 final int N = pkgInfo.verifiers.length; 9849 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9850 for (int i = 0; i < N; i++) { 9851 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9852 9853 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9854 receivers); 9855 if (comp == null) { 9856 continue; 9857 } 9858 9859 final int verifierUid = getUidForVerifier(verifierInfo); 9860 if (verifierUid == -1) { 9861 continue; 9862 } 9863 9864 if (DEBUG_VERIFY) { 9865 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9866 + " with the correct signature"); 9867 } 9868 sufficientVerifiers.add(comp); 9869 verificationState.addSufficientVerifier(verifierUid); 9870 } 9871 9872 return sufficientVerifiers; 9873 } 9874 9875 private int getUidForVerifier(VerifierInfo verifierInfo) { 9876 synchronized (mPackages) { 9877 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9878 if (pkg == null) { 9879 return -1; 9880 } else if (pkg.mSignatures.length != 1) { 9881 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9882 + " has more than one signature; ignoring"); 9883 return -1; 9884 } 9885 9886 /* 9887 * If the public key of the package's signature does not match 9888 * our expected public key, then this is a different package and 9889 * we should skip. 9890 */ 9891 9892 final byte[] expectedPublicKey; 9893 try { 9894 final Signature verifierSig = pkg.mSignatures[0]; 9895 final PublicKey publicKey = verifierSig.getPublicKey(); 9896 expectedPublicKey = publicKey.getEncoded(); 9897 } catch (CertificateException e) { 9898 return -1; 9899 } 9900 9901 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9902 9903 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9904 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9905 + " does not have the expected public key; ignoring"); 9906 return -1; 9907 } 9908 9909 return pkg.applicationInfo.uid; 9910 } 9911 } 9912 9913 @Override 9914 public void finishPackageInstall(int token) { 9915 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9916 9917 if (DEBUG_INSTALL) { 9918 Slog.v(TAG, "BM finishing package install for " + token); 9919 } 9920 9921 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9922 mHandler.sendMessage(msg); 9923 } 9924 9925 /** 9926 * Get the verification agent timeout. 9927 * 9928 * @return verification timeout in milliseconds 9929 */ 9930 private long getVerificationTimeout() { 9931 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9932 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9933 DEFAULT_VERIFICATION_TIMEOUT); 9934 } 9935 9936 /** 9937 * Get the default verification agent response code. 9938 * 9939 * @return default verification response code 9940 */ 9941 private int getDefaultVerificationResponse() { 9942 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9943 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9944 DEFAULT_VERIFICATION_RESPONSE); 9945 } 9946 9947 /** 9948 * Check whether or not package verification has been enabled. 9949 * 9950 * @return true if verification should be performed 9951 */ 9952 private boolean isVerificationEnabled(int userId, int installFlags) { 9953 if (!DEFAULT_VERIFY_ENABLE) { 9954 return false; 9955 } 9956 9957 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9958 9959 // Check if installing from ADB 9960 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9961 // Do not run verification in a test harness environment 9962 if (ActivityManager.isRunningInTestHarness()) { 9963 return false; 9964 } 9965 if (ensureVerifyAppsEnabled) { 9966 return true; 9967 } 9968 // Check if the developer does not want package verification for ADB installs 9969 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9970 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9971 return false; 9972 } 9973 } 9974 9975 if (ensureVerifyAppsEnabled) { 9976 return true; 9977 } 9978 9979 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9980 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9981 } 9982 9983 @Override 9984 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9985 throws RemoteException { 9986 mContext.enforceCallingOrSelfPermission( 9987 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9988 "Only intentfilter verification agents can verify applications"); 9989 9990 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9991 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9992 Binder.getCallingUid(), verificationCode, failedDomains); 9993 msg.arg1 = id; 9994 msg.obj = response; 9995 mHandler.sendMessage(msg); 9996 } 9997 9998 @Override 9999 public int getIntentVerificationStatus(String packageName, int userId) { 10000 synchronized (mPackages) { 10001 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10002 } 10003 } 10004 10005 @Override 10006 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10007 mContext.enforceCallingOrSelfPermission( 10008 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10009 10010 boolean result = false; 10011 synchronized (mPackages) { 10012 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10013 } 10014 if (result) { 10015 scheduleWritePackageRestrictionsLocked(userId); 10016 } 10017 return result; 10018 } 10019 10020 @Override 10021 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10022 synchronized (mPackages) { 10023 return mSettings.getIntentFilterVerificationsLPr(packageName); 10024 } 10025 } 10026 10027 @Override 10028 public List<IntentFilter> getAllIntentFilters(String packageName) { 10029 if (TextUtils.isEmpty(packageName)) { 10030 return Collections.<IntentFilter>emptyList(); 10031 } 10032 synchronized (mPackages) { 10033 PackageParser.Package pkg = mPackages.get(packageName); 10034 if (pkg == null || pkg.activities == null) { 10035 return Collections.<IntentFilter>emptyList(); 10036 } 10037 final int count = pkg.activities.size(); 10038 ArrayList<IntentFilter> result = new ArrayList<>(); 10039 for (int n=0; n<count; n++) { 10040 PackageParser.Activity activity = pkg.activities.get(n); 10041 if (activity.intents != null || activity.intents.size() > 0) { 10042 result.addAll(activity.intents); 10043 } 10044 } 10045 return result; 10046 } 10047 } 10048 10049 @Override 10050 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10051 mContext.enforceCallingOrSelfPermission( 10052 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10053 10054 synchronized (mPackages) { 10055 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10056 if (packageName != null) { 10057 result |= updateIntentVerificationStatus(packageName, 10058 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10059 userId); 10060 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10061 packageName, userId); 10062 } 10063 return result; 10064 } 10065 } 10066 10067 @Override 10068 public String getDefaultBrowserPackageName(int userId) { 10069 synchronized (mPackages) { 10070 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10071 } 10072 } 10073 10074 /** 10075 * Get the "allow unknown sources" setting. 10076 * 10077 * @return the current "allow unknown sources" setting 10078 */ 10079 private int getUnknownSourcesSettings() { 10080 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10081 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10082 -1); 10083 } 10084 10085 @Override 10086 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10087 final int uid = Binder.getCallingUid(); 10088 // writer 10089 synchronized (mPackages) { 10090 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10091 if (targetPackageSetting == null) { 10092 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10093 } 10094 10095 PackageSetting installerPackageSetting; 10096 if (installerPackageName != null) { 10097 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10098 if (installerPackageSetting == null) { 10099 throw new IllegalArgumentException("Unknown installer package: " 10100 + installerPackageName); 10101 } 10102 } else { 10103 installerPackageSetting = null; 10104 } 10105 10106 Signature[] callerSignature; 10107 Object obj = mSettings.getUserIdLPr(uid); 10108 if (obj != null) { 10109 if (obj instanceof SharedUserSetting) { 10110 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10111 } else if (obj instanceof PackageSetting) { 10112 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10113 } else { 10114 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10115 } 10116 } else { 10117 throw new SecurityException("Unknown calling uid " + uid); 10118 } 10119 10120 // Verify: can't set installerPackageName to a package that is 10121 // not signed with the same cert as the caller. 10122 if (installerPackageSetting != null) { 10123 if (compareSignatures(callerSignature, 10124 installerPackageSetting.signatures.mSignatures) 10125 != PackageManager.SIGNATURE_MATCH) { 10126 throw new SecurityException( 10127 "Caller does not have same cert as new installer package " 10128 + installerPackageName); 10129 } 10130 } 10131 10132 // Verify: if target already has an installer package, it must 10133 // be signed with the same cert as the caller. 10134 if (targetPackageSetting.installerPackageName != null) { 10135 PackageSetting setting = mSettings.mPackages.get( 10136 targetPackageSetting.installerPackageName); 10137 // If the currently set package isn't valid, then it's always 10138 // okay to change it. 10139 if (setting != null) { 10140 if (compareSignatures(callerSignature, 10141 setting.signatures.mSignatures) 10142 != PackageManager.SIGNATURE_MATCH) { 10143 throw new SecurityException( 10144 "Caller does not have same cert as old installer package " 10145 + targetPackageSetting.installerPackageName); 10146 } 10147 } 10148 } 10149 10150 // Okay! 10151 targetPackageSetting.installerPackageName = installerPackageName; 10152 scheduleWriteSettingsLocked(); 10153 } 10154 } 10155 10156 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10157 // Queue up an async operation since the package installation may take a little while. 10158 mHandler.post(new Runnable() { 10159 public void run() { 10160 mHandler.removeCallbacks(this); 10161 // Result object to be returned 10162 PackageInstalledInfo res = new PackageInstalledInfo(); 10163 res.returnCode = currentStatus; 10164 res.uid = -1; 10165 res.pkg = null; 10166 res.removedInfo = new PackageRemovedInfo(); 10167 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10168 args.doPreInstall(res.returnCode); 10169 synchronized (mInstallLock) { 10170 installPackageLI(args, res); 10171 } 10172 args.doPostInstall(res.returnCode, res.uid); 10173 } 10174 10175 // A restore should be performed at this point if (a) the install 10176 // succeeded, (b) the operation is not an update, and (c) the new 10177 // package has not opted out of backup participation. 10178 final boolean update = res.removedInfo.removedPackage != null; 10179 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10180 boolean doRestore = !update 10181 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10182 10183 // Set up the post-install work request bookkeeping. This will be used 10184 // and cleaned up by the post-install event handling regardless of whether 10185 // there's a restore pass performed. Token values are >= 1. 10186 int token; 10187 if (mNextInstallToken < 0) mNextInstallToken = 1; 10188 token = mNextInstallToken++; 10189 10190 PostInstallData data = new PostInstallData(args, res); 10191 mRunningInstalls.put(token, data); 10192 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10193 10194 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10195 // Pass responsibility to the Backup Manager. It will perform a 10196 // restore if appropriate, then pass responsibility back to the 10197 // Package Manager to run the post-install observer callbacks 10198 // and broadcasts. 10199 IBackupManager bm = IBackupManager.Stub.asInterface( 10200 ServiceManager.getService(Context.BACKUP_SERVICE)); 10201 if (bm != null) { 10202 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10203 + " to BM for possible restore"); 10204 try { 10205 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10206 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10207 } else { 10208 doRestore = false; 10209 } 10210 } catch (RemoteException e) { 10211 // can't happen; the backup manager is local 10212 } catch (Exception e) { 10213 Slog.e(TAG, "Exception trying to enqueue restore", e); 10214 doRestore = false; 10215 } 10216 } else { 10217 Slog.e(TAG, "Backup Manager not found!"); 10218 doRestore = false; 10219 } 10220 } 10221 10222 if (!doRestore) { 10223 // No restore possible, or the Backup Manager was mysteriously not 10224 // available -- just fire the post-install work request directly. 10225 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10226 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10227 mHandler.sendMessage(msg); 10228 } 10229 } 10230 }); 10231 } 10232 10233 private abstract class HandlerParams { 10234 private static final int MAX_RETRIES = 4; 10235 10236 /** 10237 * Number of times startCopy() has been attempted and had a non-fatal 10238 * error. 10239 */ 10240 private int mRetries = 0; 10241 10242 /** User handle for the user requesting the information or installation. */ 10243 private final UserHandle mUser; 10244 10245 HandlerParams(UserHandle user) { 10246 mUser = user; 10247 } 10248 10249 UserHandle getUser() { 10250 return mUser; 10251 } 10252 10253 final boolean startCopy() { 10254 boolean res; 10255 try { 10256 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10257 10258 if (++mRetries > MAX_RETRIES) { 10259 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10260 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10261 handleServiceError(); 10262 return false; 10263 } else { 10264 handleStartCopy(); 10265 res = true; 10266 } 10267 } catch (RemoteException e) { 10268 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10269 mHandler.sendEmptyMessage(MCS_RECONNECT); 10270 res = false; 10271 } 10272 handleReturnCode(); 10273 return res; 10274 } 10275 10276 final void serviceError() { 10277 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10278 handleServiceError(); 10279 handleReturnCode(); 10280 } 10281 10282 abstract void handleStartCopy() throws RemoteException; 10283 abstract void handleServiceError(); 10284 abstract void handleReturnCode(); 10285 } 10286 10287 class MeasureParams extends HandlerParams { 10288 private final PackageStats mStats; 10289 private boolean mSuccess; 10290 10291 private final IPackageStatsObserver mObserver; 10292 10293 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10294 super(new UserHandle(stats.userHandle)); 10295 mObserver = observer; 10296 mStats = stats; 10297 } 10298 10299 @Override 10300 public String toString() { 10301 return "MeasureParams{" 10302 + Integer.toHexString(System.identityHashCode(this)) 10303 + " " + mStats.packageName + "}"; 10304 } 10305 10306 @Override 10307 void handleStartCopy() throws RemoteException { 10308 synchronized (mInstallLock) { 10309 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10310 } 10311 10312 if (mSuccess) { 10313 final boolean mounted; 10314 if (Environment.isExternalStorageEmulated()) { 10315 mounted = true; 10316 } else { 10317 final String status = Environment.getExternalStorageState(); 10318 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10319 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10320 } 10321 10322 if (mounted) { 10323 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10324 10325 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10326 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10327 10328 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10329 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10330 10331 // Always subtract cache size, since it's a subdirectory 10332 mStats.externalDataSize -= mStats.externalCacheSize; 10333 10334 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10335 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10336 10337 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10338 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10339 } 10340 } 10341 } 10342 10343 @Override 10344 void handleReturnCode() { 10345 if (mObserver != null) { 10346 try { 10347 mObserver.onGetStatsCompleted(mStats, mSuccess); 10348 } catch (RemoteException e) { 10349 Slog.i(TAG, "Observer no longer exists."); 10350 } 10351 } 10352 } 10353 10354 @Override 10355 void handleServiceError() { 10356 Slog.e(TAG, "Could not measure application " + mStats.packageName 10357 + " external storage"); 10358 } 10359 } 10360 10361 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10362 throws RemoteException { 10363 long result = 0; 10364 for (File path : paths) { 10365 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10366 } 10367 return result; 10368 } 10369 10370 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10371 for (File path : paths) { 10372 try { 10373 mcs.clearDirectory(path.getAbsolutePath()); 10374 } catch (RemoteException e) { 10375 } 10376 } 10377 } 10378 10379 static class OriginInfo { 10380 /** 10381 * Location where install is coming from, before it has been 10382 * copied/renamed into place. This could be a single monolithic APK 10383 * file, or a cluster directory. This location may be untrusted. 10384 */ 10385 final File file; 10386 final String cid; 10387 10388 /** 10389 * Flag indicating that {@link #file} or {@link #cid} has already been 10390 * staged, meaning downstream users don't need to defensively copy the 10391 * contents. 10392 */ 10393 final boolean staged; 10394 10395 /** 10396 * Flag indicating that {@link #file} or {@link #cid} is an already 10397 * installed app that is being moved. 10398 */ 10399 final boolean existing; 10400 10401 final String resolvedPath; 10402 final File resolvedFile; 10403 10404 static OriginInfo fromNothing() { 10405 return new OriginInfo(null, null, false, false); 10406 } 10407 10408 static OriginInfo fromUntrustedFile(File file) { 10409 return new OriginInfo(file, null, false, false); 10410 } 10411 10412 static OriginInfo fromExistingFile(File file) { 10413 return new OriginInfo(file, null, false, true); 10414 } 10415 10416 static OriginInfo fromStagedFile(File file) { 10417 return new OriginInfo(file, null, true, false); 10418 } 10419 10420 static OriginInfo fromStagedContainer(String cid) { 10421 return new OriginInfo(null, cid, true, false); 10422 } 10423 10424 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10425 this.file = file; 10426 this.cid = cid; 10427 this.staged = staged; 10428 this.existing = existing; 10429 10430 if (cid != null) { 10431 resolvedPath = PackageHelper.getSdDir(cid); 10432 resolvedFile = new File(resolvedPath); 10433 } else if (file != null) { 10434 resolvedPath = file.getAbsolutePath(); 10435 resolvedFile = file; 10436 } else { 10437 resolvedPath = null; 10438 resolvedFile = null; 10439 } 10440 } 10441 } 10442 10443 class MoveInfo { 10444 final int moveId; 10445 final String fromUuid; 10446 final String toUuid; 10447 final String packageName; 10448 final String dataAppName; 10449 final int appId; 10450 final String seinfo; 10451 10452 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10453 String dataAppName, int appId, String seinfo) { 10454 this.moveId = moveId; 10455 this.fromUuid = fromUuid; 10456 this.toUuid = toUuid; 10457 this.packageName = packageName; 10458 this.dataAppName = dataAppName; 10459 this.appId = appId; 10460 this.seinfo = seinfo; 10461 } 10462 } 10463 10464 class InstallParams extends HandlerParams { 10465 final OriginInfo origin; 10466 final MoveInfo move; 10467 final IPackageInstallObserver2 observer; 10468 int installFlags; 10469 final String installerPackageName; 10470 final String volumeUuid; 10471 final VerificationParams verificationParams; 10472 private InstallArgs mArgs; 10473 private int mRet; 10474 final String packageAbiOverride; 10475 final String[] grantedRuntimePermissions; 10476 10477 10478 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10479 int installFlags, String installerPackageName, String volumeUuid, 10480 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10481 String[] grantedPermissions) { 10482 super(user); 10483 this.origin = origin; 10484 this.move = move; 10485 this.observer = observer; 10486 this.installFlags = installFlags; 10487 this.installerPackageName = installerPackageName; 10488 this.volumeUuid = volumeUuid; 10489 this.verificationParams = verificationParams; 10490 this.packageAbiOverride = packageAbiOverride; 10491 this.grantedRuntimePermissions = grantedPermissions; 10492 } 10493 10494 @Override 10495 public String toString() { 10496 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10497 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10498 } 10499 10500 public ManifestDigest getManifestDigest() { 10501 if (verificationParams == null) { 10502 return null; 10503 } 10504 return verificationParams.getManifestDigest(); 10505 } 10506 10507 private int installLocationPolicy(PackageInfoLite pkgLite) { 10508 String packageName = pkgLite.packageName; 10509 int installLocation = pkgLite.installLocation; 10510 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10511 // reader 10512 synchronized (mPackages) { 10513 PackageParser.Package pkg = mPackages.get(packageName); 10514 if (pkg != null) { 10515 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10516 // Check for downgrading. 10517 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10518 try { 10519 checkDowngrade(pkg, pkgLite); 10520 } catch (PackageManagerException e) { 10521 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10522 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10523 } 10524 } 10525 // Check for updated system application. 10526 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10527 if (onSd) { 10528 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10529 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10530 } 10531 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10532 } else { 10533 if (onSd) { 10534 // Install flag overrides everything. 10535 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10536 } 10537 // If current upgrade specifies particular preference 10538 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10539 // Application explicitly specified internal. 10540 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10541 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10542 // App explictly prefers external. Let policy decide 10543 } else { 10544 // Prefer previous location 10545 if (isExternal(pkg)) { 10546 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10547 } 10548 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10549 } 10550 } 10551 } else { 10552 // Invalid install. Return error code 10553 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10554 } 10555 } 10556 } 10557 // All the special cases have been taken care of. 10558 // Return result based on recommended install location. 10559 if (onSd) { 10560 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10561 } 10562 return pkgLite.recommendedInstallLocation; 10563 } 10564 10565 /* 10566 * Invoke remote method to get package information and install 10567 * location values. Override install location based on default 10568 * policy if needed and then create install arguments based 10569 * on the install location. 10570 */ 10571 public void handleStartCopy() throws RemoteException { 10572 int ret = PackageManager.INSTALL_SUCCEEDED; 10573 10574 // If we're already staged, we've firmly committed to an install location 10575 if (origin.staged) { 10576 if (origin.file != null) { 10577 installFlags |= PackageManager.INSTALL_INTERNAL; 10578 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10579 } else if (origin.cid != null) { 10580 installFlags |= PackageManager.INSTALL_EXTERNAL; 10581 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10582 } else { 10583 throw new IllegalStateException("Invalid stage location"); 10584 } 10585 } 10586 10587 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10588 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10589 10590 PackageInfoLite pkgLite = null; 10591 10592 if (onInt && onSd) { 10593 // Check if both bits are set. 10594 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10595 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10596 } else { 10597 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10598 packageAbiOverride); 10599 10600 /* 10601 * If we have too little free space, try to free cache 10602 * before giving up. 10603 */ 10604 if (!origin.staged && pkgLite.recommendedInstallLocation 10605 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10606 // TODO: focus freeing disk space on the target device 10607 final StorageManager storage = StorageManager.from(mContext); 10608 final long lowThreshold = storage.getStorageLowBytes( 10609 Environment.getDataDirectory()); 10610 10611 final long sizeBytes = mContainerService.calculateInstalledSize( 10612 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10613 10614 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10615 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10616 installFlags, packageAbiOverride); 10617 } 10618 10619 /* 10620 * The cache free must have deleted the file we 10621 * downloaded to install. 10622 * 10623 * TODO: fix the "freeCache" call to not delete 10624 * the file we care about. 10625 */ 10626 if (pkgLite.recommendedInstallLocation 10627 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10628 pkgLite.recommendedInstallLocation 10629 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10630 } 10631 } 10632 } 10633 10634 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10635 int loc = pkgLite.recommendedInstallLocation; 10636 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10637 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10638 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10639 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10640 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10641 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10642 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10643 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10644 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10645 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10646 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10647 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10648 } else { 10649 // Override with defaults if needed. 10650 loc = installLocationPolicy(pkgLite); 10651 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10652 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10653 } else if (!onSd && !onInt) { 10654 // Override install location with flags 10655 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10656 // Set the flag to install on external media. 10657 installFlags |= PackageManager.INSTALL_EXTERNAL; 10658 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10659 } else { 10660 // Make sure the flag for installing on external 10661 // media is unset 10662 installFlags |= PackageManager.INSTALL_INTERNAL; 10663 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10664 } 10665 } 10666 } 10667 } 10668 10669 final InstallArgs args = createInstallArgs(this); 10670 mArgs = args; 10671 10672 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10673 /* 10674 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10675 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10676 */ 10677 int userIdentifier = getUser().getIdentifier(); 10678 if (userIdentifier == UserHandle.USER_ALL 10679 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10680 userIdentifier = UserHandle.USER_OWNER; 10681 } 10682 10683 /* 10684 * Determine if we have any installed package verifiers. If we 10685 * do, then we'll defer to them to verify the packages. 10686 */ 10687 final int requiredUid = mRequiredVerifierPackage == null ? -1 10688 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10689 if (!origin.existing && requiredUid != -1 10690 && isVerificationEnabled(userIdentifier, installFlags)) { 10691 final Intent verification = new Intent( 10692 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10693 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10694 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10695 PACKAGE_MIME_TYPE); 10696 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10697 10698 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10699 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10700 0 /* TODO: Which userId? */); 10701 10702 if (DEBUG_VERIFY) { 10703 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10704 + verification.toString() + " with " + pkgLite.verifiers.length 10705 + " optional verifiers"); 10706 } 10707 10708 final int verificationId = mPendingVerificationToken++; 10709 10710 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10711 10712 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10713 installerPackageName); 10714 10715 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10716 installFlags); 10717 10718 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10719 pkgLite.packageName); 10720 10721 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10722 pkgLite.versionCode); 10723 10724 if (verificationParams != null) { 10725 if (verificationParams.getVerificationURI() != null) { 10726 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10727 verificationParams.getVerificationURI()); 10728 } 10729 if (verificationParams.getOriginatingURI() != null) { 10730 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10731 verificationParams.getOriginatingURI()); 10732 } 10733 if (verificationParams.getReferrer() != null) { 10734 verification.putExtra(Intent.EXTRA_REFERRER, 10735 verificationParams.getReferrer()); 10736 } 10737 if (verificationParams.getOriginatingUid() >= 0) { 10738 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10739 verificationParams.getOriginatingUid()); 10740 } 10741 if (verificationParams.getInstallerUid() >= 0) { 10742 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10743 verificationParams.getInstallerUid()); 10744 } 10745 } 10746 10747 final PackageVerificationState verificationState = new PackageVerificationState( 10748 requiredUid, args); 10749 10750 mPendingVerification.append(verificationId, verificationState); 10751 10752 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10753 receivers, verificationState); 10754 10755 // Apps installed for "all" users use the device owner to verify the app 10756 UserHandle verifierUser = getUser(); 10757 if (verifierUser == UserHandle.ALL) { 10758 verifierUser = UserHandle.OWNER; 10759 } 10760 10761 /* 10762 * If any sufficient verifiers were listed in the package 10763 * manifest, attempt to ask them. 10764 */ 10765 if (sufficientVerifiers != null) { 10766 final int N = sufficientVerifiers.size(); 10767 if (N == 0) { 10768 Slog.i(TAG, "Additional verifiers required, but none installed."); 10769 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10770 } else { 10771 for (int i = 0; i < N; i++) { 10772 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10773 10774 final Intent sufficientIntent = new Intent(verification); 10775 sufficientIntent.setComponent(verifierComponent); 10776 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10777 } 10778 } 10779 } 10780 10781 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10782 mRequiredVerifierPackage, receivers); 10783 if (ret == PackageManager.INSTALL_SUCCEEDED 10784 && mRequiredVerifierPackage != null) { 10785 /* 10786 * Send the intent to the required verification agent, 10787 * but only start the verification timeout after the 10788 * target BroadcastReceivers have run. 10789 */ 10790 verification.setComponent(requiredVerifierComponent); 10791 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10792 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10793 new BroadcastReceiver() { 10794 @Override 10795 public void onReceive(Context context, Intent intent) { 10796 final Message msg = mHandler 10797 .obtainMessage(CHECK_PENDING_VERIFICATION); 10798 msg.arg1 = verificationId; 10799 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10800 } 10801 }, null, 0, null, null); 10802 10803 /* 10804 * We don't want the copy to proceed until verification 10805 * succeeds, so null out this field. 10806 */ 10807 mArgs = null; 10808 } 10809 } else { 10810 /* 10811 * No package verification is enabled, so immediately start 10812 * the remote call to initiate copy using temporary file. 10813 */ 10814 ret = args.copyApk(mContainerService, true); 10815 } 10816 } 10817 10818 mRet = ret; 10819 } 10820 10821 @Override 10822 void handleReturnCode() { 10823 // If mArgs is null, then MCS couldn't be reached. When it 10824 // reconnects, it will try again to install. At that point, this 10825 // will succeed. 10826 if (mArgs != null) { 10827 processPendingInstall(mArgs, mRet); 10828 } 10829 } 10830 10831 @Override 10832 void handleServiceError() { 10833 mArgs = createInstallArgs(this); 10834 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10835 } 10836 10837 public boolean isForwardLocked() { 10838 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10839 } 10840 } 10841 10842 /** 10843 * Used during creation of InstallArgs 10844 * 10845 * @param installFlags package installation flags 10846 * @return true if should be installed on external storage 10847 */ 10848 private static boolean installOnExternalAsec(int installFlags) { 10849 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10850 return false; 10851 } 10852 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10853 return true; 10854 } 10855 return false; 10856 } 10857 10858 /** 10859 * Used during creation of InstallArgs 10860 * 10861 * @param installFlags package installation flags 10862 * @return true if should be installed as forward locked 10863 */ 10864 private static boolean installForwardLocked(int installFlags) { 10865 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10866 } 10867 10868 private InstallArgs createInstallArgs(InstallParams params) { 10869 if (params.move != null) { 10870 return new MoveInstallArgs(params); 10871 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10872 return new AsecInstallArgs(params); 10873 } else { 10874 return new FileInstallArgs(params); 10875 } 10876 } 10877 10878 /** 10879 * Create args that describe an existing installed package. Typically used 10880 * when cleaning up old installs, or used as a move source. 10881 */ 10882 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10883 String resourcePath, String[] instructionSets) { 10884 final boolean isInAsec; 10885 if (installOnExternalAsec(installFlags)) { 10886 /* Apps on SD card are always in ASEC containers. */ 10887 isInAsec = true; 10888 } else if (installForwardLocked(installFlags) 10889 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10890 /* 10891 * Forward-locked apps are only in ASEC containers if they're the 10892 * new style 10893 */ 10894 isInAsec = true; 10895 } else { 10896 isInAsec = false; 10897 } 10898 10899 if (isInAsec) { 10900 return new AsecInstallArgs(codePath, instructionSets, 10901 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10902 } else { 10903 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10904 } 10905 } 10906 10907 static abstract class InstallArgs { 10908 /** @see InstallParams#origin */ 10909 final OriginInfo origin; 10910 /** @see InstallParams#move */ 10911 final MoveInfo move; 10912 10913 final IPackageInstallObserver2 observer; 10914 // Always refers to PackageManager flags only 10915 final int installFlags; 10916 final String installerPackageName; 10917 final String volumeUuid; 10918 final ManifestDigest manifestDigest; 10919 final UserHandle user; 10920 final String abiOverride; 10921 final String[] installGrantPermissions; 10922 10923 // The list of instruction sets supported by this app. This is currently 10924 // only used during the rmdex() phase to clean up resources. We can get rid of this 10925 // if we move dex files under the common app path. 10926 /* nullable */ String[] instructionSets; 10927 10928 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10929 int installFlags, String installerPackageName, String volumeUuid, 10930 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10931 String abiOverride, String[] installGrantPermissions) { 10932 this.origin = origin; 10933 this.move = move; 10934 this.installFlags = installFlags; 10935 this.observer = observer; 10936 this.installerPackageName = installerPackageName; 10937 this.volumeUuid = volumeUuid; 10938 this.manifestDigest = manifestDigest; 10939 this.user = user; 10940 this.instructionSets = instructionSets; 10941 this.abiOverride = abiOverride; 10942 this.installGrantPermissions = installGrantPermissions; 10943 } 10944 10945 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10946 abstract int doPreInstall(int status); 10947 10948 /** 10949 * Rename package into final resting place. All paths on the given 10950 * scanned package should be updated to reflect the rename. 10951 */ 10952 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10953 abstract int doPostInstall(int status, int uid); 10954 10955 /** @see PackageSettingBase#codePathString */ 10956 abstract String getCodePath(); 10957 /** @see PackageSettingBase#resourcePathString */ 10958 abstract String getResourcePath(); 10959 10960 // Need installer lock especially for dex file removal. 10961 abstract void cleanUpResourcesLI(); 10962 abstract boolean doPostDeleteLI(boolean delete); 10963 10964 /** 10965 * Called before the source arguments are copied. This is used mostly 10966 * for MoveParams when it needs to read the source file to put it in the 10967 * destination. 10968 */ 10969 int doPreCopy() { 10970 return PackageManager.INSTALL_SUCCEEDED; 10971 } 10972 10973 /** 10974 * Called after the source arguments are copied. This is used mostly for 10975 * MoveParams when it needs to read the source file to put it in the 10976 * destination. 10977 * 10978 * @return 10979 */ 10980 int doPostCopy(int uid) { 10981 return PackageManager.INSTALL_SUCCEEDED; 10982 } 10983 10984 protected boolean isFwdLocked() { 10985 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10986 } 10987 10988 protected boolean isExternalAsec() { 10989 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10990 } 10991 10992 UserHandle getUser() { 10993 return user; 10994 } 10995 } 10996 10997 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10998 if (!allCodePaths.isEmpty()) { 10999 if (instructionSets == null) { 11000 throw new IllegalStateException("instructionSet == null"); 11001 } 11002 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11003 for (String codePath : allCodePaths) { 11004 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11005 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11006 if (retCode < 0) { 11007 Slog.w(TAG, "Couldn't remove dex file for package: " 11008 + " at location " + codePath + ", retcode=" + retCode); 11009 // we don't consider this to be a failure of the core package deletion 11010 } 11011 } 11012 } 11013 } 11014 } 11015 11016 /** 11017 * Logic to handle installation of non-ASEC applications, including copying 11018 * and renaming logic. 11019 */ 11020 class FileInstallArgs extends InstallArgs { 11021 private File codeFile; 11022 private File resourceFile; 11023 11024 // Example topology: 11025 // /data/app/com.example/base.apk 11026 // /data/app/com.example/split_foo.apk 11027 // /data/app/com.example/lib/arm/libfoo.so 11028 // /data/app/com.example/lib/arm64/libfoo.so 11029 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11030 11031 /** New install */ 11032 FileInstallArgs(InstallParams params) { 11033 super(params.origin, params.move, params.observer, params.installFlags, 11034 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11035 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11036 params.grantedRuntimePermissions); 11037 if (isFwdLocked()) { 11038 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11039 } 11040 } 11041 11042 /** Existing install */ 11043 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11044 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11045 null, null); 11046 this.codeFile = (codePath != null) ? new File(codePath) : null; 11047 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11048 } 11049 11050 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11051 if (origin.staged) { 11052 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11053 codeFile = origin.file; 11054 resourceFile = origin.file; 11055 return PackageManager.INSTALL_SUCCEEDED; 11056 } 11057 11058 try { 11059 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11060 codeFile = tempDir; 11061 resourceFile = tempDir; 11062 } catch (IOException e) { 11063 Slog.w(TAG, "Failed to create copy file: " + e); 11064 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11065 } 11066 11067 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11068 @Override 11069 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11070 if (!FileUtils.isValidExtFilename(name)) { 11071 throw new IllegalArgumentException("Invalid filename: " + name); 11072 } 11073 try { 11074 final File file = new File(codeFile, name); 11075 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11076 O_RDWR | O_CREAT, 0644); 11077 Os.chmod(file.getAbsolutePath(), 0644); 11078 return new ParcelFileDescriptor(fd); 11079 } catch (ErrnoException e) { 11080 throw new RemoteException("Failed to open: " + e.getMessage()); 11081 } 11082 } 11083 }; 11084 11085 int ret = PackageManager.INSTALL_SUCCEEDED; 11086 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11087 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11088 Slog.e(TAG, "Failed to copy package"); 11089 return ret; 11090 } 11091 11092 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11093 NativeLibraryHelper.Handle handle = null; 11094 try { 11095 handle = NativeLibraryHelper.Handle.create(codeFile); 11096 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11097 abiOverride); 11098 } catch (IOException e) { 11099 Slog.e(TAG, "Copying native libraries failed", e); 11100 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11101 } finally { 11102 IoUtils.closeQuietly(handle); 11103 } 11104 11105 return ret; 11106 } 11107 11108 int doPreInstall(int status) { 11109 if (status != PackageManager.INSTALL_SUCCEEDED) { 11110 cleanUp(); 11111 } 11112 return status; 11113 } 11114 11115 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11116 if (status != PackageManager.INSTALL_SUCCEEDED) { 11117 cleanUp(); 11118 return false; 11119 } 11120 11121 final File targetDir = codeFile.getParentFile(); 11122 final File beforeCodeFile = codeFile; 11123 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11124 11125 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11126 try { 11127 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11128 } catch (ErrnoException e) { 11129 Slog.w(TAG, "Failed to rename", e); 11130 return false; 11131 } 11132 11133 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11134 Slog.w(TAG, "Failed to restorecon"); 11135 return false; 11136 } 11137 11138 // Reflect the rename internally 11139 codeFile = afterCodeFile; 11140 resourceFile = afterCodeFile; 11141 11142 // Reflect the rename in scanned details 11143 pkg.codePath = afterCodeFile.getAbsolutePath(); 11144 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11145 pkg.baseCodePath); 11146 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11147 pkg.splitCodePaths); 11148 11149 // Reflect the rename in app info 11150 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11151 pkg.applicationInfo.setCodePath(pkg.codePath); 11152 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11153 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11154 pkg.applicationInfo.setResourcePath(pkg.codePath); 11155 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11156 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11157 11158 return true; 11159 } 11160 11161 int doPostInstall(int status, int uid) { 11162 if (status != PackageManager.INSTALL_SUCCEEDED) { 11163 cleanUp(); 11164 } 11165 return status; 11166 } 11167 11168 @Override 11169 String getCodePath() { 11170 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11171 } 11172 11173 @Override 11174 String getResourcePath() { 11175 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11176 } 11177 11178 private boolean cleanUp() { 11179 if (codeFile == null || !codeFile.exists()) { 11180 return false; 11181 } 11182 11183 if (codeFile.isDirectory()) { 11184 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11185 } else { 11186 codeFile.delete(); 11187 } 11188 11189 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11190 resourceFile.delete(); 11191 } 11192 11193 return true; 11194 } 11195 11196 void cleanUpResourcesLI() { 11197 // Try enumerating all code paths before deleting 11198 List<String> allCodePaths = Collections.EMPTY_LIST; 11199 if (codeFile != null && codeFile.exists()) { 11200 try { 11201 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11202 allCodePaths = pkg.getAllCodePaths(); 11203 } catch (PackageParserException e) { 11204 // Ignored; we tried our best 11205 } 11206 } 11207 11208 cleanUp(); 11209 removeDexFiles(allCodePaths, instructionSets); 11210 } 11211 11212 boolean doPostDeleteLI(boolean delete) { 11213 // XXX err, shouldn't we respect the delete flag? 11214 cleanUpResourcesLI(); 11215 return true; 11216 } 11217 } 11218 11219 private boolean isAsecExternal(String cid) { 11220 final String asecPath = PackageHelper.getSdFilesystem(cid); 11221 return !asecPath.startsWith(mAsecInternalPath); 11222 } 11223 11224 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11225 PackageManagerException { 11226 if (copyRet < 0) { 11227 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11228 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11229 throw new PackageManagerException(copyRet, message); 11230 } 11231 } 11232 } 11233 11234 /** 11235 * Extract the MountService "container ID" from the full code path of an 11236 * .apk. 11237 */ 11238 static String cidFromCodePath(String fullCodePath) { 11239 int eidx = fullCodePath.lastIndexOf("/"); 11240 String subStr1 = fullCodePath.substring(0, eidx); 11241 int sidx = subStr1.lastIndexOf("/"); 11242 return subStr1.substring(sidx+1, eidx); 11243 } 11244 11245 /** 11246 * Logic to handle installation of ASEC applications, including copying and 11247 * renaming logic. 11248 */ 11249 class AsecInstallArgs extends InstallArgs { 11250 static final String RES_FILE_NAME = "pkg.apk"; 11251 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11252 11253 String cid; 11254 String packagePath; 11255 String resourcePath; 11256 11257 /** New install */ 11258 AsecInstallArgs(InstallParams params) { 11259 super(params.origin, params.move, params.observer, params.installFlags, 11260 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11261 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11262 params.grantedRuntimePermissions); 11263 } 11264 11265 /** Existing install */ 11266 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11267 boolean isExternal, boolean isForwardLocked) { 11268 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11269 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11270 instructionSets, null, null); 11271 // Hackily pretend we're still looking at a full code path 11272 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11273 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11274 } 11275 11276 // Extract cid from fullCodePath 11277 int eidx = fullCodePath.lastIndexOf("/"); 11278 String subStr1 = fullCodePath.substring(0, eidx); 11279 int sidx = subStr1.lastIndexOf("/"); 11280 cid = subStr1.substring(sidx+1, eidx); 11281 setMountPath(subStr1); 11282 } 11283 11284 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11285 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11286 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11287 instructionSets, null, null); 11288 this.cid = cid; 11289 setMountPath(PackageHelper.getSdDir(cid)); 11290 } 11291 11292 void createCopyFile() { 11293 cid = mInstallerService.allocateExternalStageCidLegacy(); 11294 } 11295 11296 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11297 if (origin.staged) { 11298 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11299 cid = origin.cid; 11300 setMountPath(PackageHelper.getSdDir(cid)); 11301 return PackageManager.INSTALL_SUCCEEDED; 11302 } 11303 11304 if (temp) { 11305 createCopyFile(); 11306 } else { 11307 /* 11308 * Pre-emptively destroy the container since it's destroyed if 11309 * copying fails due to it existing anyway. 11310 */ 11311 PackageHelper.destroySdDir(cid); 11312 } 11313 11314 final String newMountPath = imcs.copyPackageToContainer( 11315 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11316 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11317 11318 if (newMountPath != null) { 11319 setMountPath(newMountPath); 11320 return PackageManager.INSTALL_SUCCEEDED; 11321 } else { 11322 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11323 } 11324 } 11325 11326 @Override 11327 String getCodePath() { 11328 return packagePath; 11329 } 11330 11331 @Override 11332 String getResourcePath() { 11333 return resourcePath; 11334 } 11335 11336 int doPreInstall(int status) { 11337 if (status != PackageManager.INSTALL_SUCCEEDED) { 11338 // Destroy container 11339 PackageHelper.destroySdDir(cid); 11340 } else { 11341 boolean mounted = PackageHelper.isContainerMounted(cid); 11342 if (!mounted) { 11343 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11344 Process.SYSTEM_UID); 11345 if (newMountPath != null) { 11346 setMountPath(newMountPath); 11347 } else { 11348 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11349 } 11350 } 11351 } 11352 return status; 11353 } 11354 11355 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11356 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11357 String newMountPath = null; 11358 if (PackageHelper.isContainerMounted(cid)) { 11359 // Unmount the container 11360 if (!PackageHelper.unMountSdDir(cid)) { 11361 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11362 return false; 11363 } 11364 } 11365 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11366 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11367 " which might be stale. Will try to clean up."); 11368 // Clean up the stale container and proceed to recreate. 11369 if (!PackageHelper.destroySdDir(newCacheId)) { 11370 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11371 return false; 11372 } 11373 // Successfully cleaned up stale container. Try to rename again. 11374 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11375 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11376 + " inspite of cleaning it up."); 11377 return false; 11378 } 11379 } 11380 if (!PackageHelper.isContainerMounted(newCacheId)) { 11381 Slog.w(TAG, "Mounting container " + newCacheId); 11382 newMountPath = PackageHelper.mountSdDir(newCacheId, 11383 getEncryptKey(), Process.SYSTEM_UID); 11384 } else { 11385 newMountPath = PackageHelper.getSdDir(newCacheId); 11386 } 11387 if (newMountPath == null) { 11388 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11389 return false; 11390 } 11391 Log.i(TAG, "Succesfully renamed " + cid + 11392 " to " + newCacheId + 11393 " at new path: " + newMountPath); 11394 cid = newCacheId; 11395 11396 final File beforeCodeFile = new File(packagePath); 11397 setMountPath(newMountPath); 11398 final File afterCodeFile = new File(packagePath); 11399 11400 // Reflect the rename in scanned details 11401 pkg.codePath = afterCodeFile.getAbsolutePath(); 11402 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11403 pkg.baseCodePath); 11404 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11405 pkg.splitCodePaths); 11406 11407 // Reflect the rename in app info 11408 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11409 pkg.applicationInfo.setCodePath(pkg.codePath); 11410 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11411 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11412 pkg.applicationInfo.setResourcePath(pkg.codePath); 11413 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11414 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11415 11416 return true; 11417 } 11418 11419 private void setMountPath(String mountPath) { 11420 final File mountFile = new File(mountPath); 11421 11422 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11423 if (monolithicFile.exists()) { 11424 packagePath = monolithicFile.getAbsolutePath(); 11425 if (isFwdLocked()) { 11426 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11427 } else { 11428 resourcePath = packagePath; 11429 } 11430 } else { 11431 packagePath = mountFile.getAbsolutePath(); 11432 resourcePath = packagePath; 11433 } 11434 } 11435 11436 int doPostInstall(int status, int uid) { 11437 if (status != PackageManager.INSTALL_SUCCEEDED) { 11438 cleanUp(); 11439 } else { 11440 final int groupOwner; 11441 final String protectedFile; 11442 if (isFwdLocked()) { 11443 groupOwner = UserHandle.getSharedAppGid(uid); 11444 protectedFile = RES_FILE_NAME; 11445 } else { 11446 groupOwner = -1; 11447 protectedFile = null; 11448 } 11449 11450 if (uid < Process.FIRST_APPLICATION_UID 11451 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11452 Slog.e(TAG, "Failed to finalize " + cid); 11453 PackageHelper.destroySdDir(cid); 11454 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11455 } 11456 11457 boolean mounted = PackageHelper.isContainerMounted(cid); 11458 if (!mounted) { 11459 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11460 } 11461 } 11462 return status; 11463 } 11464 11465 private void cleanUp() { 11466 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11467 11468 // Destroy secure container 11469 PackageHelper.destroySdDir(cid); 11470 } 11471 11472 private List<String> getAllCodePaths() { 11473 final File codeFile = new File(getCodePath()); 11474 if (codeFile != null && codeFile.exists()) { 11475 try { 11476 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11477 return pkg.getAllCodePaths(); 11478 } catch (PackageParserException e) { 11479 // Ignored; we tried our best 11480 } 11481 } 11482 return Collections.EMPTY_LIST; 11483 } 11484 11485 void cleanUpResourcesLI() { 11486 // Enumerate all code paths before deleting 11487 cleanUpResourcesLI(getAllCodePaths()); 11488 } 11489 11490 private void cleanUpResourcesLI(List<String> allCodePaths) { 11491 cleanUp(); 11492 removeDexFiles(allCodePaths, instructionSets); 11493 } 11494 11495 String getPackageName() { 11496 return getAsecPackageName(cid); 11497 } 11498 11499 boolean doPostDeleteLI(boolean delete) { 11500 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11501 final List<String> allCodePaths = getAllCodePaths(); 11502 boolean mounted = PackageHelper.isContainerMounted(cid); 11503 if (mounted) { 11504 // Unmount first 11505 if (PackageHelper.unMountSdDir(cid)) { 11506 mounted = false; 11507 } 11508 } 11509 if (!mounted && delete) { 11510 cleanUpResourcesLI(allCodePaths); 11511 } 11512 return !mounted; 11513 } 11514 11515 @Override 11516 int doPreCopy() { 11517 if (isFwdLocked()) { 11518 if (!PackageHelper.fixSdPermissions(cid, 11519 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11520 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11521 } 11522 } 11523 11524 return PackageManager.INSTALL_SUCCEEDED; 11525 } 11526 11527 @Override 11528 int doPostCopy(int uid) { 11529 if (isFwdLocked()) { 11530 if (uid < Process.FIRST_APPLICATION_UID 11531 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11532 RES_FILE_NAME)) { 11533 Slog.e(TAG, "Failed to finalize " + cid); 11534 PackageHelper.destroySdDir(cid); 11535 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11536 } 11537 } 11538 11539 return PackageManager.INSTALL_SUCCEEDED; 11540 } 11541 } 11542 11543 /** 11544 * Logic to handle movement of existing installed applications. 11545 */ 11546 class MoveInstallArgs extends InstallArgs { 11547 private File codeFile; 11548 private File resourceFile; 11549 11550 /** New install */ 11551 MoveInstallArgs(InstallParams params) { 11552 super(params.origin, params.move, params.observer, params.installFlags, 11553 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11554 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11555 params.grantedRuntimePermissions); 11556 } 11557 11558 int copyApk(IMediaContainerService imcs, boolean temp) { 11559 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11560 + move.fromUuid + " to " + move.toUuid); 11561 synchronized (mInstaller) { 11562 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11563 move.dataAppName, move.appId, move.seinfo) != 0) { 11564 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11565 } 11566 } 11567 11568 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11569 resourceFile = codeFile; 11570 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11571 11572 return PackageManager.INSTALL_SUCCEEDED; 11573 } 11574 11575 int doPreInstall(int status) { 11576 if (status != PackageManager.INSTALL_SUCCEEDED) { 11577 cleanUp(move.toUuid); 11578 } 11579 return status; 11580 } 11581 11582 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11583 if (status != PackageManager.INSTALL_SUCCEEDED) { 11584 cleanUp(move.toUuid); 11585 return false; 11586 } 11587 11588 // Reflect the move in app info 11589 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11590 pkg.applicationInfo.setCodePath(pkg.codePath); 11591 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11592 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11593 pkg.applicationInfo.setResourcePath(pkg.codePath); 11594 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11595 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11596 11597 return true; 11598 } 11599 11600 int doPostInstall(int status, int uid) { 11601 if (status == PackageManager.INSTALL_SUCCEEDED) { 11602 cleanUp(move.fromUuid); 11603 } else { 11604 cleanUp(move.toUuid); 11605 } 11606 return status; 11607 } 11608 11609 @Override 11610 String getCodePath() { 11611 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11612 } 11613 11614 @Override 11615 String getResourcePath() { 11616 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11617 } 11618 11619 private boolean cleanUp(String volumeUuid) { 11620 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11621 move.dataAppName); 11622 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11623 synchronized (mInstallLock) { 11624 // Clean up both app data and code 11625 removeDataDirsLI(volumeUuid, move.packageName); 11626 if (codeFile.isDirectory()) { 11627 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11628 } else { 11629 codeFile.delete(); 11630 } 11631 } 11632 return true; 11633 } 11634 11635 void cleanUpResourcesLI() { 11636 throw new UnsupportedOperationException(); 11637 } 11638 11639 boolean doPostDeleteLI(boolean delete) { 11640 throw new UnsupportedOperationException(); 11641 } 11642 } 11643 11644 static String getAsecPackageName(String packageCid) { 11645 int idx = packageCid.lastIndexOf("-"); 11646 if (idx == -1) { 11647 return packageCid; 11648 } 11649 return packageCid.substring(0, idx); 11650 } 11651 11652 // Utility method used to create code paths based on package name and available index. 11653 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11654 String idxStr = ""; 11655 int idx = 1; 11656 // Fall back to default value of idx=1 if prefix is not 11657 // part of oldCodePath 11658 if (oldCodePath != null) { 11659 String subStr = oldCodePath; 11660 // Drop the suffix right away 11661 if (suffix != null && subStr.endsWith(suffix)) { 11662 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11663 } 11664 // If oldCodePath already contains prefix find out the 11665 // ending index to either increment or decrement. 11666 int sidx = subStr.lastIndexOf(prefix); 11667 if (sidx != -1) { 11668 subStr = subStr.substring(sidx + prefix.length()); 11669 if (subStr != null) { 11670 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11671 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11672 } 11673 try { 11674 idx = Integer.parseInt(subStr); 11675 if (idx <= 1) { 11676 idx++; 11677 } else { 11678 idx--; 11679 } 11680 } catch(NumberFormatException e) { 11681 } 11682 } 11683 } 11684 } 11685 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11686 return prefix + idxStr; 11687 } 11688 11689 private File getNextCodePath(File targetDir, String packageName) { 11690 int suffix = 1; 11691 File result; 11692 do { 11693 result = new File(targetDir, packageName + "-" + suffix); 11694 suffix++; 11695 } while (result.exists()); 11696 return result; 11697 } 11698 11699 // Utility method that returns the relative package path with respect 11700 // to the installation directory. Like say for /data/data/com.test-1.apk 11701 // string com.test-1 is returned. 11702 static String deriveCodePathName(String codePath) { 11703 if (codePath == null) { 11704 return null; 11705 } 11706 final File codeFile = new File(codePath); 11707 final String name = codeFile.getName(); 11708 if (codeFile.isDirectory()) { 11709 return name; 11710 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11711 final int lastDot = name.lastIndexOf('.'); 11712 return name.substring(0, lastDot); 11713 } else { 11714 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11715 return null; 11716 } 11717 } 11718 11719 class PackageInstalledInfo { 11720 String name; 11721 int uid; 11722 // The set of users that originally had this package installed. 11723 int[] origUsers; 11724 // The set of users that now have this package installed. 11725 int[] newUsers; 11726 PackageParser.Package pkg; 11727 int returnCode; 11728 String returnMsg; 11729 PackageRemovedInfo removedInfo; 11730 11731 public void setError(int code, String msg) { 11732 returnCode = code; 11733 returnMsg = msg; 11734 Slog.w(TAG, msg); 11735 } 11736 11737 public void setError(String msg, PackageParserException e) { 11738 returnCode = e.error; 11739 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11740 Slog.w(TAG, msg, e); 11741 } 11742 11743 public void setError(String msg, PackageManagerException e) { 11744 returnCode = e.error; 11745 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11746 Slog.w(TAG, msg, e); 11747 } 11748 11749 // In some error cases we want to convey more info back to the observer 11750 String origPackage; 11751 String origPermission; 11752 } 11753 11754 /* 11755 * Install a non-existing package. 11756 */ 11757 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11758 UserHandle user, String installerPackageName, String volumeUuid, 11759 PackageInstalledInfo res) { 11760 // Remember this for later, in case we need to rollback this install 11761 String pkgName = pkg.packageName; 11762 11763 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11764 final boolean dataDirExists = Environment 11765 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11766 synchronized(mPackages) { 11767 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11768 // A package with the same name is already installed, though 11769 // it has been renamed to an older name. The package we 11770 // are trying to install should be installed as an update to 11771 // the existing one, but that has not been requested, so bail. 11772 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11773 + " without first uninstalling package running as " 11774 + mSettings.mRenamedPackages.get(pkgName)); 11775 return; 11776 } 11777 if (mPackages.containsKey(pkgName)) { 11778 // Don't allow installation over an existing package with the same name. 11779 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11780 + " without first uninstalling."); 11781 return; 11782 } 11783 } 11784 11785 try { 11786 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11787 System.currentTimeMillis(), user); 11788 11789 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11790 // delete the partially installed application. the data directory will have to be 11791 // restored if it was already existing 11792 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11793 // remove package from internal structures. Note that we want deletePackageX to 11794 // delete the package data and cache directories that it created in 11795 // scanPackageLocked, unless those directories existed before we even tried to 11796 // install. 11797 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11798 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11799 res.removedInfo, true); 11800 } 11801 11802 } catch (PackageManagerException e) { 11803 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11804 } 11805 } 11806 11807 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11808 // Can't rotate keys during boot or if sharedUser. 11809 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11810 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11811 return false; 11812 } 11813 // app is using upgradeKeySets; make sure all are valid 11814 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11815 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11816 for (int i = 0; i < upgradeKeySets.length; i++) { 11817 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11818 Slog.wtf(TAG, "Package " 11819 + (oldPs.name != null ? oldPs.name : "<null>") 11820 + " contains upgrade-key-set reference to unknown key-set: " 11821 + upgradeKeySets[i] 11822 + " reverting to signatures check."); 11823 return false; 11824 } 11825 } 11826 return true; 11827 } 11828 11829 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11830 // Upgrade keysets are being used. Determine if new package has a superset of the 11831 // required keys. 11832 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11833 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11834 for (int i = 0; i < upgradeKeySets.length; i++) { 11835 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11836 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11837 return true; 11838 } 11839 } 11840 return false; 11841 } 11842 11843 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11844 UserHandle user, String installerPackageName, String volumeUuid, 11845 PackageInstalledInfo res) { 11846 final PackageParser.Package oldPackage; 11847 final String pkgName = pkg.packageName; 11848 final int[] allUsers; 11849 final boolean[] perUserInstalled; 11850 11851 // First find the old package info and check signatures 11852 synchronized(mPackages) { 11853 oldPackage = mPackages.get(pkgName); 11854 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11855 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11856 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11857 if(!checkUpgradeKeySetLP(ps, pkg)) { 11858 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11859 "New package not signed by keys specified by upgrade-keysets: " 11860 + pkgName); 11861 return; 11862 } 11863 } else { 11864 // default to original signature matching 11865 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11866 != PackageManager.SIGNATURE_MATCH) { 11867 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11868 "New package has a different signature: " + pkgName); 11869 return; 11870 } 11871 } 11872 11873 // In case of rollback, remember per-user/profile install state 11874 allUsers = sUserManager.getUserIds(); 11875 perUserInstalled = new boolean[allUsers.length]; 11876 for (int i = 0; i < allUsers.length; i++) { 11877 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11878 } 11879 } 11880 11881 boolean sysPkg = (isSystemApp(oldPackage)); 11882 if (sysPkg) { 11883 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11884 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11885 } else { 11886 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11887 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11888 } 11889 } 11890 11891 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11892 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11893 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11894 String volumeUuid, PackageInstalledInfo res) { 11895 String pkgName = deletedPackage.packageName; 11896 boolean deletedPkg = true; 11897 boolean updatedSettings = false; 11898 11899 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11900 + deletedPackage); 11901 long origUpdateTime; 11902 if (pkg.mExtras != null) { 11903 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11904 } else { 11905 origUpdateTime = 0; 11906 } 11907 11908 // First delete the existing package while retaining the data directory 11909 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11910 res.removedInfo, true)) { 11911 // If the existing package wasn't successfully deleted 11912 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11913 deletedPkg = false; 11914 } else { 11915 // Successfully deleted the old package; proceed with replace. 11916 11917 // If deleted package lived in a container, give users a chance to 11918 // relinquish resources before killing. 11919 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11920 if (DEBUG_INSTALL) { 11921 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11922 } 11923 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11924 final ArrayList<String> pkgList = new ArrayList<String>(1); 11925 pkgList.add(deletedPackage.applicationInfo.packageName); 11926 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11927 } 11928 11929 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11930 try { 11931 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11932 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11933 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11934 perUserInstalled, res, user); 11935 updatedSettings = true; 11936 } catch (PackageManagerException e) { 11937 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11938 } 11939 } 11940 11941 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11942 // remove package from internal structures. Note that we want deletePackageX to 11943 // delete the package data and cache directories that it created in 11944 // scanPackageLocked, unless those directories existed before we even tried to 11945 // install. 11946 if(updatedSettings) { 11947 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11948 deletePackageLI( 11949 pkgName, null, true, allUsers, perUserInstalled, 11950 PackageManager.DELETE_KEEP_DATA, 11951 res.removedInfo, true); 11952 } 11953 // Since we failed to install the new package we need to restore the old 11954 // package that we deleted. 11955 if (deletedPkg) { 11956 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11957 File restoreFile = new File(deletedPackage.codePath); 11958 // Parse old package 11959 boolean oldExternal = isExternal(deletedPackage); 11960 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11961 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11962 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11963 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11964 try { 11965 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11966 } catch (PackageManagerException e) { 11967 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11968 + e.getMessage()); 11969 return; 11970 } 11971 // Restore of old package succeeded. Update permissions. 11972 // writer 11973 synchronized (mPackages) { 11974 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11975 UPDATE_PERMISSIONS_ALL); 11976 // can downgrade to reader 11977 mSettings.writeLPr(); 11978 } 11979 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11980 } 11981 } 11982 } 11983 11984 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11985 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11986 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11987 String volumeUuid, PackageInstalledInfo res) { 11988 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11989 + ", old=" + deletedPackage); 11990 boolean disabledSystem = false; 11991 boolean updatedSettings = false; 11992 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11993 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11994 != 0) { 11995 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11996 } 11997 String packageName = deletedPackage.packageName; 11998 if (packageName == null) { 11999 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12000 "Attempt to delete null packageName."); 12001 return; 12002 } 12003 PackageParser.Package oldPkg; 12004 PackageSetting oldPkgSetting; 12005 // reader 12006 synchronized (mPackages) { 12007 oldPkg = mPackages.get(packageName); 12008 oldPkgSetting = mSettings.mPackages.get(packageName); 12009 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12010 (oldPkgSetting == null)) { 12011 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12012 "Couldn't find package:" + packageName + " information"); 12013 return; 12014 } 12015 } 12016 12017 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12018 12019 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12020 res.removedInfo.removedPackage = packageName; 12021 // Remove existing system package 12022 removePackageLI(oldPkgSetting, true); 12023 // writer 12024 synchronized (mPackages) { 12025 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12026 if (!disabledSystem && deletedPackage != null) { 12027 // We didn't need to disable the .apk as a current system package, 12028 // which means we are replacing another update that is already 12029 // installed. We need to make sure to delete the older one's .apk. 12030 res.removedInfo.args = createInstallArgsForExisting(0, 12031 deletedPackage.applicationInfo.getCodePath(), 12032 deletedPackage.applicationInfo.getResourcePath(), 12033 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12034 } else { 12035 res.removedInfo.args = null; 12036 } 12037 } 12038 12039 // Successfully disabled the old package. Now proceed with re-installation 12040 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12041 12042 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12043 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12044 12045 PackageParser.Package newPackage = null; 12046 try { 12047 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 12048 if (newPackage.mExtras != null) { 12049 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12050 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12051 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12052 12053 // is the update attempting to change shared user? that isn't going to work... 12054 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12055 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12056 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12057 + " to " + newPkgSetting.sharedUser); 12058 updatedSettings = true; 12059 } 12060 } 12061 12062 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12063 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12064 perUserInstalled, res, user); 12065 updatedSettings = true; 12066 } 12067 12068 } catch (PackageManagerException e) { 12069 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12070 } 12071 12072 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12073 // Re installation failed. Restore old information 12074 // Remove new pkg information 12075 if (newPackage != null) { 12076 removeInstalledPackageLI(newPackage, true); 12077 } 12078 // Add back the old system package 12079 try { 12080 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12081 } catch (PackageManagerException e) { 12082 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12083 } 12084 // Restore the old system information in Settings 12085 synchronized (mPackages) { 12086 if (disabledSystem) { 12087 mSettings.enableSystemPackageLPw(packageName); 12088 } 12089 if (updatedSettings) { 12090 mSettings.setInstallerPackageName(packageName, 12091 oldPkgSetting.installerPackageName); 12092 } 12093 mSettings.writeLPr(); 12094 } 12095 } 12096 } 12097 12098 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12099 // Collect all used permissions in the UID 12100 ArraySet<String> usedPermissions = new ArraySet<>(); 12101 final int packageCount = su.packages.size(); 12102 for (int i = 0; i < packageCount; i++) { 12103 PackageSetting ps = su.packages.valueAt(i); 12104 if (ps.pkg == null) { 12105 continue; 12106 } 12107 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12108 for (int j = 0; j < requestedPermCount; j++) { 12109 String permission = ps.pkg.requestedPermissions.get(j); 12110 BasePermission bp = mSettings.mPermissions.get(permission); 12111 if (bp != null) { 12112 usedPermissions.add(permission); 12113 } 12114 } 12115 } 12116 12117 PermissionsState permissionsState = su.getPermissionsState(); 12118 // Prune install permissions 12119 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12120 final int installPermCount = installPermStates.size(); 12121 for (int i = installPermCount - 1; i >= 0; i--) { 12122 PermissionState permissionState = installPermStates.get(i); 12123 if (!usedPermissions.contains(permissionState.getName())) { 12124 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12125 if (bp != null) { 12126 permissionsState.revokeInstallPermission(bp); 12127 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12128 PackageManager.MASK_PERMISSION_FLAGS, 0); 12129 } 12130 } 12131 } 12132 12133 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12134 12135 // Prune runtime permissions 12136 for (int userId : allUserIds) { 12137 List<PermissionState> runtimePermStates = permissionsState 12138 .getRuntimePermissionStates(userId); 12139 final int runtimePermCount = runtimePermStates.size(); 12140 for (int i = runtimePermCount - 1; i >= 0; i--) { 12141 PermissionState permissionState = runtimePermStates.get(i); 12142 if (!usedPermissions.contains(permissionState.getName())) { 12143 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12144 if (bp != null) { 12145 permissionsState.revokeRuntimePermission(bp, userId); 12146 permissionsState.updatePermissionFlags(bp, userId, 12147 PackageManager.MASK_PERMISSION_FLAGS, 0); 12148 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12149 runtimePermissionChangedUserIds, userId); 12150 } 12151 } 12152 } 12153 } 12154 12155 return runtimePermissionChangedUserIds; 12156 } 12157 12158 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12159 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12160 UserHandle user) { 12161 String pkgName = newPackage.packageName; 12162 synchronized (mPackages) { 12163 //write settings. the installStatus will be incomplete at this stage. 12164 //note that the new package setting would have already been 12165 //added to mPackages. It hasn't been persisted yet. 12166 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12167 mSettings.writeLPr(); 12168 } 12169 12170 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12171 12172 synchronized (mPackages) { 12173 updatePermissionsLPw(newPackage.packageName, newPackage, 12174 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12175 ? UPDATE_PERMISSIONS_ALL : 0)); 12176 // For system-bundled packages, we assume that installing an upgraded version 12177 // of the package implies that the user actually wants to run that new code, 12178 // so we enable the package. 12179 PackageSetting ps = mSettings.mPackages.get(pkgName); 12180 if (ps != null) { 12181 if (isSystemApp(newPackage)) { 12182 // NB: implicit assumption that system package upgrades apply to all users 12183 if (DEBUG_INSTALL) { 12184 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12185 } 12186 if (res.origUsers != null) { 12187 for (int userHandle : res.origUsers) { 12188 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12189 userHandle, installerPackageName); 12190 } 12191 } 12192 // Also convey the prior install/uninstall state 12193 if (allUsers != null && perUserInstalled != null) { 12194 for (int i = 0; i < allUsers.length; i++) { 12195 if (DEBUG_INSTALL) { 12196 Slog.d(TAG, " user " + allUsers[i] 12197 + " => " + perUserInstalled[i]); 12198 } 12199 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12200 } 12201 // these install state changes will be persisted in the 12202 // upcoming call to mSettings.writeLPr(). 12203 } 12204 } 12205 // It's implied that when a user requests installation, they want the app to be 12206 // installed and enabled. 12207 int userId = user.getIdentifier(); 12208 if (userId != UserHandle.USER_ALL) { 12209 ps.setInstalled(true, userId); 12210 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12211 } 12212 } 12213 res.name = pkgName; 12214 res.uid = newPackage.applicationInfo.uid; 12215 res.pkg = newPackage; 12216 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12217 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12218 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12219 //to update install status 12220 mSettings.writeLPr(); 12221 } 12222 } 12223 12224 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12225 final int installFlags = args.installFlags; 12226 final String installerPackageName = args.installerPackageName; 12227 final String volumeUuid = args.volumeUuid; 12228 final File tmpPackageFile = new File(args.getCodePath()); 12229 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12230 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12231 || (args.volumeUuid != null)); 12232 boolean replace = false; 12233 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12234 if (args.move != null) { 12235 // moving a complete application; perfom an initial scan on the new install location 12236 scanFlags |= SCAN_INITIAL; 12237 } 12238 // Result object to be returned 12239 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12240 12241 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12242 // Retrieve PackageSettings and parse package 12243 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12244 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12245 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12246 PackageParser pp = new PackageParser(); 12247 pp.setSeparateProcesses(mSeparateProcesses); 12248 pp.setDisplayMetrics(mMetrics); 12249 12250 final PackageParser.Package pkg; 12251 try { 12252 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12253 } catch (PackageParserException e) { 12254 res.setError("Failed parse during installPackageLI", e); 12255 return; 12256 } 12257 12258 // Mark that we have an install time CPU ABI override. 12259 pkg.cpuAbiOverride = args.abiOverride; 12260 12261 String pkgName = res.name = pkg.packageName; 12262 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12263 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12264 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12265 return; 12266 } 12267 } 12268 12269 try { 12270 pp.collectCertificates(pkg, parseFlags); 12271 pp.collectManifestDigest(pkg); 12272 } catch (PackageParserException e) { 12273 res.setError("Failed collect during installPackageLI", e); 12274 return; 12275 } 12276 12277 /* If the installer passed in a manifest digest, compare it now. */ 12278 if (args.manifestDigest != null) { 12279 if (DEBUG_INSTALL) { 12280 final String parsedManifest = pkg.manifestDigest == null ? "null" 12281 : pkg.manifestDigest.toString(); 12282 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12283 + parsedManifest); 12284 } 12285 12286 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12287 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12288 return; 12289 } 12290 } else if (DEBUG_INSTALL) { 12291 final String parsedManifest = pkg.manifestDigest == null 12292 ? "null" : pkg.manifestDigest.toString(); 12293 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12294 } 12295 12296 // Get rid of all references to package scan path via parser. 12297 pp = null; 12298 String oldCodePath = null; 12299 boolean systemApp = false; 12300 synchronized (mPackages) { 12301 // Check if installing already existing package 12302 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12303 String oldName = mSettings.mRenamedPackages.get(pkgName); 12304 if (pkg.mOriginalPackages != null 12305 && pkg.mOriginalPackages.contains(oldName) 12306 && mPackages.containsKey(oldName)) { 12307 // This package is derived from an original package, 12308 // and this device has been updating from that original 12309 // name. We must continue using the original name, so 12310 // rename the new package here. 12311 pkg.setPackageName(oldName); 12312 pkgName = pkg.packageName; 12313 replace = true; 12314 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12315 + oldName + " pkgName=" + pkgName); 12316 } else if (mPackages.containsKey(pkgName)) { 12317 // This package, under its official name, already exists 12318 // on the device; we should replace it. 12319 replace = true; 12320 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12321 } 12322 12323 // Prevent apps opting out from runtime permissions 12324 if (replace) { 12325 PackageParser.Package oldPackage = mPackages.get(pkgName); 12326 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12327 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12328 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12329 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12330 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12331 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12332 + " doesn't support runtime permissions but the old" 12333 + " target SDK " + oldTargetSdk + " does."); 12334 return; 12335 } 12336 } 12337 } 12338 12339 PackageSetting ps = mSettings.mPackages.get(pkgName); 12340 if (ps != null) { 12341 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12342 12343 // Quick sanity check that we're signed correctly if updating; 12344 // we'll check this again later when scanning, but we want to 12345 // bail early here before tripping over redefined permissions. 12346 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12347 if (!checkUpgradeKeySetLP(ps, pkg)) { 12348 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12349 + pkg.packageName + " upgrade keys do not match the " 12350 + "previously installed version"); 12351 return; 12352 } 12353 } else { 12354 try { 12355 verifySignaturesLP(ps, pkg); 12356 } catch (PackageManagerException e) { 12357 res.setError(e.error, e.getMessage()); 12358 return; 12359 } 12360 } 12361 12362 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12363 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12364 systemApp = (ps.pkg.applicationInfo.flags & 12365 ApplicationInfo.FLAG_SYSTEM) != 0; 12366 } 12367 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12368 } 12369 12370 // Check whether the newly-scanned package wants to define an already-defined perm 12371 int N = pkg.permissions.size(); 12372 for (int i = N-1; i >= 0; i--) { 12373 PackageParser.Permission perm = pkg.permissions.get(i); 12374 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12375 if (bp != null) { 12376 // If the defining package is signed with our cert, it's okay. This 12377 // also includes the "updating the same package" case, of course. 12378 // "updating same package" could also involve key-rotation. 12379 final boolean sigsOk; 12380 if (bp.sourcePackage.equals(pkg.packageName) 12381 && (bp.packageSetting instanceof PackageSetting) 12382 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12383 scanFlags))) { 12384 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12385 } else { 12386 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12387 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12388 } 12389 if (!sigsOk) { 12390 // If the owning package is the system itself, we log but allow 12391 // install to proceed; we fail the install on all other permission 12392 // redefinitions. 12393 if (!bp.sourcePackage.equals("android")) { 12394 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12395 + pkg.packageName + " attempting to redeclare permission " 12396 + perm.info.name + " already owned by " + bp.sourcePackage); 12397 res.origPermission = perm.info.name; 12398 res.origPackage = bp.sourcePackage; 12399 return; 12400 } else { 12401 Slog.w(TAG, "Package " + pkg.packageName 12402 + " attempting to redeclare system permission " 12403 + perm.info.name + "; ignoring new declaration"); 12404 pkg.permissions.remove(i); 12405 } 12406 } 12407 } 12408 } 12409 12410 } 12411 12412 if (systemApp && onExternal) { 12413 // Disable updates to system apps on sdcard 12414 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12415 "Cannot install updates to system apps on sdcard"); 12416 return; 12417 } 12418 12419 if (args.move != null) { 12420 // We did an in-place move, so dex is ready to roll 12421 scanFlags |= SCAN_NO_DEX; 12422 scanFlags |= SCAN_MOVE; 12423 12424 synchronized (mPackages) { 12425 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12426 if (ps == null) { 12427 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12428 "Missing settings for moved package " + pkgName); 12429 } 12430 12431 // We moved the entire application as-is, so bring over the 12432 // previously derived ABI information. 12433 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12434 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12435 } 12436 12437 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12438 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12439 scanFlags |= SCAN_NO_DEX; 12440 12441 try { 12442 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12443 true /* extract libs */); 12444 } catch (PackageManagerException pme) { 12445 Slog.e(TAG, "Error deriving application ABI", pme); 12446 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12447 return; 12448 } 12449 12450 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12451 int result = mPackageDexOptimizer 12452 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12453 false /* defer */, false /* inclDependencies */, 12454 true /* boot complete */); 12455 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12456 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12457 return; 12458 } 12459 } 12460 12461 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12462 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12463 return; 12464 } 12465 12466 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12467 12468 if (replace) { 12469 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12470 installerPackageName, volumeUuid, res); 12471 } else { 12472 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12473 args.user, installerPackageName, volumeUuid, res); 12474 } 12475 synchronized (mPackages) { 12476 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12477 if (ps != null) { 12478 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12479 } 12480 } 12481 } 12482 12483 private void startIntentFilterVerifications(int userId, boolean replacing, 12484 PackageParser.Package pkg) { 12485 if (mIntentFilterVerifierComponent == null) { 12486 Slog.w(TAG, "No IntentFilter verification will not be done as " 12487 + "there is no IntentFilterVerifier available!"); 12488 return; 12489 } 12490 12491 final int verifierUid = getPackageUid( 12492 mIntentFilterVerifierComponent.getPackageName(), 12493 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12494 12495 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12496 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12497 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12498 mHandler.sendMessage(msg); 12499 } 12500 12501 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12502 PackageParser.Package pkg) { 12503 int size = pkg.activities.size(); 12504 if (size == 0) { 12505 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12506 "No activity, so no need to verify any IntentFilter!"); 12507 return; 12508 } 12509 12510 final boolean hasDomainURLs = hasDomainURLs(pkg); 12511 if (!hasDomainURLs) { 12512 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12513 "No domain URLs, so no need to verify any IntentFilter!"); 12514 return; 12515 } 12516 12517 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12518 + " if any IntentFilter from the " + size 12519 + " Activities needs verification ..."); 12520 12521 int count = 0; 12522 final String packageName = pkg.packageName; 12523 12524 synchronized (mPackages) { 12525 // If this is a new install and we see that we've already run verification for this 12526 // package, we have nothing to do: it means the state was restored from backup. 12527 if (!replacing) { 12528 IntentFilterVerificationInfo ivi = 12529 mSettings.getIntentFilterVerificationLPr(packageName); 12530 if (ivi != null) { 12531 if (DEBUG_DOMAIN_VERIFICATION) { 12532 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12533 + ivi.getStatusString()); 12534 } 12535 return; 12536 } 12537 } 12538 12539 // If any filters need to be verified, then all need to be. 12540 boolean needToVerify = false; 12541 for (PackageParser.Activity a : pkg.activities) { 12542 for (ActivityIntentInfo filter : a.intents) { 12543 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12544 if (DEBUG_DOMAIN_VERIFICATION) { 12545 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12546 } 12547 needToVerify = true; 12548 break; 12549 } 12550 } 12551 } 12552 12553 if (needToVerify) { 12554 final int verificationId = mIntentFilterVerificationToken++; 12555 for (PackageParser.Activity a : pkg.activities) { 12556 for (ActivityIntentInfo filter : a.intents) { 12557 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12558 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12559 "Verification needed for IntentFilter:" + filter.toString()); 12560 mIntentFilterVerifier.addOneIntentFilterVerification( 12561 verifierUid, userId, verificationId, filter, packageName); 12562 count++; 12563 } 12564 } 12565 } 12566 } 12567 } 12568 12569 if (count > 0) { 12570 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12571 + " IntentFilter verification" + (count > 1 ? "s" : "") 12572 + " for userId:" + userId); 12573 mIntentFilterVerifier.startVerifications(userId); 12574 } else { 12575 if (DEBUG_DOMAIN_VERIFICATION) { 12576 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12577 } 12578 } 12579 } 12580 12581 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12582 final ComponentName cn = filter.activity.getComponentName(); 12583 final String packageName = cn.getPackageName(); 12584 12585 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12586 packageName); 12587 if (ivi == null) { 12588 return true; 12589 } 12590 int status = ivi.getStatus(); 12591 switch (status) { 12592 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12593 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12594 return true; 12595 12596 default: 12597 // Nothing to do 12598 return false; 12599 } 12600 } 12601 12602 private static boolean isMultiArch(PackageSetting ps) { 12603 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12604 } 12605 12606 private static boolean isMultiArch(ApplicationInfo info) { 12607 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12608 } 12609 12610 private static boolean isExternal(PackageParser.Package pkg) { 12611 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12612 } 12613 12614 private static boolean isExternal(PackageSetting ps) { 12615 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12616 } 12617 12618 private static boolean isExternal(ApplicationInfo info) { 12619 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12620 } 12621 12622 private static boolean isSystemApp(PackageParser.Package pkg) { 12623 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12624 } 12625 12626 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12627 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12628 } 12629 12630 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12631 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12632 } 12633 12634 private static boolean isSystemApp(PackageSetting ps) { 12635 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12636 } 12637 12638 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12639 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12640 } 12641 12642 private int packageFlagsToInstallFlags(PackageSetting ps) { 12643 int installFlags = 0; 12644 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12645 // This existing package was an external ASEC install when we have 12646 // the external flag without a UUID 12647 installFlags |= PackageManager.INSTALL_EXTERNAL; 12648 } 12649 if (ps.isForwardLocked()) { 12650 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12651 } 12652 return installFlags; 12653 } 12654 12655 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 12656 if (isExternal(pkg)) { 12657 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12658 return StorageManager.UUID_PRIMARY_PHYSICAL; 12659 } else { 12660 return pkg.volumeUuid; 12661 } 12662 } else { 12663 return StorageManager.UUID_PRIVATE_INTERNAL; 12664 } 12665 } 12666 12667 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12668 if (isExternal(pkg)) { 12669 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12670 return mSettings.getExternalVersion(); 12671 } else { 12672 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12673 } 12674 } else { 12675 return mSettings.getInternalVersion(); 12676 } 12677 } 12678 12679 private void deleteTempPackageFiles() { 12680 final FilenameFilter filter = new FilenameFilter() { 12681 public boolean accept(File dir, String name) { 12682 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12683 } 12684 }; 12685 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12686 file.delete(); 12687 } 12688 } 12689 12690 @Override 12691 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12692 int flags) { 12693 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12694 flags); 12695 } 12696 12697 @Override 12698 public void deletePackage(final String packageName, 12699 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12700 mContext.enforceCallingOrSelfPermission( 12701 android.Manifest.permission.DELETE_PACKAGES, null); 12702 Preconditions.checkNotNull(packageName); 12703 Preconditions.checkNotNull(observer); 12704 final int uid = Binder.getCallingUid(); 12705 if (UserHandle.getUserId(uid) != userId) { 12706 mContext.enforceCallingPermission( 12707 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12708 "deletePackage for user " + userId); 12709 } 12710 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12711 try { 12712 observer.onPackageDeleted(packageName, 12713 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12714 } catch (RemoteException re) { 12715 } 12716 return; 12717 } 12718 12719 boolean uninstallBlocked = false; 12720 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12721 int[] users = sUserManager.getUserIds(); 12722 for (int i = 0; i < users.length; ++i) { 12723 if (getBlockUninstallForUser(packageName, users[i])) { 12724 uninstallBlocked = true; 12725 break; 12726 } 12727 } 12728 } else { 12729 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12730 } 12731 if (uninstallBlocked) { 12732 try { 12733 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12734 null); 12735 } catch (RemoteException re) { 12736 } 12737 return; 12738 } 12739 12740 if (DEBUG_REMOVE) { 12741 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12742 } 12743 // Queue up an async operation since the package deletion may take a little while. 12744 mHandler.post(new Runnable() { 12745 public void run() { 12746 mHandler.removeCallbacks(this); 12747 final int returnCode = deletePackageX(packageName, userId, flags); 12748 if (observer != null) { 12749 try { 12750 observer.onPackageDeleted(packageName, returnCode, null); 12751 } catch (RemoteException e) { 12752 Log.i(TAG, "Observer no longer exists."); 12753 } //end catch 12754 } //end if 12755 } //end run 12756 }); 12757 } 12758 12759 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12760 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12761 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12762 try { 12763 if (dpm != null) { 12764 if (dpm.isDeviceOwner(packageName)) { 12765 return true; 12766 } 12767 int[] users; 12768 if (userId == UserHandle.USER_ALL) { 12769 users = sUserManager.getUserIds(); 12770 } else { 12771 users = new int[]{userId}; 12772 } 12773 for (int i = 0; i < users.length; ++i) { 12774 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12775 return true; 12776 } 12777 } 12778 } 12779 } catch (RemoteException e) { 12780 } 12781 return false; 12782 } 12783 12784 /** 12785 * This method is an internal method that could be get invoked either 12786 * to delete an installed package or to clean up a failed installation. 12787 * After deleting an installed package, a broadcast is sent to notify any 12788 * listeners that the package has been installed. For cleaning up a failed 12789 * installation, the broadcast is not necessary since the package's 12790 * installation wouldn't have sent the initial broadcast either 12791 * The key steps in deleting a package are 12792 * deleting the package information in internal structures like mPackages, 12793 * deleting the packages base directories through installd 12794 * updating mSettings to reflect current status 12795 * persisting settings for later use 12796 * sending a broadcast if necessary 12797 */ 12798 private int deletePackageX(String packageName, int userId, int flags) { 12799 final PackageRemovedInfo info = new PackageRemovedInfo(); 12800 final boolean res; 12801 12802 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12803 ? UserHandle.ALL : new UserHandle(userId); 12804 12805 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12806 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12807 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12808 } 12809 12810 boolean removedForAllUsers = false; 12811 boolean systemUpdate = false; 12812 12813 // for the uninstall-updates case and restricted profiles, remember the per- 12814 // userhandle installed state 12815 int[] allUsers; 12816 boolean[] perUserInstalled; 12817 synchronized (mPackages) { 12818 PackageSetting ps = mSettings.mPackages.get(packageName); 12819 allUsers = sUserManager.getUserIds(); 12820 perUserInstalled = new boolean[allUsers.length]; 12821 for (int i = 0; i < allUsers.length; i++) { 12822 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12823 } 12824 } 12825 12826 synchronized (mInstallLock) { 12827 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12828 res = deletePackageLI(packageName, removeForUser, 12829 true, allUsers, perUserInstalled, 12830 flags | REMOVE_CHATTY, info, true); 12831 systemUpdate = info.isRemovedPackageSystemUpdate; 12832 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12833 removedForAllUsers = true; 12834 } 12835 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12836 + " removedForAllUsers=" + removedForAllUsers); 12837 } 12838 12839 if (res) { 12840 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12841 12842 // If the removed package was a system update, the old system package 12843 // was re-enabled; we need to broadcast this information 12844 if (systemUpdate) { 12845 Bundle extras = new Bundle(1); 12846 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12847 ? info.removedAppId : info.uid); 12848 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12849 12850 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12851 extras, null, null, null); 12852 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12853 extras, null, null, null); 12854 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12855 null, packageName, null, null); 12856 } 12857 } 12858 // Force a gc here. 12859 Runtime.getRuntime().gc(); 12860 // Delete the resources here after sending the broadcast to let 12861 // other processes clean up before deleting resources. 12862 if (info.args != null) { 12863 synchronized (mInstallLock) { 12864 info.args.doPostDeleteLI(true); 12865 } 12866 } 12867 12868 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12869 } 12870 12871 class PackageRemovedInfo { 12872 String removedPackage; 12873 int uid = -1; 12874 int removedAppId = -1; 12875 int[] removedUsers = null; 12876 boolean isRemovedPackageSystemUpdate = false; 12877 // Clean up resources deleted packages. 12878 InstallArgs args = null; 12879 12880 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12881 Bundle extras = new Bundle(1); 12882 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12883 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12884 if (replacing) { 12885 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12886 } 12887 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12888 if (removedPackage != null) { 12889 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12890 extras, null, null, removedUsers); 12891 if (fullRemove && !replacing) { 12892 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12893 extras, null, null, removedUsers); 12894 } 12895 } 12896 if (removedAppId >= 0) { 12897 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12898 removedUsers); 12899 } 12900 } 12901 } 12902 12903 /* 12904 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12905 * flag is not set, the data directory is removed as well. 12906 * make sure this flag is set for partially installed apps. If not its meaningless to 12907 * delete a partially installed application. 12908 */ 12909 private void removePackageDataLI(PackageSetting ps, 12910 int[] allUserHandles, boolean[] perUserInstalled, 12911 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12912 String packageName = ps.name; 12913 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12914 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12915 // Retrieve object to delete permissions for shared user later on 12916 final PackageSetting deletedPs; 12917 // reader 12918 synchronized (mPackages) { 12919 deletedPs = mSettings.mPackages.get(packageName); 12920 if (outInfo != null) { 12921 outInfo.removedPackage = packageName; 12922 outInfo.removedUsers = deletedPs != null 12923 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12924 : null; 12925 } 12926 } 12927 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12928 removeDataDirsLI(ps.volumeUuid, packageName); 12929 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12930 } 12931 // writer 12932 synchronized (mPackages) { 12933 if (deletedPs != null) { 12934 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12935 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12936 clearDefaultBrowserIfNeeded(packageName); 12937 if (outInfo != null) { 12938 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12939 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12940 } 12941 updatePermissionsLPw(deletedPs.name, null, 0); 12942 if (deletedPs.sharedUser != null) { 12943 // Remove permissions associated with package. Since runtime 12944 // permissions are per user we have to kill the removed package 12945 // or packages running under the shared user of the removed 12946 // package if revoking the permissions requested only by the removed 12947 // package is successful and this causes a change in gids. 12948 for (int userId : UserManagerService.getInstance().getUserIds()) { 12949 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12950 userId); 12951 if (userIdToKill == UserHandle.USER_ALL 12952 || userIdToKill >= UserHandle.USER_OWNER) { 12953 // If gids changed for this user, kill all affected packages. 12954 mHandler.post(new Runnable() { 12955 @Override 12956 public void run() { 12957 // This has to happen with no lock held. 12958 killApplication(deletedPs.name, deletedPs.appId, 12959 KILL_APP_REASON_GIDS_CHANGED); 12960 } 12961 }); 12962 break; 12963 } 12964 } 12965 } 12966 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12967 } 12968 // make sure to preserve per-user disabled state if this removal was just 12969 // a downgrade of a system app to the factory package 12970 if (allUserHandles != null && perUserInstalled != null) { 12971 if (DEBUG_REMOVE) { 12972 Slog.d(TAG, "Propagating install state across downgrade"); 12973 } 12974 for (int i = 0; i < allUserHandles.length; i++) { 12975 if (DEBUG_REMOVE) { 12976 Slog.d(TAG, " user " + allUserHandles[i] 12977 + " => " + perUserInstalled[i]); 12978 } 12979 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12980 } 12981 } 12982 } 12983 // can downgrade to reader 12984 if (writeSettings) { 12985 // Save settings now 12986 mSettings.writeLPr(); 12987 } 12988 } 12989 if (outInfo != null) { 12990 // A user ID was deleted here. Go through all users and remove it 12991 // from KeyStore. 12992 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12993 } 12994 } 12995 12996 static boolean locationIsPrivileged(File path) { 12997 try { 12998 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12999 .getCanonicalPath(); 13000 return path.getCanonicalPath().startsWith(privilegedAppDir); 13001 } catch (IOException e) { 13002 Slog.e(TAG, "Unable to access code path " + path); 13003 } 13004 return false; 13005 } 13006 13007 /* 13008 * Tries to delete system package. 13009 */ 13010 private boolean deleteSystemPackageLI(PackageSetting newPs, 13011 int[] allUserHandles, boolean[] perUserInstalled, 13012 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13013 final boolean applyUserRestrictions 13014 = (allUserHandles != null) && (perUserInstalled != null); 13015 PackageSetting disabledPs = null; 13016 // Confirm if the system package has been updated 13017 // An updated system app can be deleted. This will also have to restore 13018 // the system pkg from system partition 13019 // reader 13020 synchronized (mPackages) { 13021 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13022 } 13023 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13024 + " disabledPs=" + disabledPs); 13025 if (disabledPs == null) { 13026 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13027 return false; 13028 } else if (DEBUG_REMOVE) { 13029 Slog.d(TAG, "Deleting system pkg from data partition"); 13030 } 13031 if (DEBUG_REMOVE) { 13032 if (applyUserRestrictions) { 13033 Slog.d(TAG, "Remembering install states:"); 13034 for (int i = 0; i < allUserHandles.length; i++) { 13035 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13036 } 13037 } 13038 } 13039 // Delete the updated package 13040 outInfo.isRemovedPackageSystemUpdate = true; 13041 if (disabledPs.versionCode < newPs.versionCode) { 13042 // Delete data for downgrades 13043 flags &= ~PackageManager.DELETE_KEEP_DATA; 13044 } else { 13045 // Preserve data by setting flag 13046 flags |= PackageManager.DELETE_KEEP_DATA; 13047 } 13048 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13049 allUserHandles, perUserInstalled, outInfo, writeSettings); 13050 if (!ret) { 13051 return false; 13052 } 13053 // writer 13054 synchronized (mPackages) { 13055 // Reinstate the old system package 13056 mSettings.enableSystemPackageLPw(newPs.name); 13057 // Remove any native libraries from the upgraded package. 13058 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13059 } 13060 // Install the system package 13061 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13062 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13063 if (locationIsPrivileged(disabledPs.codePath)) { 13064 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13065 } 13066 13067 final PackageParser.Package newPkg; 13068 try { 13069 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13070 } catch (PackageManagerException e) { 13071 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13072 return false; 13073 } 13074 13075 // writer 13076 synchronized (mPackages) { 13077 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13078 13079 // Propagate the permissions state as we do not want to drop on the floor 13080 // runtime permissions. The update permissions method below will take 13081 // care of removing obsolete permissions and grant install permissions. 13082 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13083 updatePermissionsLPw(newPkg.packageName, newPkg, 13084 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13085 13086 if (applyUserRestrictions) { 13087 if (DEBUG_REMOVE) { 13088 Slog.d(TAG, "Propagating install state across reinstall"); 13089 } 13090 for (int i = 0; i < allUserHandles.length; i++) { 13091 if (DEBUG_REMOVE) { 13092 Slog.d(TAG, " user " + allUserHandles[i] 13093 + " => " + perUserInstalled[i]); 13094 } 13095 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13096 13097 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13098 } 13099 // Regardless of writeSettings we need to ensure that this restriction 13100 // state propagation is persisted 13101 mSettings.writeAllUsersPackageRestrictionsLPr(); 13102 } 13103 // can downgrade to reader here 13104 if (writeSettings) { 13105 mSettings.writeLPr(); 13106 } 13107 } 13108 return true; 13109 } 13110 13111 private boolean deleteInstalledPackageLI(PackageSetting ps, 13112 boolean deleteCodeAndResources, int flags, 13113 int[] allUserHandles, boolean[] perUserInstalled, 13114 PackageRemovedInfo outInfo, boolean writeSettings) { 13115 if (outInfo != null) { 13116 outInfo.uid = ps.appId; 13117 } 13118 13119 // Delete package data from internal structures and also remove data if flag is set 13120 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13121 13122 // Delete application code and resources 13123 if (deleteCodeAndResources && (outInfo != null)) { 13124 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13125 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13126 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13127 } 13128 return true; 13129 } 13130 13131 @Override 13132 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13133 int userId) { 13134 mContext.enforceCallingOrSelfPermission( 13135 android.Manifest.permission.DELETE_PACKAGES, null); 13136 synchronized (mPackages) { 13137 PackageSetting ps = mSettings.mPackages.get(packageName); 13138 if (ps == null) { 13139 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13140 return false; 13141 } 13142 if (!ps.getInstalled(userId)) { 13143 // Can't block uninstall for an app that is not installed or enabled. 13144 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13145 return false; 13146 } 13147 ps.setBlockUninstall(blockUninstall, userId); 13148 mSettings.writePackageRestrictionsLPr(userId); 13149 } 13150 return true; 13151 } 13152 13153 @Override 13154 public boolean getBlockUninstallForUser(String packageName, int userId) { 13155 synchronized (mPackages) { 13156 PackageSetting ps = mSettings.mPackages.get(packageName); 13157 if (ps == null) { 13158 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13159 return false; 13160 } 13161 return ps.getBlockUninstall(userId); 13162 } 13163 } 13164 13165 /* 13166 * This method handles package deletion in general 13167 */ 13168 private boolean deletePackageLI(String packageName, UserHandle user, 13169 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13170 int flags, PackageRemovedInfo outInfo, 13171 boolean writeSettings) { 13172 if (packageName == null) { 13173 Slog.w(TAG, "Attempt to delete null packageName."); 13174 return false; 13175 } 13176 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13177 PackageSetting ps; 13178 boolean dataOnly = false; 13179 int removeUser = -1; 13180 int appId = -1; 13181 synchronized (mPackages) { 13182 ps = mSettings.mPackages.get(packageName); 13183 if (ps == null) { 13184 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13185 return false; 13186 } 13187 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13188 && user.getIdentifier() != UserHandle.USER_ALL) { 13189 // The caller is asking that the package only be deleted for a single 13190 // user. To do this, we just mark its uninstalled state and delete 13191 // its data. If this is a system app, we only allow this to happen if 13192 // they have set the special DELETE_SYSTEM_APP which requests different 13193 // semantics than normal for uninstalling system apps. 13194 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13195 final int userId = user.getIdentifier(); 13196 ps.setUserState(userId, 13197 COMPONENT_ENABLED_STATE_DEFAULT, 13198 false, //installed 13199 true, //stopped 13200 true, //notLaunched 13201 false, //hidden 13202 null, null, null, 13203 false, // blockUninstall 13204 ps.readUserState(userId).domainVerificationStatus, 0); 13205 if (!isSystemApp(ps)) { 13206 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13207 // Other user still have this package installed, so all 13208 // we need to do is clear this user's data and save that 13209 // it is uninstalled. 13210 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13211 removeUser = user.getIdentifier(); 13212 appId = ps.appId; 13213 scheduleWritePackageRestrictionsLocked(removeUser); 13214 } else { 13215 // We need to set it back to 'installed' so the uninstall 13216 // broadcasts will be sent correctly. 13217 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13218 ps.setInstalled(true, user.getIdentifier()); 13219 } 13220 } else { 13221 // This is a system app, so we assume that the 13222 // other users still have this package installed, so all 13223 // we need to do is clear this user's data and save that 13224 // it is uninstalled. 13225 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13226 removeUser = user.getIdentifier(); 13227 appId = ps.appId; 13228 scheduleWritePackageRestrictionsLocked(removeUser); 13229 } 13230 } 13231 } 13232 13233 if (removeUser >= 0) { 13234 // From above, we determined that we are deleting this only 13235 // for a single user. Continue the work here. 13236 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13237 if (outInfo != null) { 13238 outInfo.removedPackage = packageName; 13239 outInfo.removedAppId = appId; 13240 outInfo.removedUsers = new int[] {removeUser}; 13241 } 13242 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13243 removeKeystoreDataIfNeeded(removeUser, appId); 13244 schedulePackageCleaning(packageName, removeUser, false); 13245 synchronized (mPackages) { 13246 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13247 scheduleWritePackageRestrictionsLocked(removeUser); 13248 } 13249 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13250 } 13251 return true; 13252 } 13253 13254 if (dataOnly) { 13255 // Delete application data first 13256 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13257 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13258 return true; 13259 } 13260 13261 boolean ret = false; 13262 if (isSystemApp(ps)) { 13263 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13264 // When an updated system application is deleted we delete the existing resources as well and 13265 // fall back to existing code in system partition 13266 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13267 flags, outInfo, writeSettings); 13268 } else { 13269 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13270 // Kill application pre-emptively especially for apps on sd. 13271 killApplication(packageName, ps.appId, "uninstall pkg"); 13272 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13273 allUserHandles, perUserInstalled, 13274 outInfo, writeSettings); 13275 } 13276 13277 return ret; 13278 } 13279 13280 private final class ClearStorageConnection implements ServiceConnection { 13281 IMediaContainerService mContainerService; 13282 13283 @Override 13284 public void onServiceConnected(ComponentName name, IBinder service) { 13285 synchronized (this) { 13286 mContainerService = IMediaContainerService.Stub.asInterface(service); 13287 notifyAll(); 13288 } 13289 } 13290 13291 @Override 13292 public void onServiceDisconnected(ComponentName name) { 13293 } 13294 } 13295 13296 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13297 final boolean mounted; 13298 if (Environment.isExternalStorageEmulated()) { 13299 mounted = true; 13300 } else { 13301 final String status = Environment.getExternalStorageState(); 13302 13303 mounted = status.equals(Environment.MEDIA_MOUNTED) 13304 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13305 } 13306 13307 if (!mounted) { 13308 return; 13309 } 13310 13311 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13312 int[] users; 13313 if (userId == UserHandle.USER_ALL) { 13314 users = sUserManager.getUserIds(); 13315 } else { 13316 users = new int[] { userId }; 13317 } 13318 final ClearStorageConnection conn = new ClearStorageConnection(); 13319 if (mContext.bindServiceAsUser( 13320 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13321 try { 13322 for (int curUser : users) { 13323 long timeout = SystemClock.uptimeMillis() + 5000; 13324 synchronized (conn) { 13325 long now = SystemClock.uptimeMillis(); 13326 while (conn.mContainerService == null && now < timeout) { 13327 try { 13328 conn.wait(timeout - now); 13329 } catch (InterruptedException e) { 13330 } 13331 } 13332 } 13333 if (conn.mContainerService == null) { 13334 return; 13335 } 13336 13337 final UserEnvironment userEnv = new UserEnvironment(curUser); 13338 clearDirectory(conn.mContainerService, 13339 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13340 if (allData) { 13341 clearDirectory(conn.mContainerService, 13342 userEnv.buildExternalStorageAppDataDirs(packageName)); 13343 clearDirectory(conn.mContainerService, 13344 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13345 } 13346 } 13347 } finally { 13348 mContext.unbindService(conn); 13349 } 13350 } 13351 } 13352 13353 @Override 13354 public void clearApplicationUserData(final String packageName, 13355 final IPackageDataObserver observer, final int userId) { 13356 mContext.enforceCallingOrSelfPermission( 13357 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13358 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13359 // Queue up an async operation since the package deletion may take a little while. 13360 mHandler.post(new Runnable() { 13361 public void run() { 13362 mHandler.removeCallbacks(this); 13363 final boolean succeeded; 13364 synchronized (mInstallLock) { 13365 succeeded = clearApplicationUserDataLI(packageName, userId); 13366 } 13367 clearExternalStorageDataSync(packageName, userId, true); 13368 if (succeeded) { 13369 // invoke DeviceStorageMonitor's update method to clear any notifications 13370 DeviceStorageMonitorInternal 13371 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13372 if (dsm != null) { 13373 dsm.checkMemory(); 13374 } 13375 } 13376 if(observer != null) { 13377 try { 13378 observer.onRemoveCompleted(packageName, succeeded); 13379 } catch (RemoteException e) { 13380 Log.i(TAG, "Observer no longer exists."); 13381 } 13382 } //end if observer 13383 } //end run 13384 }); 13385 } 13386 13387 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13388 if (packageName == null) { 13389 Slog.w(TAG, "Attempt to delete null packageName."); 13390 return false; 13391 } 13392 13393 // Try finding details about the requested package 13394 PackageParser.Package pkg; 13395 synchronized (mPackages) { 13396 pkg = mPackages.get(packageName); 13397 if (pkg == null) { 13398 final PackageSetting ps = mSettings.mPackages.get(packageName); 13399 if (ps != null) { 13400 pkg = ps.pkg; 13401 } 13402 } 13403 13404 if (pkg == null) { 13405 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13406 return false; 13407 } 13408 13409 PackageSetting ps = (PackageSetting) pkg.mExtras; 13410 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13411 } 13412 13413 // Always delete data directories for package, even if we found no other 13414 // record of app. This helps users recover from UID mismatches without 13415 // resorting to a full data wipe. 13416 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13417 if (retCode < 0) { 13418 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13419 return false; 13420 } 13421 13422 final int appId = pkg.applicationInfo.uid; 13423 removeKeystoreDataIfNeeded(userId, appId); 13424 13425 // Create a native library symlink only if we have native libraries 13426 // and if the native libraries are 32 bit libraries. We do not provide 13427 // this symlink for 64 bit libraries. 13428 if (pkg.applicationInfo.primaryCpuAbi != null && 13429 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13430 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13431 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13432 nativeLibPath, userId) < 0) { 13433 Slog.w(TAG, "Failed linking native library dir"); 13434 return false; 13435 } 13436 } 13437 13438 return true; 13439 } 13440 13441 /** 13442 * Reverts user permission state changes (permissions and flags) in 13443 * all packages for a given user. 13444 * 13445 * @param userId The device user for which to do a reset. 13446 */ 13447 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13448 final int packageCount = mPackages.size(); 13449 for (int i = 0; i < packageCount; i++) { 13450 PackageParser.Package pkg = mPackages.valueAt(i); 13451 PackageSetting ps = (PackageSetting) pkg.mExtras; 13452 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13453 } 13454 } 13455 13456 /** 13457 * Reverts user permission state changes (permissions and flags). 13458 * 13459 * @param ps The package for which to reset. 13460 * @param userId The device user for which to do a reset. 13461 */ 13462 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13463 final PackageSetting ps, final int userId) { 13464 if (ps.pkg == null) { 13465 return; 13466 } 13467 13468 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13469 | FLAG_PERMISSION_USER_FIXED 13470 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13471 13472 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13473 | FLAG_PERMISSION_POLICY_FIXED; 13474 13475 boolean writeInstallPermissions = false; 13476 boolean writeRuntimePermissions = false; 13477 13478 final int permissionCount = ps.pkg.requestedPermissions.size(); 13479 for (int i = 0; i < permissionCount; i++) { 13480 String permission = ps.pkg.requestedPermissions.get(i); 13481 13482 BasePermission bp = mSettings.mPermissions.get(permission); 13483 if (bp == null) { 13484 continue; 13485 } 13486 13487 // If shared user we just reset the state to which only this app contributed. 13488 if (ps.sharedUser != null) { 13489 boolean used = false; 13490 final int packageCount = ps.sharedUser.packages.size(); 13491 for (int j = 0; j < packageCount; j++) { 13492 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13493 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13494 && pkg.pkg.requestedPermissions.contains(permission)) { 13495 used = true; 13496 break; 13497 } 13498 } 13499 if (used) { 13500 continue; 13501 } 13502 } 13503 13504 PermissionsState permissionsState = ps.getPermissionsState(); 13505 13506 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13507 13508 // Always clear the user settable flags. 13509 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13510 bp.name) != null; 13511 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13512 if (hasInstallState) { 13513 writeInstallPermissions = true; 13514 } else { 13515 writeRuntimePermissions = true; 13516 } 13517 } 13518 13519 // Below is only runtime permission handling. 13520 if (!bp.isRuntime()) { 13521 continue; 13522 } 13523 13524 // Never clobber system or policy. 13525 if ((oldFlags & policyOrSystemFlags) != 0) { 13526 continue; 13527 } 13528 13529 // If this permission was granted by default, make sure it is. 13530 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13531 if (permissionsState.grantRuntimePermission(bp, userId) 13532 != PERMISSION_OPERATION_FAILURE) { 13533 writeRuntimePermissions = true; 13534 } 13535 } else { 13536 // Otherwise, reset the permission. 13537 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13538 switch (revokeResult) { 13539 case PERMISSION_OPERATION_SUCCESS: { 13540 writeRuntimePermissions = true; 13541 } break; 13542 13543 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13544 writeRuntimePermissions = true; 13545 final int appId = ps.appId; 13546 mHandler.post(new Runnable() { 13547 @Override 13548 public void run() { 13549 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13550 } 13551 }); 13552 } break; 13553 } 13554 } 13555 } 13556 13557 // Synchronously write as we are taking permissions away. 13558 if (writeRuntimePermissions) { 13559 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13560 } 13561 13562 // Synchronously write as we are taking permissions away. 13563 if (writeInstallPermissions) { 13564 mSettings.writeLPr(); 13565 } 13566 } 13567 13568 /** 13569 * Remove entries from the keystore daemon. Will only remove it if the 13570 * {@code appId} is valid. 13571 */ 13572 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13573 if (appId < 0) { 13574 return; 13575 } 13576 13577 final KeyStore keyStore = KeyStore.getInstance(); 13578 if (keyStore != null) { 13579 if (userId == UserHandle.USER_ALL) { 13580 for (final int individual : sUserManager.getUserIds()) { 13581 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13582 } 13583 } else { 13584 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13585 } 13586 } else { 13587 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13588 } 13589 } 13590 13591 @Override 13592 public void deleteApplicationCacheFiles(final String packageName, 13593 final IPackageDataObserver observer) { 13594 mContext.enforceCallingOrSelfPermission( 13595 android.Manifest.permission.DELETE_CACHE_FILES, null); 13596 // Queue up an async operation since the package deletion may take a little while. 13597 final int userId = UserHandle.getCallingUserId(); 13598 mHandler.post(new Runnable() { 13599 public void run() { 13600 mHandler.removeCallbacks(this); 13601 final boolean succeded; 13602 synchronized (mInstallLock) { 13603 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13604 } 13605 clearExternalStorageDataSync(packageName, userId, false); 13606 if (observer != null) { 13607 try { 13608 observer.onRemoveCompleted(packageName, succeded); 13609 } catch (RemoteException e) { 13610 Log.i(TAG, "Observer no longer exists."); 13611 } 13612 } //end if observer 13613 } //end run 13614 }); 13615 } 13616 13617 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13618 if (packageName == null) { 13619 Slog.w(TAG, "Attempt to delete null packageName."); 13620 return false; 13621 } 13622 PackageParser.Package p; 13623 synchronized (mPackages) { 13624 p = mPackages.get(packageName); 13625 } 13626 if (p == null) { 13627 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13628 return false; 13629 } 13630 final ApplicationInfo applicationInfo = p.applicationInfo; 13631 if (applicationInfo == null) { 13632 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13633 return false; 13634 } 13635 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13636 if (retCode < 0) { 13637 Slog.w(TAG, "Couldn't remove cache files for package: " 13638 + packageName + " u" + userId); 13639 return false; 13640 } 13641 return true; 13642 } 13643 13644 @Override 13645 public void getPackageSizeInfo(final String packageName, int userHandle, 13646 final IPackageStatsObserver observer) { 13647 mContext.enforceCallingOrSelfPermission( 13648 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13649 if (packageName == null) { 13650 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13651 } 13652 13653 PackageStats stats = new PackageStats(packageName, userHandle); 13654 13655 /* 13656 * Queue up an async operation since the package measurement may take a 13657 * little while. 13658 */ 13659 Message msg = mHandler.obtainMessage(INIT_COPY); 13660 msg.obj = new MeasureParams(stats, observer); 13661 mHandler.sendMessage(msg); 13662 } 13663 13664 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13665 PackageStats pStats) { 13666 if (packageName == null) { 13667 Slog.w(TAG, "Attempt to get size of null packageName."); 13668 return false; 13669 } 13670 PackageParser.Package p; 13671 boolean dataOnly = false; 13672 String libDirRoot = null; 13673 String asecPath = null; 13674 PackageSetting ps = null; 13675 synchronized (mPackages) { 13676 p = mPackages.get(packageName); 13677 ps = mSettings.mPackages.get(packageName); 13678 if(p == null) { 13679 dataOnly = true; 13680 if((ps == null) || (ps.pkg == null)) { 13681 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13682 return false; 13683 } 13684 p = ps.pkg; 13685 } 13686 if (ps != null) { 13687 libDirRoot = ps.legacyNativeLibraryPathString; 13688 } 13689 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 13690 final long token = Binder.clearCallingIdentity(); 13691 try { 13692 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13693 if (secureContainerId != null) { 13694 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13695 } 13696 } finally { 13697 Binder.restoreCallingIdentity(token); 13698 } 13699 } 13700 } 13701 String publicSrcDir = null; 13702 if(!dataOnly) { 13703 final ApplicationInfo applicationInfo = p.applicationInfo; 13704 if (applicationInfo == null) { 13705 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13706 return false; 13707 } 13708 if (p.isForwardLocked()) { 13709 publicSrcDir = applicationInfo.getBaseResourcePath(); 13710 } 13711 } 13712 // TODO: extend to measure size of split APKs 13713 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13714 // not just the first level. 13715 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13716 // just the primary. 13717 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13718 13719 String apkPath; 13720 File packageDir = new File(p.codePath); 13721 13722 if (packageDir.isDirectory() && p.canHaveOatDir()) { 13723 apkPath = packageDir.getAbsolutePath(); 13724 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 13725 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 13726 libDirRoot = null; 13727 } 13728 } else { 13729 apkPath = p.baseCodePath; 13730 } 13731 13732 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 13733 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13734 if (res < 0) { 13735 return false; 13736 } 13737 13738 // Fix-up for forward-locked applications in ASEC containers. 13739 if (!isExternal(p)) { 13740 pStats.codeSize += pStats.externalCodeSize; 13741 pStats.externalCodeSize = 0L; 13742 } 13743 13744 return true; 13745 } 13746 13747 13748 @Override 13749 public void addPackageToPreferred(String packageName) { 13750 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13751 } 13752 13753 @Override 13754 public void removePackageFromPreferred(String packageName) { 13755 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13756 } 13757 13758 @Override 13759 public List<PackageInfo> getPreferredPackages(int flags) { 13760 return new ArrayList<PackageInfo>(); 13761 } 13762 13763 private int getUidTargetSdkVersionLockedLPr(int uid) { 13764 Object obj = mSettings.getUserIdLPr(uid); 13765 if (obj instanceof SharedUserSetting) { 13766 final SharedUserSetting sus = (SharedUserSetting) obj; 13767 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13768 final Iterator<PackageSetting> it = sus.packages.iterator(); 13769 while (it.hasNext()) { 13770 final PackageSetting ps = it.next(); 13771 if (ps.pkg != null) { 13772 int v = ps.pkg.applicationInfo.targetSdkVersion; 13773 if (v < vers) vers = v; 13774 } 13775 } 13776 return vers; 13777 } else if (obj instanceof PackageSetting) { 13778 final PackageSetting ps = (PackageSetting) obj; 13779 if (ps.pkg != null) { 13780 return ps.pkg.applicationInfo.targetSdkVersion; 13781 } 13782 } 13783 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13784 } 13785 13786 @Override 13787 public void addPreferredActivity(IntentFilter filter, int match, 13788 ComponentName[] set, ComponentName activity, int userId) { 13789 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13790 "Adding preferred"); 13791 } 13792 13793 private void addPreferredActivityInternal(IntentFilter filter, int match, 13794 ComponentName[] set, ComponentName activity, boolean always, int userId, 13795 String opname) { 13796 // writer 13797 int callingUid = Binder.getCallingUid(); 13798 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13799 if (filter.countActions() == 0) { 13800 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13801 return; 13802 } 13803 synchronized (mPackages) { 13804 if (mContext.checkCallingOrSelfPermission( 13805 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13806 != PackageManager.PERMISSION_GRANTED) { 13807 if (getUidTargetSdkVersionLockedLPr(callingUid) 13808 < Build.VERSION_CODES.FROYO) { 13809 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13810 + callingUid); 13811 return; 13812 } 13813 mContext.enforceCallingOrSelfPermission( 13814 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13815 } 13816 13817 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13818 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13819 + userId + ":"); 13820 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13821 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13822 scheduleWritePackageRestrictionsLocked(userId); 13823 } 13824 } 13825 13826 @Override 13827 public void replacePreferredActivity(IntentFilter filter, int match, 13828 ComponentName[] set, ComponentName activity, int userId) { 13829 if (filter.countActions() != 1) { 13830 throw new IllegalArgumentException( 13831 "replacePreferredActivity expects filter to have only 1 action."); 13832 } 13833 if (filter.countDataAuthorities() != 0 13834 || filter.countDataPaths() != 0 13835 || filter.countDataSchemes() > 1 13836 || filter.countDataTypes() != 0) { 13837 throw new IllegalArgumentException( 13838 "replacePreferredActivity expects filter to have no data authorities, " + 13839 "paths, or types; and at most one scheme."); 13840 } 13841 13842 final int callingUid = Binder.getCallingUid(); 13843 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13844 synchronized (mPackages) { 13845 if (mContext.checkCallingOrSelfPermission( 13846 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13847 != PackageManager.PERMISSION_GRANTED) { 13848 if (getUidTargetSdkVersionLockedLPr(callingUid) 13849 < Build.VERSION_CODES.FROYO) { 13850 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13851 + Binder.getCallingUid()); 13852 return; 13853 } 13854 mContext.enforceCallingOrSelfPermission( 13855 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13856 } 13857 13858 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13859 if (pir != null) { 13860 // Get all of the existing entries that exactly match this filter. 13861 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13862 if (existing != null && existing.size() == 1) { 13863 PreferredActivity cur = existing.get(0); 13864 if (DEBUG_PREFERRED) { 13865 Slog.i(TAG, "Checking replace of preferred:"); 13866 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13867 if (!cur.mPref.mAlways) { 13868 Slog.i(TAG, " -- CUR; not mAlways!"); 13869 } else { 13870 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13871 Slog.i(TAG, " -- CUR: mSet=" 13872 + Arrays.toString(cur.mPref.mSetComponents)); 13873 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13874 Slog.i(TAG, " -- NEW: mMatch=" 13875 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13876 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13877 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13878 } 13879 } 13880 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13881 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13882 && cur.mPref.sameSet(set)) { 13883 // Setting the preferred activity to what it happens to be already 13884 if (DEBUG_PREFERRED) { 13885 Slog.i(TAG, "Replacing with same preferred activity " 13886 + cur.mPref.mShortComponent + " for user " 13887 + userId + ":"); 13888 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13889 } 13890 return; 13891 } 13892 } 13893 13894 if (existing != null) { 13895 if (DEBUG_PREFERRED) { 13896 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13897 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13898 } 13899 for (int i = 0; i < existing.size(); i++) { 13900 PreferredActivity pa = existing.get(i); 13901 if (DEBUG_PREFERRED) { 13902 Slog.i(TAG, "Removing existing preferred activity " 13903 + pa.mPref.mComponent + ":"); 13904 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13905 } 13906 pir.removeFilter(pa); 13907 } 13908 } 13909 } 13910 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13911 "Replacing preferred"); 13912 } 13913 } 13914 13915 @Override 13916 public void clearPackagePreferredActivities(String packageName) { 13917 final int uid = Binder.getCallingUid(); 13918 // writer 13919 synchronized (mPackages) { 13920 PackageParser.Package pkg = mPackages.get(packageName); 13921 if (pkg == null || pkg.applicationInfo.uid != uid) { 13922 if (mContext.checkCallingOrSelfPermission( 13923 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13924 != PackageManager.PERMISSION_GRANTED) { 13925 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13926 < Build.VERSION_CODES.FROYO) { 13927 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13928 + Binder.getCallingUid()); 13929 return; 13930 } 13931 mContext.enforceCallingOrSelfPermission( 13932 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13933 } 13934 } 13935 13936 int user = UserHandle.getCallingUserId(); 13937 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13938 scheduleWritePackageRestrictionsLocked(user); 13939 } 13940 } 13941 } 13942 13943 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13944 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13945 ArrayList<PreferredActivity> removed = null; 13946 boolean changed = false; 13947 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13948 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13949 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13950 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13951 continue; 13952 } 13953 Iterator<PreferredActivity> it = pir.filterIterator(); 13954 while (it.hasNext()) { 13955 PreferredActivity pa = it.next(); 13956 // Mark entry for removal only if it matches the package name 13957 // and the entry is of type "always". 13958 if (packageName == null || 13959 (pa.mPref.mComponent.getPackageName().equals(packageName) 13960 && pa.mPref.mAlways)) { 13961 if (removed == null) { 13962 removed = new ArrayList<PreferredActivity>(); 13963 } 13964 removed.add(pa); 13965 } 13966 } 13967 if (removed != null) { 13968 for (int j=0; j<removed.size(); j++) { 13969 PreferredActivity pa = removed.get(j); 13970 pir.removeFilter(pa); 13971 } 13972 changed = true; 13973 } 13974 } 13975 return changed; 13976 } 13977 13978 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13979 private void clearIntentFilterVerificationsLPw(int userId) { 13980 final int packageCount = mPackages.size(); 13981 for (int i = 0; i < packageCount; i++) { 13982 PackageParser.Package pkg = mPackages.valueAt(i); 13983 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13984 } 13985 } 13986 13987 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13988 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13989 if (userId == UserHandle.USER_ALL) { 13990 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13991 sUserManager.getUserIds())) { 13992 for (int oneUserId : sUserManager.getUserIds()) { 13993 scheduleWritePackageRestrictionsLocked(oneUserId); 13994 } 13995 } 13996 } else { 13997 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13998 scheduleWritePackageRestrictionsLocked(userId); 13999 } 14000 } 14001 } 14002 14003 void clearDefaultBrowserIfNeeded(String packageName) { 14004 for (int oneUserId : sUserManager.getUserIds()) { 14005 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14006 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14007 if (packageName.equals(defaultBrowserPackageName)) { 14008 setDefaultBrowserPackageName(null, oneUserId); 14009 } 14010 } 14011 } 14012 14013 @Override 14014 public void resetApplicationPreferences(int userId) { 14015 mContext.enforceCallingOrSelfPermission( 14016 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14017 // writer 14018 synchronized (mPackages) { 14019 final long identity = Binder.clearCallingIdentity(); 14020 try { 14021 clearPackagePreferredActivitiesLPw(null, userId); 14022 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14023 // TODO: We have to reset the default SMS and Phone. This requires 14024 // significant refactoring to keep all default apps in the package 14025 // manager (cleaner but more work) or have the services provide 14026 // callbacks to the package manager to request a default app reset. 14027 applyFactoryDefaultBrowserLPw(userId); 14028 clearIntentFilterVerificationsLPw(userId); 14029 primeDomainVerificationsLPw(userId); 14030 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14031 scheduleWritePackageRestrictionsLocked(userId); 14032 } finally { 14033 Binder.restoreCallingIdentity(identity); 14034 } 14035 } 14036 } 14037 14038 @Override 14039 public int getPreferredActivities(List<IntentFilter> outFilters, 14040 List<ComponentName> outActivities, String packageName) { 14041 14042 int num = 0; 14043 final int userId = UserHandle.getCallingUserId(); 14044 // reader 14045 synchronized (mPackages) { 14046 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14047 if (pir != null) { 14048 final Iterator<PreferredActivity> it = pir.filterIterator(); 14049 while (it.hasNext()) { 14050 final PreferredActivity pa = it.next(); 14051 if (packageName == null 14052 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14053 && pa.mPref.mAlways)) { 14054 if (outFilters != null) { 14055 outFilters.add(new IntentFilter(pa)); 14056 } 14057 if (outActivities != null) { 14058 outActivities.add(pa.mPref.mComponent); 14059 } 14060 } 14061 } 14062 } 14063 } 14064 14065 return num; 14066 } 14067 14068 @Override 14069 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14070 int userId) { 14071 int callingUid = Binder.getCallingUid(); 14072 if (callingUid != Process.SYSTEM_UID) { 14073 throw new SecurityException( 14074 "addPersistentPreferredActivity can only be run by the system"); 14075 } 14076 if (filter.countActions() == 0) { 14077 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14078 return; 14079 } 14080 synchronized (mPackages) { 14081 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14082 " :"); 14083 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14084 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14085 new PersistentPreferredActivity(filter, activity)); 14086 scheduleWritePackageRestrictionsLocked(userId); 14087 } 14088 } 14089 14090 @Override 14091 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14092 int callingUid = Binder.getCallingUid(); 14093 if (callingUid != Process.SYSTEM_UID) { 14094 throw new SecurityException( 14095 "clearPackagePersistentPreferredActivities can only be run by the system"); 14096 } 14097 ArrayList<PersistentPreferredActivity> removed = null; 14098 boolean changed = false; 14099 synchronized (mPackages) { 14100 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14101 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14102 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14103 .valueAt(i); 14104 if (userId != thisUserId) { 14105 continue; 14106 } 14107 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14108 while (it.hasNext()) { 14109 PersistentPreferredActivity ppa = it.next(); 14110 // Mark entry for removal only if it matches the package name. 14111 if (ppa.mComponent.getPackageName().equals(packageName)) { 14112 if (removed == null) { 14113 removed = new ArrayList<PersistentPreferredActivity>(); 14114 } 14115 removed.add(ppa); 14116 } 14117 } 14118 if (removed != null) { 14119 for (int j=0; j<removed.size(); j++) { 14120 PersistentPreferredActivity ppa = removed.get(j); 14121 ppir.removeFilter(ppa); 14122 } 14123 changed = true; 14124 } 14125 } 14126 14127 if (changed) { 14128 scheduleWritePackageRestrictionsLocked(userId); 14129 } 14130 } 14131 } 14132 14133 /** 14134 * Common machinery for picking apart a restored XML blob and passing 14135 * it to a caller-supplied functor to be applied to the running system. 14136 */ 14137 private void restoreFromXml(XmlPullParser parser, int userId, 14138 String expectedStartTag, BlobXmlRestorer functor) 14139 throws IOException, XmlPullParserException { 14140 int type; 14141 while ((type = parser.next()) != XmlPullParser.START_TAG 14142 && type != XmlPullParser.END_DOCUMENT) { 14143 } 14144 if (type != XmlPullParser.START_TAG) { 14145 // oops didn't find a start tag?! 14146 if (DEBUG_BACKUP) { 14147 Slog.e(TAG, "Didn't find start tag during restore"); 14148 } 14149 return; 14150 } 14151 14152 // this is supposed to be TAG_PREFERRED_BACKUP 14153 if (!expectedStartTag.equals(parser.getName())) { 14154 if (DEBUG_BACKUP) { 14155 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14156 } 14157 return; 14158 } 14159 14160 // skip interfering stuff, then we're aligned with the backing implementation 14161 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14162 functor.apply(parser, userId); 14163 } 14164 14165 private interface BlobXmlRestorer { 14166 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14167 } 14168 14169 /** 14170 * Non-Binder method, support for the backup/restore mechanism: write the 14171 * full set of preferred activities in its canonical XML format. Returns the 14172 * XML output as a byte array, or null if there is none. 14173 */ 14174 @Override 14175 public byte[] getPreferredActivityBackup(int userId) { 14176 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14177 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14178 } 14179 14180 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14181 try { 14182 final XmlSerializer serializer = new FastXmlSerializer(); 14183 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14184 serializer.startDocument(null, true); 14185 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14186 14187 synchronized (mPackages) { 14188 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14189 } 14190 14191 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14192 serializer.endDocument(); 14193 serializer.flush(); 14194 } catch (Exception e) { 14195 if (DEBUG_BACKUP) { 14196 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14197 } 14198 return null; 14199 } 14200 14201 return dataStream.toByteArray(); 14202 } 14203 14204 @Override 14205 public void restorePreferredActivities(byte[] backup, int userId) { 14206 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14207 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14208 } 14209 14210 try { 14211 final XmlPullParser parser = Xml.newPullParser(); 14212 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14213 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14214 new BlobXmlRestorer() { 14215 @Override 14216 public void apply(XmlPullParser parser, int userId) 14217 throws XmlPullParserException, IOException { 14218 synchronized (mPackages) { 14219 mSettings.readPreferredActivitiesLPw(parser, userId); 14220 } 14221 } 14222 } ); 14223 } catch (Exception e) { 14224 if (DEBUG_BACKUP) { 14225 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14226 } 14227 } 14228 } 14229 14230 /** 14231 * Non-Binder method, support for the backup/restore mechanism: write the 14232 * default browser (etc) settings in its canonical XML format. Returns the default 14233 * browser XML representation as a byte array, or null if there is none. 14234 */ 14235 @Override 14236 public byte[] getDefaultAppsBackup(int userId) { 14237 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14238 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14239 } 14240 14241 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14242 try { 14243 final XmlSerializer serializer = new FastXmlSerializer(); 14244 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14245 serializer.startDocument(null, true); 14246 serializer.startTag(null, TAG_DEFAULT_APPS); 14247 14248 synchronized (mPackages) { 14249 mSettings.writeDefaultAppsLPr(serializer, userId); 14250 } 14251 14252 serializer.endTag(null, TAG_DEFAULT_APPS); 14253 serializer.endDocument(); 14254 serializer.flush(); 14255 } catch (Exception e) { 14256 if (DEBUG_BACKUP) { 14257 Slog.e(TAG, "Unable to write default apps for backup", e); 14258 } 14259 return null; 14260 } 14261 14262 return dataStream.toByteArray(); 14263 } 14264 14265 @Override 14266 public void restoreDefaultApps(byte[] backup, int userId) { 14267 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14268 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14269 } 14270 14271 try { 14272 final XmlPullParser parser = Xml.newPullParser(); 14273 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14274 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14275 new BlobXmlRestorer() { 14276 @Override 14277 public void apply(XmlPullParser parser, int userId) 14278 throws XmlPullParserException, IOException { 14279 synchronized (mPackages) { 14280 mSettings.readDefaultAppsLPw(parser, userId); 14281 } 14282 } 14283 } ); 14284 } catch (Exception e) { 14285 if (DEBUG_BACKUP) { 14286 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14287 } 14288 } 14289 } 14290 14291 @Override 14292 public byte[] getIntentFilterVerificationBackup(int userId) { 14293 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14294 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14295 } 14296 14297 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14298 try { 14299 final XmlSerializer serializer = new FastXmlSerializer(); 14300 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14301 serializer.startDocument(null, true); 14302 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14303 14304 synchronized (mPackages) { 14305 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14306 } 14307 14308 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14309 serializer.endDocument(); 14310 serializer.flush(); 14311 } catch (Exception e) { 14312 if (DEBUG_BACKUP) { 14313 Slog.e(TAG, "Unable to write default apps for backup", e); 14314 } 14315 return null; 14316 } 14317 14318 return dataStream.toByteArray(); 14319 } 14320 14321 @Override 14322 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14323 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14324 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14325 } 14326 14327 try { 14328 final XmlPullParser parser = Xml.newPullParser(); 14329 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14330 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14331 new BlobXmlRestorer() { 14332 @Override 14333 public void apply(XmlPullParser parser, int userId) 14334 throws XmlPullParserException, IOException { 14335 synchronized (mPackages) { 14336 mSettings.readAllDomainVerificationsLPr(parser, userId); 14337 mSettings.writeLPr(); 14338 } 14339 } 14340 } ); 14341 } catch (Exception e) { 14342 if (DEBUG_BACKUP) { 14343 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14344 } 14345 } 14346 } 14347 14348 @Override 14349 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14350 int sourceUserId, int targetUserId, int flags) { 14351 mContext.enforceCallingOrSelfPermission( 14352 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14353 int callingUid = Binder.getCallingUid(); 14354 enforceOwnerRights(ownerPackage, callingUid); 14355 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14356 if (intentFilter.countActions() == 0) { 14357 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14358 return; 14359 } 14360 synchronized (mPackages) { 14361 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14362 ownerPackage, targetUserId, flags); 14363 CrossProfileIntentResolver resolver = 14364 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14365 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14366 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14367 if (existing != null) { 14368 int size = existing.size(); 14369 for (int i = 0; i < size; i++) { 14370 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14371 return; 14372 } 14373 } 14374 } 14375 resolver.addFilter(newFilter); 14376 scheduleWritePackageRestrictionsLocked(sourceUserId); 14377 } 14378 } 14379 14380 @Override 14381 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14382 mContext.enforceCallingOrSelfPermission( 14383 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14384 int callingUid = Binder.getCallingUid(); 14385 enforceOwnerRights(ownerPackage, callingUid); 14386 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14387 synchronized (mPackages) { 14388 CrossProfileIntentResolver resolver = 14389 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14390 ArraySet<CrossProfileIntentFilter> set = 14391 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14392 for (CrossProfileIntentFilter filter : set) { 14393 if (filter.getOwnerPackage().equals(ownerPackage)) { 14394 resolver.removeFilter(filter); 14395 } 14396 } 14397 scheduleWritePackageRestrictionsLocked(sourceUserId); 14398 } 14399 } 14400 14401 // Enforcing that callingUid is owning pkg on userId 14402 private void enforceOwnerRights(String pkg, int callingUid) { 14403 // The system owns everything. 14404 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14405 return; 14406 } 14407 int callingUserId = UserHandle.getUserId(callingUid); 14408 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14409 if (pi == null) { 14410 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14411 + callingUserId); 14412 } 14413 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14414 throw new SecurityException("Calling uid " + callingUid 14415 + " does not own package " + pkg); 14416 } 14417 } 14418 14419 @Override 14420 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14421 Intent intent = new Intent(Intent.ACTION_MAIN); 14422 intent.addCategory(Intent.CATEGORY_HOME); 14423 14424 final int callingUserId = UserHandle.getCallingUserId(); 14425 List<ResolveInfo> list = queryIntentActivities(intent, null, 14426 PackageManager.GET_META_DATA, callingUserId); 14427 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14428 true, false, false, callingUserId); 14429 14430 allHomeCandidates.clear(); 14431 if (list != null) { 14432 for (ResolveInfo ri : list) { 14433 allHomeCandidates.add(ri); 14434 } 14435 } 14436 return (preferred == null || preferred.activityInfo == null) 14437 ? null 14438 : new ComponentName(preferred.activityInfo.packageName, 14439 preferred.activityInfo.name); 14440 } 14441 14442 @Override 14443 public void setApplicationEnabledSetting(String appPackageName, 14444 int newState, int flags, int userId, String callingPackage) { 14445 if (!sUserManager.exists(userId)) return; 14446 if (callingPackage == null) { 14447 callingPackage = Integer.toString(Binder.getCallingUid()); 14448 } 14449 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14450 } 14451 14452 @Override 14453 public void setComponentEnabledSetting(ComponentName componentName, 14454 int newState, int flags, int userId) { 14455 if (!sUserManager.exists(userId)) return; 14456 setEnabledSetting(componentName.getPackageName(), 14457 componentName.getClassName(), newState, flags, userId, null); 14458 } 14459 14460 private void setEnabledSetting(final String packageName, String className, int newState, 14461 final int flags, int userId, String callingPackage) { 14462 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14463 || newState == COMPONENT_ENABLED_STATE_ENABLED 14464 || newState == COMPONENT_ENABLED_STATE_DISABLED 14465 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14466 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14467 throw new IllegalArgumentException("Invalid new component state: " 14468 + newState); 14469 } 14470 PackageSetting pkgSetting; 14471 final int uid = Binder.getCallingUid(); 14472 final int permission = mContext.checkCallingOrSelfPermission( 14473 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14474 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14475 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14476 boolean sendNow = false; 14477 boolean isApp = (className == null); 14478 String componentName = isApp ? packageName : className; 14479 int packageUid = -1; 14480 ArrayList<String> components; 14481 14482 // writer 14483 synchronized (mPackages) { 14484 pkgSetting = mSettings.mPackages.get(packageName); 14485 if (pkgSetting == null) { 14486 if (className == null) { 14487 throw new IllegalArgumentException( 14488 "Unknown package: " + packageName); 14489 } 14490 throw new IllegalArgumentException( 14491 "Unknown component: " + packageName 14492 + "/" + className); 14493 } 14494 // Allow root and verify that userId is not being specified by a different user 14495 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14496 throw new SecurityException( 14497 "Permission Denial: attempt to change component state from pid=" 14498 + Binder.getCallingPid() 14499 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14500 } 14501 if (className == null) { 14502 // We're dealing with an application/package level state change 14503 if (pkgSetting.getEnabled(userId) == newState) { 14504 // Nothing to do 14505 return; 14506 } 14507 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14508 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14509 // Don't care about who enables an app. 14510 callingPackage = null; 14511 } 14512 pkgSetting.setEnabled(newState, userId, callingPackage); 14513 // pkgSetting.pkg.mSetEnabled = newState; 14514 } else { 14515 // We're dealing with a component level state change 14516 // First, verify that this is a valid class name. 14517 PackageParser.Package pkg = pkgSetting.pkg; 14518 if (pkg == null || !pkg.hasComponentClassName(className)) { 14519 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14520 throw new IllegalArgumentException("Component class " + className 14521 + " does not exist in " + packageName); 14522 } else { 14523 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14524 + className + " does not exist in " + packageName); 14525 } 14526 } 14527 switch (newState) { 14528 case COMPONENT_ENABLED_STATE_ENABLED: 14529 if (!pkgSetting.enableComponentLPw(className, userId)) { 14530 return; 14531 } 14532 break; 14533 case COMPONENT_ENABLED_STATE_DISABLED: 14534 if (!pkgSetting.disableComponentLPw(className, userId)) { 14535 return; 14536 } 14537 break; 14538 case COMPONENT_ENABLED_STATE_DEFAULT: 14539 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14540 return; 14541 } 14542 break; 14543 default: 14544 Slog.e(TAG, "Invalid new component state: " + newState); 14545 return; 14546 } 14547 } 14548 scheduleWritePackageRestrictionsLocked(userId); 14549 components = mPendingBroadcasts.get(userId, packageName); 14550 final boolean newPackage = components == null; 14551 if (newPackage) { 14552 components = new ArrayList<String>(); 14553 } 14554 if (!components.contains(componentName)) { 14555 components.add(componentName); 14556 } 14557 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14558 sendNow = true; 14559 // Purge entry from pending broadcast list if another one exists already 14560 // since we are sending one right away. 14561 mPendingBroadcasts.remove(userId, packageName); 14562 } else { 14563 if (newPackage) { 14564 mPendingBroadcasts.put(userId, packageName, components); 14565 } 14566 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14567 // Schedule a message 14568 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14569 } 14570 } 14571 } 14572 14573 long callingId = Binder.clearCallingIdentity(); 14574 try { 14575 if (sendNow) { 14576 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14577 sendPackageChangedBroadcast(packageName, 14578 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14579 } 14580 } finally { 14581 Binder.restoreCallingIdentity(callingId); 14582 } 14583 } 14584 14585 private void sendPackageChangedBroadcast(String packageName, 14586 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14587 if (DEBUG_INSTALL) 14588 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14589 + componentNames); 14590 Bundle extras = new Bundle(4); 14591 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14592 String nameList[] = new String[componentNames.size()]; 14593 componentNames.toArray(nameList); 14594 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14595 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14596 extras.putInt(Intent.EXTRA_UID, packageUid); 14597 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14598 new int[] {UserHandle.getUserId(packageUid)}); 14599 } 14600 14601 @Override 14602 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14603 if (!sUserManager.exists(userId)) return; 14604 final int uid = Binder.getCallingUid(); 14605 final int permission = mContext.checkCallingOrSelfPermission( 14606 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14607 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14608 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14609 // writer 14610 synchronized (mPackages) { 14611 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14612 allowedByPermission, uid, userId)) { 14613 scheduleWritePackageRestrictionsLocked(userId); 14614 } 14615 } 14616 } 14617 14618 @Override 14619 public String getInstallerPackageName(String packageName) { 14620 // reader 14621 synchronized (mPackages) { 14622 return mSettings.getInstallerPackageNameLPr(packageName); 14623 } 14624 } 14625 14626 @Override 14627 public int getApplicationEnabledSetting(String packageName, int userId) { 14628 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14629 int uid = Binder.getCallingUid(); 14630 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14631 // reader 14632 synchronized (mPackages) { 14633 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14634 } 14635 } 14636 14637 @Override 14638 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14639 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14640 int uid = Binder.getCallingUid(); 14641 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14642 // reader 14643 synchronized (mPackages) { 14644 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14645 } 14646 } 14647 14648 @Override 14649 public void enterSafeMode() { 14650 enforceSystemOrRoot("Only the system can request entering safe mode"); 14651 14652 if (!mSystemReady) { 14653 mSafeMode = true; 14654 } 14655 } 14656 14657 @Override 14658 public void systemReady() { 14659 mSystemReady = true; 14660 14661 // Read the compatibilty setting when the system is ready. 14662 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14663 mContext.getContentResolver(), 14664 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14665 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14666 if (DEBUG_SETTINGS) { 14667 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14668 } 14669 14670 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14671 14672 synchronized (mPackages) { 14673 // Verify that all of the preferred activity components actually 14674 // exist. It is possible for applications to be updated and at 14675 // that point remove a previously declared activity component that 14676 // had been set as a preferred activity. We try to clean this up 14677 // the next time we encounter that preferred activity, but it is 14678 // possible for the user flow to never be able to return to that 14679 // situation so here we do a sanity check to make sure we haven't 14680 // left any junk around. 14681 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14682 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14683 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14684 removed.clear(); 14685 for (PreferredActivity pa : pir.filterSet()) { 14686 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14687 removed.add(pa); 14688 } 14689 } 14690 if (removed.size() > 0) { 14691 for (int r=0; r<removed.size(); r++) { 14692 PreferredActivity pa = removed.get(r); 14693 Slog.w(TAG, "Removing dangling preferred activity: " 14694 + pa.mPref.mComponent); 14695 pir.removeFilter(pa); 14696 } 14697 mSettings.writePackageRestrictionsLPr( 14698 mSettings.mPreferredActivities.keyAt(i)); 14699 } 14700 } 14701 14702 for (int userId : UserManagerService.getInstance().getUserIds()) { 14703 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14704 grantPermissionsUserIds = ArrayUtils.appendInt( 14705 grantPermissionsUserIds, userId); 14706 } 14707 } 14708 } 14709 sUserManager.systemReady(); 14710 14711 // If we upgraded grant all default permissions before kicking off. 14712 for (int userId : grantPermissionsUserIds) { 14713 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14714 } 14715 14716 // Kick off any messages waiting for system ready 14717 if (mPostSystemReadyMessages != null) { 14718 for (Message msg : mPostSystemReadyMessages) { 14719 msg.sendToTarget(); 14720 } 14721 mPostSystemReadyMessages = null; 14722 } 14723 14724 // Watch for external volumes that come and go over time 14725 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14726 storage.registerListener(mStorageListener); 14727 14728 mInstallerService.systemReady(); 14729 mPackageDexOptimizer.systemReady(); 14730 14731 MountServiceInternal mountServiceInternal = LocalServices.getService( 14732 MountServiceInternal.class); 14733 mountServiceInternal.addExternalStoragePolicy( 14734 new MountServiceInternal.ExternalStorageMountPolicy() { 14735 @Override 14736 public int getMountMode(int uid, String packageName) { 14737 if (Process.isIsolated(uid)) { 14738 return Zygote.MOUNT_EXTERNAL_NONE; 14739 } 14740 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14741 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14742 } 14743 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14744 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14745 } 14746 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14747 return Zygote.MOUNT_EXTERNAL_READ; 14748 } 14749 return Zygote.MOUNT_EXTERNAL_WRITE; 14750 } 14751 14752 @Override 14753 public boolean hasExternalStorage(int uid, String packageName) { 14754 return true; 14755 } 14756 }); 14757 } 14758 14759 @Override 14760 public boolean isSafeMode() { 14761 return mSafeMode; 14762 } 14763 14764 @Override 14765 public boolean hasSystemUidErrors() { 14766 return mHasSystemUidErrors; 14767 } 14768 14769 static String arrayToString(int[] array) { 14770 StringBuffer buf = new StringBuffer(128); 14771 buf.append('['); 14772 if (array != null) { 14773 for (int i=0; i<array.length; i++) { 14774 if (i > 0) buf.append(", "); 14775 buf.append(array[i]); 14776 } 14777 } 14778 buf.append(']'); 14779 return buf.toString(); 14780 } 14781 14782 static class DumpState { 14783 public static final int DUMP_LIBS = 1 << 0; 14784 public static final int DUMP_FEATURES = 1 << 1; 14785 public static final int DUMP_RESOLVERS = 1 << 2; 14786 public static final int DUMP_PERMISSIONS = 1 << 3; 14787 public static final int DUMP_PACKAGES = 1 << 4; 14788 public static final int DUMP_SHARED_USERS = 1 << 5; 14789 public static final int DUMP_MESSAGES = 1 << 6; 14790 public static final int DUMP_PROVIDERS = 1 << 7; 14791 public static final int DUMP_VERIFIERS = 1 << 8; 14792 public static final int DUMP_PREFERRED = 1 << 9; 14793 public static final int DUMP_PREFERRED_XML = 1 << 10; 14794 public static final int DUMP_KEYSETS = 1 << 11; 14795 public static final int DUMP_VERSION = 1 << 12; 14796 public static final int DUMP_INSTALLS = 1 << 13; 14797 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14798 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14799 14800 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14801 14802 private int mTypes; 14803 14804 private int mOptions; 14805 14806 private boolean mTitlePrinted; 14807 14808 private SharedUserSetting mSharedUser; 14809 14810 public boolean isDumping(int type) { 14811 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14812 return true; 14813 } 14814 14815 return (mTypes & type) != 0; 14816 } 14817 14818 public void setDump(int type) { 14819 mTypes |= type; 14820 } 14821 14822 public boolean isOptionEnabled(int option) { 14823 return (mOptions & option) != 0; 14824 } 14825 14826 public void setOptionEnabled(int option) { 14827 mOptions |= option; 14828 } 14829 14830 public boolean onTitlePrinted() { 14831 final boolean printed = mTitlePrinted; 14832 mTitlePrinted = true; 14833 return printed; 14834 } 14835 14836 public boolean getTitlePrinted() { 14837 return mTitlePrinted; 14838 } 14839 14840 public void setTitlePrinted(boolean enabled) { 14841 mTitlePrinted = enabled; 14842 } 14843 14844 public SharedUserSetting getSharedUser() { 14845 return mSharedUser; 14846 } 14847 14848 public void setSharedUser(SharedUserSetting user) { 14849 mSharedUser = user; 14850 } 14851 } 14852 14853 @Override 14854 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14855 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14856 != PackageManager.PERMISSION_GRANTED) { 14857 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14858 + Binder.getCallingPid() 14859 + ", uid=" + Binder.getCallingUid() 14860 + " without permission " 14861 + android.Manifest.permission.DUMP); 14862 return; 14863 } 14864 14865 DumpState dumpState = new DumpState(); 14866 boolean fullPreferred = false; 14867 boolean checkin = false; 14868 14869 String packageName = null; 14870 ArraySet<String> permissionNames = null; 14871 14872 int opti = 0; 14873 while (opti < args.length) { 14874 String opt = args[opti]; 14875 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14876 break; 14877 } 14878 opti++; 14879 14880 if ("-a".equals(opt)) { 14881 // Right now we only know how to print all. 14882 } else if ("-h".equals(opt)) { 14883 pw.println("Package manager dump options:"); 14884 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14885 pw.println(" --checkin: dump for a checkin"); 14886 pw.println(" -f: print details of intent filters"); 14887 pw.println(" -h: print this help"); 14888 pw.println(" cmd may be one of:"); 14889 pw.println(" l[ibraries]: list known shared libraries"); 14890 pw.println(" f[ibraries]: list device features"); 14891 pw.println(" k[eysets]: print known keysets"); 14892 pw.println(" r[esolvers]: dump intent resolvers"); 14893 pw.println(" perm[issions]: dump permissions"); 14894 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14895 pw.println(" pref[erred]: print preferred package settings"); 14896 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14897 pw.println(" prov[iders]: dump content providers"); 14898 pw.println(" p[ackages]: dump installed packages"); 14899 pw.println(" s[hared-users]: dump shared user IDs"); 14900 pw.println(" m[essages]: print collected runtime messages"); 14901 pw.println(" v[erifiers]: print package verifier info"); 14902 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14903 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14904 pw.println(" version: print database version info"); 14905 pw.println(" write: write current settings now"); 14906 pw.println(" installs: details about install sessions"); 14907 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 14908 pw.println(" <package.name>: info about given package"); 14909 return; 14910 } else if ("--checkin".equals(opt)) { 14911 checkin = true; 14912 } else if ("-f".equals(opt)) { 14913 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14914 } else { 14915 pw.println("Unknown argument: " + opt + "; use -h for help"); 14916 } 14917 } 14918 14919 // Is the caller requesting to dump a particular piece of data? 14920 if (opti < args.length) { 14921 String cmd = args[opti]; 14922 opti++; 14923 // Is this a package name? 14924 if ("android".equals(cmd) || cmd.contains(".")) { 14925 packageName = cmd; 14926 // When dumping a single package, we always dump all of its 14927 // filter information since the amount of data will be reasonable. 14928 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14929 } else if ("check-permission".equals(cmd)) { 14930 if (opti >= args.length) { 14931 pw.println("Error: check-permission missing permission argument"); 14932 return; 14933 } 14934 String perm = args[opti]; 14935 opti++; 14936 if (opti >= args.length) { 14937 pw.println("Error: check-permission missing package argument"); 14938 return; 14939 } 14940 String pkg = args[opti]; 14941 opti++; 14942 int user = UserHandle.getUserId(Binder.getCallingUid()); 14943 if (opti < args.length) { 14944 try { 14945 user = Integer.parseInt(args[opti]); 14946 } catch (NumberFormatException e) { 14947 pw.println("Error: check-permission user argument is not a number: " 14948 + args[opti]); 14949 return; 14950 } 14951 } 14952 pw.println(checkPermission(perm, pkg, user)); 14953 return; 14954 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14955 dumpState.setDump(DumpState.DUMP_LIBS); 14956 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14957 dumpState.setDump(DumpState.DUMP_FEATURES); 14958 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14959 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14960 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14961 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14962 } else if ("permission".equals(cmd)) { 14963 if (opti >= args.length) { 14964 pw.println("Error: permission requires permission name"); 14965 return; 14966 } 14967 permissionNames = new ArraySet<>(); 14968 while (opti < args.length) { 14969 permissionNames.add(args[opti]); 14970 opti++; 14971 } 14972 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14973 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14974 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14975 dumpState.setDump(DumpState.DUMP_PREFERRED); 14976 } else if ("preferred-xml".equals(cmd)) { 14977 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14978 if (opti < args.length && "--full".equals(args[opti])) { 14979 fullPreferred = true; 14980 opti++; 14981 } 14982 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14983 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14984 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14985 dumpState.setDump(DumpState.DUMP_PACKAGES); 14986 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14987 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14988 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14989 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14990 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14991 dumpState.setDump(DumpState.DUMP_MESSAGES); 14992 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14993 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14994 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14995 || "intent-filter-verifiers".equals(cmd)) { 14996 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14997 } else if ("version".equals(cmd)) { 14998 dumpState.setDump(DumpState.DUMP_VERSION); 14999 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15000 dumpState.setDump(DumpState.DUMP_KEYSETS); 15001 } else if ("installs".equals(cmd)) { 15002 dumpState.setDump(DumpState.DUMP_INSTALLS); 15003 } else if ("write".equals(cmd)) { 15004 synchronized (mPackages) { 15005 mSettings.writeLPr(); 15006 pw.println("Settings written."); 15007 return; 15008 } 15009 } 15010 } 15011 15012 if (checkin) { 15013 pw.println("vers,1"); 15014 } 15015 15016 // reader 15017 synchronized (mPackages) { 15018 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15019 if (!checkin) { 15020 if (dumpState.onTitlePrinted()) 15021 pw.println(); 15022 pw.println("Database versions:"); 15023 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15024 } 15025 } 15026 15027 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15028 if (!checkin) { 15029 if (dumpState.onTitlePrinted()) 15030 pw.println(); 15031 pw.println("Verifiers:"); 15032 pw.print(" Required: "); 15033 pw.print(mRequiredVerifierPackage); 15034 pw.print(" (uid="); 15035 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15036 pw.println(")"); 15037 } else if (mRequiredVerifierPackage != null) { 15038 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15039 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15040 } 15041 } 15042 15043 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15044 packageName == null) { 15045 if (mIntentFilterVerifierComponent != null) { 15046 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15047 if (!checkin) { 15048 if (dumpState.onTitlePrinted()) 15049 pw.println(); 15050 pw.println("Intent Filter Verifier:"); 15051 pw.print(" Using: "); 15052 pw.print(verifierPackageName); 15053 pw.print(" (uid="); 15054 pw.print(getPackageUid(verifierPackageName, 0)); 15055 pw.println(")"); 15056 } else if (verifierPackageName != null) { 15057 pw.print("ifv,"); pw.print(verifierPackageName); 15058 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15059 } 15060 } else { 15061 pw.println(); 15062 pw.println("No Intent Filter Verifier available!"); 15063 } 15064 } 15065 15066 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15067 boolean printedHeader = false; 15068 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15069 while (it.hasNext()) { 15070 String name = it.next(); 15071 SharedLibraryEntry ent = mSharedLibraries.get(name); 15072 if (!checkin) { 15073 if (!printedHeader) { 15074 if (dumpState.onTitlePrinted()) 15075 pw.println(); 15076 pw.println("Libraries:"); 15077 printedHeader = true; 15078 } 15079 pw.print(" "); 15080 } else { 15081 pw.print("lib,"); 15082 } 15083 pw.print(name); 15084 if (!checkin) { 15085 pw.print(" -> "); 15086 } 15087 if (ent.path != null) { 15088 if (!checkin) { 15089 pw.print("(jar) "); 15090 pw.print(ent.path); 15091 } else { 15092 pw.print(",jar,"); 15093 pw.print(ent.path); 15094 } 15095 } else { 15096 if (!checkin) { 15097 pw.print("(apk) "); 15098 pw.print(ent.apk); 15099 } else { 15100 pw.print(",apk,"); 15101 pw.print(ent.apk); 15102 } 15103 } 15104 pw.println(); 15105 } 15106 } 15107 15108 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15109 if (dumpState.onTitlePrinted()) 15110 pw.println(); 15111 if (!checkin) { 15112 pw.println("Features:"); 15113 } 15114 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15115 while (it.hasNext()) { 15116 String name = it.next(); 15117 if (!checkin) { 15118 pw.print(" "); 15119 } else { 15120 pw.print("feat,"); 15121 } 15122 pw.println(name); 15123 } 15124 } 15125 15126 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15127 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15128 : "Activity Resolver Table:", " ", packageName, 15129 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15130 dumpState.setTitlePrinted(true); 15131 } 15132 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15133 : "Receiver Resolver Table:", " ", packageName, 15134 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15135 dumpState.setTitlePrinted(true); 15136 } 15137 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15138 : "Service Resolver Table:", " ", packageName, 15139 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15140 dumpState.setTitlePrinted(true); 15141 } 15142 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15143 : "Provider Resolver Table:", " ", packageName, 15144 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15145 dumpState.setTitlePrinted(true); 15146 } 15147 } 15148 15149 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15150 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15151 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15152 int user = mSettings.mPreferredActivities.keyAt(i); 15153 if (pir.dump(pw, 15154 dumpState.getTitlePrinted() 15155 ? "\nPreferred Activities User " + user + ":" 15156 : "Preferred Activities User " + user + ":", " ", 15157 packageName, true, false)) { 15158 dumpState.setTitlePrinted(true); 15159 } 15160 } 15161 } 15162 15163 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15164 pw.flush(); 15165 FileOutputStream fout = new FileOutputStream(fd); 15166 BufferedOutputStream str = new BufferedOutputStream(fout); 15167 XmlSerializer serializer = new FastXmlSerializer(); 15168 try { 15169 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15170 serializer.startDocument(null, true); 15171 serializer.setFeature( 15172 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15173 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15174 serializer.endDocument(); 15175 serializer.flush(); 15176 } catch (IllegalArgumentException e) { 15177 pw.println("Failed writing: " + e); 15178 } catch (IllegalStateException e) { 15179 pw.println("Failed writing: " + e); 15180 } catch (IOException e) { 15181 pw.println("Failed writing: " + e); 15182 } 15183 } 15184 15185 if (!checkin 15186 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15187 && packageName == null) { 15188 pw.println(); 15189 int count = mSettings.mPackages.size(); 15190 if (count == 0) { 15191 pw.println("No applications!"); 15192 pw.println(); 15193 } else { 15194 final String prefix = " "; 15195 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15196 if (allPackageSettings.size() == 0) { 15197 pw.println("No domain preferred apps!"); 15198 pw.println(); 15199 } else { 15200 pw.println("App verification status:"); 15201 pw.println(); 15202 count = 0; 15203 for (PackageSetting ps : allPackageSettings) { 15204 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15205 if (ivi == null || ivi.getPackageName() == null) continue; 15206 pw.println(prefix + "Package: " + ivi.getPackageName()); 15207 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15208 pw.println(prefix + "Status: " + ivi.getStatusString()); 15209 pw.println(); 15210 count++; 15211 } 15212 if (count == 0) { 15213 pw.println(prefix + "No app verification established."); 15214 pw.println(); 15215 } 15216 for (int userId : sUserManager.getUserIds()) { 15217 pw.println("App linkages for user " + userId + ":"); 15218 pw.println(); 15219 count = 0; 15220 for (PackageSetting ps : allPackageSettings) { 15221 final long status = ps.getDomainVerificationStatusForUser(userId); 15222 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15223 continue; 15224 } 15225 pw.println(prefix + "Package: " + ps.name); 15226 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15227 String statusStr = IntentFilterVerificationInfo. 15228 getStatusStringFromValue(status); 15229 pw.println(prefix + "Status: " + statusStr); 15230 pw.println(); 15231 count++; 15232 } 15233 if (count == 0) { 15234 pw.println(prefix + "No configured app linkages."); 15235 pw.println(); 15236 } 15237 } 15238 } 15239 } 15240 } 15241 15242 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15243 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15244 if (packageName == null && permissionNames == null) { 15245 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15246 if (iperm == 0) { 15247 if (dumpState.onTitlePrinted()) 15248 pw.println(); 15249 pw.println("AppOp Permissions:"); 15250 } 15251 pw.print(" AppOp Permission "); 15252 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15253 pw.println(":"); 15254 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15255 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15256 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15257 } 15258 } 15259 } 15260 } 15261 15262 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15263 boolean printedSomething = false; 15264 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15265 if (packageName != null && !packageName.equals(p.info.packageName)) { 15266 continue; 15267 } 15268 if (!printedSomething) { 15269 if (dumpState.onTitlePrinted()) 15270 pw.println(); 15271 pw.println("Registered ContentProviders:"); 15272 printedSomething = true; 15273 } 15274 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15275 pw.print(" "); pw.println(p.toString()); 15276 } 15277 printedSomething = false; 15278 for (Map.Entry<String, PackageParser.Provider> entry : 15279 mProvidersByAuthority.entrySet()) { 15280 PackageParser.Provider p = entry.getValue(); 15281 if (packageName != null && !packageName.equals(p.info.packageName)) { 15282 continue; 15283 } 15284 if (!printedSomething) { 15285 if (dumpState.onTitlePrinted()) 15286 pw.println(); 15287 pw.println("ContentProvider Authorities:"); 15288 printedSomething = true; 15289 } 15290 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15291 pw.print(" "); pw.println(p.toString()); 15292 if (p.info != null && p.info.applicationInfo != null) { 15293 final String appInfo = p.info.applicationInfo.toString(); 15294 pw.print(" applicationInfo="); pw.println(appInfo); 15295 } 15296 } 15297 } 15298 15299 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15300 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15301 } 15302 15303 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15304 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15305 } 15306 15307 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15308 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15309 } 15310 15311 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15312 // XXX should handle packageName != null by dumping only install data that 15313 // the given package is involved with. 15314 if (dumpState.onTitlePrinted()) pw.println(); 15315 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15316 } 15317 15318 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15319 if (dumpState.onTitlePrinted()) pw.println(); 15320 mSettings.dumpReadMessagesLPr(pw, dumpState); 15321 15322 pw.println(); 15323 pw.println("Package warning messages:"); 15324 BufferedReader in = null; 15325 String line = null; 15326 try { 15327 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15328 while ((line = in.readLine()) != null) { 15329 if (line.contains("ignored: updated version")) continue; 15330 pw.println(line); 15331 } 15332 } catch (IOException ignored) { 15333 } finally { 15334 IoUtils.closeQuietly(in); 15335 } 15336 } 15337 15338 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15339 BufferedReader in = null; 15340 String line = null; 15341 try { 15342 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15343 while ((line = in.readLine()) != null) { 15344 if (line.contains("ignored: updated version")) continue; 15345 pw.print("msg,"); 15346 pw.println(line); 15347 } 15348 } catch (IOException ignored) { 15349 } finally { 15350 IoUtils.closeQuietly(in); 15351 } 15352 } 15353 } 15354 } 15355 15356 private String dumpDomainString(String packageName) { 15357 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15358 List<IntentFilter> filters = getAllIntentFilters(packageName); 15359 15360 ArraySet<String> result = new ArraySet<>(); 15361 if (iviList.size() > 0) { 15362 for (IntentFilterVerificationInfo ivi : iviList) { 15363 for (String host : ivi.getDomains()) { 15364 result.add(host); 15365 } 15366 } 15367 } 15368 if (filters != null && filters.size() > 0) { 15369 for (IntentFilter filter : filters) { 15370 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15371 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15372 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15373 result.addAll(filter.getHostsList()); 15374 } 15375 } 15376 } 15377 15378 StringBuilder sb = new StringBuilder(result.size() * 16); 15379 for (String domain : result) { 15380 if (sb.length() > 0) sb.append(" "); 15381 sb.append(domain); 15382 } 15383 return sb.toString(); 15384 } 15385 15386 // ------- apps on sdcard specific code ------- 15387 static final boolean DEBUG_SD_INSTALL = false; 15388 15389 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15390 15391 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15392 15393 private boolean mMediaMounted = false; 15394 15395 static String getEncryptKey() { 15396 try { 15397 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15398 SD_ENCRYPTION_KEYSTORE_NAME); 15399 if (sdEncKey == null) { 15400 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15401 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15402 if (sdEncKey == null) { 15403 Slog.e(TAG, "Failed to create encryption keys"); 15404 return null; 15405 } 15406 } 15407 return sdEncKey; 15408 } catch (NoSuchAlgorithmException nsae) { 15409 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15410 return null; 15411 } catch (IOException ioe) { 15412 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15413 return null; 15414 } 15415 } 15416 15417 /* 15418 * Update media status on PackageManager. 15419 */ 15420 @Override 15421 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15422 int callingUid = Binder.getCallingUid(); 15423 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15424 throw new SecurityException("Media status can only be updated by the system"); 15425 } 15426 // reader; this apparently protects mMediaMounted, but should probably 15427 // be a different lock in that case. 15428 synchronized (mPackages) { 15429 Log.i(TAG, "Updating external media status from " 15430 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15431 + (mediaStatus ? "mounted" : "unmounted")); 15432 if (DEBUG_SD_INSTALL) 15433 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15434 + ", mMediaMounted=" + mMediaMounted); 15435 if (mediaStatus == mMediaMounted) { 15436 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15437 : 0, -1); 15438 mHandler.sendMessage(msg); 15439 return; 15440 } 15441 mMediaMounted = mediaStatus; 15442 } 15443 // Queue up an async operation since the package installation may take a 15444 // little while. 15445 mHandler.post(new Runnable() { 15446 public void run() { 15447 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15448 } 15449 }); 15450 } 15451 15452 /** 15453 * Called by MountService when the initial ASECs to scan are available. 15454 * Should block until all the ASEC containers are finished being scanned. 15455 */ 15456 public void scanAvailableAsecs() { 15457 updateExternalMediaStatusInner(true, false, false); 15458 if (mShouldRestoreconData) { 15459 SELinuxMMAC.setRestoreconDone(); 15460 mShouldRestoreconData = false; 15461 } 15462 } 15463 15464 /* 15465 * Collect information of applications on external media, map them against 15466 * existing containers and update information based on current mount status. 15467 * Please note that we always have to report status if reportStatus has been 15468 * set to true especially when unloading packages. 15469 */ 15470 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15471 boolean externalStorage) { 15472 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15473 int[] uidArr = EmptyArray.INT; 15474 15475 final String[] list = PackageHelper.getSecureContainerList(); 15476 if (ArrayUtils.isEmpty(list)) { 15477 Log.i(TAG, "No secure containers found"); 15478 } else { 15479 // Process list of secure containers and categorize them 15480 // as active or stale based on their package internal state. 15481 15482 // reader 15483 synchronized (mPackages) { 15484 for (String cid : list) { 15485 // Leave stages untouched for now; installer service owns them 15486 if (PackageInstallerService.isStageName(cid)) continue; 15487 15488 if (DEBUG_SD_INSTALL) 15489 Log.i(TAG, "Processing container " + cid); 15490 String pkgName = getAsecPackageName(cid); 15491 if (pkgName == null) { 15492 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15493 continue; 15494 } 15495 if (DEBUG_SD_INSTALL) 15496 Log.i(TAG, "Looking for pkg : " + pkgName); 15497 15498 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15499 if (ps == null) { 15500 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15501 continue; 15502 } 15503 15504 /* 15505 * Skip packages that are not external if we're unmounting 15506 * external storage. 15507 */ 15508 if (externalStorage && !isMounted && !isExternal(ps)) { 15509 continue; 15510 } 15511 15512 final AsecInstallArgs args = new AsecInstallArgs(cid, 15513 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15514 // The package status is changed only if the code path 15515 // matches between settings and the container id. 15516 if (ps.codePathString != null 15517 && ps.codePathString.startsWith(args.getCodePath())) { 15518 if (DEBUG_SD_INSTALL) { 15519 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15520 + " at code path: " + ps.codePathString); 15521 } 15522 15523 // We do have a valid package installed on sdcard 15524 processCids.put(args, ps.codePathString); 15525 final int uid = ps.appId; 15526 if (uid != -1) { 15527 uidArr = ArrayUtils.appendInt(uidArr, uid); 15528 } 15529 } else { 15530 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15531 + ps.codePathString); 15532 } 15533 } 15534 } 15535 15536 Arrays.sort(uidArr); 15537 } 15538 15539 // Process packages with valid entries. 15540 if (isMounted) { 15541 if (DEBUG_SD_INSTALL) 15542 Log.i(TAG, "Loading packages"); 15543 loadMediaPackages(processCids, uidArr, externalStorage); 15544 startCleaningPackages(); 15545 mInstallerService.onSecureContainersAvailable(); 15546 } else { 15547 if (DEBUG_SD_INSTALL) 15548 Log.i(TAG, "Unloading packages"); 15549 unloadMediaPackages(processCids, uidArr, reportStatus); 15550 } 15551 } 15552 15553 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15554 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15555 final int size = infos.size(); 15556 final String[] packageNames = new String[size]; 15557 final int[] packageUids = new int[size]; 15558 for (int i = 0; i < size; i++) { 15559 final ApplicationInfo info = infos.get(i); 15560 packageNames[i] = info.packageName; 15561 packageUids[i] = info.uid; 15562 } 15563 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15564 finishedReceiver); 15565 } 15566 15567 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15568 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15569 sendResourcesChangedBroadcast(mediaStatus, replacing, 15570 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15571 } 15572 15573 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15574 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15575 int size = pkgList.length; 15576 if (size > 0) { 15577 // Send broadcasts here 15578 Bundle extras = new Bundle(); 15579 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15580 if (uidArr != null) { 15581 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15582 } 15583 if (replacing) { 15584 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15585 } 15586 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15587 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15588 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15589 } 15590 } 15591 15592 /* 15593 * Look at potentially valid container ids from processCids If package 15594 * information doesn't match the one on record or package scanning fails, 15595 * the cid is added to list of removeCids. We currently don't delete stale 15596 * containers. 15597 */ 15598 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 15599 boolean externalStorage) { 15600 ArrayList<String> pkgList = new ArrayList<String>(); 15601 Set<AsecInstallArgs> keys = processCids.keySet(); 15602 15603 for (AsecInstallArgs args : keys) { 15604 String codePath = processCids.get(args); 15605 if (DEBUG_SD_INSTALL) 15606 Log.i(TAG, "Loading container : " + args.cid); 15607 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15608 try { 15609 // Make sure there are no container errors first. 15610 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15611 Slog.e(TAG, "Failed to mount cid : " + args.cid 15612 + " when installing from sdcard"); 15613 continue; 15614 } 15615 // Check code path here. 15616 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15617 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15618 + " does not match one in settings " + codePath); 15619 continue; 15620 } 15621 // Parse package 15622 int parseFlags = mDefParseFlags; 15623 if (args.isExternalAsec()) { 15624 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15625 } 15626 if (args.isFwdLocked()) { 15627 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15628 } 15629 15630 synchronized (mInstallLock) { 15631 PackageParser.Package pkg = null; 15632 try { 15633 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15634 } catch (PackageManagerException e) { 15635 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15636 } 15637 // Scan the package 15638 if (pkg != null) { 15639 /* 15640 * TODO why is the lock being held? doPostInstall is 15641 * called in other places without the lock. This needs 15642 * to be straightened out. 15643 */ 15644 // writer 15645 synchronized (mPackages) { 15646 retCode = PackageManager.INSTALL_SUCCEEDED; 15647 pkgList.add(pkg.packageName); 15648 // Post process args 15649 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15650 pkg.applicationInfo.uid); 15651 } 15652 } else { 15653 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15654 } 15655 } 15656 15657 } finally { 15658 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15659 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15660 } 15661 } 15662 } 15663 // writer 15664 synchronized (mPackages) { 15665 // If the platform SDK has changed since the last time we booted, 15666 // we need to re-grant app permission to catch any new ones that 15667 // appear. This is really a hack, and means that apps can in some 15668 // cases get permissions that the user didn't initially explicitly 15669 // allow... it would be nice to have some better way to handle 15670 // this situation. 15671 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 15672 : mSettings.getInternalVersion(); 15673 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 15674 : StorageManager.UUID_PRIVATE_INTERNAL; 15675 15676 int updateFlags = UPDATE_PERMISSIONS_ALL; 15677 if (ver.sdkVersion != mSdkVersion) { 15678 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15679 + mSdkVersion + "; regranting permissions for external"); 15680 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15681 } 15682 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 15683 15684 // Yay, everything is now upgraded 15685 ver.forceCurrent(); 15686 15687 // can downgrade to reader 15688 // Persist settings 15689 mSettings.writeLPr(); 15690 } 15691 // Send a broadcast to let everyone know we are done processing 15692 if (pkgList.size() > 0) { 15693 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15694 } 15695 } 15696 15697 /* 15698 * Utility method to unload a list of specified containers 15699 */ 15700 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15701 // Just unmount all valid containers. 15702 for (AsecInstallArgs arg : cidArgs) { 15703 synchronized (mInstallLock) { 15704 arg.doPostDeleteLI(false); 15705 } 15706 } 15707 } 15708 15709 /* 15710 * Unload packages mounted on external media. This involves deleting package 15711 * data from internal structures, sending broadcasts about diabled packages, 15712 * gc'ing to free up references, unmounting all secure containers 15713 * corresponding to packages on external media, and posting a 15714 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15715 * that we always have to post this message if status has been requested no 15716 * matter what. 15717 */ 15718 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15719 final boolean reportStatus) { 15720 if (DEBUG_SD_INSTALL) 15721 Log.i(TAG, "unloading media packages"); 15722 ArrayList<String> pkgList = new ArrayList<String>(); 15723 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15724 final Set<AsecInstallArgs> keys = processCids.keySet(); 15725 for (AsecInstallArgs args : keys) { 15726 String pkgName = args.getPackageName(); 15727 if (DEBUG_SD_INSTALL) 15728 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15729 // Delete package internally 15730 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15731 synchronized (mInstallLock) { 15732 boolean res = deletePackageLI(pkgName, null, false, null, null, 15733 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15734 if (res) { 15735 pkgList.add(pkgName); 15736 } else { 15737 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15738 failedList.add(args); 15739 } 15740 } 15741 } 15742 15743 // reader 15744 synchronized (mPackages) { 15745 // We didn't update the settings after removing each package; 15746 // write them now for all packages. 15747 mSettings.writeLPr(); 15748 } 15749 15750 // We have to absolutely send UPDATED_MEDIA_STATUS only 15751 // after confirming that all the receivers processed the ordered 15752 // broadcast when packages get disabled, force a gc to clean things up. 15753 // and unload all the containers. 15754 if (pkgList.size() > 0) { 15755 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15756 new IIntentReceiver.Stub() { 15757 public void performReceive(Intent intent, int resultCode, String data, 15758 Bundle extras, boolean ordered, boolean sticky, 15759 int sendingUser) throws RemoteException { 15760 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15761 reportStatus ? 1 : 0, 1, keys); 15762 mHandler.sendMessage(msg); 15763 } 15764 }); 15765 } else { 15766 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15767 keys); 15768 mHandler.sendMessage(msg); 15769 } 15770 } 15771 15772 private void loadPrivatePackages(final VolumeInfo vol) { 15773 mHandler.post(new Runnable() { 15774 @Override 15775 public void run() { 15776 loadPrivatePackagesInner(vol); 15777 } 15778 }); 15779 } 15780 15781 private void loadPrivatePackagesInner(VolumeInfo vol) { 15782 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15783 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15784 15785 final VersionInfo ver; 15786 final List<PackageSetting> packages; 15787 synchronized (mPackages) { 15788 ver = mSettings.findOrCreateVersion(vol.fsUuid); 15789 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15790 } 15791 15792 for (PackageSetting ps : packages) { 15793 synchronized (mInstallLock) { 15794 final PackageParser.Package pkg; 15795 try { 15796 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15797 loaded.add(pkg.applicationInfo); 15798 } catch (PackageManagerException e) { 15799 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15800 } 15801 15802 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15803 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15804 } 15805 } 15806 } 15807 15808 synchronized (mPackages) { 15809 int updateFlags = UPDATE_PERMISSIONS_ALL; 15810 if (ver.sdkVersion != mSdkVersion) { 15811 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15812 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15813 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15814 } 15815 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 15816 15817 // Yay, everything is now upgraded 15818 ver.forceCurrent(); 15819 15820 mSettings.writeLPr(); 15821 } 15822 15823 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15824 sendResourcesChangedBroadcast(true, false, loaded, null); 15825 } 15826 15827 private void unloadPrivatePackages(final VolumeInfo vol) { 15828 mHandler.post(new Runnable() { 15829 @Override 15830 public void run() { 15831 unloadPrivatePackagesInner(vol); 15832 } 15833 }); 15834 } 15835 15836 private void unloadPrivatePackagesInner(VolumeInfo vol) { 15837 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15838 synchronized (mInstallLock) { 15839 synchronized (mPackages) { 15840 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15841 for (PackageSetting ps : packages) { 15842 if (ps.pkg == null) continue; 15843 15844 final ApplicationInfo info = ps.pkg.applicationInfo; 15845 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15846 if (deletePackageLI(ps.name, null, false, null, null, 15847 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15848 unloaded.add(info); 15849 } else { 15850 Slog.w(TAG, "Failed to unload " + ps.codePath); 15851 } 15852 } 15853 15854 mSettings.writeLPr(); 15855 } 15856 } 15857 15858 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15859 sendResourcesChangedBroadcast(false, false, unloaded, null); 15860 } 15861 15862 /** 15863 * Examine all users present on given mounted volume, and destroy data 15864 * belonging to users that are no longer valid, or whose user ID has been 15865 * recycled. 15866 */ 15867 private void reconcileUsers(String volumeUuid) { 15868 final File[] files = FileUtils 15869 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15870 for (File file : files) { 15871 if (!file.isDirectory()) continue; 15872 15873 final int userId; 15874 final UserInfo info; 15875 try { 15876 userId = Integer.parseInt(file.getName()); 15877 info = sUserManager.getUserInfo(userId); 15878 } catch (NumberFormatException e) { 15879 Slog.w(TAG, "Invalid user directory " + file); 15880 continue; 15881 } 15882 15883 boolean destroyUser = false; 15884 if (info == null) { 15885 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15886 + " because no matching user was found"); 15887 destroyUser = true; 15888 } else { 15889 try { 15890 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15891 } catch (IOException e) { 15892 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15893 + " because we failed to enforce serial number: " + e); 15894 destroyUser = true; 15895 } 15896 } 15897 15898 if (destroyUser) { 15899 synchronized (mInstallLock) { 15900 mInstaller.removeUserDataDirs(volumeUuid, userId); 15901 } 15902 } 15903 } 15904 15905 final UserManager um = mContext.getSystemService(UserManager.class); 15906 for (UserInfo user : um.getUsers()) { 15907 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15908 if (userDir.exists()) continue; 15909 15910 try { 15911 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15912 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15913 } catch (IOException e) { 15914 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15915 } 15916 } 15917 } 15918 15919 /** 15920 * Examine all apps present on given mounted volume, and destroy apps that 15921 * aren't expected, either due to uninstallation or reinstallation on 15922 * another volume. 15923 */ 15924 private void reconcileApps(String volumeUuid) { 15925 final File[] files = FileUtils 15926 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15927 for (File file : files) { 15928 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15929 && !PackageInstallerService.isStageName(file.getName()); 15930 if (!isPackage) { 15931 // Ignore entries which are not packages 15932 continue; 15933 } 15934 15935 boolean destroyApp = false; 15936 String packageName = null; 15937 try { 15938 final PackageLite pkg = PackageParser.parsePackageLite(file, 15939 PackageParser.PARSE_MUST_BE_APK); 15940 packageName = pkg.packageName; 15941 15942 synchronized (mPackages) { 15943 final PackageSetting ps = mSettings.mPackages.get(packageName); 15944 if (ps == null) { 15945 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15946 + volumeUuid + " because we found no install record"); 15947 destroyApp = true; 15948 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15949 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15950 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15951 destroyApp = true; 15952 } 15953 } 15954 15955 } catch (PackageParserException e) { 15956 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15957 destroyApp = true; 15958 } 15959 15960 if (destroyApp) { 15961 synchronized (mInstallLock) { 15962 if (packageName != null) { 15963 removeDataDirsLI(volumeUuid, packageName); 15964 } 15965 if (file.isDirectory()) { 15966 mInstaller.rmPackageDir(file.getAbsolutePath()); 15967 } else { 15968 file.delete(); 15969 } 15970 } 15971 } 15972 } 15973 } 15974 15975 private void unfreezePackage(String packageName) { 15976 synchronized (mPackages) { 15977 final PackageSetting ps = mSettings.mPackages.get(packageName); 15978 if (ps != null) { 15979 ps.frozen = false; 15980 } 15981 } 15982 } 15983 15984 @Override 15985 public int movePackage(final String packageName, final String volumeUuid) { 15986 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15987 15988 final int moveId = mNextMoveId.getAndIncrement(); 15989 try { 15990 movePackageInternal(packageName, volumeUuid, moveId); 15991 } catch (PackageManagerException e) { 15992 Slog.w(TAG, "Failed to move " + packageName, e); 15993 mMoveCallbacks.notifyStatusChanged(moveId, 15994 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15995 } 15996 return moveId; 15997 } 15998 15999 private void movePackageInternal(final String packageName, final String volumeUuid, 16000 final int moveId) throws PackageManagerException { 16001 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16002 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16003 final PackageManager pm = mContext.getPackageManager(); 16004 16005 final boolean currentAsec; 16006 final String currentVolumeUuid; 16007 final File codeFile; 16008 final String installerPackageName; 16009 final String packageAbiOverride; 16010 final int appId; 16011 final String seinfo; 16012 final String label; 16013 16014 // reader 16015 synchronized (mPackages) { 16016 final PackageParser.Package pkg = mPackages.get(packageName); 16017 final PackageSetting ps = mSettings.mPackages.get(packageName); 16018 if (pkg == null || ps == null) { 16019 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16020 } 16021 16022 if (pkg.applicationInfo.isSystemApp()) { 16023 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16024 "Cannot move system application"); 16025 } 16026 16027 if (pkg.applicationInfo.isExternalAsec()) { 16028 currentAsec = true; 16029 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16030 } else if (pkg.applicationInfo.isForwardLocked()) { 16031 currentAsec = true; 16032 currentVolumeUuid = "forward_locked"; 16033 } else { 16034 currentAsec = false; 16035 currentVolumeUuid = ps.volumeUuid; 16036 16037 final File probe = new File(pkg.codePath); 16038 final File probeOat = new File(probe, "oat"); 16039 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16040 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16041 "Move only supported for modern cluster style installs"); 16042 } 16043 } 16044 16045 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16046 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16047 "Package already moved to " + volumeUuid); 16048 } 16049 16050 if (ps.frozen) { 16051 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16052 "Failed to move already frozen package"); 16053 } 16054 ps.frozen = true; 16055 16056 codeFile = new File(pkg.codePath); 16057 installerPackageName = ps.installerPackageName; 16058 packageAbiOverride = ps.cpuAbiOverrideString; 16059 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16060 seinfo = pkg.applicationInfo.seinfo; 16061 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16062 } 16063 16064 // Now that we're guarded by frozen state, kill app during move 16065 final long token = Binder.clearCallingIdentity(); 16066 try { 16067 killApplication(packageName, appId, "move pkg"); 16068 } finally { 16069 Binder.restoreCallingIdentity(token); 16070 } 16071 16072 final Bundle extras = new Bundle(); 16073 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16074 extras.putString(Intent.EXTRA_TITLE, label); 16075 mMoveCallbacks.notifyCreated(moveId, extras); 16076 16077 int installFlags; 16078 final boolean moveCompleteApp; 16079 final File measurePath; 16080 16081 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16082 installFlags = INSTALL_INTERNAL; 16083 moveCompleteApp = !currentAsec; 16084 measurePath = Environment.getDataAppDirectory(volumeUuid); 16085 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16086 installFlags = INSTALL_EXTERNAL; 16087 moveCompleteApp = false; 16088 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16089 } else { 16090 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16091 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16092 || !volume.isMountedWritable()) { 16093 unfreezePackage(packageName); 16094 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16095 "Move location not mounted private volume"); 16096 } 16097 16098 Preconditions.checkState(!currentAsec); 16099 16100 installFlags = INSTALL_INTERNAL; 16101 moveCompleteApp = true; 16102 measurePath = Environment.getDataAppDirectory(volumeUuid); 16103 } 16104 16105 final PackageStats stats = new PackageStats(null, -1); 16106 synchronized (mInstaller) { 16107 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16108 unfreezePackage(packageName); 16109 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16110 "Failed to measure package size"); 16111 } 16112 } 16113 16114 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16115 + stats.dataSize); 16116 16117 final long startFreeBytes = measurePath.getFreeSpace(); 16118 final long sizeBytes; 16119 if (moveCompleteApp) { 16120 sizeBytes = stats.codeSize + stats.dataSize; 16121 } else { 16122 sizeBytes = stats.codeSize; 16123 } 16124 16125 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16126 unfreezePackage(packageName); 16127 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16128 "Not enough free space to move"); 16129 } 16130 16131 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16132 16133 final CountDownLatch installedLatch = new CountDownLatch(1); 16134 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16135 @Override 16136 public void onUserActionRequired(Intent intent) throws RemoteException { 16137 throw new IllegalStateException(); 16138 } 16139 16140 @Override 16141 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16142 Bundle extras) throws RemoteException { 16143 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16144 + PackageManager.installStatusToString(returnCode, msg)); 16145 16146 installedLatch.countDown(); 16147 16148 // Regardless of success or failure of the move operation, 16149 // always unfreeze the package 16150 unfreezePackage(packageName); 16151 16152 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16153 switch (status) { 16154 case PackageInstaller.STATUS_SUCCESS: 16155 mMoveCallbacks.notifyStatusChanged(moveId, 16156 PackageManager.MOVE_SUCCEEDED); 16157 break; 16158 case PackageInstaller.STATUS_FAILURE_STORAGE: 16159 mMoveCallbacks.notifyStatusChanged(moveId, 16160 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16161 break; 16162 default: 16163 mMoveCallbacks.notifyStatusChanged(moveId, 16164 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16165 break; 16166 } 16167 } 16168 }; 16169 16170 final MoveInfo move; 16171 if (moveCompleteApp) { 16172 // Kick off a thread to report progress estimates 16173 new Thread() { 16174 @Override 16175 public void run() { 16176 while (true) { 16177 try { 16178 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16179 break; 16180 } 16181 } catch (InterruptedException ignored) { 16182 } 16183 16184 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16185 final int progress = 10 + (int) MathUtils.constrain( 16186 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16187 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16188 } 16189 } 16190 }.start(); 16191 16192 final String dataAppName = codeFile.getName(); 16193 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16194 dataAppName, appId, seinfo); 16195 } else { 16196 move = null; 16197 } 16198 16199 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16200 16201 final Message msg = mHandler.obtainMessage(INIT_COPY); 16202 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16203 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 16204 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16205 mHandler.sendMessage(msg); 16206 } 16207 16208 @Override 16209 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16210 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16211 16212 final int realMoveId = mNextMoveId.getAndIncrement(); 16213 final Bundle extras = new Bundle(); 16214 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16215 mMoveCallbacks.notifyCreated(realMoveId, extras); 16216 16217 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16218 @Override 16219 public void onCreated(int moveId, Bundle extras) { 16220 // Ignored 16221 } 16222 16223 @Override 16224 public void onStatusChanged(int moveId, int status, long estMillis) { 16225 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16226 } 16227 }; 16228 16229 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16230 storage.setPrimaryStorageUuid(volumeUuid, callback); 16231 return realMoveId; 16232 } 16233 16234 @Override 16235 public int getMoveStatus(int moveId) { 16236 mContext.enforceCallingOrSelfPermission( 16237 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16238 return mMoveCallbacks.mLastStatus.get(moveId); 16239 } 16240 16241 @Override 16242 public void registerMoveCallback(IPackageMoveObserver callback) { 16243 mContext.enforceCallingOrSelfPermission( 16244 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16245 mMoveCallbacks.register(callback); 16246 } 16247 16248 @Override 16249 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16250 mContext.enforceCallingOrSelfPermission( 16251 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16252 mMoveCallbacks.unregister(callback); 16253 } 16254 16255 @Override 16256 public boolean setInstallLocation(int loc) { 16257 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16258 null); 16259 if (getInstallLocation() == loc) { 16260 return true; 16261 } 16262 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16263 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16264 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16265 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16266 return true; 16267 } 16268 return false; 16269 } 16270 16271 @Override 16272 public int getInstallLocation() { 16273 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16274 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16275 PackageHelper.APP_INSTALL_AUTO); 16276 } 16277 16278 /** Called by UserManagerService */ 16279 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16280 mDirtyUsers.remove(userHandle); 16281 mSettings.removeUserLPw(userHandle); 16282 mPendingBroadcasts.remove(userHandle); 16283 if (mInstaller != null) { 16284 // Technically, we shouldn't be doing this with the package lock 16285 // held. However, this is very rare, and there is already so much 16286 // other disk I/O going on, that we'll let it slide for now. 16287 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16288 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16289 final String volumeUuid = vol.getFsUuid(); 16290 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16291 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16292 } 16293 } 16294 mUserNeedsBadging.delete(userHandle); 16295 removeUnusedPackagesLILPw(userManager, userHandle); 16296 } 16297 16298 /** 16299 * We're removing userHandle and would like to remove any downloaded packages 16300 * that are no longer in use by any other user. 16301 * @param userHandle the user being removed 16302 */ 16303 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16304 final boolean DEBUG_CLEAN_APKS = false; 16305 int [] users = userManager.getUserIdsLPr(); 16306 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16307 while (psit.hasNext()) { 16308 PackageSetting ps = psit.next(); 16309 if (ps.pkg == null) { 16310 continue; 16311 } 16312 final String packageName = ps.pkg.packageName; 16313 // Skip over if system app 16314 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16315 continue; 16316 } 16317 if (DEBUG_CLEAN_APKS) { 16318 Slog.i(TAG, "Checking package " + packageName); 16319 } 16320 boolean keep = false; 16321 for (int i = 0; i < users.length; i++) { 16322 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16323 keep = true; 16324 if (DEBUG_CLEAN_APKS) { 16325 Slog.i(TAG, " Keeping package " + packageName + " for user " 16326 + users[i]); 16327 } 16328 break; 16329 } 16330 } 16331 if (!keep) { 16332 if (DEBUG_CLEAN_APKS) { 16333 Slog.i(TAG, " Removing package " + packageName); 16334 } 16335 mHandler.post(new Runnable() { 16336 public void run() { 16337 deletePackageX(packageName, userHandle, 0); 16338 } //end run 16339 }); 16340 } 16341 } 16342 } 16343 16344 /** Called by UserManagerService */ 16345 void createNewUserLILPw(int userHandle) { 16346 if (mInstaller != null) { 16347 mInstaller.createUserConfig(userHandle); 16348 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16349 applyFactoryDefaultBrowserLPw(userHandle); 16350 primeDomainVerificationsLPw(userHandle); 16351 } 16352 } 16353 16354 void newUserCreated(final int userHandle) { 16355 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16356 } 16357 16358 @Override 16359 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16360 mContext.enforceCallingOrSelfPermission( 16361 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16362 "Only package verification agents can read the verifier device identity"); 16363 16364 synchronized (mPackages) { 16365 return mSettings.getVerifierDeviceIdentityLPw(); 16366 } 16367 } 16368 16369 @Override 16370 public void setPermissionEnforced(String permission, boolean enforced) { 16371 // TODO: Now that we no longer change GID for storage, this should to away. 16372 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16373 "setPermissionEnforced"); 16374 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16375 synchronized (mPackages) { 16376 if (mSettings.mReadExternalStorageEnforced == null 16377 || mSettings.mReadExternalStorageEnforced != enforced) { 16378 mSettings.mReadExternalStorageEnforced = enforced; 16379 mSettings.writeLPr(); 16380 } 16381 } 16382 // kill any non-foreground processes so we restart them and 16383 // grant/revoke the GID. 16384 final IActivityManager am = ActivityManagerNative.getDefault(); 16385 if (am != null) { 16386 final long token = Binder.clearCallingIdentity(); 16387 try { 16388 am.killProcessesBelowForeground("setPermissionEnforcement"); 16389 } catch (RemoteException e) { 16390 } finally { 16391 Binder.restoreCallingIdentity(token); 16392 } 16393 } 16394 } else { 16395 throw new IllegalArgumentException("No selective enforcement for " + permission); 16396 } 16397 } 16398 16399 @Override 16400 @Deprecated 16401 public boolean isPermissionEnforced(String permission) { 16402 return true; 16403 } 16404 16405 @Override 16406 public boolean isStorageLow() { 16407 final long token = Binder.clearCallingIdentity(); 16408 try { 16409 final DeviceStorageMonitorInternal 16410 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16411 if (dsm != null) { 16412 return dsm.isMemoryLow(); 16413 } else { 16414 return false; 16415 } 16416 } finally { 16417 Binder.restoreCallingIdentity(token); 16418 } 16419 } 16420 16421 @Override 16422 public IPackageInstaller getPackageInstaller() { 16423 return mInstallerService; 16424 } 16425 16426 private boolean userNeedsBadging(int userId) { 16427 int index = mUserNeedsBadging.indexOfKey(userId); 16428 if (index < 0) { 16429 final UserInfo userInfo; 16430 final long token = Binder.clearCallingIdentity(); 16431 try { 16432 userInfo = sUserManager.getUserInfo(userId); 16433 } finally { 16434 Binder.restoreCallingIdentity(token); 16435 } 16436 final boolean b; 16437 if (userInfo != null && userInfo.isManagedProfile()) { 16438 b = true; 16439 } else { 16440 b = false; 16441 } 16442 mUserNeedsBadging.put(userId, b); 16443 return b; 16444 } 16445 return mUserNeedsBadging.valueAt(index); 16446 } 16447 16448 @Override 16449 public KeySet getKeySetByAlias(String packageName, String alias) { 16450 if (packageName == null || alias == null) { 16451 return null; 16452 } 16453 synchronized(mPackages) { 16454 final PackageParser.Package pkg = mPackages.get(packageName); 16455 if (pkg == null) { 16456 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16457 throw new IllegalArgumentException("Unknown package: " + packageName); 16458 } 16459 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16460 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16461 } 16462 } 16463 16464 @Override 16465 public KeySet getSigningKeySet(String packageName) { 16466 if (packageName == null) { 16467 return null; 16468 } 16469 synchronized(mPackages) { 16470 final PackageParser.Package pkg = mPackages.get(packageName); 16471 if (pkg == null) { 16472 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16473 throw new IllegalArgumentException("Unknown package: " + packageName); 16474 } 16475 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16476 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16477 throw new SecurityException("May not access signing KeySet of other apps."); 16478 } 16479 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16480 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16481 } 16482 } 16483 16484 @Override 16485 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16486 if (packageName == null || ks == null) { 16487 return false; 16488 } 16489 synchronized(mPackages) { 16490 final PackageParser.Package pkg = mPackages.get(packageName); 16491 if (pkg == null) { 16492 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16493 throw new IllegalArgumentException("Unknown package: " + packageName); 16494 } 16495 IBinder ksh = ks.getToken(); 16496 if (ksh instanceof KeySetHandle) { 16497 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16498 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16499 } 16500 return false; 16501 } 16502 } 16503 16504 @Override 16505 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16506 if (packageName == null || ks == null) { 16507 return false; 16508 } 16509 synchronized(mPackages) { 16510 final PackageParser.Package pkg = mPackages.get(packageName); 16511 if (pkg == null) { 16512 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16513 throw new IllegalArgumentException("Unknown package: " + packageName); 16514 } 16515 IBinder ksh = ks.getToken(); 16516 if (ksh instanceof KeySetHandle) { 16517 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16518 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16519 } 16520 return false; 16521 } 16522 } 16523 16524 public void getUsageStatsIfNoPackageUsageInfo() { 16525 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16526 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16527 if (usm == null) { 16528 throw new IllegalStateException("UsageStatsManager must be initialized"); 16529 } 16530 long now = System.currentTimeMillis(); 16531 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16532 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16533 String packageName = entry.getKey(); 16534 PackageParser.Package pkg = mPackages.get(packageName); 16535 if (pkg == null) { 16536 continue; 16537 } 16538 UsageStats usage = entry.getValue(); 16539 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16540 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16541 } 16542 } 16543 } 16544 16545 /** 16546 * Check and throw if the given before/after packages would be considered a 16547 * downgrade. 16548 */ 16549 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16550 throws PackageManagerException { 16551 if (after.versionCode < before.mVersionCode) { 16552 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16553 "Update version code " + after.versionCode + " is older than current " 16554 + before.mVersionCode); 16555 } else if (after.versionCode == before.mVersionCode) { 16556 if (after.baseRevisionCode < before.baseRevisionCode) { 16557 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16558 "Update base revision code " + after.baseRevisionCode 16559 + " is older than current " + before.baseRevisionCode); 16560 } 16561 16562 if (!ArrayUtils.isEmpty(after.splitNames)) { 16563 for (int i = 0; i < after.splitNames.length; i++) { 16564 final String splitName = after.splitNames[i]; 16565 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16566 if (j != -1) { 16567 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16568 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16569 "Update split " + splitName + " revision code " 16570 + after.splitRevisionCodes[i] + " is older than current " 16571 + before.splitRevisionCodes[j]); 16572 } 16573 } 16574 } 16575 } 16576 } 16577 } 16578 16579 private static class MoveCallbacks extends Handler { 16580 private static final int MSG_CREATED = 1; 16581 private static final int MSG_STATUS_CHANGED = 2; 16582 16583 private final RemoteCallbackList<IPackageMoveObserver> 16584 mCallbacks = new RemoteCallbackList<>(); 16585 16586 private final SparseIntArray mLastStatus = new SparseIntArray(); 16587 16588 public MoveCallbacks(Looper looper) { 16589 super(looper); 16590 } 16591 16592 public void register(IPackageMoveObserver callback) { 16593 mCallbacks.register(callback); 16594 } 16595 16596 public void unregister(IPackageMoveObserver callback) { 16597 mCallbacks.unregister(callback); 16598 } 16599 16600 @Override 16601 public void handleMessage(Message msg) { 16602 final SomeArgs args = (SomeArgs) msg.obj; 16603 final int n = mCallbacks.beginBroadcast(); 16604 for (int i = 0; i < n; i++) { 16605 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16606 try { 16607 invokeCallback(callback, msg.what, args); 16608 } catch (RemoteException ignored) { 16609 } 16610 } 16611 mCallbacks.finishBroadcast(); 16612 args.recycle(); 16613 } 16614 16615 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16616 throws RemoteException { 16617 switch (what) { 16618 case MSG_CREATED: { 16619 callback.onCreated(args.argi1, (Bundle) args.arg2); 16620 break; 16621 } 16622 case MSG_STATUS_CHANGED: { 16623 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16624 break; 16625 } 16626 } 16627 } 16628 16629 private void notifyCreated(int moveId, Bundle extras) { 16630 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16631 16632 final SomeArgs args = SomeArgs.obtain(); 16633 args.argi1 = moveId; 16634 args.arg2 = extras; 16635 obtainMessage(MSG_CREATED, args).sendToTarget(); 16636 } 16637 16638 private void notifyStatusChanged(int moveId, int status) { 16639 notifyStatusChanged(moveId, status, -1); 16640 } 16641 16642 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16643 Slog.v(TAG, "Move " + moveId + " status " + status); 16644 16645 final SomeArgs args = SomeArgs.obtain(); 16646 args.argi1 = moveId; 16647 args.argi2 = status; 16648 args.arg3 = estMillis; 16649 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16650 16651 synchronized (mLastStatus) { 16652 mLastStatus.put(moveId, status); 16653 } 16654 } 16655 } 16656 16657 private final class OnPermissionChangeListeners extends Handler { 16658 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16659 16660 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16661 new RemoteCallbackList<>(); 16662 16663 public OnPermissionChangeListeners(Looper looper) { 16664 super(looper); 16665 } 16666 16667 @Override 16668 public void handleMessage(Message msg) { 16669 switch (msg.what) { 16670 case MSG_ON_PERMISSIONS_CHANGED: { 16671 final int uid = msg.arg1; 16672 handleOnPermissionsChanged(uid); 16673 } break; 16674 } 16675 } 16676 16677 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16678 mPermissionListeners.register(listener); 16679 16680 } 16681 16682 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16683 mPermissionListeners.unregister(listener); 16684 } 16685 16686 public void onPermissionsChanged(int uid) { 16687 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16688 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16689 } 16690 } 16691 16692 private void handleOnPermissionsChanged(int uid) { 16693 final int count = mPermissionListeners.beginBroadcast(); 16694 try { 16695 for (int i = 0; i < count; i++) { 16696 IOnPermissionsChangeListener callback = mPermissionListeners 16697 .getBroadcastItem(i); 16698 try { 16699 callback.onPermissionsChanged(uid); 16700 } catch (RemoteException e) { 16701 Log.e(TAG, "Permission listener is dead", e); 16702 } 16703 } 16704 } finally { 16705 mPermissionListeners.finishBroadcast(); 16706 } 16707 } 16708 } 16709 16710 private class PackageManagerInternalImpl extends PackageManagerInternal { 16711 @Override 16712 public void setLocationPackagesProvider(PackagesProvider provider) { 16713 synchronized (mPackages) { 16714 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16715 } 16716 } 16717 16718 @Override 16719 public void setImePackagesProvider(PackagesProvider provider) { 16720 synchronized (mPackages) { 16721 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16722 } 16723 } 16724 16725 @Override 16726 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16727 synchronized (mPackages) { 16728 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16729 } 16730 } 16731 16732 @Override 16733 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16734 synchronized (mPackages) { 16735 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16736 } 16737 } 16738 16739 @Override 16740 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16741 synchronized (mPackages) { 16742 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16743 } 16744 } 16745 16746 @Override 16747 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16748 synchronized (mPackages) { 16749 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16750 } 16751 } 16752 16753 @Override 16754 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16755 synchronized (mPackages) { 16756 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16757 } 16758 } 16759 16760 @Override 16761 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16762 synchronized (mPackages) { 16763 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16764 packageName, userId); 16765 } 16766 } 16767 16768 @Override 16769 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16770 synchronized (mPackages) { 16771 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16772 packageName, userId); 16773 } 16774 } 16775 @Override 16776 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16777 synchronized (mPackages) { 16778 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16779 packageName, userId); 16780 } 16781 } 16782 } 16783 16784 @Override 16785 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16786 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16787 synchronized (mPackages) { 16788 final long identity = Binder.clearCallingIdentity(); 16789 try { 16790 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16791 packageNames, userId); 16792 } finally { 16793 Binder.restoreCallingIdentity(identity); 16794 } 16795 } 16796 } 16797 16798 private static void enforceSystemOrPhoneCaller(String tag) { 16799 int callingUid = Binder.getCallingUid(); 16800 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16801 throw new SecurityException( 16802 "Cannot call " + tag + " from UID " + callingUid); 16803 } 16804 } 16805} 16806