PackageManagerService.java revision 949ea1442925cbbce72ccff1b0ffc7c7f876e97b
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.Installer.DEXOPT_PUBLIC; 78import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 81import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 82import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 86 87import android.Manifest; 88import android.app.ActivityManager; 89import android.app.ActivityManagerNative; 90import android.app.AppGlobals; 91import android.app.IActivityManager; 92import android.app.admin.IDevicePolicyManager; 93import android.app.backup.IBackupManager; 94import android.app.usage.UsageStats; 95import android.app.usage.UsageStatsManager; 96import android.content.BroadcastReceiver; 97import android.content.ComponentName; 98import android.content.Context; 99import android.content.IIntentReceiver; 100import android.content.Intent; 101import android.content.IntentFilter; 102import android.content.IntentSender; 103import android.content.IntentSender.SendIntentException; 104import android.content.ServiceConnection; 105import android.content.pm.ActivityInfo; 106import android.content.pm.ApplicationInfo; 107import android.content.pm.FeatureInfo; 108import android.content.pm.IOnPermissionsChangeListener; 109import android.content.pm.IPackageDataObserver; 110import android.content.pm.IPackageDeleteObserver; 111import android.content.pm.IPackageDeleteObserver2; 112import android.content.pm.IPackageInstallObserver2; 113import android.content.pm.IPackageInstaller; 114import android.content.pm.IPackageManager; 115import android.content.pm.IPackageMoveObserver; 116import android.content.pm.IPackageStatsObserver; 117import android.content.pm.InstrumentationInfo; 118import android.content.pm.IntentFilterVerificationInfo; 119import android.content.pm.KeySet; 120import android.content.pm.ManifestDigest; 121import android.content.pm.PackageCleanItem; 122import android.content.pm.PackageInfo; 123import android.content.pm.PackageInfoLite; 124import android.content.pm.PackageInstaller; 125import android.content.pm.PackageManager; 126import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 127import android.content.pm.PackageManagerInternal; 128import android.content.pm.PackageParser; 129import android.content.pm.PackageParser.ActivityIntentInfo; 130import android.content.pm.PackageParser.PackageLite; 131import android.content.pm.PackageParser.PackageParserException; 132import android.content.pm.PackageStats; 133import android.content.pm.PackageUserState; 134import android.content.pm.ParceledListSlice; 135import android.content.pm.PermissionGroupInfo; 136import android.content.pm.PermissionInfo; 137import android.content.pm.ProviderInfo; 138import android.content.pm.ResolveInfo; 139import android.content.pm.ServiceInfo; 140import android.content.pm.Signature; 141import android.content.pm.UserInfo; 142import android.content.pm.VerificationParams; 143import android.content.pm.VerifierDeviceIdentity; 144import android.content.pm.VerifierInfo; 145import android.content.res.Resources; 146import android.hardware.display.DisplayManager; 147import android.net.Uri; 148import android.os.Debug; 149import android.os.Binder; 150import android.os.Build; 151import android.os.Bundle; 152import android.os.Environment; 153import android.os.Environment.UserEnvironment; 154import android.os.FileUtils; 155import android.os.Handler; 156import android.os.IBinder; 157import android.os.Looper; 158import android.os.Message; 159import android.os.Parcel; 160import android.os.ParcelFileDescriptor; 161import android.os.Process; 162import android.os.RemoteCallbackList; 163import android.os.RemoteException; 164import android.os.SELinux; 165import android.os.ServiceManager; 166import android.os.SystemClock; 167import android.os.SystemProperties; 168import android.os.UserHandle; 169import android.os.UserManager; 170import android.os.storage.IMountService; 171import android.os.storage.MountServiceInternal; 172import android.os.storage.StorageEventListener; 173import android.os.storage.StorageManager; 174import android.os.storage.VolumeInfo; 175import android.os.storage.VolumeRecord; 176import android.security.KeyStore; 177import android.security.SystemKeyStore; 178import android.system.ErrnoException; 179import android.system.Os; 180import android.system.StructStat; 181import android.text.TextUtils; 182import android.text.format.DateUtils; 183import android.util.ArrayMap; 184import android.util.ArraySet; 185import android.util.AtomicFile; 186import android.util.DisplayMetrics; 187import android.util.EventLog; 188import android.util.ExceptionUtils; 189import android.util.Log; 190import android.util.LogPrinter; 191import android.util.MathUtils; 192import android.util.PrintStreamPrinter; 193import android.util.Slog; 194import android.util.SparseArray; 195import android.util.SparseBooleanArray; 196import android.util.SparseIntArray; 197import android.util.Xml; 198import android.view.Display; 199 200import dalvik.system.DexFile; 201import dalvik.system.VMRuntime; 202 203import libcore.io.IoUtils; 204import libcore.util.EmptyArray; 205 206import com.android.internal.R; 207import com.android.internal.annotations.GuardedBy; 208import com.android.internal.app.IMediaContainerService; 209import com.android.internal.app.ResolverActivity; 210import com.android.internal.content.NativeLibraryHelper; 211import com.android.internal.content.PackageHelper; 212import com.android.internal.os.IParcelFileDescriptorFactory; 213import com.android.internal.os.SomeArgs; 214import com.android.internal.os.Zygote; 215import com.android.internal.util.ArrayUtils; 216import com.android.internal.util.FastPrintWriter; 217import com.android.internal.util.FastXmlSerializer; 218import com.android.internal.util.IndentingPrintWriter; 219import com.android.internal.util.Preconditions; 220import com.android.server.EventLogTags; 221import com.android.server.FgThread; 222import com.android.server.IntentResolver; 223import com.android.server.LocalServices; 224import com.android.server.ServiceThread; 225import com.android.server.SystemConfig; 226import com.android.server.Watchdog; 227import com.android.server.pm.PermissionsState.PermissionState; 228import com.android.server.pm.Settings.DatabaseVersion; 229import com.android.server.pm.Settings.VersionInfo; 230import com.android.server.storage.DeviceStorageMonitorInternal; 231 232import org.xmlpull.v1.XmlPullParser; 233import org.xmlpull.v1.XmlPullParserException; 234import org.xmlpull.v1.XmlSerializer; 235 236import java.io.BufferedInputStream; 237import java.io.BufferedOutputStream; 238import java.io.BufferedReader; 239import java.io.ByteArrayInputStream; 240import java.io.ByteArrayOutputStream; 241import java.io.File; 242import java.io.FileDescriptor; 243import java.io.FileNotFoundException; 244import java.io.FileOutputStream; 245import java.io.FileReader; 246import java.io.FilenameFilter; 247import java.io.IOException; 248import java.io.InputStream; 249import java.io.PrintWriter; 250import java.nio.charset.StandardCharsets; 251import java.security.NoSuchAlgorithmException; 252import java.security.PublicKey; 253import java.security.cert.CertificateEncodingException; 254import java.security.cert.CertificateException; 255import java.text.SimpleDateFormat; 256import java.util.ArrayList; 257import java.util.Arrays; 258import java.util.Collection; 259import java.util.Collections; 260import java.util.Comparator; 261import java.util.Date; 262import java.util.Iterator; 263import java.util.List; 264import java.util.Map; 265import java.util.Objects; 266import java.util.Set; 267import java.util.concurrent.CountDownLatch; 268import java.util.concurrent.TimeUnit; 269import java.util.concurrent.atomic.AtomicBoolean; 270import java.util.concurrent.atomic.AtomicInteger; 271import java.util.concurrent.atomic.AtomicLong; 272 273/** 274 * Keep track of all those .apks everywhere. 275 * 276 * This is very central to the platform's security; please run the unit 277 * tests whenever making modifications here: 278 * 279mmm frameworks/base/tests/AndroidTests 280adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 281adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 282 * 283 * {@hide} 284 */ 285public class PackageManagerService extends IPackageManager.Stub { 286 static final String TAG = "PackageManager"; 287 static final boolean DEBUG_SETTINGS = false; 288 static final boolean DEBUG_PREFERRED = false; 289 static final boolean DEBUG_UPGRADE = false; 290 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 291 private static final boolean DEBUG_BACKUP = false; 292 private static final boolean DEBUG_INSTALL = false; 293 private static final boolean DEBUG_REMOVE = false; 294 private static final boolean DEBUG_BROADCASTS = false; 295 private static final boolean DEBUG_SHOW_INFO = false; 296 private static final boolean DEBUG_PACKAGE_INFO = false; 297 private static final boolean DEBUG_INTENT_MATCHING = false; 298 private static final boolean DEBUG_PACKAGE_SCANNING = false; 299 private static final boolean DEBUG_VERIFY = false; 300 private static final boolean DEBUG_DEXOPT = false; 301 private static final boolean DEBUG_ABI_SELECTION = false; 302 303 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 304 305 private static final int RADIO_UID = Process.PHONE_UID; 306 private static final int LOG_UID = Process.LOG_UID; 307 private static final int NFC_UID = Process.NFC_UID; 308 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 309 private static final int SHELL_UID = Process.SHELL_UID; 310 311 // Cap the size of permission trees that 3rd party apps can define 312 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 313 314 // Suffix used during package installation when copying/moving 315 // package apks to install directory. 316 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 317 318 static final int SCAN_NO_DEX = 1<<1; 319 static final int SCAN_FORCE_DEX = 1<<2; 320 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 321 static final int SCAN_NEW_INSTALL = 1<<4; 322 static final int SCAN_NO_PATHS = 1<<5; 323 static final int SCAN_UPDATE_TIME = 1<<6; 324 static final int SCAN_DEFER_DEX = 1<<7; 325 static final int SCAN_BOOTING = 1<<8; 326 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 327 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 328 static final int SCAN_REPLACING = 1<<11; 329 static final int SCAN_REQUIRE_KNOWN = 1<<12; 330 static final int SCAN_MOVE = 1<<13; 331 static final int SCAN_INITIAL = 1<<14; 332 333 static final int REMOVE_CHATTY = 1<<16; 334 335 private static final int[] EMPTY_INT_ARRAY = new int[0]; 336 337 /** 338 * Timeout (in milliseconds) after which the watchdog should declare that 339 * our handler thread is wedged. The usual default for such things is one 340 * minute but we sometimes do very lengthy I/O operations on this thread, 341 * such as installing multi-gigabyte applications, so ours needs to be longer. 342 */ 343 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 344 345 /** 346 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 347 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 348 * settings entry if available, otherwise we use the hardcoded default. If it's been 349 * more than this long since the last fstrim, we force one during the boot sequence. 350 * 351 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 352 * one gets run at the next available charging+idle time. This final mandatory 353 * no-fstrim check kicks in only of the other scheduling criteria is never met. 354 */ 355 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 356 357 /** 358 * Whether verification is enabled by default. 359 */ 360 private static final boolean DEFAULT_VERIFY_ENABLE = true; 361 362 /** 363 * The default maximum time to wait for the verification agent to return in 364 * milliseconds. 365 */ 366 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 367 368 /** 369 * The default response for package verification timeout. 370 * 371 * This can be either PackageManager.VERIFICATION_ALLOW or 372 * PackageManager.VERIFICATION_REJECT. 373 */ 374 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 375 376 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 377 378 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 379 DEFAULT_CONTAINER_PACKAGE, 380 "com.android.defcontainer.DefaultContainerService"); 381 382 private static final String KILL_APP_REASON_GIDS_CHANGED = 383 "permission grant or revoke changed gids"; 384 385 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 386 "permissions revoked"; 387 388 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 389 390 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 391 392 /** Permission grant: not grant the permission. */ 393 private static final int GRANT_DENIED = 1; 394 395 /** Permission grant: grant the permission as an install permission. */ 396 private static final int GRANT_INSTALL = 2; 397 398 /** Permission grant: grant the permission as an install permission for a legacy app. */ 399 private static final int GRANT_INSTALL_LEGACY = 3; 400 401 /** Permission grant: grant the permission as a runtime one. */ 402 private static final int GRANT_RUNTIME = 4; 403 404 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 405 private static final int GRANT_UPGRADE = 5; 406 407 /** Canonical intent used to identify what counts as a "web browser" app */ 408 private static final Intent sBrowserIntent; 409 static { 410 sBrowserIntent = new Intent(); 411 sBrowserIntent.setAction(Intent.ACTION_VIEW); 412 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 413 sBrowserIntent.setData(Uri.parse("http:")); 414 } 415 416 final ServiceThread mHandlerThread; 417 418 final PackageHandler mHandler; 419 420 /** 421 * Messages for {@link #mHandler} that need to wait for system ready before 422 * being dispatched. 423 */ 424 private ArrayList<Message> mPostSystemReadyMessages; 425 426 final int mSdkVersion = Build.VERSION.SDK_INT; 427 428 final Context mContext; 429 final boolean mFactoryTest; 430 final boolean mOnlyCore; 431 final boolean mLazyDexOpt; 432 final long mDexOptLRUThresholdInMills; 433 final DisplayMetrics mMetrics; 434 final int mDefParseFlags; 435 final String[] mSeparateProcesses; 436 final boolean mIsUpgrade; 437 438 // This is where all application persistent data goes. 439 final File mAppDataDir; 440 441 // This is where all application persistent data goes for secondary users. 442 final File mUserAppDataDir; 443 444 /** The location for ASEC container files on internal storage. */ 445 final String mAsecInternalPath; 446 447 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 448 // LOCK HELD. Can be called with mInstallLock held. 449 @GuardedBy("mInstallLock") 450 final Installer mInstaller; 451 452 /** Directory where installed third-party apps stored */ 453 final File mAppInstallDir; 454 455 /** 456 * Directory to which applications installed internally have their 457 * 32 bit native libraries copied. 458 */ 459 private File mAppLib32InstallDir; 460 461 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 462 // apps. 463 final File mDrmAppPrivateInstallDir; 464 465 // ---------------------------------------------------------------- 466 467 // Lock for state used when installing and doing other long running 468 // operations. Methods that must be called with this lock held have 469 // the suffix "LI". 470 final Object mInstallLock = new Object(); 471 472 // ---------------------------------------------------------------- 473 474 // Keys are String (package name), values are Package. This also serves 475 // as the lock for the global state. Methods that must be called with 476 // this lock held have the prefix "LP". 477 @GuardedBy("mPackages") 478 final ArrayMap<String, PackageParser.Package> mPackages = 479 new ArrayMap<String, PackageParser.Package>(); 480 481 // Tracks available target package names -> overlay package paths. 482 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 483 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 484 485 /** 486 * Tracks new system packages [received in an OTA] that we expect to 487 * find updated user-installed versions. Keys are package name, values 488 * are package location. 489 */ 490 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 491 492 /** 493 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 494 */ 495 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 496 /** 497 * Whether or not system app permissions should be promoted from install to runtime. 498 */ 499 boolean mPromoteSystemApps; 500 501 final Settings mSettings; 502 boolean mRestoredSettings; 503 504 // System configuration read by SystemConfig. 505 final int[] mGlobalGids; 506 final SparseArray<ArraySet<String>> mSystemPermissions; 507 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 508 509 // If mac_permissions.xml was found for seinfo labeling. 510 boolean mFoundPolicyFile; 511 512 // If a recursive restorecon of /data/data/<pkg> is needed. 513 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 514 515 public static final class SharedLibraryEntry { 516 public final String path; 517 public final String apk; 518 519 SharedLibraryEntry(String _path, String _apk) { 520 path = _path; 521 apk = _apk; 522 } 523 } 524 525 // Currently known shared libraries. 526 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 527 new ArrayMap<String, SharedLibraryEntry>(); 528 529 // All available activities, for your resolving pleasure. 530 final ActivityIntentResolver mActivities = 531 new ActivityIntentResolver(); 532 533 // All available receivers, for your resolving pleasure. 534 final ActivityIntentResolver mReceivers = 535 new ActivityIntentResolver(); 536 537 // All available services, for your resolving pleasure. 538 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 539 540 // All available providers, for your resolving pleasure. 541 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 542 543 // Mapping from provider base names (first directory in content URI codePath) 544 // to the provider information. 545 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 546 new ArrayMap<String, PackageParser.Provider>(); 547 548 // Mapping from instrumentation class names to info about them. 549 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 550 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 551 552 // Mapping from permission names to info about them. 553 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 554 new ArrayMap<String, PackageParser.PermissionGroup>(); 555 556 // Packages whose data we have transfered into another package, thus 557 // should no longer exist. 558 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 559 560 // Broadcast actions that are only available to the system. 561 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 562 563 /** List of packages waiting for verification. */ 564 final SparseArray<PackageVerificationState> mPendingVerification 565 = new SparseArray<PackageVerificationState>(); 566 567 /** Set of packages associated with each app op permission. */ 568 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 569 570 final PackageInstallerService mInstallerService; 571 572 private final PackageDexOptimizer mPackageDexOptimizer; 573 574 private AtomicInteger mNextMoveId = new AtomicInteger(); 575 private final MoveCallbacks mMoveCallbacks; 576 577 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 578 579 // Cache of users who need badging. 580 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 581 582 /** Token for keys in mPendingVerification. */ 583 private int mPendingVerificationToken = 0; 584 585 volatile boolean mSystemReady; 586 volatile boolean mSafeMode; 587 volatile boolean mHasSystemUidErrors; 588 589 ApplicationInfo mAndroidApplication; 590 final ActivityInfo mResolveActivity = new ActivityInfo(); 591 final ResolveInfo mResolveInfo = new ResolveInfo(); 592 ComponentName mResolveComponentName; 593 PackageParser.Package mPlatformPackage; 594 ComponentName mCustomResolverComponentName; 595 596 boolean mResolverReplaced = false; 597 598 private final ComponentName mIntentFilterVerifierComponent; 599 private int mIntentFilterVerificationToken = 0; 600 601 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 602 = new SparseArray<IntentFilterVerificationState>(); 603 604 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 605 new DefaultPermissionGrantPolicy(this); 606 607 private static class IFVerificationParams { 608 PackageParser.Package pkg; 609 boolean replacing; 610 int userId; 611 int verifierUid; 612 613 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 614 int _userId, int _verifierUid) { 615 pkg = _pkg; 616 replacing = _replacing; 617 userId = _userId; 618 replacing = _replacing; 619 verifierUid = _verifierUid; 620 } 621 } 622 623 private interface IntentFilterVerifier<T extends IntentFilter> { 624 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 625 T filter, String packageName); 626 void startVerifications(int userId); 627 void receiveVerificationResponse(int verificationId); 628 } 629 630 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 631 private Context mContext; 632 private ComponentName mIntentFilterVerifierComponent; 633 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 634 635 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 636 mContext = context; 637 mIntentFilterVerifierComponent = verifierComponent; 638 } 639 640 private String getDefaultScheme() { 641 return IntentFilter.SCHEME_HTTPS; 642 } 643 644 @Override 645 public void startVerifications(int userId) { 646 // Launch verifications requests 647 int count = mCurrentIntentFilterVerifications.size(); 648 for (int n=0; n<count; n++) { 649 int verificationId = mCurrentIntentFilterVerifications.get(n); 650 final IntentFilterVerificationState ivs = 651 mIntentFilterVerificationStates.get(verificationId); 652 653 String packageName = ivs.getPackageName(); 654 655 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 656 final int filterCount = filters.size(); 657 ArraySet<String> domainsSet = new ArraySet<>(); 658 for (int m=0; m<filterCount; m++) { 659 PackageParser.ActivityIntentInfo filter = filters.get(m); 660 domainsSet.addAll(filter.getHostsList()); 661 } 662 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 663 synchronized (mPackages) { 664 if (mSettings.createIntentFilterVerificationIfNeededLPw( 665 packageName, domainsList) != null) { 666 scheduleWriteSettingsLocked(); 667 } 668 } 669 sendVerificationRequest(userId, verificationId, ivs); 670 } 671 mCurrentIntentFilterVerifications.clear(); 672 } 673 674 private void sendVerificationRequest(int userId, int verificationId, 675 IntentFilterVerificationState ivs) { 676 677 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 678 verificationIntent.putExtra( 679 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 680 verificationId); 681 verificationIntent.putExtra( 682 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 683 getDefaultScheme()); 684 verificationIntent.putExtra( 685 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 686 ivs.getHostsString()); 687 verificationIntent.putExtra( 688 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 689 ivs.getPackageName()); 690 verificationIntent.setComponent(mIntentFilterVerifierComponent); 691 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 692 693 UserHandle user = new UserHandle(userId); 694 mContext.sendBroadcastAsUser(verificationIntent, user); 695 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 696 "Sending IntentFilter verification broadcast"); 697 } 698 699 public void receiveVerificationResponse(int verificationId) { 700 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 701 702 final boolean verified = ivs.isVerified(); 703 704 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 705 final int count = filters.size(); 706 if (DEBUG_DOMAIN_VERIFICATION) { 707 Slog.i(TAG, "Received verification response " + verificationId 708 + " for " + count + " filters, verified=" + verified); 709 } 710 for (int n=0; n<count; n++) { 711 PackageParser.ActivityIntentInfo filter = filters.get(n); 712 filter.setVerified(verified); 713 714 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 715 + " verified with result:" + verified + " and hosts:" 716 + ivs.getHostsString()); 717 } 718 719 mIntentFilterVerificationStates.remove(verificationId); 720 721 final String packageName = ivs.getPackageName(); 722 IntentFilterVerificationInfo ivi = null; 723 724 synchronized (mPackages) { 725 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 726 } 727 if (ivi == null) { 728 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 729 + verificationId + " packageName:" + packageName); 730 return; 731 } 732 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 733 "Updating IntentFilterVerificationInfo for package " + packageName 734 +" verificationId:" + verificationId); 735 736 synchronized (mPackages) { 737 if (verified) { 738 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 739 } else { 740 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 741 } 742 scheduleWriteSettingsLocked(); 743 744 final int userId = ivs.getUserId(); 745 if (userId != UserHandle.USER_ALL) { 746 final int userStatus = 747 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 748 749 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 750 boolean needUpdate = false; 751 752 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 753 // already been set by the User thru the Disambiguation dialog 754 switch (userStatus) { 755 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 756 if (verified) { 757 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 758 } else { 759 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 760 } 761 needUpdate = true; 762 break; 763 764 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 765 if (verified) { 766 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 767 needUpdate = true; 768 } 769 break; 770 771 default: 772 // Nothing to do 773 } 774 775 if (needUpdate) { 776 mSettings.updateIntentFilterVerificationStatusLPw( 777 packageName, updatedStatus, userId); 778 scheduleWritePackageRestrictionsLocked(userId); 779 } 780 } 781 } 782 } 783 784 @Override 785 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 786 ActivityIntentInfo filter, String packageName) { 787 if (!hasValidDomains(filter)) { 788 return false; 789 } 790 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 791 if (ivs == null) { 792 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 793 packageName); 794 } 795 if (DEBUG_DOMAIN_VERIFICATION) { 796 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 797 } 798 ivs.addFilter(filter); 799 return true; 800 } 801 802 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 803 int userId, int verificationId, String packageName) { 804 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 805 verifierUid, userId, packageName); 806 ivs.setPendingState(); 807 synchronized (mPackages) { 808 mIntentFilterVerificationStates.append(verificationId, ivs); 809 mCurrentIntentFilterVerifications.add(verificationId); 810 } 811 return ivs; 812 } 813 } 814 815 private static boolean hasValidDomains(ActivityIntentInfo filter) { 816 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 817 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 818 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 819 } 820 821 private IntentFilterVerifier mIntentFilterVerifier; 822 823 // Set of pending broadcasts for aggregating enable/disable of components. 824 static class PendingPackageBroadcasts { 825 // for each user id, a map of <package name -> components within that package> 826 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 827 828 public PendingPackageBroadcasts() { 829 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 830 } 831 832 public ArrayList<String> get(int userId, String packageName) { 833 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 834 return packages.get(packageName); 835 } 836 837 public void put(int userId, String packageName, ArrayList<String> components) { 838 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 839 packages.put(packageName, components); 840 } 841 842 public void remove(int userId, String packageName) { 843 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 844 if (packages != null) { 845 packages.remove(packageName); 846 } 847 } 848 849 public void remove(int userId) { 850 mUidMap.remove(userId); 851 } 852 853 public int userIdCount() { 854 return mUidMap.size(); 855 } 856 857 public int userIdAt(int n) { 858 return mUidMap.keyAt(n); 859 } 860 861 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 862 return mUidMap.get(userId); 863 } 864 865 public int size() { 866 // total number of pending broadcast entries across all userIds 867 int num = 0; 868 for (int i = 0; i< mUidMap.size(); i++) { 869 num += mUidMap.valueAt(i).size(); 870 } 871 return num; 872 } 873 874 public void clear() { 875 mUidMap.clear(); 876 } 877 878 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 879 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 880 if (map == null) { 881 map = new ArrayMap<String, ArrayList<String>>(); 882 mUidMap.put(userId, map); 883 } 884 return map; 885 } 886 } 887 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 888 889 // Service Connection to remote media container service to copy 890 // package uri's from external media onto secure containers 891 // or internal storage. 892 private IMediaContainerService mContainerService = null; 893 894 static final int SEND_PENDING_BROADCAST = 1; 895 static final int MCS_BOUND = 3; 896 static final int END_COPY = 4; 897 static final int INIT_COPY = 5; 898 static final int MCS_UNBIND = 6; 899 static final int START_CLEANING_PACKAGE = 7; 900 static final int FIND_INSTALL_LOC = 8; 901 static final int POST_INSTALL = 9; 902 static final int MCS_RECONNECT = 10; 903 static final int MCS_GIVE_UP = 11; 904 static final int UPDATED_MEDIA_STATUS = 12; 905 static final int WRITE_SETTINGS = 13; 906 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 907 static final int PACKAGE_VERIFIED = 15; 908 static final int CHECK_PENDING_VERIFICATION = 16; 909 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 910 static final int INTENT_FILTER_VERIFIED = 18; 911 912 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 913 914 // Delay time in millisecs 915 static final int BROADCAST_DELAY = 10 * 1000; 916 917 static UserManagerService sUserManager; 918 919 // Stores a list of users whose package restrictions file needs to be updated 920 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 921 922 final private DefaultContainerConnection mDefContainerConn = 923 new DefaultContainerConnection(); 924 class DefaultContainerConnection implements ServiceConnection { 925 public void onServiceConnected(ComponentName name, IBinder service) { 926 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 927 IMediaContainerService imcs = 928 IMediaContainerService.Stub.asInterface(service); 929 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 930 } 931 932 public void onServiceDisconnected(ComponentName name) { 933 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 934 } 935 } 936 937 // Recordkeeping of restore-after-install operations that are currently in flight 938 // between the Package Manager and the Backup Manager 939 class PostInstallData { 940 public InstallArgs args; 941 public PackageInstalledInfo res; 942 943 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 944 args = _a; 945 res = _r; 946 } 947 } 948 949 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 950 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 951 952 // XML tags for backup/restore of various bits of state 953 private static final String TAG_PREFERRED_BACKUP = "pa"; 954 private static final String TAG_DEFAULT_APPS = "da"; 955 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 956 957 final String mRequiredVerifierPackage; 958 final String mRequiredInstallerPackage; 959 960 private final PackageUsage mPackageUsage = new PackageUsage(); 961 962 private class PackageUsage { 963 private static final int WRITE_INTERVAL 964 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 965 966 private final Object mFileLock = new Object(); 967 private final AtomicLong mLastWritten = new AtomicLong(0); 968 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 969 970 private boolean mIsHistoricalPackageUsageAvailable = true; 971 972 boolean isHistoricalPackageUsageAvailable() { 973 return mIsHistoricalPackageUsageAvailable; 974 } 975 976 void write(boolean force) { 977 if (force) { 978 writeInternal(); 979 return; 980 } 981 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 982 && !DEBUG_DEXOPT) { 983 return; 984 } 985 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 986 new Thread("PackageUsage_DiskWriter") { 987 @Override 988 public void run() { 989 try { 990 writeInternal(); 991 } finally { 992 mBackgroundWriteRunning.set(false); 993 } 994 } 995 }.start(); 996 } 997 } 998 999 private void writeInternal() { 1000 synchronized (mPackages) { 1001 synchronized (mFileLock) { 1002 AtomicFile file = getFile(); 1003 FileOutputStream f = null; 1004 try { 1005 f = file.startWrite(); 1006 BufferedOutputStream out = new BufferedOutputStream(f); 1007 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1008 StringBuilder sb = new StringBuilder(); 1009 for (PackageParser.Package pkg : mPackages.values()) { 1010 if (pkg.mLastPackageUsageTimeInMills == 0) { 1011 continue; 1012 } 1013 sb.setLength(0); 1014 sb.append(pkg.packageName); 1015 sb.append(' '); 1016 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1017 sb.append('\n'); 1018 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1019 } 1020 out.flush(); 1021 file.finishWrite(f); 1022 } catch (IOException e) { 1023 if (f != null) { 1024 file.failWrite(f); 1025 } 1026 Log.e(TAG, "Failed to write package usage times", e); 1027 } 1028 } 1029 } 1030 mLastWritten.set(SystemClock.elapsedRealtime()); 1031 } 1032 1033 void readLP() { 1034 synchronized (mFileLock) { 1035 AtomicFile file = getFile(); 1036 BufferedInputStream in = null; 1037 try { 1038 in = new BufferedInputStream(file.openRead()); 1039 StringBuffer sb = new StringBuffer(); 1040 while (true) { 1041 String packageName = readToken(in, sb, ' '); 1042 if (packageName == null) { 1043 break; 1044 } 1045 String timeInMillisString = readToken(in, sb, '\n'); 1046 if (timeInMillisString == null) { 1047 throw new IOException("Failed to find last usage time for package " 1048 + packageName); 1049 } 1050 PackageParser.Package pkg = mPackages.get(packageName); 1051 if (pkg == null) { 1052 continue; 1053 } 1054 long timeInMillis; 1055 try { 1056 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1057 } catch (NumberFormatException e) { 1058 throw new IOException("Failed to parse " + timeInMillisString 1059 + " as a long.", e); 1060 } 1061 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1062 } 1063 } catch (FileNotFoundException expected) { 1064 mIsHistoricalPackageUsageAvailable = false; 1065 } catch (IOException e) { 1066 Log.w(TAG, "Failed to read package usage times", e); 1067 } finally { 1068 IoUtils.closeQuietly(in); 1069 } 1070 } 1071 mLastWritten.set(SystemClock.elapsedRealtime()); 1072 } 1073 1074 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1075 throws IOException { 1076 sb.setLength(0); 1077 while (true) { 1078 int ch = in.read(); 1079 if (ch == -1) { 1080 if (sb.length() == 0) { 1081 return null; 1082 } 1083 throw new IOException("Unexpected EOF"); 1084 } 1085 if (ch == endOfToken) { 1086 return sb.toString(); 1087 } 1088 sb.append((char)ch); 1089 } 1090 } 1091 1092 private AtomicFile getFile() { 1093 File dataDir = Environment.getDataDirectory(); 1094 File systemDir = new File(dataDir, "system"); 1095 File fname = new File(systemDir, "package-usage.list"); 1096 return new AtomicFile(fname); 1097 } 1098 } 1099 1100 class PackageHandler extends Handler { 1101 private boolean mBound = false; 1102 final ArrayList<HandlerParams> mPendingInstalls = 1103 new ArrayList<HandlerParams>(); 1104 1105 private boolean connectToService() { 1106 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1107 " DefaultContainerService"); 1108 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1109 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1110 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1111 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1113 mBound = true; 1114 return true; 1115 } 1116 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1117 return false; 1118 } 1119 1120 private void disconnectService() { 1121 mContainerService = null; 1122 mBound = false; 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1124 mContext.unbindService(mDefContainerConn); 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } 1127 1128 PackageHandler(Looper looper) { 1129 super(looper); 1130 } 1131 1132 public void handleMessage(Message msg) { 1133 try { 1134 doHandleMessage(msg); 1135 } finally { 1136 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1137 } 1138 } 1139 1140 void doHandleMessage(Message msg) { 1141 switch (msg.what) { 1142 case INIT_COPY: { 1143 HandlerParams params = (HandlerParams) msg.obj; 1144 int idx = mPendingInstalls.size(); 1145 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1146 // If a bind was already initiated we dont really 1147 // need to do anything. The pending install 1148 // will be processed later on. 1149 if (!mBound) { 1150 // If this is the only one pending we might 1151 // have to bind to the service again. 1152 if (!connectToService()) { 1153 Slog.e(TAG, "Failed to bind to media container service"); 1154 params.serviceError(); 1155 return; 1156 } else { 1157 // Once we bind to the service, the first 1158 // pending request will be processed. 1159 mPendingInstalls.add(idx, params); 1160 } 1161 } else { 1162 mPendingInstalls.add(idx, params); 1163 // Already bound to the service. Just make 1164 // sure we trigger off processing the first request. 1165 if (idx == 0) { 1166 mHandler.sendEmptyMessage(MCS_BOUND); 1167 } 1168 } 1169 break; 1170 } 1171 case MCS_BOUND: { 1172 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1173 if (msg.obj != null) { 1174 mContainerService = (IMediaContainerService) msg.obj; 1175 } 1176 if (mContainerService == null) { 1177 if (!mBound) { 1178 // Something seriously wrong since we are not bound and we are not 1179 // waiting for connection. Bail out. 1180 Slog.e(TAG, "Cannot bind to media container service"); 1181 for (HandlerParams params : mPendingInstalls) { 1182 // Indicate service bind error 1183 params.serviceError(); 1184 } 1185 mPendingInstalls.clear(); 1186 } else { 1187 Slog.w(TAG, "Waiting to connect to media container service"); 1188 } 1189 } else if (mPendingInstalls.size() > 0) { 1190 HandlerParams params = mPendingInstalls.get(0); 1191 if (params != null) { 1192 if (params.startCopy()) { 1193 // We are done... look for more work or to 1194 // go idle. 1195 if (DEBUG_SD_INSTALL) Log.i(TAG, 1196 "Checking for more work or unbind..."); 1197 // Delete pending install 1198 if (mPendingInstalls.size() > 0) { 1199 mPendingInstalls.remove(0); 1200 } 1201 if (mPendingInstalls.size() == 0) { 1202 if (mBound) { 1203 if (DEBUG_SD_INSTALL) Log.i(TAG, 1204 "Posting delayed MCS_UNBIND"); 1205 removeMessages(MCS_UNBIND); 1206 Message ubmsg = obtainMessage(MCS_UNBIND); 1207 // Unbind after a little delay, to avoid 1208 // continual thrashing. 1209 sendMessageDelayed(ubmsg, 10000); 1210 } 1211 } else { 1212 // There are more pending requests in queue. 1213 // Just post MCS_BOUND message to trigger processing 1214 // of next pending install. 1215 if (DEBUG_SD_INSTALL) Log.i(TAG, 1216 "Posting MCS_BOUND for next work"); 1217 mHandler.sendEmptyMessage(MCS_BOUND); 1218 } 1219 } 1220 } 1221 } else { 1222 // Should never happen ideally. 1223 Slog.w(TAG, "Empty queue"); 1224 } 1225 break; 1226 } 1227 case MCS_RECONNECT: { 1228 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1229 if (mPendingInstalls.size() > 0) { 1230 if (mBound) { 1231 disconnectService(); 1232 } 1233 if (!connectToService()) { 1234 Slog.e(TAG, "Failed to bind to media container service"); 1235 for (HandlerParams params : mPendingInstalls) { 1236 // Indicate service bind error 1237 params.serviceError(); 1238 } 1239 mPendingInstalls.clear(); 1240 } 1241 } 1242 break; 1243 } 1244 case MCS_UNBIND: { 1245 // If there is no actual work left, then time to unbind. 1246 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1247 1248 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1249 if (mBound) { 1250 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1251 1252 disconnectService(); 1253 } 1254 } else if (mPendingInstalls.size() > 0) { 1255 // There are more pending requests in queue. 1256 // Just post MCS_BOUND message to trigger processing 1257 // of next pending install. 1258 mHandler.sendEmptyMessage(MCS_BOUND); 1259 } 1260 1261 break; 1262 } 1263 case MCS_GIVE_UP: { 1264 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1265 mPendingInstalls.remove(0); 1266 break; 1267 } 1268 case SEND_PENDING_BROADCAST: { 1269 String packages[]; 1270 ArrayList<String> components[]; 1271 int size = 0; 1272 int uids[]; 1273 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1274 synchronized (mPackages) { 1275 if (mPendingBroadcasts == null) { 1276 return; 1277 } 1278 size = mPendingBroadcasts.size(); 1279 if (size <= 0) { 1280 // Nothing to be done. Just return 1281 return; 1282 } 1283 packages = new String[size]; 1284 components = new ArrayList[size]; 1285 uids = new int[size]; 1286 int i = 0; // filling out the above arrays 1287 1288 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1289 int packageUserId = mPendingBroadcasts.userIdAt(n); 1290 Iterator<Map.Entry<String, ArrayList<String>>> it 1291 = mPendingBroadcasts.packagesForUserId(packageUserId) 1292 .entrySet().iterator(); 1293 while (it.hasNext() && i < size) { 1294 Map.Entry<String, ArrayList<String>> ent = it.next(); 1295 packages[i] = ent.getKey(); 1296 components[i] = ent.getValue(); 1297 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1298 uids[i] = (ps != null) 1299 ? UserHandle.getUid(packageUserId, ps.appId) 1300 : -1; 1301 i++; 1302 } 1303 } 1304 size = i; 1305 mPendingBroadcasts.clear(); 1306 } 1307 // Send broadcasts 1308 for (int i = 0; i < size; i++) { 1309 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1310 } 1311 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1312 break; 1313 } 1314 case START_CLEANING_PACKAGE: { 1315 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1316 final String packageName = (String)msg.obj; 1317 final int userId = msg.arg1; 1318 final boolean andCode = msg.arg2 != 0; 1319 synchronized (mPackages) { 1320 if (userId == UserHandle.USER_ALL) { 1321 int[] users = sUserManager.getUserIds(); 1322 for (int user : users) { 1323 mSettings.addPackageToCleanLPw( 1324 new PackageCleanItem(user, packageName, andCode)); 1325 } 1326 } else { 1327 mSettings.addPackageToCleanLPw( 1328 new PackageCleanItem(userId, packageName, andCode)); 1329 } 1330 } 1331 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1332 startCleaningPackages(); 1333 } break; 1334 case POST_INSTALL: { 1335 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1336 PostInstallData data = mRunningInstalls.get(msg.arg1); 1337 mRunningInstalls.delete(msg.arg1); 1338 boolean deleteOld = false; 1339 1340 if (data != null) { 1341 InstallArgs args = data.args; 1342 PackageInstalledInfo res = data.res; 1343 1344 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1345 final String packageName = res.pkg.applicationInfo.packageName; 1346 res.removedInfo.sendBroadcast(false, true, false); 1347 Bundle extras = new Bundle(1); 1348 extras.putInt(Intent.EXTRA_UID, res.uid); 1349 1350 // Now that we successfully installed the package, grant runtime 1351 // permissions if requested before broadcasting the install. 1352 if ((args.installFlags 1353 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1354 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1355 args.installGrantPermissions); 1356 } 1357 1358 // Determine the set of users who are adding this 1359 // package for the first time vs. those who are seeing 1360 // an update. 1361 int[] firstUsers; 1362 int[] updateUsers = new int[0]; 1363 if (res.origUsers == null || res.origUsers.length == 0) { 1364 firstUsers = res.newUsers; 1365 } else { 1366 firstUsers = new int[0]; 1367 for (int i=0; i<res.newUsers.length; i++) { 1368 int user = res.newUsers[i]; 1369 boolean isNew = true; 1370 for (int j=0; j<res.origUsers.length; j++) { 1371 if (res.origUsers[j] == user) { 1372 isNew = false; 1373 break; 1374 } 1375 } 1376 if (isNew) { 1377 int[] newFirst = new int[firstUsers.length+1]; 1378 System.arraycopy(firstUsers, 0, newFirst, 0, 1379 firstUsers.length); 1380 newFirst[firstUsers.length] = user; 1381 firstUsers = newFirst; 1382 } else { 1383 int[] newUpdate = new int[updateUsers.length+1]; 1384 System.arraycopy(updateUsers, 0, newUpdate, 0, 1385 updateUsers.length); 1386 newUpdate[updateUsers.length] = user; 1387 updateUsers = newUpdate; 1388 } 1389 } 1390 } 1391 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1392 packageName, extras, null, null, firstUsers); 1393 final boolean update = res.removedInfo.removedPackage != null; 1394 if (update) { 1395 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1396 } 1397 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1398 packageName, extras, null, null, updateUsers); 1399 if (update) { 1400 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1401 packageName, extras, null, null, updateUsers); 1402 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1403 null, null, packageName, null, updateUsers); 1404 1405 // treat asec-hosted packages like removable media on upgrade 1406 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1407 if (DEBUG_INSTALL) { 1408 Slog.i(TAG, "upgrading pkg " + res.pkg 1409 + " is ASEC-hosted -> AVAILABLE"); 1410 } 1411 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1412 ArrayList<String> pkgList = new ArrayList<String>(1); 1413 pkgList.add(packageName); 1414 sendResourcesChangedBroadcast(true, true, 1415 pkgList,uidArray, null); 1416 } 1417 } 1418 if (res.removedInfo.args != null) { 1419 // Remove the replaced package's older resources safely now 1420 deleteOld = true; 1421 } 1422 1423 // If this app is a browser and it's newly-installed for some 1424 // users, clear any default-browser state in those users 1425 if (firstUsers.length > 0) { 1426 // the app's nature doesn't depend on the user, so we can just 1427 // check its browser nature in any user and generalize. 1428 if (packageIsBrowser(packageName, firstUsers[0])) { 1429 synchronized (mPackages) { 1430 for (int userId : firstUsers) { 1431 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1432 } 1433 } 1434 } 1435 } 1436 // Log current value of "unknown sources" setting 1437 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1438 getUnknownSourcesSettings()); 1439 } 1440 // Force a gc to clear up things 1441 Runtime.getRuntime().gc(); 1442 // We delete after a gc for applications on sdcard. 1443 if (deleteOld) { 1444 synchronized (mInstallLock) { 1445 res.removedInfo.args.doPostDeleteLI(true); 1446 } 1447 } 1448 if (args.observer != null) { 1449 try { 1450 Bundle extras = extrasForInstallResult(res); 1451 args.observer.onPackageInstalled(res.name, res.returnCode, 1452 res.returnMsg, extras); 1453 } catch (RemoteException e) { 1454 Slog.i(TAG, "Observer no longer exists."); 1455 } 1456 } 1457 } else { 1458 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1459 } 1460 } break; 1461 case UPDATED_MEDIA_STATUS: { 1462 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1463 boolean reportStatus = msg.arg1 == 1; 1464 boolean doGc = msg.arg2 == 1; 1465 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1466 if (doGc) { 1467 // Force a gc to clear up stale containers. 1468 Runtime.getRuntime().gc(); 1469 } 1470 if (msg.obj != null) { 1471 @SuppressWarnings("unchecked") 1472 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1473 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1474 // Unload containers 1475 unloadAllContainers(args); 1476 } 1477 if (reportStatus) { 1478 try { 1479 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1480 PackageHelper.getMountService().finishMediaUpdate(); 1481 } catch (RemoteException e) { 1482 Log.e(TAG, "MountService not running?"); 1483 } 1484 } 1485 } break; 1486 case WRITE_SETTINGS: { 1487 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1488 synchronized (mPackages) { 1489 removeMessages(WRITE_SETTINGS); 1490 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1491 mSettings.writeLPr(); 1492 mDirtyUsers.clear(); 1493 } 1494 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1495 } break; 1496 case WRITE_PACKAGE_RESTRICTIONS: { 1497 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1498 synchronized (mPackages) { 1499 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1500 for (int userId : mDirtyUsers) { 1501 mSettings.writePackageRestrictionsLPr(userId); 1502 } 1503 mDirtyUsers.clear(); 1504 } 1505 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1506 } break; 1507 case CHECK_PENDING_VERIFICATION: { 1508 final int verificationId = msg.arg1; 1509 final PackageVerificationState state = mPendingVerification.get(verificationId); 1510 1511 if ((state != null) && !state.timeoutExtended()) { 1512 final InstallArgs args = state.getInstallArgs(); 1513 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1514 1515 Slog.i(TAG, "Verification timed out for " + originUri); 1516 mPendingVerification.remove(verificationId); 1517 1518 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1519 1520 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1521 Slog.i(TAG, "Continuing with installation of " + originUri); 1522 state.setVerifierResponse(Binder.getCallingUid(), 1523 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1524 broadcastPackageVerified(verificationId, originUri, 1525 PackageManager.VERIFICATION_ALLOW, 1526 state.getInstallArgs().getUser()); 1527 try { 1528 ret = args.copyApk(mContainerService, true); 1529 } catch (RemoteException e) { 1530 Slog.e(TAG, "Could not contact the ContainerService"); 1531 } 1532 } else { 1533 broadcastPackageVerified(verificationId, originUri, 1534 PackageManager.VERIFICATION_REJECT, 1535 state.getInstallArgs().getUser()); 1536 } 1537 1538 processPendingInstall(args, ret); 1539 mHandler.sendEmptyMessage(MCS_UNBIND); 1540 } 1541 break; 1542 } 1543 case PACKAGE_VERIFIED: { 1544 final int verificationId = msg.arg1; 1545 1546 final PackageVerificationState state = mPendingVerification.get(verificationId); 1547 if (state == null) { 1548 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1549 break; 1550 } 1551 1552 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1553 1554 state.setVerifierResponse(response.callerUid, response.code); 1555 1556 if (state.isVerificationComplete()) { 1557 mPendingVerification.remove(verificationId); 1558 1559 final InstallArgs args = state.getInstallArgs(); 1560 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1561 1562 int ret; 1563 if (state.isInstallAllowed()) { 1564 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1565 broadcastPackageVerified(verificationId, originUri, 1566 response.code, state.getInstallArgs().getUser()); 1567 try { 1568 ret = args.copyApk(mContainerService, true); 1569 } catch (RemoteException e) { 1570 Slog.e(TAG, "Could not contact the ContainerService"); 1571 } 1572 } else { 1573 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1574 } 1575 1576 processPendingInstall(args, ret); 1577 1578 mHandler.sendEmptyMessage(MCS_UNBIND); 1579 } 1580 1581 break; 1582 } 1583 case START_INTENT_FILTER_VERIFICATIONS: { 1584 IFVerificationParams params = (IFVerificationParams) msg.obj; 1585 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1586 params.replacing, params.pkg); 1587 break; 1588 } 1589 case INTENT_FILTER_VERIFIED: { 1590 final int verificationId = msg.arg1; 1591 1592 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1593 verificationId); 1594 if (state == null) { 1595 Slog.w(TAG, "Invalid IntentFilter verification token " 1596 + verificationId + " received"); 1597 break; 1598 } 1599 1600 final int userId = state.getUserId(); 1601 1602 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1603 "Processing IntentFilter verification with token:" 1604 + verificationId + " and userId:" + userId); 1605 1606 final IntentFilterVerificationResponse response = 1607 (IntentFilterVerificationResponse) msg.obj; 1608 1609 state.setVerifierResponse(response.callerUid, response.code); 1610 1611 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1612 "IntentFilter verification with token:" + verificationId 1613 + " and userId:" + userId 1614 + " is settings verifier response with response code:" 1615 + response.code); 1616 1617 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1618 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1619 + response.getFailedDomainsString()); 1620 } 1621 1622 if (state.isVerificationComplete()) { 1623 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1624 } else { 1625 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1626 "IntentFilter verification with token:" + verificationId 1627 + " was not said to be complete"); 1628 } 1629 1630 break; 1631 } 1632 } 1633 } 1634 } 1635 1636 private StorageEventListener mStorageListener = new StorageEventListener() { 1637 @Override 1638 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1639 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1640 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1641 final String volumeUuid = vol.getFsUuid(); 1642 1643 // Clean up any users or apps that were removed or recreated 1644 // while this volume was missing 1645 reconcileUsers(volumeUuid); 1646 reconcileApps(volumeUuid); 1647 1648 // Clean up any install sessions that expired or were 1649 // cancelled while this volume was missing 1650 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1651 1652 loadPrivatePackages(vol); 1653 1654 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1655 unloadPrivatePackages(vol); 1656 } 1657 } 1658 1659 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1660 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1661 updateExternalMediaStatus(true, false); 1662 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1663 updateExternalMediaStatus(false, false); 1664 } 1665 } 1666 } 1667 1668 @Override 1669 public void onVolumeForgotten(String fsUuid) { 1670 if (TextUtils.isEmpty(fsUuid)) { 1671 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1672 return; 1673 } 1674 1675 // Remove any apps installed on the forgotten volume 1676 synchronized (mPackages) { 1677 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1678 for (PackageSetting ps : packages) { 1679 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1680 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1681 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1682 } 1683 1684 mSettings.onVolumeForgotten(fsUuid); 1685 mSettings.writeLPr(); 1686 } 1687 } 1688 }; 1689 1690 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1691 String[] grantedPermissions) { 1692 if (userId >= UserHandle.USER_OWNER) { 1693 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1694 } else if (userId == UserHandle.USER_ALL) { 1695 final int[] userIds; 1696 synchronized (mPackages) { 1697 userIds = UserManagerService.getInstance().getUserIds(); 1698 } 1699 for (int someUserId : userIds) { 1700 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1701 } 1702 } 1703 1704 // We could have touched GID membership, so flush out packages.list 1705 synchronized (mPackages) { 1706 mSettings.writePackageListLPr(); 1707 } 1708 } 1709 1710 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1711 String[] grantedPermissions) { 1712 SettingBase sb = (SettingBase) pkg.mExtras; 1713 if (sb == null) { 1714 return; 1715 } 1716 1717 PermissionsState permissionsState = sb.getPermissionsState(); 1718 1719 for (String permission : pkg.requestedPermissions) { 1720 BasePermission bp = mSettings.mPermissions.get(permission); 1721 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1722 || ArrayUtils.contains(grantedPermissions, permission))) { 1723 permissionsState.grantRuntimePermission(bp, userId); 1724 } 1725 } 1726 } 1727 1728 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1729 Bundle extras = null; 1730 switch (res.returnCode) { 1731 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1732 extras = new Bundle(); 1733 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1734 res.origPermission); 1735 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1736 res.origPackage); 1737 break; 1738 } 1739 case PackageManager.INSTALL_SUCCEEDED: { 1740 extras = new Bundle(); 1741 extras.putBoolean(Intent.EXTRA_REPLACING, 1742 res.removedInfo != null && res.removedInfo.removedPackage != null); 1743 break; 1744 } 1745 } 1746 return extras; 1747 } 1748 1749 void scheduleWriteSettingsLocked() { 1750 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1751 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1752 } 1753 } 1754 1755 void scheduleWritePackageRestrictionsLocked(int userId) { 1756 if (!sUserManager.exists(userId)) return; 1757 mDirtyUsers.add(userId); 1758 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1759 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1760 } 1761 } 1762 1763 public static PackageManagerService main(Context context, Installer installer, 1764 boolean factoryTest, boolean onlyCore) { 1765 PackageManagerService m = new PackageManagerService(context, installer, 1766 factoryTest, onlyCore); 1767 ServiceManager.addService("package", m); 1768 return m; 1769 } 1770 1771 static String[] splitString(String str, char sep) { 1772 int count = 1; 1773 int i = 0; 1774 while ((i=str.indexOf(sep, i)) >= 0) { 1775 count++; 1776 i++; 1777 } 1778 1779 String[] res = new String[count]; 1780 i=0; 1781 count = 0; 1782 int lastI=0; 1783 while ((i=str.indexOf(sep, i)) >= 0) { 1784 res[count] = str.substring(lastI, i); 1785 count++; 1786 i++; 1787 lastI = i; 1788 } 1789 res[count] = str.substring(lastI, str.length()); 1790 return res; 1791 } 1792 1793 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1794 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1795 Context.DISPLAY_SERVICE); 1796 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1797 } 1798 1799 public PackageManagerService(Context context, Installer installer, 1800 boolean factoryTest, boolean onlyCore) { 1801 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1802 SystemClock.uptimeMillis()); 1803 1804 if (mSdkVersion <= 0) { 1805 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1806 } 1807 1808 mContext = context; 1809 mFactoryTest = factoryTest; 1810 mOnlyCore = onlyCore; 1811 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1812 mMetrics = new DisplayMetrics(); 1813 mSettings = new Settings(mPackages); 1814 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1815 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1816 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1817 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1818 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1819 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1820 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1821 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1822 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1823 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1824 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1825 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1826 1827 // TODO: add a property to control this? 1828 long dexOptLRUThresholdInMinutes; 1829 if (mLazyDexOpt) { 1830 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1831 } else { 1832 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1833 } 1834 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1835 1836 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1837 if (separateProcesses != null && separateProcesses.length() > 0) { 1838 if ("*".equals(separateProcesses)) { 1839 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1840 mSeparateProcesses = null; 1841 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1842 } else { 1843 mDefParseFlags = 0; 1844 mSeparateProcesses = separateProcesses.split(","); 1845 Slog.w(TAG, "Running with debug.separate_processes: " 1846 + separateProcesses); 1847 } 1848 } else { 1849 mDefParseFlags = 0; 1850 mSeparateProcesses = null; 1851 } 1852 1853 mInstaller = installer; 1854 mPackageDexOptimizer = new PackageDexOptimizer(this); 1855 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1856 1857 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1858 FgThread.get().getLooper()); 1859 1860 getDefaultDisplayMetrics(context, mMetrics); 1861 1862 SystemConfig systemConfig = SystemConfig.getInstance(); 1863 mGlobalGids = systemConfig.getGlobalGids(); 1864 mSystemPermissions = systemConfig.getSystemPermissions(); 1865 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1866 1867 synchronized (mInstallLock) { 1868 // writer 1869 synchronized (mPackages) { 1870 mHandlerThread = new ServiceThread(TAG, 1871 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1872 mHandlerThread.start(); 1873 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1874 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1875 1876 File dataDir = Environment.getDataDirectory(); 1877 mAppDataDir = new File(dataDir, "data"); 1878 mAppInstallDir = new File(dataDir, "app"); 1879 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1880 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1881 mUserAppDataDir = new File(dataDir, "user"); 1882 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1883 1884 sUserManager = new UserManagerService(context, this, 1885 mInstallLock, mPackages); 1886 1887 // Propagate permission configuration in to package manager. 1888 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1889 = systemConfig.getPermissions(); 1890 for (int i=0; i<permConfig.size(); i++) { 1891 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1892 BasePermission bp = mSettings.mPermissions.get(perm.name); 1893 if (bp == null) { 1894 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1895 mSettings.mPermissions.put(perm.name, bp); 1896 } 1897 if (perm.gids != null) { 1898 bp.setGids(perm.gids, perm.perUser); 1899 } 1900 } 1901 1902 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1903 for (int i=0; i<libConfig.size(); i++) { 1904 mSharedLibraries.put(libConfig.keyAt(i), 1905 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1906 } 1907 1908 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1909 1910 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1911 mSdkVersion, mOnlyCore); 1912 1913 String customResolverActivity = Resources.getSystem().getString( 1914 R.string.config_customResolverActivity); 1915 if (TextUtils.isEmpty(customResolverActivity)) { 1916 customResolverActivity = null; 1917 } else { 1918 mCustomResolverComponentName = ComponentName.unflattenFromString( 1919 customResolverActivity); 1920 } 1921 1922 long startTime = SystemClock.uptimeMillis(); 1923 1924 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1925 startTime); 1926 1927 // Set flag to monitor and not change apk file paths when 1928 // scanning install directories. 1929 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1930 1931 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1932 1933 /** 1934 * Add everything in the in the boot class path to the 1935 * list of process files because dexopt will have been run 1936 * if necessary during zygote startup. 1937 */ 1938 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1939 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1940 1941 if (bootClassPath != null) { 1942 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1943 for (String element : bootClassPathElements) { 1944 alreadyDexOpted.add(element); 1945 } 1946 } else { 1947 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1948 } 1949 1950 if (systemServerClassPath != null) { 1951 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1952 for (String element : systemServerClassPathElements) { 1953 alreadyDexOpted.add(element); 1954 } 1955 } else { 1956 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1957 } 1958 1959 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1960 final String[] dexCodeInstructionSets = 1961 getDexCodeInstructionSets( 1962 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1963 1964 /** 1965 * Ensure all external libraries have had dexopt run on them. 1966 */ 1967 if (mSharedLibraries.size() > 0) { 1968 // NOTE: For now, we're compiling these system "shared libraries" 1969 // (and framework jars) into all available architectures. It's possible 1970 // to compile them only when we come across an app that uses them (there's 1971 // already logic for that in scanPackageLI) but that adds some complexity. 1972 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1973 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1974 final String lib = libEntry.path; 1975 if (lib == null) { 1976 continue; 1977 } 1978 1979 try { 1980 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1981 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1982 alreadyDexOpted.add(lib); 1983 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 1984 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 1985 } 1986 } catch (FileNotFoundException e) { 1987 Slog.w(TAG, "Library not found: " + lib); 1988 } catch (IOException e) { 1989 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1990 + e.getMessage()); 1991 } 1992 } 1993 } 1994 } 1995 1996 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1997 1998 // Gross hack for now: we know this file doesn't contain any 1999 // code, so don't dexopt it to avoid the resulting log spew. 2000 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2001 2002 // Gross hack for now: we know this file is only part of 2003 // the boot class path for art, so don't dexopt it to 2004 // avoid the resulting log spew. 2005 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2006 2007 /** 2008 * There are a number of commands implemented in Java, which 2009 * we currently need to do the dexopt on so that they can be 2010 * run from a non-root shell. 2011 */ 2012 String[] frameworkFiles = frameworkDir.list(); 2013 if (frameworkFiles != null) { 2014 // TODO: We could compile these only for the most preferred ABI. We should 2015 // first double check that the dex files for these commands are not referenced 2016 // by other system apps. 2017 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2018 for (int i=0; i<frameworkFiles.length; i++) { 2019 File libPath = new File(frameworkDir, frameworkFiles[i]); 2020 String path = libPath.getPath(); 2021 // Skip the file if we already did it. 2022 if (alreadyDexOpted.contains(path)) { 2023 continue; 2024 } 2025 // Skip the file if it is not a type we want to dexopt. 2026 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2027 continue; 2028 } 2029 try { 2030 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2031 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2032 mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet, 2033 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 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 if (!sUserManager.exists(userId)) return -1; 2739 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2740 2741 // reader 2742 synchronized (mPackages) { 2743 PackageParser.Package p = mPackages.get(packageName); 2744 if(p != null) { 2745 return UserHandle.getUid(userId, p.applicationInfo.uid); 2746 } 2747 PackageSetting ps = mSettings.mPackages.get(packageName); 2748 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2749 return -1; 2750 } 2751 p = ps.pkg; 2752 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2753 } 2754 } 2755 2756 @Override 2757 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2758 if (!sUserManager.exists(userId)) { 2759 return null; 2760 } 2761 2762 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2763 "getPackageGids"); 2764 2765 // reader 2766 synchronized (mPackages) { 2767 PackageParser.Package p = mPackages.get(packageName); 2768 if (DEBUG_PACKAGE_INFO) { 2769 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2770 } 2771 if (p != null) { 2772 PackageSetting ps = (PackageSetting) p.mExtras; 2773 return ps.getPermissionsState().computeGids(userId); 2774 } 2775 } 2776 2777 return null; 2778 } 2779 2780 static PermissionInfo generatePermissionInfo( 2781 BasePermission bp, int flags) { 2782 if (bp.perm != null) { 2783 return PackageParser.generatePermissionInfo(bp.perm, flags); 2784 } 2785 PermissionInfo pi = new PermissionInfo(); 2786 pi.name = bp.name; 2787 pi.packageName = bp.sourcePackage; 2788 pi.nonLocalizedLabel = bp.name; 2789 pi.protectionLevel = bp.protectionLevel; 2790 return pi; 2791 } 2792 2793 @Override 2794 public PermissionInfo getPermissionInfo(String name, int flags) { 2795 // reader 2796 synchronized (mPackages) { 2797 final BasePermission p = mSettings.mPermissions.get(name); 2798 if (p != null) { 2799 return generatePermissionInfo(p, flags); 2800 } 2801 return null; 2802 } 2803 } 2804 2805 @Override 2806 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2807 // reader 2808 synchronized (mPackages) { 2809 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2810 for (BasePermission p : mSettings.mPermissions.values()) { 2811 if (group == null) { 2812 if (p.perm == null || p.perm.info.group == null) { 2813 out.add(generatePermissionInfo(p, flags)); 2814 } 2815 } else { 2816 if (p.perm != null && group.equals(p.perm.info.group)) { 2817 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2818 } 2819 } 2820 } 2821 2822 if (out.size() > 0) { 2823 return out; 2824 } 2825 return mPermissionGroups.containsKey(group) ? out : null; 2826 } 2827 } 2828 2829 @Override 2830 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2831 // reader 2832 synchronized (mPackages) { 2833 return PackageParser.generatePermissionGroupInfo( 2834 mPermissionGroups.get(name), flags); 2835 } 2836 } 2837 2838 @Override 2839 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2840 // reader 2841 synchronized (mPackages) { 2842 final int N = mPermissionGroups.size(); 2843 ArrayList<PermissionGroupInfo> out 2844 = new ArrayList<PermissionGroupInfo>(N); 2845 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2846 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2847 } 2848 return out; 2849 } 2850 } 2851 2852 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2853 int userId) { 2854 if (!sUserManager.exists(userId)) return null; 2855 PackageSetting ps = mSettings.mPackages.get(packageName); 2856 if (ps != null) { 2857 if (ps.pkg == null) { 2858 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2859 flags, userId); 2860 if (pInfo != null) { 2861 return pInfo.applicationInfo; 2862 } 2863 return null; 2864 } 2865 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2866 ps.readUserState(userId), userId); 2867 } 2868 return null; 2869 } 2870 2871 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2872 int userId) { 2873 if (!sUserManager.exists(userId)) return null; 2874 PackageSetting ps = mSettings.mPackages.get(packageName); 2875 if (ps != null) { 2876 PackageParser.Package pkg = ps.pkg; 2877 if (pkg == null) { 2878 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2879 return null; 2880 } 2881 // Only data remains, so we aren't worried about code paths 2882 pkg = new PackageParser.Package(packageName); 2883 pkg.applicationInfo.packageName = packageName; 2884 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2885 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2886 pkg.applicationInfo.dataDir = Environment 2887 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2888 .getAbsolutePath(); 2889 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2890 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2891 } 2892 return generatePackageInfo(pkg, flags, userId); 2893 } 2894 return null; 2895 } 2896 2897 @Override 2898 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2899 if (!sUserManager.exists(userId)) return null; 2900 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2901 // writer 2902 synchronized (mPackages) { 2903 PackageParser.Package p = mPackages.get(packageName); 2904 if (DEBUG_PACKAGE_INFO) Log.v( 2905 TAG, "getApplicationInfo " + packageName 2906 + ": " + p); 2907 if (p != null) { 2908 PackageSetting ps = mSettings.mPackages.get(packageName); 2909 if (ps == null) return null; 2910 // Note: isEnabledLP() does not apply here - always return info 2911 return PackageParser.generateApplicationInfo( 2912 p, flags, ps.readUserState(userId), userId); 2913 } 2914 if ("android".equals(packageName)||"system".equals(packageName)) { 2915 return mAndroidApplication; 2916 } 2917 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2918 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2919 } 2920 } 2921 return null; 2922 } 2923 2924 @Override 2925 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2926 final IPackageDataObserver observer) { 2927 mContext.enforceCallingOrSelfPermission( 2928 android.Manifest.permission.CLEAR_APP_CACHE, null); 2929 // Queue up an async operation since clearing cache may take a little while. 2930 mHandler.post(new Runnable() { 2931 public void run() { 2932 mHandler.removeCallbacks(this); 2933 int retCode = -1; 2934 synchronized (mInstallLock) { 2935 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2936 if (retCode < 0) { 2937 Slog.w(TAG, "Couldn't clear application caches"); 2938 } 2939 } 2940 if (observer != null) { 2941 try { 2942 observer.onRemoveCompleted(null, (retCode >= 0)); 2943 } catch (RemoteException e) { 2944 Slog.w(TAG, "RemoveException when invoking call back"); 2945 } 2946 } 2947 } 2948 }); 2949 } 2950 2951 @Override 2952 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2953 final IntentSender pi) { 2954 mContext.enforceCallingOrSelfPermission( 2955 android.Manifest.permission.CLEAR_APP_CACHE, null); 2956 // Queue up an async operation since clearing cache may take a little while. 2957 mHandler.post(new Runnable() { 2958 public void run() { 2959 mHandler.removeCallbacks(this); 2960 int retCode = -1; 2961 synchronized (mInstallLock) { 2962 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2963 if (retCode < 0) { 2964 Slog.w(TAG, "Couldn't clear application caches"); 2965 } 2966 } 2967 if(pi != null) { 2968 try { 2969 // Callback via pending intent 2970 int code = (retCode >= 0) ? 1 : 0; 2971 pi.sendIntent(null, code, null, 2972 null, null); 2973 } catch (SendIntentException e1) { 2974 Slog.i(TAG, "Failed to send pending intent"); 2975 } 2976 } 2977 } 2978 }); 2979 } 2980 2981 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2982 synchronized (mInstallLock) { 2983 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2984 throw new IOException("Failed to free enough space"); 2985 } 2986 } 2987 } 2988 2989 @Override 2990 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2991 if (!sUserManager.exists(userId)) return null; 2992 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2993 synchronized (mPackages) { 2994 PackageParser.Activity a = mActivities.mActivities.get(component); 2995 2996 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2997 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2998 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2999 if (ps == null) return null; 3000 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3001 userId); 3002 } 3003 if (mResolveComponentName.equals(component)) { 3004 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3005 new PackageUserState(), userId); 3006 } 3007 } 3008 return null; 3009 } 3010 3011 @Override 3012 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3013 String resolvedType) { 3014 synchronized (mPackages) { 3015 if (component.equals(mResolveComponentName)) { 3016 // The resolver supports EVERYTHING! 3017 return true; 3018 } 3019 PackageParser.Activity a = mActivities.mActivities.get(component); 3020 if (a == null) { 3021 return false; 3022 } 3023 for (int i=0; i<a.intents.size(); i++) { 3024 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3025 intent.getData(), intent.getCategories(), TAG) >= 0) { 3026 return true; 3027 } 3028 } 3029 return false; 3030 } 3031 } 3032 3033 @Override 3034 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3035 if (!sUserManager.exists(userId)) return null; 3036 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3037 synchronized (mPackages) { 3038 PackageParser.Activity a = mReceivers.mActivities.get(component); 3039 if (DEBUG_PACKAGE_INFO) Log.v( 3040 TAG, "getReceiverInfo " + component + ": " + a); 3041 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3042 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3043 if (ps == null) return null; 3044 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3045 userId); 3046 } 3047 } 3048 return null; 3049 } 3050 3051 @Override 3052 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3053 if (!sUserManager.exists(userId)) return null; 3054 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3055 synchronized (mPackages) { 3056 PackageParser.Service s = mServices.mServices.get(component); 3057 if (DEBUG_PACKAGE_INFO) Log.v( 3058 TAG, "getServiceInfo " + component + ": " + s); 3059 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3060 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3061 if (ps == null) return null; 3062 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3063 userId); 3064 } 3065 } 3066 return null; 3067 } 3068 3069 @Override 3070 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3071 if (!sUserManager.exists(userId)) return null; 3072 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3073 synchronized (mPackages) { 3074 PackageParser.Provider p = mProviders.mProviders.get(component); 3075 if (DEBUG_PACKAGE_INFO) Log.v( 3076 TAG, "getProviderInfo " + component + ": " + p); 3077 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3078 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3079 if (ps == null) return null; 3080 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3081 userId); 3082 } 3083 } 3084 return null; 3085 } 3086 3087 @Override 3088 public String[] getSystemSharedLibraryNames() { 3089 Set<String> libSet; 3090 synchronized (mPackages) { 3091 libSet = mSharedLibraries.keySet(); 3092 int size = libSet.size(); 3093 if (size > 0) { 3094 String[] libs = new String[size]; 3095 libSet.toArray(libs); 3096 return libs; 3097 } 3098 } 3099 return null; 3100 } 3101 3102 /** 3103 * @hide 3104 */ 3105 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3106 synchronized (mPackages) { 3107 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3108 if (lib != null && lib.apk != null) { 3109 return mPackages.get(lib.apk); 3110 } 3111 } 3112 return null; 3113 } 3114 3115 @Override 3116 public FeatureInfo[] getSystemAvailableFeatures() { 3117 Collection<FeatureInfo> featSet; 3118 synchronized (mPackages) { 3119 featSet = mAvailableFeatures.values(); 3120 int size = featSet.size(); 3121 if (size > 0) { 3122 FeatureInfo[] features = new FeatureInfo[size+1]; 3123 featSet.toArray(features); 3124 FeatureInfo fi = new FeatureInfo(); 3125 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3126 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3127 features[size] = fi; 3128 return features; 3129 } 3130 } 3131 return null; 3132 } 3133 3134 @Override 3135 public boolean hasSystemFeature(String name) { 3136 synchronized (mPackages) { 3137 return mAvailableFeatures.containsKey(name); 3138 } 3139 } 3140 3141 private void checkValidCaller(int uid, int userId) { 3142 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3143 return; 3144 3145 throw new SecurityException("Caller uid=" + uid 3146 + " is not privileged to communicate with user=" + userId); 3147 } 3148 3149 @Override 3150 public int checkPermission(String permName, String pkgName, int userId) { 3151 if (!sUserManager.exists(userId)) { 3152 return PackageManager.PERMISSION_DENIED; 3153 } 3154 3155 synchronized (mPackages) { 3156 final PackageParser.Package p = mPackages.get(pkgName); 3157 if (p != null && p.mExtras != null) { 3158 final PackageSetting ps = (PackageSetting) p.mExtras; 3159 final PermissionsState permissionsState = ps.getPermissionsState(); 3160 if (permissionsState.hasPermission(permName, userId)) { 3161 return PackageManager.PERMISSION_GRANTED; 3162 } 3163 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3164 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3165 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3166 return PackageManager.PERMISSION_GRANTED; 3167 } 3168 } 3169 } 3170 3171 return PackageManager.PERMISSION_DENIED; 3172 } 3173 3174 @Override 3175 public int checkUidPermission(String permName, int uid) { 3176 final int userId = UserHandle.getUserId(uid); 3177 3178 if (!sUserManager.exists(userId)) { 3179 return PackageManager.PERMISSION_DENIED; 3180 } 3181 3182 synchronized (mPackages) { 3183 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3184 if (obj != null) { 3185 final SettingBase ps = (SettingBase) obj; 3186 final PermissionsState permissionsState = ps.getPermissionsState(); 3187 if (permissionsState.hasPermission(permName, userId)) { 3188 return PackageManager.PERMISSION_GRANTED; 3189 } 3190 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3191 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3192 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3193 return PackageManager.PERMISSION_GRANTED; 3194 } 3195 } else { 3196 ArraySet<String> perms = mSystemPermissions.get(uid); 3197 if (perms != null) { 3198 if (perms.contains(permName)) { 3199 return PackageManager.PERMISSION_GRANTED; 3200 } 3201 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3202 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3203 return PackageManager.PERMISSION_GRANTED; 3204 } 3205 } 3206 } 3207 } 3208 3209 return PackageManager.PERMISSION_DENIED; 3210 } 3211 3212 @Override 3213 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3214 if (UserHandle.getCallingUserId() != userId) { 3215 mContext.enforceCallingPermission( 3216 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3217 "isPermissionRevokedByPolicy for user " + userId); 3218 } 3219 3220 if (checkPermission(permission, packageName, userId) 3221 == PackageManager.PERMISSION_GRANTED) { 3222 return false; 3223 } 3224 3225 final long identity = Binder.clearCallingIdentity(); 3226 try { 3227 final int flags = getPermissionFlags(permission, packageName, userId); 3228 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3229 } finally { 3230 Binder.restoreCallingIdentity(identity); 3231 } 3232 } 3233 3234 @Override 3235 public String getPermissionControllerPackageName() { 3236 synchronized (mPackages) { 3237 return mRequiredInstallerPackage; 3238 } 3239 } 3240 3241 /** 3242 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3243 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3244 * @param checkShell TODO(yamasani): 3245 * @param message the message to log on security exception 3246 */ 3247 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3248 boolean checkShell, String message) { 3249 if (userId < 0) { 3250 throw new IllegalArgumentException("Invalid userId " + userId); 3251 } 3252 if (checkShell) { 3253 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3254 } 3255 if (userId == UserHandle.getUserId(callingUid)) return; 3256 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3257 if (requireFullPermission) { 3258 mContext.enforceCallingOrSelfPermission( 3259 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3260 } else { 3261 try { 3262 mContext.enforceCallingOrSelfPermission( 3263 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3264 } catch (SecurityException se) { 3265 mContext.enforceCallingOrSelfPermission( 3266 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3267 } 3268 } 3269 } 3270 } 3271 3272 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3273 if (callingUid == Process.SHELL_UID) { 3274 if (userHandle >= 0 3275 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3276 throw new SecurityException("Shell does not have permission to access user " 3277 + userHandle); 3278 } else if (userHandle < 0) { 3279 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3280 + Debug.getCallers(3)); 3281 } 3282 } 3283 } 3284 3285 private BasePermission findPermissionTreeLP(String permName) { 3286 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3287 if (permName.startsWith(bp.name) && 3288 permName.length() > bp.name.length() && 3289 permName.charAt(bp.name.length()) == '.') { 3290 return bp; 3291 } 3292 } 3293 return null; 3294 } 3295 3296 private BasePermission checkPermissionTreeLP(String permName) { 3297 if (permName != null) { 3298 BasePermission bp = findPermissionTreeLP(permName); 3299 if (bp != null) { 3300 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3301 return bp; 3302 } 3303 throw new SecurityException("Calling uid " 3304 + Binder.getCallingUid() 3305 + " is not allowed to add to permission tree " 3306 + bp.name + " owned by uid " + bp.uid); 3307 } 3308 } 3309 throw new SecurityException("No permission tree found for " + permName); 3310 } 3311 3312 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3313 if (s1 == null) { 3314 return s2 == null; 3315 } 3316 if (s2 == null) { 3317 return false; 3318 } 3319 if (s1.getClass() != s2.getClass()) { 3320 return false; 3321 } 3322 return s1.equals(s2); 3323 } 3324 3325 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3326 if (pi1.icon != pi2.icon) return false; 3327 if (pi1.logo != pi2.logo) return false; 3328 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3329 if (!compareStrings(pi1.name, pi2.name)) return false; 3330 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3331 // We'll take care of setting this one. 3332 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3333 // These are not currently stored in settings. 3334 //if (!compareStrings(pi1.group, pi2.group)) return false; 3335 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3336 //if (pi1.labelRes != pi2.labelRes) return false; 3337 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3338 return true; 3339 } 3340 3341 int permissionInfoFootprint(PermissionInfo info) { 3342 int size = info.name.length(); 3343 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3344 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3345 return size; 3346 } 3347 3348 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3349 int size = 0; 3350 for (BasePermission perm : mSettings.mPermissions.values()) { 3351 if (perm.uid == tree.uid) { 3352 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3353 } 3354 } 3355 return size; 3356 } 3357 3358 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3359 // We calculate the max size of permissions defined by this uid and throw 3360 // if that plus the size of 'info' would exceed our stated maximum. 3361 if (tree.uid != Process.SYSTEM_UID) { 3362 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3363 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3364 throw new SecurityException("Permission tree size cap exceeded"); 3365 } 3366 } 3367 } 3368 3369 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3370 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3371 throw new SecurityException("Label must be specified in permission"); 3372 } 3373 BasePermission tree = checkPermissionTreeLP(info.name); 3374 BasePermission bp = mSettings.mPermissions.get(info.name); 3375 boolean added = bp == null; 3376 boolean changed = true; 3377 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3378 if (added) { 3379 enforcePermissionCapLocked(info, tree); 3380 bp = new BasePermission(info.name, tree.sourcePackage, 3381 BasePermission.TYPE_DYNAMIC); 3382 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3383 throw new SecurityException( 3384 "Not allowed to modify non-dynamic permission " 3385 + info.name); 3386 } else { 3387 if (bp.protectionLevel == fixedLevel 3388 && bp.perm.owner.equals(tree.perm.owner) 3389 && bp.uid == tree.uid 3390 && comparePermissionInfos(bp.perm.info, info)) { 3391 changed = false; 3392 } 3393 } 3394 bp.protectionLevel = fixedLevel; 3395 info = new PermissionInfo(info); 3396 info.protectionLevel = fixedLevel; 3397 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3398 bp.perm.info.packageName = tree.perm.info.packageName; 3399 bp.uid = tree.uid; 3400 if (added) { 3401 mSettings.mPermissions.put(info.name, bp); 3402 } 3403 if (changed) { 3404 if (!async) { 3405 mSettings.writeLPr(); 3406 } else { 3407 scheduleWriteSettingsLocked(); 3408 } 3409 } 3410 return added; 3411 } 3412 3413 @Override 3414 public boolean addPermission(PermissionInfo info) { 3415 synchronized (mPackages) { 3416 return addPermissionLocked(info, false); 3417 } 3418 } 3419 3420 @Override 3421 public boolean addPermissionAsync(PermissionInfo info) { 3422 synchronized (mPackages) { 3423 return addPermissionLocked(info, true); 3424 } 3425 } 3426 3427 @Override 3428 public void removePermission(String name) { 3429 synchronized (mPackages) { 3430 checkPermissionTreeLP(name); 3431 BasePermission bp = mSettings.mPermissions.get(name); 3432 if (bp != null) { 3433 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3434 throw new SecurityException( 3435 "Not allowed to modify non-dynamic permission " 3436 + name); 3437 } 3438 mSettings.mPermissions.remove(name); 3439 mSettings.writeLPr(); 3440 } 3441 } 3442 } 3443 3444 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3445 BasePermission bp) { 3446 int index = pkg.requestedPermissions.indexOf(bp.name); 3447 if (index == -1) { 3448 throw new SecurityException("Package " + pkg.packageName 3449 + " has not requested permission " + bp.name); 3450 } 3451 if (!bp.isRuntime() && !bp.isDevelopment()) { 3452 throw new SecurityException("Permission " + bp.name 3453 + " is not a changeable permission type"); 3454 } 3455 } 3456 3457 @Override 3458 public void grantRuntimePermission(String packageName, String name, final int userId) { 3459 if (!sUserManager.exists(userId)) { 3460 Log.e(TAG, "No such user:" + userId); 3461 return; 3462 } 3463 3464 mContext.enforceCallingOrSelfPermission( 3465 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3466 "grantRuntimePermission"); 3467 3468 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3469 "grantRuntimePermission"); 3470 3471 final int uid; 3472 final SettingBase sb; 3473 3474 synchronized (mPackages) { 3475 final PackageParser.Package pkg = mPackages.get(packageName); 3476 if (pkg == null) { 3477 throw new IllegalArgumentException("Unknown package: " + packageName); 3478 } 3479 3480 final BasePermission bp = mSettings.mPermissions.get(name); 3481 if (bp == null) { 3482 throw new IllegalArgumentException("Unknown permission: " + name); 3483 } 3484 3485 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3486 3487 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3488 sb = (SettingBase) pkg.mExtras; 3489 if (sb == null) { 3490 throw new IllegalArgumentException("Unknown package: " + packageName); 3491 } 3492 3493 final PermissionsState permissionsState = sb.getPermissionsState(); 3494 3495 final int flags = permissionsState.getPermissionFlags(name, userId); 3496 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3497 throw new SecurityException("Cannot grant system fixed permission: " 3498 + name + " for package: " + packageName); 3499 } 3500 3501 if (bp.isDevelopment()) { 3502 // Development permissions must be handled specially, since they are not 3503 // normal runtime permissions. For now they apply to all users. 3504 if (permissionsState.grantInstallPermission(bp) != 3505 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3506 scheduleWriteSettingsLocked(); 3507 } 3508 return; 3509 } 3510 3511 final int result = permissionsState.grantRuntimePermission(bp, userId); 3512 switch (result) { 3513 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3514 return; 3515 } 3516 3517 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3518 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3519 mHandler.post(new Runnable() { 3520 @Override 3521 public void run() { 3522 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3523 } 3524 }); 3525 } break; 3526 } 3527 3528 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3529 3530 // Not critical if that is lost - app has to request again. 3531 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3532 } 3533 3534 // Only need to do this if user is initialized. Otherwise it's a new user 3535 // and there are no processes running as the user yet and there's no need 3536 // to make an expensive call to remount processes for the changed permissions. 3537 if (READ_EXTERNAL_STORAGE.equals(name) 3538 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3539 final long token = Binder.clearCallingIdentity(); 3540 try { 3541 if (sUserManager.isInitialized(userId)) { 3542 MountServiceInternal mountServiceInternal = LocalServices.getService( 3543 MountServiceInternal.class); 3544 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3545 } 3546 } finally { 3547 Binder.restoreCallingIdentity(token); 3548 } 3549 } 3550 } 3551 3552 @Override 3553 public void revokeRuntimePermission(String packageName, String name, int userId) { 3554 if (!sUserManager.exists(userId)) { 3555 Log.e(TAG, "No such user:" + userId); 3556 return; 3557 } 3558 3559 mContext.enforceCallingOrSelfPermission( 3560 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3561 "revokeRuntimePermission"); 3562 3563 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3564 "revokeRuntimePermission"); 3565 3566 final int appId; 3567 3568 synchronized (mPackages) { 3569 final PackageParser.Package pkg = mPackages.get(packageName); 3570 if (pkg == null) { 3571 throw new IllegalArgumentException("Unknown package: " + packageName); 3572 } 3573 3574 final BasePermission bp = mSettings.mPermissions.get(name); 3575 if (bp == null) { 3576 throw new IllegalArgumentException("Unknown permission: " + name); 3577 } 3578 3579 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3580 3581 SettingBase sb = (SettingBase) pkg.mExtras; 3582 if (sb == null) { 3583 throw new IllegalArgumentException("Unknown package: " + packageName); 3584 } 3585 3586 final PermissionsState permissionsState = sb.getPermissionsState(); 3587 3588 final int flags = permissionsState.getPermissionFlags(name, userId); 3589 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3590 throw new SecurityException("Cannot revoke system fixed permission: " 3591 + name + " for package: " + packageName); 3592 } 3593 3594 if (bp.isDevelopment()) { 3595 // Development permissions must be handled specially, since they are not 3596 // normal runtime permissions. For now they apply to all users. 3597 if (permissionsState.revokeInstallPermission(bp) != 3598 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3599 scheduleWriteSettingsLocked(); 3600 } 3601 return; 3602 } 3603 3604 if (permissionsState.revokeRuntimePermission(bp, userId) == 3605 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3606 return; 3607 } 3608 3609 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3610 3611 // Critical, after this call app should never have the permission. 3612 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3613 3614 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3615 } 3616 3617 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3618 } 3619 3620 @Override 3621 public void resetRuntimePermissions() { 3622 mContext.enforceCallingOrSelfPermission( 3623 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3624 "revokeRuntimePermission"); 3625 3626 int callingUid = Binder.getCallingUid(); 3627 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3628 mContext.enforceCallingOrSelfPermission( 3629 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3630 "resetRuntimePermissions"); 3631 } 3632 3633 synchronized (mPackages) { 3634 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3635 for (int userId : UserManagerService.getInstance().getUserIds()) { 3636 final int packageCount = mPackages.size(); 3637 for (int i = 0; i < packageCount; i++) { 3638 PackageParser.Package pkg = mPackages.valueAt(i); 3639 if (!(pkg.mExtras instanceof PackageSetting)) { 3640 continue; 3641 } 3642 PackageSetting ps = (PackageSetting) pkg.mExtras; 3643 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3644 } 3645 } 3646 } 3647 } 3648 3649 @Override 3650 public int getPermissionFlags(String name, String packageName, int userId) { 3651 if (!sUserManager.exists(userId)) { 3652 return 0; 3653 } 3654 3655 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3656 3657 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3658 "getPermissionFlags"); 3659 3660 synchronized (mPackages) { 3661 final PackageParser.Package pkg = mPackages.get(packageName); 3662 if (pkg == null) { 3663 throw new IllegalArgumentException("Unknown package: " + packageName); 3664 } 3665 3666 final BasePermission bp = mSettings.mPermissions.get(name); 3667 if (bp == null) { 3668 throw new IllegalArgumentException("Unknown permission: " + name); 3669 } 3670 3671 SettingBase sb = (SettingBase) pkg.mExtras; 3672 if (sb == null) { 3673 throw new IllegalArgumentException("Unknown package: " + packageName); 3674 } 3675 3676 PermissionsState permissionsState = sb.getPermissionsState(); 3677 return permissionsState.getPermissionFlags(name, userId); 3678 } 3679 } 3680 3681 @Override 3682 public void updatePermissionFlags(String name, String packageName, int flagMask, 3683 int flagValues, int userId) { 3684 if (!sUserManager.exists(userId)) { 3685 return; 3686 } 3687 3688 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3689 3690 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3691 "updatePermissionFlags"); 3692 3693 // Only the system can change these flags and nothing else. 3694 if (getCallingUid() != Process.SYSTEM_UID) { 3695 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3696 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3697 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3698 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3699 } 3700 3701 synchronized (mPackages) { 3702 final PackageParser.Package pkg = mPackages.get(packageName); 3703 if (pkg == null) { 3704 throw new IllegalArgumentException("Unknown package: " + packageName); 3705 } 3706 3707 final BasePermission bp = mSettings.mPermissions.get(name); 3708 if (bp == null) { 3709 throw new IllegalArgumentException("Unknown permission: " + name); 3710 } 3711 3712 SettingBase sb = (SettingBase) pkg.mExtras; 3713 if (sb == null) { 3714 throw new IllegalArgumentException("Unknown package: " + packageName); 3715 } 3716 3717 PermissionsState permissionsState = sb.getPermissionsState(); 3718 3719 // Only the package manager can change flags for system component permissions. 3720 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3721 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3722 return; 3723 } 3724 3725 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3726 3727 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3728 // Install and runtime permissions are stored in different places, 3729 // so figure out what permission changed and persist the change. 3730 if (permissionsState.getInstallPermissionState(name) != null) { 3731 scheduleWriteSettingsLocked(); 3732 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3733 || hadState) { 3734 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3735 } 3736 } 3737 } 3738 } 3739 3740 /** 3741 * Update the permission flags for all packages and runtime permissions of a user in order 3742 * to allow device or profile owner to remove POLICY_FIXED. 3743 */ 3744 @Override 3745 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3746 if (!sUserManager.exists(userId)) { 3747 return; 3748 } 3749 3750 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3751 3752 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3753 "updatePermissionFlagsForAllApps"); 3754 3755 // Only the system can change system fixed flags. 3756 if (getCallingUid() != Process.SYSTEM_UID) { 3757 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3758 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3759 } 3760 3761 synchronized (mPackages) { 3762 boolean changed = false; 3763 final int packageCount = mPackages.size(); 3764 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3765 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3766 SettingBase sb = (SettingBase) pkg.mExtras; 3767 if (sb == null) { 3768 continue; 3769 } 3770 PermissionsState permissionsState = sb.getPermissionsState(); 3771 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3772 userId, flagMask, flagValues); 3773 } 3774 if (changed) { 3775 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3776 } 3777 } 3778 } 3779 3780 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3781 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3782 != PackageManager.PERMISSION_GRANTED 3783 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3784 != PackageManager.PERMISSION_GRANTED) { 3785 throw new SecurityException(message + " requires " 3786 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3787 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3788 } 3789 } 3790 3791 @Override 3792 public boolean shouldShowRequestPermissionRationale(String permissionName, 3793 String packageName, int userId) { 3794 if (UserHandle.getCallingUserId() != userId) { 3795 mContext.enforceCallingPermission( 3796 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3797 "canShowRequestPermissionRationale for user " + userId); 3798 } 3799 3800 final int uid = getPackageUid(packageName, userId); 3801 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3802 return false; 3803 } 3804 3805 if (checkPermission(permissionName, packageName, userId) 3806 == PackageManager.PERMISSION_GRANTED) { 3807 return false; 3808 } 3809 3810 final int flags; 3811 3812 final long identity = Binder.clearCallingIdentity(); 3813 try { 3814 flags = getPermissionFlags(permissionName, 3815 packageName, userId); 3816 } finally { 3817 Binder.restoreCallingIdentity(identity); 3818 } 3819 3820 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3821 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3822 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3823 3824 if ((flags & fixedFlags) != 0) { 3825 return false; 3826 } 3827 3828 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3829 } 3830 3831 @Override 3832 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3833 mContext.enforceCallingOrSelfPermission( 3834 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3835 "addOnPermissionsChangeListener"); 3836 3837 synchronized (mPackages) { 3838 mOnPermissionChangeListeners.addListenerLocked(listener); 3839 } 3840 } 3841 3842 @Override 3843 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3844 synchronized (mPackages) { 3845 mOnPermissionChangeListeners.removeListenerLocked(listener); 3846 } 3847 } 3848 3849 @Override 3850 public boolean isProtectedBroadcast(String actionName) { 3851 synchronized (mPackages) { 3852 return mProtectedBroadcasts.contains(actionName); 3853 } 3854 } 3855 3856 @Override 3857 public int checkSignatures(String pkg1, String pkg2) { 3858 synchronized (mPackages) { 3859 final PackageParser.Package p1 = mPackages.get(pkg1); 3860 final PackageParser.Package p2 = mPackages.get(pkg2); 3861 if (p1 == null || p1.mExtras == null 3862 || p2 == null || p2.mExtras == null) { 3863 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3864 } 3865 return compareSignatures(p1.mSignatures, p2.mSignatures); 3866 } 3867 } 3868 3869 @Override 3870 public int checkUidSignatures(int uid1, int uid2) { 3871 // Map to base uids. 3872 uid1 = UserHandle.getAppId(uid1); 3873 uid2 = UserHandle.getAppId(uid2); 3874 // reader 3875 synchronized (mPackages) { 3876 Signature[] s1; 3877 Signature[] s2; 3878 Object obj = mSettings.getUserIdLPr(uid1); 3879 if (obj != null) { 3880 if (obj instanceof SharedUserSetting) { 3881 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3882 } else if (obj instanceof PackageSetting) { 3883 s1 = ((PackageSetting)obj).signatures.mSignatures; 3884 } else { 3885 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3886 } 3887 } else { 3888 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3889 } 3890 obj = mSettings.getUserIdLPr(uid2); 3891 if (obj != null) { 3892 if (obj instanceof SharedUserSetting) { 3893 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3894 } else if (obj instanceof PackageSetting) { 3895 s2 = ((PackageSetting)obj).signatures.mSignatures; 3896 } else { 3897 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3898 } 3899 } else { 3900 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3901 } 3902 return compareSignatures(s1, s2); 3903 } 3904 } 3905 3906 private void killUid(int appId, int userId, String reason) { 3907 final long identity = Binder.clearCallingIdentity(); 3908 try { 3909 IActivityManager am = ActivityManagerNative.getDefault(); 3910 if (am != null) { 3911 try { 3912 am.killUid(appId, userId, reason); 3913 } catch (RemoteException e) { 3914 /* ignore - same process */ 3915 } 3916 } 3917 } finally { 3918 Binder.restoreCallingIdentity(identity); 3919 } 3920 } 3921 3922 /** 3923 * Compares two sets of signatures. Returns: 3924 * <br /> 3925 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3926 * <br /> 3927 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3928 * <br /> 3929 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3930 * <br /> 3931 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3932 * <br /> 3933 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3934 */ 3935 static int compareSignatures(Signature[] s1, Signature[] s2) { 3936 if (s1 == null) { 3937 return s2 == null 3938 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3939 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3940 } 3941 3942 if (s2 == null) { 3943 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3944 } 3945 3946 if (s1.length != s2.length) { 3947 return PackageManager.SIGNATURE_NO_MATCH; 3948 } 3949 3950 // Since both signature sets are of size 1, we can compare without HashSets. 3951 if (s1.length == 1) { 3952 return s1[0].equals(s2[0]) ? 3953 PackageManager.SIGNATURE_MATCH : 3954 PackageManager.SIGNATURE_NO_MATCH; 3955 } 3956 3957 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3958 for (Signature sig : s1) { 3959 set1.add(sig); 3960 } 3961 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3962 for (Signature sig : s2) { 3963 set2.add(sig); 3964 } 3965 // Make sure s2 contains all signatures in s1. 3966 if (set1.equals(set2)) { 3967 return PackageManager.SIGNATURE_MATCH; 3968 } 3969 return PackageManager.SIGNATURE_NO_MATCH; 3970 } 3971 3972 /** 3973 * If the database version for this type of package (internal storage or 3974 * external storage) is less than the version where package signatures 3975 * were updated, return true. 3976 */ 3977 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3978 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3979 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3980 } 3981 3982 /** 3983 * Used for backward compatibility to make sure any packages with 3984 * certificate chains get upgraded to the new style. {@code existingSigs} 3985 * will be in the old format (since they were stored on disk from before the 3986 * system upgrade) and {@code scannedSigs} will be in the newer format. 3987 */ 3988 private int compareSignaturesCompat(PackageSignatures existingSigs, 3989 PackageParser.Package scannedPkg) { 3990 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3991 return PackageManager.SIGNATURE_NO_MATCH; 3992 } 3993 3994 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3995 for (Signature sig : existingSigs.mSignatures) { 3996 existingSet.add(sig); 3997 } 3998 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3999 for (Signature sig : scannedPkg.mSignatures) { 4000 try { 4001 Signature[] chainSignatures = sig.getChainSignatures(); 4002 for (Signature chainSig : chainSignatures) { 4003 scannedCompatSet.add(chainSig); 4004 } 4005 } catch (CertificateEncodingException e) { 4006 scannedCompatSet.add(sig); 4007 } 4008 } 4009 /* 4010 * Make sure the expanded scanned set contains all signatures in the 4011 * existing one. 4012 */ 4013 if (scannedCompatSet.equals(existingSet)) { 4014 // Migrate the old signatures to the new scheme. 4015 existingSigs.assignSignatures(scannedPkg.mSignatures); 4016 // The new KeySets will be re-added later in the scanning process. 4017 synchronized (mPackages) { 4018 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4019 } 4020 return PackageManager.SIGNATURE_MATCH; 4021 } 4022 return PackageManager.SIGNATURE_NO_MATCH; 4023 } 4024 4025 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4026 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4027 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4028 } 4029 4030 private int compareSignaturesRecover(PackageSignatures existingSigs, 4031 PackageParser.Package scannedPkg) { 4032 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4033 return PackageManager.SIGNATURE_NO_MATCH; 4034 } 4035 4036 String msg = null; 4037 try { 4038 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4039 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4040 + scannedPkg.packageName); 4041 return PackageManager.SIGNATURE_MATCH; 4042 } 4043 } catch (CertificateException e) { 4044 msg = e.getMessage(); 4045 } 4046 4047 logCriticalInfo(Log.INFO, 4048 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4049 return PackageManager.SIGNATURE_NO_MATCH; 4050 } 4051 4052 @Override 4053 public String[] getPackagesForUid(int uid) { 4054 uid = UserHandle.getAppId(uid); 4055 // reader 4056 synchronized (mPackages) { 4057 Object obj = mSettings.getUserIdLPr(uid); 4058 if (obj instanceof SharedUserSetting) { 4059 final SharedUserSetting sus = (SharedUserSetting) obj; 4060 final int N = sus.packages.size(); 4061 final String[] res = new String[N]; 4062 final Iterator<PackageSetting> it = sus.packages.iterator(); 4063 int i = 0; 4064 while (it.hasNext()) { 4065 res[i++] = it.next().name; 4066 } 4067 return res; 4068 } else if (obj instanceof PackageSetting) { 4069 final PackageSetting ps = (PackageSetting) obj; 4070 return new String[] { ps.name }; 4071 } 4072 } 4073 return null; 4074 } 4075 4076 @Override 4077 public String getNameForUid(int uid) { 4078 // reader 4079 synchronized (mPackages) { 4080 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4081 if (obj instanceof SharedUserSetting) { 4082 final SharedUserSetting sus = (SharedUserSetting) obj; 4083 return sus.name + ":" + sus.userId; 4084 } else if (obj instanceof PackageSetting) { 4085 final PackageSetting ps = (PackageSetting) obj; 4086 return ps.name; 4087 } 4088 } 4089 return null; 4090 } 4091 4092 @Override 4093 public int getUidForSharedUser(String sharedUserName) { 4094 if(sharedUserName == null) { 4095 return -1; 4096 } 4097 // reader 4098 synchronized (mPackages) { 4099 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4100 if (suid == null) { 4101 return -1; 4102 } 4103 return suid.userId; 4104 } 4105 } 4106 4107 @Override 4108 public int getFlagsForUid(int uid) { 4109 synchronized (mPackages) { 4110 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4111 if (obj instanceof SharedUserSetting) { 4112 final SharedUserSetting sus = (SharedUserSetting) obj; 4113 return sus.pkgFlags; 4114 } else if (obj instanceof PackageSetting) { 4115 final PackageSetting ps = (PackageSetting) obj; 4116 return ps.pkgFlags; 4117 } 4118 } 4119 return 0; 4120 } 4121 4122 @Override 4123 public int getPrivateFlagsForUid(int uid) { 4124 synchronized (mPackages) { 4125 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4126 if (obj instanceof SharedUserSetting) { 4127 final SharedUserSetting sus = (SharedUserSetting) obj; 4128 return sus.pkgPrivateFlags; 4129 } else if (obj instanceof PackageSetting) { 4130 final PackageSetting ps = (PackageSetting) obj; 4131 return ps.pkgPrivateFlags; 4132 } 4133 } 4134 return 0; 4135 } 4136 4137 @Override 4138 public boolean isUidPrivileged(int uid) { 4139 uid = UserHandle.getAppId(uid); 4140 // reader 4141 synchronized (mPackages) { 4142 Object obj = mSettings.getUserIdLPr(uid); 4143 if (obj instanceof SharedUserSetting) { 4144 final SharedUserSetting sus = (SharedUserSetting) obj; 4145 final Iterator<PackageSetting> it = sus.packages.iterator(); 4146 while (it.hasNext()) { 4147 if (it.next().isPrivileged()) { 4148 return true; 4149 } 4150 } 4151 } else if (obj instanceof PackageSetting) { 4152 final PackageSetting ps = (PackageSetting) obj; 4153 return ps.isPrivileged(); 4154 } 4155 } 4156 return false; 4157 } 4158 4159 @Override 4160 public String[] getAppOpPermissionPackages(String permissionName) { 4161 synchronized (mPackages) { 4162 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4163 if (pkgs == null) { 4164 return null; 4165 } 4166 return pkgs.toArray(new String[pkgs.size()]); 4167 } 4168 } 4169 4170 @Override 4171 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4172 int flags, int userId) { 4173 if (!sUserManager.exists(userId)) return null; 4174 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4175 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4176 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4177 } 4178 4179 @Override 4180 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4181 IntentFilter filter, int match, ComponentName activity) { 4182 final int userId = UserHandle.getCallingUserId(); 4183 if (DEBUG_PREFERRED) { 4184 Log.v(TAG, "setLastChosenActivity intent=" + intent 4185 + " resolvedType=" + resolvedType 4186 + " flags=" + flags 4187 + " filter=" + filter 4188 + " match=" + match 4189 + " activity=" + activity); 4190 filter.dump(new PrintStreamPrinter(System.out), " "); 4191 } 4192 intent.setComponent(null); 4193 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4194 // Find any earlier preferred or last chosen entries and nuke them 4195 findPreferredActivity(intent, resolvedType, 4196 flags, query, 0, false, true, false, userId); 4197 // Add the new activity as the last chosen for this filter 4198 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4199 "Setting last chosen"); 4200 } 4201 4202 @Override 4203 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4204 final int userId = UserHandle.getCallingUserId(); 4205 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4206 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4207 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4208 false, false, false, userId); 4209 } 4210 4211 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4212 int flags, List<ResolveInfo> query, int userId) { 4213 if (query != null) { 4214 final int N = query.size(); 4215 if (N == 1) { 4216 return query.get(0); 4217 } else if (N > 1) { 4218 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4219 // If there is more than one activity with the same priority, 4220 // then let the user decide between them. 4221 ResolveInfo r0 = query.get(0); 4222 ResolveInfo r1 = query.get(1); 4223 if (DEBUG_INTENT_MATCHING || debug) { 4224 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4225 + r1.activityInfo.name + "=" + r1.priority); 4226 } 4227 // If the first activity has a higher priority, or a different 4228 // default, then it is always desireable to pick it. 4229 if (r0.priority != r1.priority 4230 || r0.preferredOrder != r1.preferredOrder 4231 || r0.isDefault != r1.isDefault) { 4232 return query.get(0); 4233 } 4234 // If we have saved a preference for a preferred activity for 4235 // this Intent, use that. 4236 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4237 flags, query, r0.priority, true, false, debug, userId); 4238 if (ri != null) { 4239 return ri; 4240 } 4241 ri = new ResolveInfo(mResolveInfo); 4242 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4243 ri.activityInfo.applicationInfo = new ApplicationInfo( 4244 ri.activityInfo.applicationInfo); 4245 if (userId != 0) { 4246 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4247 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4248 } 4249 // Make sure that the resolver is displayable in car mode 4250 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4251 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4252 return ri; 4253 } 4254 } 4255 return null; 4256 } 4257 4258 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4259 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4260 final int N = query.size(); 4261 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4262 .get(userId); 4263 // Get the list of persistent preferred activities that handle the intent 4264 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4265 List<PersistentPreferredActivity> pprefs = ppir != null 4266 ? ppir.queryIntent(intent, resolvedType, 4267 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4268 : null; 4269 if (pprefs != null && pprefs.size() > 0) { 4270 final int M = pprefs.size(); 4271 for (int i=0; i<M; i++) { 4272 final PersistentPreferredActivity ppa = pprefs.get(i); 4273 if (DEBUG_PREFERRED || debug) { 4274 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4275 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4276 + "\n component=" + ppa.mComponent); 4277 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4278 } 4279 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4280 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4281 if (DEBUG_PREFERRED || debug) { 4282 Slog.v(TAG, "Found persistent preferred activity:"); 4283 if (ai != null) { 4284 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4285 } else { 4286 Slog.v(TAG, " null"); 4287 } 4288 } 4289 if (ai == null) { 4290 // This previously registered persistent preferred activity 4291 // component is no longer known. Ignore it and do NOT remove it. 4292 continue; 4293 } 4294 for (int j=0; j<N; j++) { 4295 final ResolveInfo ri = query.get(j); 4296 if (!ri.activityInfo.applicationInfo.packageName 4297 .equals(ai.applicationInfo.packageName)) { 4298 continue; 4299 } 4300 if (!ri.activityInfo.name.equals(ai.name)) { 4301 continue; 4302 } 4303 // Found a persistent preference that can handle the intent. 4304 if (DEBUG_PREFERRED || debug) { 4305 Slog.v(TAG, "Returning persistent preferred activity: " + 4306 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4307 } 4308 return ri; 4309 } 4310 } 4311 } 4312 return null; 4313 } 4314 4315 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4316 List<ResolveInfo> query, int priority, boolean always, 4317 boolean removeMatches, boolean debug, int userId) { 4318 if (!sUserManager.exists(userId)) return null; 4319 // writer 4320 synchronized (mPackages) { 4321 if (intent.getSelector() != null) { 4322 intent = intent.getSelector(); 4323 } 4324 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4325 4326 // Try to find a matching persistent preferred activity. 4327 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4328 debug, userId); 4329 4330 // If a persistent preferred activity matched, use it. 4331 if (pri != null) { 4332 return pri; 4333 } 4334 4335 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4336 // Get the list of preferred activities that handle the intent 4337 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4338 List<PreferredActivity> prefs = pir != null 4339 ? pir.queryIntent(intent, resolvedType, 4340 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4341 : null; 4342 if (prefs != null && prefs.size() > 0) { 4343 boolean changed = false; 4344 try { 4345 // First figure out how good the original match set is. 4346 // We will only allow preferred activities that came 4347 // from the same match quality. 4348 int match = 0; 4349 4350 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4351 4352 final int N = query.size(); 4353 for (int j=0; j<N; j++) { 4354 final ResolveInfo ri = query.get(j); 4355 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4356 + ": 0x" + Integer.toHexString(match)); 4357 if (ri.match > match) { 4358 match = ri.match; 4359 } 4360 } 4361 4362 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4363 + Integer.toHexString(match)); 4364 4365 match &= IntentFilter.MATCH_CATEGORY_MASK; 4366 final int M = prefs.size(); 4367 for (int i=0; i<M; i++) { 4368 final PreferredActivity pa = prefs.get(i); 4369 if (DEBUG_PREFERRED || debug) { 4370 Slog.v(TAG, "Checking PreferredActivity ds=" 4371 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4372 + "\n component=" + pa.mPref.mComponent); 4373 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4374 } 4375 if (pa.mPref.mMatch != match) { 4376 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4377 + Integer.toHexString(pa.mPref.mMatch)); 4378 continue; 4379 } 4380 // If it's not an "always" type preferred activity and that's what we're 4381 // looking for, skip it. 4382 if (always && !pa.mPref.mAlways) { 4383 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4384 continue; 4385 } 4386 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4387 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4388 if (DEBUG_PREFERRED || debug) { 4389 Slog.v(TAG, "Found preferred activity:"); 4390 if (ai != null) { 4391 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4392 } else { 4393 Slog.v(TAG, " null"); 4394 } 4395 } 4396 if (ai == null) { 4397 // This previously registered preferred activity 4398 // component is no longer known. Most likely an update 4399 // to the app was installed and in the new version this 4400 // component no longer exists. Clean it up by removing 4401 // it from the preferred activities list, and skip it. 4402 Slog.w(TAG, "Removing dangling preferred activity: " 4403 + pa.mPref.mComponent); 4404 pir.removeFilter(pa); 4405 changed = true; 4406 continue; 4407 } 4408 for (int j=0; j<N; j++) { 4409 final ResolveInfo ri = query.get(j); 4410 if (!ri.activityInfo.applicationInfo.packageName 4411 .equals(ai.applicationInfo.packageName)) { 4412 continue; 4413 } 4414 if (!ri.activityInfo.name.equals(ai.name)) { 4415 continue; 4416 } 4417 4418 if (removeMatches) { 4419 pir.removeFilter(pa); 4420 changed = true; 4421 if (DEBUG_PREFERRED) { 4422 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4423 } 4424 break; 4425 } 4426 4427 // Okay we found a previously set preferred or last chosen app. 4428 // If the result set is different from when this 4429 // was created, we need to clear it and re-ask the 4430 // user their preference, if we're looking for an "always" type entry. 4431 if (always && !pa.mPref.sameSet(query)) { 4432 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4433 + intent + " type " + resolvedType); 4434 if (DEBUG_PREFERRED) { 4435 Slog.v(TAG, "Removing preferred activity since set changed " 4436 + pa.mPref.mComponent); 4437 } 4438 pir.removeFilter(pa); 4439 // Re-add the filter as a "last chosen" entry (!always) 4440 PreferredActivity lastChosen = new PreferredActivity( 4441 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4442 pir.addFilter(lastChosen); 4443 changed = true; 4444 return null; 4445 } 4446 4447 // Yay! Either the set matched or we're looking for the last chosen 4448 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4449 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4450 return ri; 4451 } 4452 } 4453 } finally { 4454 if (changed) { 4455 if (DEBUG_PREFERRED) { 4456 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4457 } 4458 scheduleWritePackageRestrictionsLocked(userId); 4459 } 4460 } 4461 } 4462 } 4463 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4464 return null; 4465 } 4466 4467 /* 4468 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4469 */ 4470 @Override 4471 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4472 int targetUserId) { 4473 mContext.enforceCallingOrSelfPermission( 4474 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4475 List<CrossProfileIntentFilter> matches = 4476 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4477 if (matches != null) { 4478 int size = matches.size(); 4479 for (int i = 0; i < size; i++) { 4480 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4481 } 4482 } 4483 if (hasWebURI(intent)) { 4484 // cross-profile app linking works only towards the parent. 4485 final UserInfo parent = getProfileParent(sourceUserId); 4486 synchronized(mPackages) { 4487 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4488 intent, resolvedType, 0, sourceUserId, parent.id); 4489 return xpDomainInfo != null; 4490 } 4491 } 4492 return false; 4493 } 4494 4495 private UserInfo getProfileParent(int userId) { 4496 final long identity = Binder.clearCallingIdentity(); 4497 try { 4498 return sUserManager.getProfileParent(userId); 4499 } finally { 4500 Binder.restoreCallingIdentity(identity); 4501 } 4502 } 4503 4504 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4505 String resolvedType, int userId) { 4506 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4507 if (resolver != null) { 4508 return resolver.queryIntent(intent, resolvedType, false, userId); 4509 } 4510 return null; 4511 } 4512 4513 @Override 4514 public List<ResolveInfo> queryIntentActivities(Intent intent, 4515 String resolvedType, int flags, int userId) { 4516 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4517 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4518 ComponentName comp = intent.getComponent(); 4519 if (comp == null) { 4520 if (intent.getSelector() != null) { 4521 intent = intent.getSelector(); 4522 comp = intent.getComponent(); 4523 } 4524 } 4525 4526 if (comp != null) { 4527 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4528 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4529 if (ai != null) { 4530 final ResolveInfo ri = new ResolveInfo(); 4531 ri.activityInfo = ai; 4532 list.add(ri); 4533 } 4534 return list; 4535 } 4536 4537 // reader 4538 synchronized (mPackages) { 4539 final String pkgName = intent.getPackage(); 4540 if (pkgName == null) { 4541 List<CrossProfileIntentFilter> matchingFilters = 4542 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4543 // Check for results that need to skip the current profile. 4544 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4545 resolvedType, flags, userId); 4546 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4547 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4548 result.add(xpResolveInfo); 4549 return filterIfNotPrimaryUser(result, userId); 4550 } 4551 4552 // Check for results in the current profile. 4553 List<ResolveInfo> result = mActivities.queryIntent( 4554 intent, resolvedType, flags, userId); 4555 4556 // Check for cross profile results. 4557 xpResolveInfo = queryCrossProfileIntents( 4558 matchingFilters, intent, resolvedType, flags, userId); 4559 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4560 result.add(xpResolveInfo); 4561 Collections.sort(result, mResolvePrioritySorter); 4562 } 4563 result = filterIfNotPrimaryUser(result, userId); 4564 if (hasWebURI(intent)) { 4565 CrossProfileDomainInfo xpDomainInfo = null; 4566 final UserInfo parent = getProfileParent(userId); 4567 if (parent != null) { 4568 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4569 flags, userId, parent.id); 4570 } 4571 if (xpDomainInfo != null) { 4572 if (xpResolveInfo != null) { 4573 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4574 // in the result. 4575 result.remove(xpResolveInfo); 4576 } 4577 if (result.size() == 0) { 4578 result.add(xpDomainInfo.resolveInfo); 4579 return result; 4580 } 4581 } else if (result.size() <= 1) { 4582 return result; 4583 } 4584 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4585 xpDomainInfo, userId); 4586 Collections.sort(result, mResolvePrioritySorter); 4587 } 4588 return result; 4589 } 4590 final PackageParser.Package pkg = mPackages.get(pkgName); 4591 if (pkg != null) { 4592 return filterIfNotPrimaryUser( 4593 mActivities.queryIntentForPackage( 4594 intent, resolvedType, flags, pkg.activities, userId), 4595 userId); 4596 } 4597 return new ArrayList<ResolveInfo>(); 4598 } 4599 } 4600 4601 private static class CrossProfileDomainInfo { 4602 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4603 ResolveInfo resolveInfo; 4604 /* Best domain verification status of the activities found in the other profile */ 4605 int bestDomainVerificationStatus; 4606 } 4607 4608 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4609 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4610 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4611 sourceUserId)) { 4612 return null; 4613 } 4614 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4615 resolvedType, flags, parentUserId); 4616 4617 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4618 return null; 4619 } 4620 CrossProfileDomainInfo result = null; 4621 int size = resultTargetUser.size(); 4622 for (int i = 0; i < size; i++) { 4623 ResolveInfo riTargetUser = resultTargetUser.get(i); 4624 // Intent filter verification is only for filters that specify a host. So don't return 4625 // those that handle all web uris. 4626 if (riTargetUser.handleAllWebDataURI) { 4627 continue; 4628 } 4629 String packageName = riTargetUser.activityInfo.packageName; 4630 PackageSetting ps = mSettings.mPackages.get(packageName); 4631 if (ps == null) { 4632 continue; 4633 } 4634 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4635 int status = (int)(verificationState >> 32); 4636 if (result == null) { 4637 result = new CrossProfileDomainInfo(); 4638 result.resolveInfo = 4639 createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId); 4640 result.bestDomainVerificationStatus = status; 4641 } else { 4642 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4643 result.bestDomainVerificationStatus); 4644 } 4645 } 4646 // Don't consider matches with status NEVER across profiles. 4647 if (result != null && result.bestDomainVerificationStatus 4648 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4649 return null; 4650 } 4651 return result; 4652 } 4653 4654 /** 4655 * Verification statuses are ordered from the worse to the best, except for 4656 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4657 */ 4658 private int bestDomainVerificationStatus(int status1, int status2) { 4659 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4660 return status2; 4661 } 4662 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4663 return status1; 4664 } 4665 return (int) MathUtils.max(status1, status2); 4666 } 4667 4668 private boolean isUserEnabled(int userId) { 4669 long callingId = Binder.clearCallingIdentity(); 4670 try { 4671 UserInfo userInfo = sUserManager.getUserInfo(userId); 4672 return userInfo != null && userInfo.isEnabled(); 4673 } finally { 4674 Binder.restoreCallingIdentity(callingId); 4675 } 4676 } 4677 4678 /** 4679 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4680 * 4681 * @return filtered list 4682 */ 4683 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4684 if (userId == UserHandle.USER_OWNER) { 4685 return resolveInfos; 4686 } 4687 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4688 ResolveInfo info = resolveInfos.get(i); 4689 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4690 resolveInfos.remove(i); 4691 } 4692 } 4693 return resolveInfos; 4694 } 4695 4696 private static boolean hasWebURI(Intent intent) { 4697 if (intent.getData() == null) { 4698 return false; 4699 } 4700 final String scheme = intent.getScheme(); 4701 if (TextUtils.isEmpty(scheme)) { 4702 return false; 4703 } 4704 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4705 } 4706 4707 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4708 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4709 int userId) { 4710 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4711 4712 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4713 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4714 candidates.size()); 4715 } 4716 4717 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4718 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4719 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4720 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4721 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4722 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4723 4724 synchronized (mPackages) { 4725 final int count = candidates.size(); 4726 // First, try to use linked apps. Partition the candidates into four lists: 4727 // one for the final results, one for the "do not use ever", one for "undefined status" 4728 // and finally one for "browser app type". 4729 for (int n=0; n<count; n++) { 4730 ResolveInfo info = candidates.get(n); 4731 String packageName = info.activityInfo.packageName; 4732 PackageSetting ps = mSettings.mPackages.get(packageName); 4733 if (ps != null) { 4734 // Add to the special match all list (Browser use case) 4735 if (info.handleAllWebDataURI) { 4736 matchAllList.add(info); 4737 continue; 4738 } 4739 // Try to get the status from User settings first 4740 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4741 int status = (int)(packedStatus >> 32); 4742 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4743 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4744 if (DEBUG_DOMAIN_VERIFICATION) { 4745 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4746 + " : linkgen=" + linkGeneration); 4747 } 4748 // Use link-enabled generation as preferredOrder, i.e. 4749 // prefer newly-enabled over earlier-enabled. 4750 info.preferredOrder = linkGeneration; 4751 alwaysList.add(info); 4752 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4753 if (DEBUG_DOMAIN_VERIFICATION) { 4754 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4755 } 4756 neverList.add(info); 4757 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4758 if (DEBUG_DOMAIN_VERIFICATION) { 4759 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4760 } 4761 alwaysAskList.add(info); 4762 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4763 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4764 if (DEBUG_DOMAIN_VERIFICATION) { 4765 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4766 } 4767 undefinedList.add(info); 4768 } 4769 } 4770 } 4771 4772 // We'll want to include browser possibilities in a few cases 4773 boolean includeBrowser = false; 4774 4775 // First try to add the "always" resolution(s) for the current user, if any 4776 if (alwaysList.size() > 0) { 4777 result.addAll(alwaysList); 4778 // if there is an "always" for the parent user, add it. 4779 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4780 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4781 result.add(xpDomainInfo.resolveInfo); 4782 } else { 4783 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4784 result.addAll(undefinedList); 4785 if (xpDomainInfo != null && ( 4786 xpDomainInfo.bestDomainVerificationStatus 4787 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4788 || xpDomainInfo.bestDomainVerificationStatus 4789 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4790 result.add(xpDomainInfo.resolveInfo); 4791 } 4792 includeBrowser = true; 4793 } 4794 4795 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4796 // If there were 'always' entries their preferred order has been set, so we also 4797 // back that off to make the alternatives equivalent 4798 if (alwaysAskList.size() > 0) { 4799 for (ResolveInfo i : result) { 4800 i.preferredOrder = 0; 4801 } 4802 result.addAll(alwaysAskList); 4803 includeBrowser = true; 4804 } 4805 4806 if (includeBrowser) { 4807 // Also add browsers (all of them or only the default one) 4808 if (DEBUG_DOMAIN_VERIFICATION) { 4809 Slog.v(TAG, " ...including browsers in candidate set"); 4810 } 4811 if ((matchFlags & MATCH_ALL) != 0) { 4812 result.addAll(matchAllList); 4813 } else { 4814 // Browser/generic handling case. If there's a default browser, go straight 4815 // to that (but only if there is no other higher-priority match). 4816 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4817 int maxMatchPrio = 0; 4818 ResolveInfo defaultBrowserMatch = null; 4819 final int numCandidates = matchAllList.size(); 4820 for (int n = 0; n < numCandidates; n++) { 4821 ResolveInfo info = matchAllList.get(n); 4822 // track the highest overall match priority... 4823 if (info.priority > maxMatchPrio) { 4824 maxMatchPrio = info.priority; 4825 } 4826 // ...and the highest-priority default browser match 4827 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4828 if (defaultBrowserMatch == null 4829 || (defaultBrowserMatch.priority < info.priority)) { 4830 if (debug) { 4831 Slog.v(TAG, "Considering default browser match " + info); 4832 } 4833 defaultBrowserMatch = info; 4834 } 4835 } 4836 } 4837 if (defaultBrowserMatch != null 4838 && defaultBrowserMatch.priority >= maxMatchPrio 4839 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4840 { 4841 if (debug) { 4842 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4843 } 4844 result.add(defaultBrowserMatch); 4845 } else { 4846 result.addAll(matchAllList); 4847 } 4848 } 4849 4850 // If there is nothing selected, add all candidates and remove the ones that the user 4851 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4852 if (result.size() == 0) { 4853 result.addAll(candidates); 4854 result.removeAll(neverList); 4855 } 4856 } 4857 } 4858 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4859 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4860 result.size()); 4861 for (ResolveInfo info : result) { 4862 Slog.v(TAG, " + " + info.activityInfo); 4863 } 4864 } 4865 return result; 4866 } 4867 4868 // Returns a packed value as a long: 4869 // 4870 // high 'int'-sized word: link status: undefined/ask/never/always. 4871 // low 'int'-sized word: relative priority among 'always' results. 4872 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4873 long result = ps.getDomainVerificationStatusForUser(userId); 4874 // if none available, get the master status 4875 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4876 if (ps.getIntentFilterVerificationInfo() != null) { 4877 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4878 } 4879 } 4880 return result; 4881 } 4882 4883 private ResolveInfo querySkipCurrentProfileIntents( 4884 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4885 int flags, int sourceUserId) { 4886 if (matchingFilters != null) { 4887 int size = matchingFilters.size(); 4888 for (int i = 0; i < size; i ++) { 4889 CrossProfileIntentFilter filter = matchingFilters.get(i); 4890 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4891 // Checking if there are activities in the target user that can handle the 4892 // intent. 4893 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4894 flags, sourceUserId); 4895 if (resolveInfo != null) { 4896 return resolveInfo; 4897 } 4898 } 4899 } 4900 } 4901 return null; 4902 } 4903 4904 // Return matching ResolveInfo if any for skip current profile intent filters. 4905 private ResolveInfo queryCrossProfileIntents( 4906 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4907 int flags, int sourceUserId) { 4908 if (matchingFilters != null) { 4909 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4910 // match the same intent. For performance reasons, it is better not to 4911 // run queryIntent twice for the same userId 4912 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4913 int size = matchingFilters.size(); 4914 for (int i = 0; i < size; i++) { 4915 CrossProfileIntentFilter filter = matchingFilters.get(i); 4916 int targetUserId = filter.getTargetUserId(); 4917 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4918 && !alreadyTriedUserIds.get(targetUserId)) { 4919 // Checking if there are activities in the target user that can handle the 4920 // intent. 4921 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4922 flags, sourceUserId); 4923 if (resolveInfo != null) return resolveInfo; 4924 alreadyTriedUserIds.put(targetUserId, true); 4925 } 4926 } 4927 } 4928 return null; 4929 } 4930 4931 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4932 String resolvedType, int flags, int sourceUserId) { 4933 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4934 resolvedType, flags, filter.getTargetUserId()); 4935 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4936 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4937 } 4938 return null; 4939 } 4940 4941 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4942 int sourceUserId, int targetUserId) { 4943 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4944 String className; 4945 if (targetUserId == UserHandle.USER_OWNER) { 4946 className = FORWARD_INTENT_TO_USER_OWNER; 4947 } else { 4948 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4949 } 4950 ComponentName forwardingActivityComponentName = new ComponentName( 4951 mAndroidApplication.packageName, className); 4952 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4953 sourceUserId); 4954 if (targetUserId == UserHandle.USER_OWNER) { 4955 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4956 forwardingResolveInfo.noResourceId = true; 4957 } 4958 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4959 forwardingResolveInfo.priority = 0; 4960 forwardingResolveInfo.preferredOrder = 0; 4961 forwardingResolveInfo.match = 0; 4962 forwardingResolveInfo.isDefault = true; 4963 forwardingResolveInfo.filter = filter; 4964 forwardingResolveInfo.targetUserId = targetUserId; 4965 return forwardingResolveInfo; 4966 } 4967 4968 @Override 4969 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4970 Intent[] specifics, String[] specificTypes, Intent intent, 4971 String resolvedType, int flags, int userId) { 4972 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4973 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4974 false, "query intent activity options"); 4975 final String resultsAction = intent.getAction(); 4976 4977 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4978 | PackageManager.GET_RESOLVED_FILTER, userId); 4979 4980 if (DEBUG_INTENT_MATCHING) { 4981 Log.v(TAG, "Query " + intent + ": " + results); 4982 } 4983 4984 int specificsPos = 0; 4985 int N; 4986 4987 // todo: note that the algorithm used here is O(N^2). This 4988 // isn't a problem in our current environment, but if we start running 4989 // into situations where we have more than 5 or 10 matches then this 4990 // should probably be changed to something smarter... 4991 4992 // First we go through and resolve each of the specific items 4993 // that were supplied, taking care of removing any corresponding 4994 // duplicate items in the generic resolve list. 4995 if (specifics != null) { 4996 for (int i=0; i<specifics.length; i++) { 4997 final Intent sintent = specifics[i]; 4998 if (sintent == null) { 4999 continue; 5000 } 5001 5002 if (DEBUG_INTENT_MATCHING) { 5003 Log.v(TAG, "Specific #" + i + ": " + sintent); 5004 } 5005 5006 String action = sintent.getAction(); 5007 if (resultsAction != null && resultsAction.equals(action)) { 5008 // If this action was explicitly requested, then don't 5009 // remove things that have it. 5010 action = null; 5011 } 5012 5013 ResolveInfo ri = null; 5014 ActivityInfo ai = null; 5015 5016 ComponentName comp = sintent.getComponent(); 5017 if (comp == null) { 5018 ri = resolveIntent( 5019 sintent, 5020 specificTypes != null ? specificTypes[i] : null, 5021 flags, userId); 5022 if (ri == null) { 5023 continue; 5024 } 5025 if (ri == mResolveInfo) { 5026 // ACK! Must do something better with this. 5027 } 5028 ai = ri.activityInfo; 5029 comp = new ComponentName(ai.applicationInfo.packageName, 5030 ai.name); 5031 } else { 5032 ai = getActivityInfo(comp, flags, userId); 5033 if (ai == null) { 5034 continue; 5035 } 5036 } 5037 5038 // Look for any generic query activities that are duplicates 5039 // of this specific one, and remove them from the results. 5040 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5041 N = results.size(); 5042 int j; 5043 for (j=specificsPos; j<N; j++) { 5044 ResolveInfo sri = results.get(j); 5045 if ((sri.activityInfo.name.equals(comp.getClassName()) 5046 && sri.activityInfo.applicationInfo.packageName.equals( 5047 comp.getPackageName())) 5048 || (action != null && sri.filter.matchAction(action))) { 5049 results.remove(j); 5050 if (DEBUG_INTENT_MATCHING) Log.v( 5051 TAG, "Removing duplicate item from " + j 5052 + " due to specific " + specificsPos); 5053 if (ri == null) { 5054 ri = sri; 5055 } 5056 j--; 5057 N--; 5058 } 5059 } 5060 5061 // Add this specific item to its proper place. 5062 if (ri == null) { 5063 ri = new ResolveInfo(); 5064 ri.activityInfo = ai; 5065 } 5066 results.add(specificsPos, ri); 5067 ri.specificIndex = i; 5068 specificsPos++; 5069 } 5070 } 5071 5072 // Now we go through the remaining generic results and remove any 5073 // duplicate actions that are found here. 5074 N = results.size(); 5075 for (int i=specificsPos; i<N-1; i++) { 5076 final ResolveInfo rii = results.get(i); 5077 if (rii.filter == null) { 5078 continue; 5079 } 5080 5081 // Iterate over all of the actions of this result's intent 5082 // filter... typically this should be just one. 5083 final Iterator<String> it = rii.filter.actionsIterator(); 5084 if (it == null) { 5085 continue; 5086 } 5087 while (it.hasNext()) { 5088 final String action = it.next(); 5089 if (resultsAction != null && resultsAction.equals(action)) { 5090 // If this action was explicitly requested, then don't 5091 // remove things that have it. 5092 continue; 5093 } 5094 for (int j=i+1; j<N; j++) { 5095 final ResolveInfo rij = results.get(j); 5096 if (rij.filter != null && rij.filter.hasAction(action)) { 5097 results.remove(j); 5098 if (DEBUG_INTENT_MATCHING) Log.v( 5099 TAG, "Removing duplicate item from " + j 5100 + " due to action " + action + " at " + i); 5101 j--; 5102 N--; 5103 } 5104 } 5105 } 5106 5107 // If the caller didn't request filter information, drop it now 5108 // so we don't have to marshall/unmarshall it. 5109 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5110 rii.filter = null; 5111 } 5112 } 5113 5114 // Filter out the caller activity if so requested. 5115 if (caller != null) { 5116 N = results.size(); 5117 for (int i=0; i<N; i++) { 5118 ActivityInfo ainfo = results.get(i).activityInfo; 5119 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5120 && caller.getClassName().equals(ainfo.name)) { 5121 results.remove(i); 5122 break; 5123 } 5124 } 5125 } 5126 5127 // If the caller didn't request filter information, 5128 // drop them now so we don't have to 5129 // marshall/unmarshall it. 5130 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5131 N = results.size(); 5132 for (int i=0; i<N; i++) { 5133 results.get(i).filter = null; 5134 } 5135 } 5136 5137 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5138 return results; 5139 } 5140 5141 @Override 5142 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5143 int userId) { 5144 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5145 ComponentName comp = intent.getComponent(); 5146 if (comp == null) { 5147 if (intent.getSelector() != null) { 5148 intent = intent.getSelector(); 5149 comp = intent.getComponent(); 5150 } 5151 } 5152 if (comp != null) { 5153 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5154 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5155 if (ai != null) { 5156 ResolveInfo ri = new ResolveInfo(); 5157 ri.activityInfo = ai; 5158 list.add(ri); 5159 } 5160 return list; 5161 } 5162 5163 // reader 5164 synchronized (mPackages) { 5165 String pkgName = intent.getPackage(); 5166 if (pkgName == null) { 5167 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5168 } 5169 final PackageParser.Package pkg = mPackages.get(pkgName); 5170 if (pkg != null) { 5171 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5172 userId); 5173 } 5174 return null; 5175 } 5176 } 5177 5178 @Override 5179 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5180 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5181 if (!sUserManager.exists(userId)) return null; 5182 if (query != null) { 5183 if (query.size() >= 1) { 5184 // If there is more than one service with the same priority, 5185 // just arbitrarily pick the first one. 5186 return query.get(0); 5187 } 5188 } 5189 return null; 5190 } 5191 5192 @Override 5193 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5194 int userId) { 5195 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5196 ComponentName comp = intent.getComponent(); 5197 if (comp == null) { 5198 if (intent.getSelector() != null) { 5199 intent = intent.getSelector(); 5200 comp = intent.getComponent(); 5201 } 5202 } 5203 if (comp != null) { 5204 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5205 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5206 if (si != null) { 5207 final ResolveInfo ri = new ResolveInfo(); 5208 ri.serviceInfo = si; 5209 list.add(ri); 5210 } 5211 return list; 5212 } 5213 5214 // reader 5215 synchronized (mPackages) { 5216 String pkgName = intent.getPackage(); 5217 if (pkgName == null) { 5218 return mServices.queryIntent(intent, resolvedType, flags, userId); 5219 } 5220 final PackageParser.Package pkg = mPackages.get(pkgName); 5221 if (pkg != null) { 5222 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5223 userId); 5224 } 5225 return null; 5226 } 5227 } 5228 5229 @Override 5230 public List<ResolveInfo> queryIntentContentProviders( 5231 Intent intent, String resolvedType, int flags, int userId) { 5232 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5233 ComponentName comp = intent.getComponent(); 5234 if (comp == null) { 5235 if (intent.getSelector() != null) { 5236 intent = intent.getSelector(); 5237 comp = intent.getComponent(); 5238 } 5239 } 5240 if (comp != null) { 5241 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5242 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5243 if (pi != null) { 5244 final ResolveInfo ri = new ResolveInfo(); 5245 ri.providerInfo = pi; 5246 list.add(ri); 5247 } 5248 return list; 5249 } 5250 5251 // reader 5252 synchronized (mPackages) { 5253 String pkgName = intent.getPackage(); 5254 if (pkgName == null) { 5255 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5256 } 5257 final PackageParser.Package pkg = mPackages.get(pkgName); 5258 if (pkg != null) { 5259 return mProviders.queryIntentForPackage( 5260 intent, resolvedType, flags, pkg.providers, userId); 5261 } 5262 return null; 5263 } 5264 } 5265 5266 @Override 5267 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5268 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5269 5270 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5271 5272 // writer 5273 synchronized (mPackages) { 5274 ArrayList<PackageInfo> list; 5275 if (listUninstalled) { 5276 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5277 for (PackageSetting ps : mSettings.mPackages.values()) { 5278 PackageInfo pi; 5279 if (ps.pkg != null) { 5280 pi = generatePackageInfo(ps.pkg, flags, userId); 5281 } else { 5282 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5283 } 5284 if (pi != null) { 5285 list.add(pi); 5286 } 5287 } 5288 } else { 5289 list = new ArrayList<PackageInfo>(mPackages.size()); 5290 for (PackageParser.Package p : mPackages.values()) { 5291 PackageInfo pi = generatePackageInfo(p, flags, userId); 5292 if (pi != null) { 5293 list.add(pi); 5294 } 5295 } 5296 } 5297 5298 return new ParceledListSlice<PackageInfo>(list); 5299 } 5300 } 5301 5302 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5303 String[] permissions, boolean[] tmp, int flags, int userId) { 5304 int numMatch = 0; 5305 final PermissionsState permissionsState = ps.getPermissionsState(); 5306 for (int i=0; i<permissions.length; i++) { 5307 final String permission = permissions[i]; 5308 if (permissionsState.hasPermission(permission, userId)) { 5309 tmp[i] = true; 5310 numMatch++; 5311 } else { 5312 tmp[i] = false; 5313 } 5314 } 5315 if (numMatch == 0) { 5316 return; 5317 } 5318 PackageInfo pi; 5319 if (ps.pkg != null) { 5320 pi = generatePackageInfo(ps.pkg, flags, userId); 5321 } else { 5322 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5323 } 5324 // The above might return null in cases of uninstalled apps or install-state 5325 // skew across users/profiles. 5326 if (pi != null) { 5327 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5328 if (numMatch == permissions.length) { 5329 pi.requestedPermissions = permissions; 5330 } else { 5331 pi.requestedPermissions = new String[numMatch]; 5332 numMatch = 0; 5333 for (int i=0; i<permissions.length; i++) { 5334 if (tmp[i]) { 5335 pi.requestedPermissions[numMatch] = permissions[i]; 5336 numMatch++; 5337 } 5338 } 5339 } 5340 } 5341 list.add(pi); 5342 } 5343 } 5344 5345 @Override 5346 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5347 String[] permissions, int flags, int userId) { 5348 if (!sUserManager.exists(userId)) return null; 5349 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5350 5351 // writer 5352 synchronized (mPackages) { 5353 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5354 boolean[] tmpBools = new boolean[permissions.length]; 5355 if (listUninstalled) { 5356 for (PackageSetting ps : mSettings.mPackages.values()) { 5357 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5358 } 5359 } else { 5360 for (PackageParser.Package pkg : mPackages.values()) { 5361 PackageSetting ps = (PackageSetting)pkg.mExtras; 5362 if (ps != null) { 5363 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5364 userId); 5365 } 5366 } 5367 } 5368 5369 return new ParceledListSlice<PackageInfo>(list); 5370 } 5371 } 5372 5373 @Override 5374 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5375 if (!sUserManager.exists(userId)) return null; 5376 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5377 5378 // writer 5379 synchronized (mPackages) { 5380 ArrayList<ApplicationInfo> list; 5381 if (listUninstalled) { 5382 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5383 for (PackageSetting ps : mSettings.mPackages.values()) { 5384 ApplicationInfo ai; 5385 if (ps.pkg != null) { 5386 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5387 ps.readUserState(userId), userId); 5388 } else { 5389 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5390 } 5391 if (ai != null) { 5392 list.add(ai); 5393 } 5394 } 5395 } else { 5396 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5397 for (PackageParser.Package p : mPackages.values()) { 5398 if (p.mExtras != null) { 5399 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5400 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5401 if (ai != null) { 5402 list.add(ai); 5403 } 5404 } 5405 } 5406 } 5407 5408 return new ParceledListSlice<ApplicationInfo>(list); 5409 } 5410 } 5411 5412 public List<ApplicationInfo> getPersistentApplications(int flags) { 5413 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5414 5415 // reader 5416 synchronized (mPackages) { 5417 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5418 final int userId = UserHandle.getCallingUserId(); 5419 while (i.hasNext()) { 5420 final PackageParser.Package p = i.next(); 5421 if (p.applicationInfo != null 5422 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5423 && (!mSafeMode || isSystemApp(p))) { 5424 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5425 if (ps != null) { 5426 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5427 ps.readUserState(userId), userId); 5428 if (ai != null) { 5429 finalList.add(ai); 5430 } 5431 } 5432 } 5433 } 5434 } 5435 5436 return finalList; 5437 } 5438 5439 @Override 5440 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5441 if (!sUserManager.exists(userId)) return null; 5442 // reader 5443 synchronized (mPackages) { 5444 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5445 PackageSetting ps = provider != null 5446 ? mSettings.mPackages.get(provider.owner.packageName) 5447 : null; 5448 return ps != null 5449 && mSettings.isEnabledLPr(provider.info, flags, userId) 5450 && (!mSafeMode || (provider.info.applicationInfo.flags 5451 &ApplicationInfo.FLAG_SYSTEM) != 0) 5452 ? PackageParser.generateProviderInfo(provider, flags, 5453 ps.readUserState(userId), userId) 5454 : null; 5455 } 5456 } 5457 5458 /** 5459 * @deprecated 5460 */ 5461 @Deprecated 5462 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5463 // reader 5464 synchronized (mPackages) { 5465 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5466 .entrySet().iterator(); 5467 final int userId = UserHandle.getCallingUserId(); 5468 while (i.hasNext()) { 5469 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5470 PackageParser.Provider p = entry.getValue(); 5471 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5472 5473 if (ps != null && p.syncable 5474 && (!mSafeMode || (p.info.applicationInfo.flags 5475 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5476 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5477 ps.readUserState(userId), userId); 5478 if (info != null) { 5479 outNames.add(entry.getKey()); 5480 outInfo.add(info); 5481 } 5482 } 5483 } 5484 } 5485 } 5486 5487 @Override 5488 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5489 int uid, int flags) { 5490 ArrayList<ProviderInfo> finalList = null; 5491 // reader 5492 synchronized (mPackages) { 5493 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5494 final int userId = processName != null ? 5495 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5496 while (i.hasNext()) { 5497 final PackageParser.Provider p = i.next(); 5498 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5499 if (ps != null && p.info.authority != null 5500 && (processName == null 5501 || (p.info.processName.equals(processName) 5502 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5503 && mSettings.isEnabledLPr(p.info, flags, userId) 5504 && (!mSafeMode 5505 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5506 if (finalList == null) { 5507 finalList = new ArrayList<ProviderInfo>(3); 5508 } 5509 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5510 ps.readUserState(userId), userId); 5511 if (info != null) { 5512 finalList.add(info); 5513 } 5514 } 5515 } 5516 } 5517 5518 if (finalList != null) { 5519 Collections.sort(finalList, mProviderInitOrderSorter); 5520 return new ParceledListSlice<ProviderInfo>(finalList); 5521 } 5522 5523 return null; 5524 } 5525 5526 @Override 5527 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5528 int flags) { 5529 // reader 5530 synchronized (mPackages) { 5531 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5532 return PackageParser.generateInstrumentationInfo(i, flags); 5533 } 5534 } 5535 5536 @Override 5537 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5538 int flags) { 5539 ArrayList<InstrumentationInfo> finalList = 5540 new ArrayList<InstrumentationInfo>(); 5541 5542 // reader 5543 synchronized (mPackages) { 5544 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5545 while (i.hasNext()) { 5546 final PackageParser.Instrumentation p = i.next(); 5547 if (targetPackage == null 5548 || targetPackage.equals(p.info.targetPackage)) { 5549 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5550 flags); 5551 if (ii != null) { 5552 finalList.add(ii); 5553 } 5554 } 5555 } 5556 } 5557 5558 return finalList; 5559 } 5560 5561 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5562 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5563 if (overlays == null) { 5564 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5565 return; 5566 } 5567 for (PackageParser.Package opkg : overlays.values()) { 5568 // Not much to do if idmap fails: we already logged the error 5569 // and we certainly don't want to abort installation of pkg simply 5570 // because an overlay didn't fit properly. For these reasons, 5571 // ignore the return value of createIdmapForPackagePairLI. 5572 createIdmapForPackagePairLI(pkg, opkg); 5573 } 5574 } 5575 5576 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5577 PackageParser.Package opkg) { 5578 if (!opkg.mTrustedOverlay) { 5579 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5580 opkg.baseCodePath + ": overlay not trusted"); 5581 return false; 5582 } 5583 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5584 if (overlaySet == null) { 5585 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5586 opkg.baseCodePath + " but target package has no known overlays"); 5587 return false; 5588 } 5589 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5590 // TODO: generate idmap for split APKs 5591 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5592 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5593 + opkg.baseCodePath); 5594 return false; 5595 } 5596 PackageParser.Package[] overlayArray = 5597 overlaySet.values().toArray(new PackageParser.Package[0]); 5598 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5599 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5600 return p1.mOverlayPriority - p2.mOverlayPriority; 5601 } 5602 }; 5603 Arrays.sort(overlayArray, cmp); 5604 5605 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5606 int i = 0; 5607 for (PackageParser.Package p : overlayArray) { 5608 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5609 } 5610 return true; 5611 } 5612 5613 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5614 final File[] files = dir.listFiles(); 5615 if (ArrayUtils.isEmpty(files)) { 5616 Log.d(TAG, "No files in app dir " + dir); 5617 return; 5618 } 5619 5620 if (DEBUG_PACKAGE_SCANNING) { 5621 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5622 + " flags=0x" + Integer.toHexString(parseFlags)); 5623 } 5624 5625 for (File file : files) { 5626 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5627 && !PackageInstallerService.isStageName(file.getName()); 5628 if (!isPackage) { 5629 // Ignore entries which are not packages 5630 continue; 5631 } 5632 try { 5633 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5634 scanFlags, currentTime, null); 5635 } catch (PackageManagerException e) { 5636 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5637 5638 // Delete invalid userdata apps 5639 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5640 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5641 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5642 if (file.isDirectory()) { 5643 mInstaller.rmPackageDir(file.getAbsolutePath()); 5644 } else { 5645 file.delete(); 5646 } 5647 } 5648 } 5649 } 5650 } 5651 5652 private static File getSettingsProblemFile() { 5653 File dataDir = Environment.getDataDirectory(); 5654 File systemDir = new File(dataDir, "system"); 5655 File fname = new File(systemDir, "uiderrors.txt"); 5656 return fname; 5657 } 5658 5659 static void reportSettingsProblem(int priority, String msg) { 5660 logCriticalInfo(priority, msg); 5661 } 5662 5663 static void logCriticalInfo(int priority, String msg) { 5664 Slog.println(priority, TAG, msg); 5665 EventLogTags.writePmCriticalInfo(msg); 5666 try { 5667 File fname = getSettingsProblemFile(); 5668 FileOutputStream out = new FileOutputStream(fname, true); 5669 PrintWriter pw = new FastPrintWriter(out); 5670 SimpleDateFormat formatter = new SimpleDateFormat(); 5671 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5672 pw.println(dateString + ": " + msg); 5673 pw.close(); 5674 FileUtils.setPermissions( 5675 fname.toString(), 5676 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5677 -1, -1); 5678 } catch (java.io.IOException e) { 5679 } 5680 } 5681 5682 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5683 PackageParser.Package pkg, File srcFile, int parseFlags) 5684 throws PackageManagerException { 5685 if (ps != null 5686 && ps.codePath.equals(srcFile) 5687 && ps.timeStamp == srcFile.lastModified() 5688 && !isCompatSignatureUpdateNeeded(pkg) 5689 && !isRecoverSignatureUpdateNeeded(pkg)) { 5690 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5691 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5692 ArraySet<PublicKey> signingKs; 5693 synchronized (mPackages) { 5694 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5695 } 5696 if (ps.signatures.mSignatures != null 5697 && ps.signatures.mSignatures.length != 0 5698 && signingKs != null) { 5699 // Optimization: reuse the existing cached certificates 5700 // if the package appears to be unchanged. 5701 pkg.mSignatures = ps.signatures.mSignatures; 5702 pkg.mSigningKeys = signingKs; 5703 return; 5704 } 5705 5706 Slog.w(TAG, "PackageSetting for " + ps.name 5707 + " is missing signatures. Collecting certs again to recover them."); 5708 } else { 5709 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5710 } 5711 5712 try { 5713 pp.collectCertificates(pkg, parseFlags); 5714 pp.collectManifestDigest(pkg); 5715 } catch (PackageParserException e) { 5716 throw PackageManagerException.from(e); 5717 } 5718 } 5719 5720 /* 5721 * Scan a package and return the newly parsed package. 5722 * Returns null in case of errors and the error code is stored in mLastScanError 5723 */ 5724 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5725 long currentTime, UserHandle user) throws PackageManagerException { 5726 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5727 parseFlags |= mDefParseFlags; 5728 PackageParser pp = new PackageParser(); 5729 pp.setSeparateProcesses(mSeparateProcesses); 5730 pp.setOnlyCoreApps(mOnlyCore); 5731 pp.setDisplayMetrics(mMetrics); 5732 5733 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5734 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5735 } 5736 5737 final PackageParser.Package pkg; 5738 try { 5739 pkg = pp.parsePackage(scanFile, parseFlags); 5740 } catch (PackageParserException e) { 5741 throw PackageManagerException.from(e); 5742 } 5743 5744 PackageSetting ps = null; 5745 PackageSetting updatedPkg; 5746 // reader 5747 synchronized (mPackages) { 5748 // Look to see if we already know about this package. 5749 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5750 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5751 // This package has been renamed to its original name. Let's 5752 // use that. 5753 ps = mSettings.peekPackageLPr(oldName); 5754 } 5755 // If there was no original package, see one for the real package name. 5756 if (ps == null) { 5757 ps = mSettings.peekPackageLPr(pkg.packageName); 5758 } 5759 // Check to see if this package could be hiding/updating a system 5760 // package. Must look for it either under the original or real 5761 // package name depending on our state. 5762 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5763 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5764 } 5765 boolean updatedPkgBetter = false; 5766 // First check if this is a system package that may involve an update 5767 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5768 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5769 // it needs to drop FLAG_PRIVILEGED. 5770 if (locationIsPrivileged(scanFile)) { 5771 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5772 } else { 5773 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5774 } 5775 5776 if (ps != null && !ps.codePath.equals(scanFile)) { 5777 // The path has changed from what was last scanned... check the 5778 // version of the new path against what we have stored to determine 5779 // what to do. 5780 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5781 if (pkg.mVersionCode <= ps.versionCode) { 5782 // The system package has been updated and the code path does not match 5783 // Ignore entry. Skip it. 5784 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5785 + " ignored: updated version " + ps.versionCode 5786 + " better than this " + pkg.mVersionCode); 5787 if (!updatedPkg.codePath.equals(scanFile)) { 5788 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5789 + ps.name + " changing from " + updatedPkg.codePathString 5790 + " to " + scanFile); 5791 updatedPkg.codePath = scanFile; 5792 updatedPkg.codePathString = scanFile.toString(); 5793 updatedPkg.resourcePath = scanFile; 5794 updatedPkg.resourcePathString = scanFile.toString(); 5795 } 5796 updatedPkg.pkg = pkg; 5797 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5798 "Package " + ps.name + " at " + scanFile 5799 + " ignored: updated version " + ps.versionCode 5800 + " better than this " + pkg.mVersionCode); 5801 } else { 5802 // The current app on the system partition is better than 5803 // what we have updated to on the data partition; switch 5804 // back to the system partition version. 5805 // At this point, its safely assumed that package installation for 5806 // apps in system partition will go through. If not there won't be a working 5807 // version of the app 5808 // writer 5809 synchronized (mPackages) { 5810 // Just remove the loaded entries from package lists. 5811 mPackages.remove(ps.name); 5812 } 5813 5814 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5815 + " reverting from " + ps.codePathString 5816 + ": new version " + pkg.mVersionCode 5817 + " better than installed " + ps.versionCode); 5818 5819 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5820 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5821 synchronized (mInstallLock) { 5822 args.cleanUpResourcesLI(); 5823 } 5824 synchronized (mPackages) { 5825 mSettings.enableSystemPackageLPw(ps.name); 5826 } 5827 updatedPkgBetter = true; 5828 } 5829 } 5830 } 5831 5832 if (updatedPkg != null) { 5833 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5834 // initially 5835 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5836 5837 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5838 // flag set initially 5839 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5840 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5841 } 5842 } 5843 5844 // Verify certificates against what was last scanned 5845 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5846 5847 /* 5848 * A new system app appeared, but we already had a non-system one of the 5849 * same name installed earlier. 5850 */ 5851 boolean shouldHideSystemApp = false; 5852 if (updatedPkg == null && ps != null 5853 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5854 /* 5855 * Check to make sure the signatures match first. If they don't, 5856 * wipe the installed application and its data. 5857 */ 5858 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5859 != PackageManager.SIGNATURE_MATCH) { 5860 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5861 + " signatures don't match existing userdata copy; removing"); 5862 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5863 ps = null; 5864 } else { 5865 /* 5866 * If the newly-added system app is an older version than the 5867 * already installed version, hide it. It will be scanned later 5868 * and re-added like an update. 5869 */ 5870 if (pkg.mVersionCode <= ps.versionCode) { 5871 shouldHideSystemApp = true; 5872 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5873 + " but new version " + pkg.mVersionCode + " better than installed " 5874 + ps.versionCode + "; hiding system"); 5875 } else { 5876 /* 5877 * The newly found system app is a newer version that the 5878 * one previously installed. Simply remove the 5879 * already-installed application and replace it with our own 5880 * while keeping the application data. 5881 */ 5882 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5883 + " reverting from " + ps.codePathString + ": new version " 5884 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5885 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5886 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5887 synchronized (mInstallLock) { 5888 args.cleanUpResourcesLI(); 5889 } 5890 } 5891 } 5892 } 5893 5894 // The apk is forward locked (not public) if its code and resources 5895 // are kept in different files. (except for app in either system or 5896 // vendor path). 5897 // TODO grab this value from PackageSettings 5898 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5899 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5900 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5901 } 5902 } 5903 5904 // TODO: extend to support forward-locked splits 5905 String resourcePath = null; 5906 String baseResourcePath = null; 5907 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5908 if (ps != null && ps.resourcePathString != null) { 5909 resourcePath = ps.resourcePathString; 5910 baseResourcePath = ps.resourcePathString; 5911 } else { 5912 // Should not happen at all. Just log an error. 5913 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5914 } 5915 } else { 5916 resourcePath = pkg.codePath; 5917 baseResourcePath = pkg.baseCodePath; 5918 } 5919 5920 // Set application objects path explicitly. 5921 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5922 pkg.applicationInfo.setCodePath(pkg.codePath); 5923 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5924 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5925 pkg.applicationInfo.setResourcePath(resourcePath); 5926 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5927 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5928 5929 // Note that we invoke the following method only if we are about to unpack an application 5930 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5931 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5932 5933 /* 5934 * If the system app should be overridden by a previously installed 5935 * data, hide the system app now and let the /data/app scan pick it up 5936 * again. 5937 */ 5938 if (shouldHideSystemApp) { 5939 synchronized (mPackages) { 5940 mSettings.disableSystemPackageLPw(pkg.packageName); 5941 } 5942 } 5943 5944 return scannedPkg; 5945 } 5946 5947 private static String fixProcessName(String defProcessName, 5948 String processName, int uid) { 5949 if (processName == null) { 5950 return defProcessName; 5951 } 5952 return processName; 5953 } 5954 5955 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5956 throws PackageManagerException { 5957 if (pkgSetting.signatures.mSignatures != null) { 5958 // Already existing package. Make sure signatures match 5959 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5960 == PackageManager.SIGNATURE_MATCH; 5961 if (!match) { 5962 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5963 == PackageManager.SIGNATURE_MATCH; 5964 } 5965 if (!match) { 5966 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5967 == PackageManager.SIGNATURE_MATCH; 5968 } 5969 if (!match) { 5970 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5971 + pkg.packageName + " signatures do not match the " 5972 + "previously installed version; ignoring!"); 5973 } 5974 } 5975 5976 // Check for shared user signatures 5977 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5978 // Already existing package. Make sure signatures match 5979 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5980 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5981 if (!match) { 5982 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5983 == PackageManager.SIGNATURE_MATCH; 5984 } 5985 if (!match) { 5986 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5987 == PackageManager.SIGNATURE_MATCH; 5988 } 5989 if (!match) { 5990 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5991 "Package " + pkg.packageName 5992 + " has no signatures that match those in shared user " 5993 + pkgSetting.sharedUser.name + "; ignoring!"); 5994 } 5995 } 5996 } 5997 5998 /** 5999 * Enforces that only the system UID or root's UID can call a method exposed 6000 * via Binder. 6001 * 6002 * @param message used as message if SecurityException is thrown 6003 * @throws SecurityException if the caller is not system or root 6004 */ 6005 private static final void enforceSystemOrRoot(String message) { 6006 final int uid = Binder.getCallingUid(); 6007 if (uid != Process.SYSTEM_UID && uid != 0) { 6008 throw new SecurityException(message); 6009 } 6010 } 6011 6012 @Override 6013 public void performBootDexOpt() { 6014 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6015 6016 // Before everything else, see whether we need to fstrim. 6017 try { 6018 IMountService ms = PackageHelper.getMountService(); 6019 if (ms != null) { 6020 final boolean isUpgrade = isUpgrade(); 6021 boolean doTrim = isUpgrade; 6022 if (doTrim) { 6023 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6024 } else { 6025 final long interval = android.provider.Settings.Global.getLong( 6026 mContext.getContentResolver(), 6027 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6028 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6029 if (interval > 0) { 6030 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6031 if (timeSinceLast > interval) { 6032 doTrim = true; 6033 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6034 + "; running immediately"); 6035 } 6036 } 6037 } 6038 if (doTrim) { 6039 if (!isFirstBoot()) { 6040 try { 6041 ActivityManagerNative.getDefault().showBootMessage( 6042 mContext.getResources().getString( 6043 R.string.android_upgrading_fstrim), true); 6044 } catch (RemoteException e) { 6045 } 6046 } 6047 ms.runMaintenance(); 6048 } 6049 } else { 6050 Slog.e(TAG, "Mount service unavailable!"); 6051 } 6052 } catch (RemoteException e) { 6053 // Can't happen; MountService is local 6054 } 6055 6056 final ArraySet<PackageParser.Package> pkgs; 6057 synchronized (mPackages) { 6058 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6059 } 6060 6061 if (pkgs != null) { 6062 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6063 // in case the device runs out of space. 6064 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6065 // Give priority to core apps. 6066 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6067 PackageParser.Package pkg = it.next(); 6068 if (pkg.coreApp) { 6069 if (DEBUG_DEXOPT) { 6070 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6071 } 6072 sortedPkgs.add(pkg); 6073 it.remove(); 6074 } 6075 } 6076 // Give priority to system apps that listen for pre boot complete. 6077 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6078 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6079 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6080 PackageParser.Package pkg = it.next(); 6081 if (pkgNames.contains(pkg.packageName)) { 6082 if (DEBUG_DEXOPT) { 6083 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6084 } 6085 sortedPkgs.add(pkg); 6086 it.remove(); 6087 } 6088 } 6089 // Filter out packages that aren't recently used. 6090 filterRecentlyUsedApps(pkgs); 6091 // Add all remaining apps. 6092 for (PackageParser.Package pkg : pkgs) { 6093 if (DEBUG_DEXOPT) { 6094 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6095 } 6096 sortedPkgs.add(pkg); 6097 } 6098 6099 // If we want to be lazy, filter everything that wasn't recently used. 6100 if (mLazyDexOpt) { 6101 filterRecentlyUsedApps(sortedPkgs); 6102 } 6103 6104 int i = 0; 6105 int total = sortedPkgs.size(); 6106 File dataDir = Environment.getDataDirectory(); 6107 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6108 if (lowThreshold == 0) { 6109 throw new IllegalStateException("Invalid low memory threshold"); 6110 } 6111 for (PackageParser.Package pkg : sortedPkgs) { 6112 long usableSpace = dataDir.getUsableSpace(); 6113 if (usableSpace < lowThreshold) { 6114 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6115 break; 6116 } 6117 performBootDexOpt(pkg, ++i, total); 6118 } 6119 } 6120 } 6121 6122 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6123 // Filter out packages that aren't recently used. 6124 // 6125 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6126 // should do a full dexopt. 6127 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6128 int total = pkgs.size(); 6129 int skipped = 0; 6130 long now = System.currentTimeMillis(); 6131 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6132 PackageParser.Package pkg = i.next(); 6133 long then = pkg.mLastPackageUsageTimeInMills; 6134 if (then + mDexOptLRUThresholdInMills < now) { 6135 if (DEBUG_DEXOPT) { 6136 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6137 ((then == 0) ? "never" : new Date(then))); 6138 } 6139 i.remove(); 6140 skipped++; 6141 } 6142 } 6143 if (DEBUG_DEXOPT) { 6144 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6145 } 6146 } 6147 } 6148 6149 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6150 List<ResolveInfo> ris = null; 6151 try { 6152 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6153 intent, null, 0, UserHandle.USER_OWNER); 6154 } catch (RemoteException e) { 6155 } 6156 ArraySet<String> pkgNames = new ArraySet<String>(); 6157 if (ris != null) { 6158 for (ResolveInfo ri : ris) { 6159 pkgNames.add(ri.activityInfo.packageName); 6160 } 6161 } 6162 return pkgNames; 6163 } 6164 6165 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6166 if (DEBUG_DEXOPT) { 6167 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6168 } 6169 if (!isFirstBoot()) { 6170 try { 6171 ActivityManagerNative.getDefault().showBootMessage( 6172 mContext.getResources().getString(R.string.android_upgrading_apk, 6173 curr, total), true); 6174 } catch (RemoteException e) { 6175 } 6176 } 6177 PackageParser.Package p = pkg; 6178 synchronized (mInstallLock) { 6179 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6180 false /* force dex */, false /* defer */, true /* include dependencies */, 6181 false /* boot complete */, false /*useJit*/); 6182 } 6183 } 6184 6185 @Override 6186 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6187 return performDexOpt(packageName, instructionSet, false); 6188 } 6189 6190 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6191 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6192 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6193 if (!dexopt && !updateUsage) { 6194 // We aren't going to dexopt or update usage, so bail early. 6195 return false; 6196 } 6197 PackageParser.Package p; 6198 final String targetInstructionSet; 6199 synchronized (mPackages) { 6200 p = mPackages.get(packageName); 6201 if (p == null) { 6202 return false; 6203 } 6204 if (updateUsage) { 6205 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6206 } 6207 mPackageUsage.write(false); 6208 if (!dexopt) { 6209 // We aren't going to dexopt, so bail early. 6210 return false; 6211 } 6212 6213 targetInstructionSet = instructionSet != null ? instructionSet : 6214 getPrimaryInstructionSet(p.applicationInfo); 6215 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6216 return false; 6217 } 6218 } 6219 long callingId = Binder.clearCallingIdentity(); 6220 try { 6221 synchronized (mInstallLock) { 6222 final String[] instructionSets = new String[] { targetInstructionSet }; 6223 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6224 false /* forceDex */, false /* defer */, true /* inclDependencies */, 6225 true /* boot complete */, false /*useJit*/); 6226 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6227 } 6228 } finally { 6229 Binder.restoreCallingIdentity(callingId); 6230 } 6231 } 6232 6233 public ArraySet<String> getPackagesThatNeedDexOpt() { 6234 ArraySet<String> pkgs = null; 6235 synchronized (mPackages) { 6236 for (PackageParser.Package p : mPackages.values()) { 6237 if (DEBUG_DEXOPT) { 6238 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6239 } 6240 if (!p.mDexOptPerformed.isEmpty()) { 6241 continue; 6242 } 6243 if (pkgs == null) { 6244 pkgs = new ArraySet<String>(); 6245 } 6246 pkgs.add(p.packageName); 6247 } 6248 } 6249 return pkgs; 6250 } 6251 6252 public void shutdown() { 6253 mPackageUsage.write(true); 6254 } 6255 6256 @Override 6257 public void forceDexOpt(String packageName) { 6258 enforceSystemOrRoot("forceDexOpt"); 6259 6260 PackageParser.Package pkg; 6261 synchronized (mPackages) { 6262 pkg = mPackages.get(packageName); 6263 if (pkg == null) { 6264 throw new IllegalArgumentException("Missing package: " + packageName); 6265 } 6266 } 6267 6268 synchronized (mInstallLock) { 6269 final String[] instructionSets = new String[] { 6270 getPrimaryInstructionSet(pkg.applicationInfo) }; 6271 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6272 true /*forceDex*/, false /* defer */, true /* inclDependencies */, 6273 true /* boot complete */, false /*useJit*/); 6274 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6275 throw new IllegalStateException("Failed to dexopt: " + res); 6276 } 6277 } 6278 } 6279 6280 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6281 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6282 Slog.w(TAG, "Unable to update from " + oldPkg.name 6283 + " to " + newPkg.packageName 6284 + ": old package not in system partition"); 6285 return false; 6286 } else if (mPackages.get(oldPkg.name) != null) { 6287 Slog.w(TAG, "Unable to update from " + oldPkg.name 6288 + " to " + newPkg.packageName 6289 + ": old package still exists"); 6290 return false; 6291 } 6292 return true; 6293 } 6294 6295 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6296 int[] users = sUserManager.getUserIds(); 6297 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6298 if (res < 0) { 6299 return res; 6300 } 6301 for (int user : users) { 6302 if (user != 0) { 6303 res = mInstaller.createUserData(volumeUuid, packageName, 6304 UserHandle.getUid(user, uid), user, seinfo); 6305 if (res < 0) { 6306 return res; 6307 } 6308 } 6309 } 6310 return res; 6311 } 6312 6313 private int removeDataDirsLI(String volumeUuid, String packageName) { 6314 int[] users = sUserManager.getUserIds(); 6315 int res = 0; 6316 for (int user : users) { 6317 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6318 if (resInner < 0) { 6319 res = resInner; 6320 } 6321 } 6322 6323 return res; 6324 } 6325 6326 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6327 int[] users = sUserManager.getUserIds(); 6328 int res = 0; 6329 for (int user : users) { 6330 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6331 if (resInner < 0) { 6332 res = resInner; 6333 } 6334 } 6335 return res; 6336 } 6337 6338 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6339 PackageParser.Package changingLib) { 6340 if (file.path != null) { 6341 usesLibraryFiles.add(file.path); 6342 return; 6343 } 6344 PackageParser.Package p = mPackages.get(file.apk); 6345 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6346 // If we are doing this while in the middle of updating a library apk, 6347 // then we need to make sure to use that new apk for determining the 6348 // dependencies here. (We haven't yet finished committing the new apk 6349 // to the package manager state.) 6350 if (p == null || p.packageName.equals(changingLib.packageName)) { 6351 p = changingLib; 6352 } 6353 } 6354 if (p != null) { 6355 usesLibraryFiles.addAll(p.getAllCodePaths()); 6356 } 6357 } 6358 6359 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6360 PackageParser.Package changingLib) throws PackageManagerException { 6361 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6362 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6363 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6364 for (int i=0; i<N; i++) { 6365 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6366 if (file == null) { 6367 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6368 "Package " + pkg.packageName + " requires unavailable shared library " 6369 + pkg.usesLibraries.get(i) + "; failing!"); 6370 } 6371 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6372 } 6373 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6374 for (int i=0; i<N; i++) { 6375 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6376 if (file == null) { 6377 Slog.w(TAG, "Package " + pkg.packageName 6378 + " desires unavailable shared library " 6379 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6380 } else { 6381 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6382 } 6383 } 6384 N = usesLibraryFiles.size(); 6385 if (N > 0) { 6386 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6387 } else { 6388 pkg.usesLibraryFiles = null; 6389 } 6390 } 6391 } 6392 6393 private static boolean hasString(List<String> list, List<String> which) { 6394 if (list == null) { 6395 return false; 6396 } 6397 for (int i=list.size()-1; i>=0; i--) { 6398 for (int j=which.size()-1; j>=0; j--) { 6399 if (which.get(j).equals(list.get(i))) { 6400 return true; 6401 } 6402 } 6403 } 6404 return false; 6405 } 6406 6407 private void updateAllSharedLibrariesLPw() { 6408 for (PackageParser.Package pkg : mPackages.values()) { 6409 try { 6410 updateSharedLibrariesLPw(pkg, null); 6411 } catch (PackageManagerException e) { 6412 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6413 } 6414 } 6415 } 6416 6417 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6418 PackageParser.Package changingPkg) { 6419 ArrayList<PackageParser.Package> res = null; 6420 for (PackageParser.Package pkg : mPackages.values()) { 6421 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6422 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6423 if (res == null) { 6424 res = new ArrayList<PackageParser.Package>(); 6425 } 6426 res.add(pkg); 6427 try { 6428 updateSharedLibrariesLPw(pkg, changingPkg); 6429 } catch (PackageManagerException e) { 6430 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6431 } 6432 } 6433 } 6434 return res; 6435 } 6436 6437 /** 6438 * Derive the value of the {@code cpuAbiOverride} based on the provided 6439 * value and an optional stored value from the package settings. 6440 */ 6441 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6442 String cpuAbiOverride = null; 6443 6444 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6445 cpuAbiOverride = null; 6446 } else if (abiOverride != null) { 6447 cpuAbiOverride = abiOverride; 6448 } else if (settings != null) { 6449 cpuAbiOverride = settings.cpuAbiOverrideString; 6450 } 6451 6452 return cpuAbiOverride; 6453 } 6454 6455 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6456 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6457 boolean success = false; 6458 try { 6459 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6460 currentTime, user); 6461 success = true; 6462 return res; 6463 } finally { 6464 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6465 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6466 } 6467 } 6468 } 6469 6470 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6471 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6472 final File scanFile = new File(pkg.codePath); 6473 if (pkg.applicationInfo.getCodePath() == null || 6474 pkg.applicationInfo.getResourcePath() == null) { 6475 // Bail out. The resource and code paths haven't been set. 6476 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6477 "Code and resource paths haven't been set correctly"); 6478 } 6479 6480 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6481 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6482 } else { 6483 // Only allow system apps to be flagged as core apps. 6484 pkg.coreApp = false; 6485 } 6486 6487 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6488 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6489 } 6490 6491 if (mCustomResolverComponentName != null && 6492 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6493 setUpCustomResolverActivity(pkg); 6494 } 6495 6496 if (pkg.packageName.equals("android")) { 6497 synchronized (mPackages) { 6498 if (mAndroidApplication != null) { 6499 Slog.w(TAG, "*************************************************"); 6500 Slog.w(TAG, "Core android package being redefined. Skipping."); 6501 Slog.w(TAG, " file=" + scanFile); 6502 Slog.w(TAG, "*************************************************"); 6503 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6504 "Core android package being redefined. Skipping."); 6505 } 6506 6507 // Set up information for our fall-back user intent resolution activity. 6508 mPlatformPackage = pkg; 6509 pkg.mVersionCode = mSdkVersion; 6510 mAndroidApplication = pkg.applicationInfo; 6511 6512 if (!mResolverReplaced) { 6513 mResolveActivity.applicationInfo = mAndroidApplication; 6514 mResolveActivity.name = ResolverActivity.class.getName(); 6515 mResolveActivity.packageName = mAndroidApplication.packageName; 6516 mResolveActivity.processName = "system:ui"; 6517 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6518 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6519 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6520 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6521 mResolveActivity.exported = true; 6522 mResolveActivity.enabled = true; 6523 mResolveInfo.activityInfo = mResolveActivity; 6524 mResolveInfo.priority = 0; 6525 mResolveInfo.preferredOrder = 0; 6526 mResolveInfo.match = 0; 6527 mResolveComponentName = new ComponentName( 6528 mAndroidApplication.packageName, mResolveActivity.name); 6529 } 6530 } 6531 } 6532 6533 if (DEBUG_PACKAGE_SCANNING) { 6534 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6535 Log.d(TAG, "Scanning package " + pkg.packageName); 6536 } 6537 6538 if (mPackages.containsKey(pkg.packageName) 6539 || mSharedLibraries.containsKey(pkg.packageName)) { 6540 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6541 "Application package " + pkg.packageName 6542 + " already installed. Skipping duplicate."); 6543 } 6544 6545 // If we're only installing presumed-existing packages, require that the 6546 // scanned APK is both already known and at the path previously established 6547 // for it. Previously unknown packages we pick up normally, but if we have an 6548 // a priori expectation about this package's install presence, enforce it. 6549 // With a singular exception for new system packages. When an OTA contains 6550 // a new system package, we allow the codepath to change from a system location 6551 // to the user-installed location. If we don't allow this change, any newer, 6552 // user-installed version of the application will be ignored. 6553 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6554 if (mExpectingBetter.containsKey(pkg.packageName)) { 6555 logCriticalInfo(Log.WARN, 6556 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6557 } else { 6558 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6559 if (known != null) { 6560 if (DEBUG_PACKAGE_SCANNING) { 6561 Log.d(TAG, "Examining " + pkg.codePath 6562 + " and requiring known paths " + known.codePathString 6563 + " & " + known.resourcePathString); 6564 } 6565 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6566 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6567 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6568 "Application package " + pkg.packageName 6569 + " found at " + pkg.applicationInfo.getCodePath() 6570 + " but expected at " + known.codePathString + "; ignoring."); 6571 } 6572 } 6573 } 6574 } 6575 6576 // Initialize package source and resource directories 6577 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6578 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6579 6580 SharedUserSetting suid = null; 6581 PackageSetting pkgSetting = null; 6582 6583 if (!isSystemApp(pkg)) { 6584 // Only system apps can use these features. 6585 pkg.mOriginalPackages = null; 6586 pkg.mRealPackage = null; 6587 pkg.mAdoptPermissions = null; 6588 } 6589 6590 // writer 6591 synchronized (mPackages) { 6592 if (pkg.mSharedUserId != null) { 6593 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6594 if (suid == null) { 6595 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6596 "Creating application package " + pkg.packageName 6597 + " for shared user failed"); 6598 } 6599 if (DEBUG_PACKAGE_SCANNING) { 6600 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6601 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6602 + "): packages=" + suid.packages); 6603 } 6604 } 6605 6606 // Check if we are renaming from an original package name. 6607 PackageSetting origPackage = null; 6608 String realName = null; 6609 if (pkg.mOriginalPackages != null) { 6610 // This package may need to be renamed to a previously 6611 // installed name. Let's check on that... 6612 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6613 if (pkg.mOriginalPackages.contains(renamed)) { 6614 // This package had originally been installed as the 6615 // original name, and we have already taken care of 6616 // transitioning to the new one. Just update the new 6617 // one to continue using the old name. 6618 realName = pkg.mRealPackage; 6619 if (!pkg.packageName.equals(renamed)) { 6620 // Callers into this function may have already taken 6621 // care of renaming the package; only do it here if 6622 // it is not already done. 6623 pkg.setPackageName(renamed); 6624 } 6625 6626 } else { 6627 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6628 if ((origPackage = mSettings.peekPackageLPr( 6629 pkg.mOriginalPackages.get(i))) != null) { 6630 // We do have the package already installed under its 6631 // original name... should we use it? 6632 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6633 // New package is not compatible with original. 6634 origPackage = null; 6635 continue; 6636 } else if (origPackage.sharedUser != null) { 6637 // Make sure uid is compatible between packages. 6638 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6639 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6640 + " to " + pkg.packageName + ": old uid " 6641 + origPackage.sharedUser.name 6642 + " differs from " + pkg.mSharedUserId); 6643 origPackage = null; 6644 continue; 6645 } 6646 } else { 6647 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6648 + pkg.packageName + " to old name " + origPackage.name); 6649 } 6650 break; 6651 } 6652 } 6653 } 6654 } 6655 6656 if (mTransferedPackages.contains(pkg.packageName)) { 6657 Slog.w(TAG, "Package " + pkg.packageName 6658 + " was transferred to another, but its .apk remains"); 6659 } 6660 6661 // Just create the setting, don't add it yet. For already existing packages 6662 // the PkgSetting exists already and doesn't have to be created. 6663 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6664 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6665 pkg.applicationInfo.primaryCpuAbi, 6666 pkg.applicationInfo.secondaryCpuAbi, 6667 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6668 user, false); 6669 if (pkgSetting == null) { 6670 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6671 "Creating application package " + pkg.packageName + " failed"); 6672 } 6673 6674 if (pkgSetting.origPackage != null) { 6675 // If we are first transitioning from an original package, 6676 // fix up the new package's name now. We need to do this after 6677 // looking up the package under its new name, so getPackageLP 6678 // can take care of fiddling things correctly. 6679 pkg.setPackageName(origPackage.name); 6680 6681 // File a report about this. 6682 String msg = "New package " + pkgSetting.realName 6683 + " renamed to replace old package " + pkgSetting.name; 6684 reportSettingsProblem(Log.WARN, msg); 6685 6686 // Make a note of it. 6687 mTransferedPackages.add(origPackage.name); 6688 6689 // No longer need to retain this. 6690 pkgSetting.origPackage = null; 6691 } 6692 6693 if (realName != null) { 6694 // Make a note of it. 6695 mTransferedPackages.add(pkg.packageName); 6696 } 6697 6698 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6699 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6700 } 6701 6702 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6703 // Check all shared libraries and map to their actual file path. 6704 // We only do this here for apps not on a system dir, because those 6705 // are the only ones that can fail an install due to this. We 6706 // will take care of the system apps by updating all of their 6707 // library paths after the scan is done. 6708 updateSharedLibrariesLPw(pkg, null); 6709 } 6710 6711 if (mFoundPolicyFile) { 6712 SELinuxMMAC.assignSeinfoValue(pkg); 6713 } 6714 6715 pkg.applicationInfo.uid = pkgSetting.appId; 6716 pkg.mExtras = pkgSetting; 6717 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6718 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6719 // We just determined the app is signed correctly, so bring 6720 // over the latest parsed certs. 6721 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6722 } else { 6723 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6724 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6725 "Package " + pkg.packageName + " upgrade keys do not match the " 6726 + "previously installed version"); 6727 } else { 6728 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6729 String msg = "System package " + pkg.packageName 6730 + " signature changed; retaining data."; 6731 reportSettingsProblem(Log.WARN, msg); 6732 } 6733 } 6734 } else { 6735 try { 6736 verifySignaturesLP(pkgSetting, pkg); 6737 // We just determined the app is signed correctly, so bring 6738 // over the latest parsed certs. 6739 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6740 } catch (PackageManagerException e) { 6741 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6742 throw e; 6743 } 6744 // The signature has changed, but this package is in the system 6745 // image... let's recover! 6746 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6747 // However... if this package is part of a shared user, but it 6748 // doesn't match the signature of the shared user, let's fail. 6749 // What this means is that you can't change the signatures 6750 // associated with an overall shared user, which doesn't seem all 6751 // that unreasonable. 6752 if (pkgSetting.sharedUser != null) { 6753 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6754 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6755 throw new PackageManagerException( 6756 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6757 "Signature mismatch for shared user : " 6758 + pkgSetting.sharedUser); 6759 } 6760 } 6761 // File a report about this. 6762 String msg = "System package " + pkg.packageName 6763 + " signature changed; retaining data."; 6764 reportSettingsProblem(Log.WARN, msg); 6765 } 6766 } 6767 // Verify that this new package doesn't have any content providers 6768 // that conflict with existing packages. Only do this if the 6769 // package isn't already installed, since we don't want to break 6770 // things that are installed. 6771 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6772 final int N = pkg.providers.size(); 6773 int i; 6774 for (i=0; i<N; i++) { 6775 PackageParser.Provider p = pkg.providers.get(i); 6776 if (p.info.authority != null) { 6777 String names[] = p.info.authority.split(";"); 6778 for (int j = 0; j < names.length; j++) { 6779 if (mProvidersByAuthority.containsKey(names[j])) { 6780 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6781 final String otherPackageName = 6782 ((other != null && other.getComponentName() != null) ? 6783 other.getComponentName().getPackageName() : "?"); 6784 throw new PackageManagerException( 6785 INSTALL_FAILED_CONFLICTING_PROVIDER, 6786 "Can't install because provider name " + names[j] 6787 + " (in package " + pkg.applicationInfo.packageName 6788 + ") is already used by " + otherPackageName); 6789 } 6790 } 6791 } 6792 } 6793 } 6794 6795 if (pkg.mAdoptPermissions != null) { 6796 // This package wants to adopt ownership of permissions from 6797 // another package. 6798 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6799 final String origName = pkg.mAdoptPermissions.get(i); 6800 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6801 if (orig != null) { 6802 if (verifyPackageUpdateLPr(orig, pkg)) { 6803 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6804 + pkg.packageName); 6805 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6806 } 6807 } 6808 } 6809 } 6810 } 6811 6812 final String pkgName = pkg.packageName; 6813 6814 final long scanFileTime = scanFile.lastModified(); 6815 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6816 pkg.applicationInfo.processName = fixProcessName( 6817 pkg.applicationInfo.packageName, 6818 pkg.applicationInfo.processName, 6819 pkg.applicationInfo.uid); 6820 6821 File dataPath; 6822 if (mPlatformPackage == pkg) { 6823 // The system package is special. 6824 dataPath = new File(Environment.getDataDirectory(), "system"); 6825 6826 pkg.applicationInfo.dataDir = dataPath.getPath(); 6827 6828 } else { 6829 // This is a normal package, need to make its data directory. 6830 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6831 UserHandle.USER_OWNER, pkg.packageName); 6832 6833 boolean uidError = false; 6834 if (dataPath.exists()) { 6835 int currentUid = 0; 6836 try { 6837 StructStat stat = Os.stat(dataPath.getPath()); 6838 currentUid = stat.st_uid; 6839 } catch (ErrnoException e) { 6840 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6841 } 6842 6843 // If we have mismatched owners for the data path, we have a problem. 6844 if (currentUid != pkg.applicationInfo.uid) { 6845 boolean recovered = false; 6846 if (currentUid == 0) { 6847 // The directory somehow became owned by root. Wow. 6848 // This is probably because the system was stopped while 6849 // installd was in the middle of messing with its libs 6850 // directory. Ask installd to fix that. 6851 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6852 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6853 if (ret >= 0) { 6854 recovered = true; 6855 String msg = "Package " + pkg.packageName 6856 + " unexpectedly changed to uid 0; recovered to " + 6857 + pkg.applicationInfo.uid; 6858 reportSettingsProblem(Log.WARN, msg); 6859 } 6860 } 6861 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6862 || (scanFlags&SCAN_BOOTING) != 0)) { 6863 // If this is a system app, we can at least delete its 6864 // current data so the application will still work. 6865 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6866 if (ret >= 0) { 6867 // TODO: Kill the processes first 6868 // Old data gone! 6869 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6870 ? "System package " : "Third party package "; 6871 String msg = prefix + pkg.packageName 6872 + " has changed from uid: " 6873 + currentUid + " to " 6874 + pkg.applicationInfo.uid + "; old data erased"; 6875 reportSettingsProblem(Log.WARN, msg); 6876 recovered = true; 6877 6878 // And now re-install the app. 6879 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6880 pkg.applicationInfo.seinfo); 6881 if (ret == -1) { 6882 // Ack should not happen! 6883 msg = prefix + pkg.packageName 6884 + " could not have data directory re-created after delete."; 6885 reportSettingsProblem(Log.WARN, msg); 6886 throw new PackageManagerException( 6887 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6888 } 6889 } 6890 if (!recovered) { 6891 mHasSystemUidErrors = true; 6892 } 6893 } else if (!recovered) { 6894 // If we allow this install to proceed, we will be broken. 6895 // Abort, abort! 6896 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6897 "scanPackageLI"); 6898 } 6899 if (!recovered) { 6900 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6901 + pkg.applicationInfo.uid + "/fs_" 6902 + currentUid; 6903 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6904 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6905 String msg = "Package " + pkg.packageName 6906 + " has mismatched uid: " 6907 + currentUid + " on disk, " 6908 + pkg.applicationInfo.uid + " in settings"; 6909 // writer 6910 synchronized (mPackages) { 6911 mSettings.mReadMessages.append(msg); 6912 mSettings.mReadMessages.append('\n'); 6913 uidError = true; 6914 if (!pkgSetting.uidError) { 6915 reportSettingsProblem(Log.ERROR, msg); 6916 } 6917 } 6918 } 6919 } 6920 pkg.applicationInfo.dataDir = dataPath.getPath(); 6921 if (mShouldRestoreconData) { 6922 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6923 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6924 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6925 } 6926 } else { 6927 if (DEBUG_PACKAGE_SCANNING) { 6928 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6929 Log.v(TAG, "Want this data dir: " + dataPath); 6930 } 6931 //invoke installer to do the actual installation 6932 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6933 pkg.applicationInfo.seinfo); 6934 if (ret < 0) { 6935 // Error from installer 6936 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6937 "Unable to create data dirs [errorCode=" + ret + "]"); 6938 } 6939 6940 if (dataPath.exists()) { 6941 pkg.applicationInfo.dataDir = dataPath.getPath(); 6942 } else { 6943 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6944 pkg.applicationInfo.dataDir = null; 6945 } 6946 } 6947 6948 pkgSetting.uidError = uidError; 6949 } 6950 6951 final String path = scanFile.getPath(); 6952 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6953 6954 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6955 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6956 6957 // Some system apps still use directory structure for native libraries 6958 // in which case we might end up not detecting abi solely based on apk 6959 // structure. Try to detect abi based on directory structure. 6960 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6961 pkg.applicationInfo.primaryCpuAbi == null) { 6962 setBundledAppAbisAndRoots(pkg, pkgSetting); 6963 setNativeLibraryPaths(pkg); 6964 } 6965 6966 } else { 6967 if ((scanFlags & SCAN_MOVE) != 0) { 6968 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6969 // but we already have this packages package info in the PackageSetting. We just 6970 // use that and derive the native library path based on the new codepath. 6971 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6972 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6973 } 6974 6975 // Set native library paths again. For moves, the path will be updated based on the 6976 // ABIs we've determined above. For non-moves, the path will be updated based on the 6977 // ABIs we determined during compilation, but the path will depend on the final 6978 // package path (after the rename away from the stage path). 6979 setNativeLibraryPaths(pkg); 6980 } 6981 6982 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6983 final int[] userIds = sUserManager.getUserIds(); 6984 synchronized (mInstallLock) { 6985 // Make sure all user data directories are ready to roll; we're okay 6986 // if they already exist 6987 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6988 for (int userId : userIds) { 6989 if (userId != 0) { 6990 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6991 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6992 pkg.applicationInfo.seinfo); 6993 } 6994 } 6995 } 6996 6997 // Create a native library symlink only if we have native libraries 6998 // and if the native libraries are 32 bit libraries. We do not provide 6999 // this symlink for 64 bit libraries. 7000 if (pkg.applicationInfo.primaryCpuAbi != null && 7001 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7002 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7003 for (int userId : userIds) { 7004 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7005 nativeLibPath, userId) < 0) { 7006 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7007 "Failed linking native library dir (user=" + userId + ")"); 7008 } 7009 } 7010 } 7011 } 7012 7013 // This is a special case for the "system" package, where the ABI is 7014 // dictated by the zygote configuration (and init.rc). We should keep track 7015 // of this ABI so that we can deal with "normal" applications that run under 7016 // the same UID correctly. 7017 if (mPlatformPackage == pkg) { 7018 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7019 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7020 } 7021 7022 // If there's a mismatch between the abi-override in the package setting 7023 // and the abiOverride specified for the install. Warn about this because we 7024 // would've already compiled the app without taking the package setting into 7025 // account. 7026 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7027 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7028 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7029 " for package: " + pkg.packageName); 7030 } 7031 } 7032 7033 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7034 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7035 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7036 7037 // Copy the derived override back to the parsed package, so that we can 7038 // update the package settings accordingly. 7039 pkg.cpuAbiOverride = cpuAbiOverride; 7040 7041 if (DEBUG_ABI_SELECTION) { 7042 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7043 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7044 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7045 } 7046 7047 // Push the derived path down into PackageSettings so we know what to 7048 // clean up at uninstall time. 7049 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7050 7051 if (DEBUG_ABI_SELECTION) { 7052 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7053 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7054 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7055 } 7056 7057 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7058 // We don't do this here during boot because we can do it all 7059 // at once after scanning all existing packages. 7060 // 7061 // We also do this *before* we perform dexopt on this package, so that 7062 // we can avoid redundant dexopts, and also to make sure we've got the 7063 // code and package path correct. 7064 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7065 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */); 7066 } 7067 7068 if ((scanFlags & SCAN_NO_DEX) == 0) { 7069 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7070 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */, 7071 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7072 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7073 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7074 } 7075 } 7076 if (mFactoryTest && pkg.requestedPermissions.contains( 7077 android.Manifest.permission.FACTORY_TEST)) { 7078 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7079 } 7080 7081 ArrayList<PackageParser.Package> clientLibPkgs = null; 7082 7083 // writer 7084 synchronized (mPackages) { 7085 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7086 // Only system apps can add new shared libraries. 7087 if (pkg.libraryNames != null) { 7088 for (int i=0; i<pkg.libraryNames.size(); i++) { 7089 String name = pkg.libraryNames.get(i); 7090 boolean allowed = false; 7091 if (pkg.isUpdatedSystemApp()) { 7092 // New library entries can only be added through the 7093 // system image. This is important to get rid of a lot 7094 // of nasty edge cases: for example if we allowed a non- 7095 // system update of the app to add a library, then uninstalling 7096 // the update would make the library go away, and assumptions 7097 // we made such as through app install filtering would now 7098 // have allowed apps on the device which aren't compatible 7099 // with it. Better to just have the restriction here, be 7100 // conservative, and create many fewer cases that can negatively 7101 // impact the user experience. 7102 final PackageSetting sysPs = mSettings 7103 .getDisabledSystemPkgLPr(pkg.packageName); 7104 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7105 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7106 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7107 allowed = true; 7108 allowed = true; 7109 break; 7110 } 7111 } 7112 } 7113 } else { 7114 allowed = true; 7115 } 7116 if (allowed) { 7117 if (!mSharedLibraries.containsKey(name)) { 7118 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7119 } else if (!name.equals(pkg.packageName)) { 7120 Slog.w(TAG, "Package " + pkg.packageName + " library " 7121 + name + " already exists; skipping"); 7122 } 7123 } else { 7124 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7125 + name + " that is not declared on system image; skipping"); 7126 } 7127 } 7128 if ((scanFlags&SCAN_BOOTING) == 0) { 7129 // If we are not booting, we need to update any applications 7130 // that are clients of our shared library. If we are booting, 7131 // this will all be done once the scan is complete. 7132 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7133 } 7134 } 7135 } 7136 } 7137 7138 // We also need to dexopt any apps that are dependent on this library. Note that 7139 // if these fail, we should abort the install since installing the library will 7140 // result in some apps being broken. 7141 if (clientLibPkgs != null) { 7142 if ((scanFlags & SCAN_NO_DEX) == 0) { 7143 for (int i = 0; i < clientLibPkgs.size(); i++) { 7144 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7145 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7146 null /* instruction sets */, forceDex, 7147 (scanFlags & SCAN_DEFER_DEX) != 0, false, 7148 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7149 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7150 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7151 "scanPackageLI failed to dexopt clientLibPkgs"); 7152 } 7153 } 7154 } 7155 } 7156 7157 // Request the ActivityManager to kill the process(only for existing packages) 7158 // so that we do not end up in a confused state while the user is still using the older 7159 // version of the application while the new one gets installed. 7160 if ((scanFlags & SCAN_REPLACING) != 0) { 7161 killApplication(pkg.applicationInfo.packageName, 7162 pkg.applicationInfo.uid, "replace pkg"); 7163 } 7164 7165 // Also need to kill any apps that are dependent on the library. 7166 if (clientLibPkgs != null) { 7167 for (int i=0; i<clientLibPkgs.size(); i++) { 7168 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7169 killApplication(clientPkg.applicationInfo.packageName, 7170 clientPkg.applicationInfo.uid, "update lib"); 7171 } 7172 } 7173 7174 // Make sure we're not adding any bogus keyset info 7175 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7176 ksms.assertScannedPackageValid(pkg); 7177 7178 // writer 7179 synchronized (mPackages) { 7180 // We don't expect installation to fail beyond this point 7181 7182 // Add the new setting to mSettings 7183 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7184 // Add the new setting to mPackages 7185 mPackages.put(pkg.applicationInfo.packageName, pkg); 7186 // Make sure we don't accidentally delete its data. 7187 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7188 while (iter.hasNext()) { 7189 PackageCleanItem item = iter.next(); 7190 if (pkgName.equals(item.packageName)) { 7191 iter.remove(); 7192 } 7193 } 7194 7195 // Take care of first install / last update times. 7196 if (currentTime != 0) { 7197 if (pkgSetting.firstInstallTime == 0) { 7198 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7199 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7200 pkgSetting.lastUpdateTime = currentTime; 7201 } 7202 } else if (pkgSetting.firstInstallTime == 0) { 7203 // We need *something*. Take time time stamp of the file. 7204 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7205 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7206 if (scanFileTime != pkgSetting.timeStamp) { 7207 // A package on the system image has changed; consider this 7208 // to be an update. 7209 pkgSetting.lastUpdateTime = scanFileTime; 7210 } 7211 } 7212 7213 // Add the package's KeySets to the global KeySetManagerService 7214 ksms.addScannedPackageLPw(pkg); 7215 7216 int N = pkg.providers.size(); 7217 StringBuilder r = null; 7218 int i; 7219 for (i=0; i<N; i++) { 7220 PackageParser.Provider p = pkg.providers.get(i); 7221 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7222 p.info.processName, pkg.applicationInfo.uid); 7223 mProviders.addProvider(p); 7224 p.syncable = p.info.isSyncable; 7225 if (p.info.authority != null) { 7226 String names[] = p.info.authority.split(";"); 7227 p.info.authority = null; 7228 for (int j = 0; j < names.length; j++) { 7229 if (j == 1 && p.syncable) { 7230 // We only want the first authority for a provider to possibly be 7231 // syncable, so if we already added this provider using a different 7232 // authority clear the syncable flag. We copy the provider before 7233 // changing it because the mProviders object contains a reference 7234 // to a provider that we don't want to change. 7235 // Only do this for the second authority since the resulting provider 7236 // object can be the same for all future authorities for this provider. 7237 p = new PackageParser.Provider(p); 7238 p.syncable = false; 7239 } 7240 if (!mProvidersByAuthority.containsKey(names[j])) { 7241 mProvidersByAuthority.put(names[j], p); 7242 if (p.info.authority == null) { 7243 p.info.authority = names[j]; 7244 } else { 7245 p.info.authority = p.info.authority + ";" + names[j]; 7246 } 7247 if (DEBUG_PACKAGE_SCANNING) { 7248 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7249 Log.d(TAG, "Registered content provider: " + names[j] 7250 + ", className = " + p.info.name + ", isSyncable = " 7251 + p.info.isSyncable); 7252 } 7253 } else { 7254 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7255 Slog.w(TAG, "Skipping provider name " + names[j] + 7256 " (in package " + pkg.applicationInfo.packageName + 7257 "): name already used by " 7258 + ((other != null && other.getComponentName() != null) 7259 ? other.getComponentName().getPackageName() : "?")); 7260 } 7261 } 7262 } 7263 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7264 if (r == null) { 7265 r = new StringBuilder(256); 7266 } else { 7267 r.append(' '); 7268 } 7269 r.append(p.info.name); 7270 } 7271 } 7272 if (r != null) { 7273 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7274 } 7275 7276 N = pkg.services.size(); 7277 r = null; 7278 for (i=0; i<N; i++) { 7279 PackageParser.Service s = pkg.services.get(i); 7280 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7281 s.info.processName, pkg.applicationInfo.uid); 7282 mServices.addService(s); 7283 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7284 if (r == null) { 7285 r = new StringBuilder(256); 7286 } else { 7287 r.append(' '); 7288 } 7289 r.append(s.info.name); 7290 } 7291 } 7292 if (r != null) { 7293 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7294 } 7295 7296 N = pkg.receivers.size(); 7297 r = null; 7298 for (i=0; i<N; i++) { 7299 PackageParser.Activity a = pkg.receivers.get(i); 7300 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7301 a.info.processName, pkg.applicationInfo.uid); 7302 mReceivers.addActivity(a, "receiver"); 7303 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7304 if (r == null) { 7305 r = new StringBuilder(256); 7306 } else { 7307 r.append(' '); 7308 } 7309 r.append(a.info.name); 7310 } 7311 } 7312 if (r != null) { 7313 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7314 } 7315 7316 N = pkg.activities.size(); 7317 r = null; 7318 for (i=0; i<N; i++) { 7319 PackageParser.Activity a = pkg.activities.get(i); 7320 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7321 a.info.processName, pkg.applicationInfo.uid); 7322 mActivities.addActivity(a, "activity"); 7323 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7324 if (r == null) { 7325 r = new StringBuilder(256); 7326 } else { 7327 r.append(' '); 7328 } 7329 r.append(a.info.name); 7330 } 7331 } 7332 if (r != null) { 7333 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7334 } 7335 7336 N = pkg.permissionGroups.size(); 7337 r = null; 7338 for (i=0; i<N; i++) { 7339 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7340 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7341 if (cur == null) { 7342 mPermissionGroups.put(pg.info.name, pg); 7343 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7344 if (r == null) { 7345 r = new StringBuilder(256); 7346 } else { 7347 r.append(' '); 7348 } 7349 r.append(pg.info.name); 7350 } 7351 } else { 7352 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7353 + pg.info.packageName + " ignored: original from " 7354 + cur.info.packageName); 7355 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7356 if (r == null) { 7357 r = new StringBuilder(256); 7358 } else { 7359 r.append(' '); 7360 } 7361 r.append("DUP:"); 7362 r.append(pg.info.name); 7363 } 7364 } 7365 } 7366 if (r != null) { 7367 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7368 } 7369 7370 N = pkg.permissions.size(); 7371 r = null; 7372 for (i=0; i<N; i++) { 7373 PackageParser.Permission p = pkg.permissions.get(i); 7374 7375 // Assume by default that we did not install this permission into the system. 7376 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7377 7378 // Now that permission groups have a special meaning, we ignore permission 7379 // groups for legacy apps to prevent unexpected behavior. In particular, 7380 // permissions for one app being granted to someone just becuase they happen 7381 // to be in a group defined by another app (before this had no implications). 7382 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7383 p.group = mPermissionGroups.get(p.info.group); 7384 // Warn for a permission in an unknown group. 7385 if (p.info.group != null && p.group == null) { 7386 Slog.w(TAG, "Permission " + p.info.name + " from package " 7387 + p.info.packageName + " in an unknown group " + p.info.group); 7388 } 7389 } 7390 7391 ArrayMap<String, BasePermission> permissionMap = 7392 p.tree ? mSettings.mPermissionTrees 7393 : mSettings.mPermissions; 7394 BasePermission bp = permissionMap.get(p.info.name); 7395 7396 // Allow system apps to redefine non-system permissions 7397 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7398 final boolean currentOwnerIsSystem = (bp.perm != null 7399 && isSystemApp(bp.perm.owner)); 7400 if (isSystemApp(p.owner)) { 7401 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7402 // It's a built-in permission and no owner, take ownership now 7403 bp.packageSetting = pkgSetting; 7404 bp.perm = p; 7405 bp.uid = pkg.applicationInfo.uid; 7406 bp.sourcePackage = p.info.packageName; 7407 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7408 } else if (!currentOwnerIsSystem) { 7409 String msg = "New decl " + p.owner + " of permission " 7410 + p.info.name + " is system; overriding " + bp.sourcePackage; 7411 reportSettingsProblem(Log.WARN, msg); 7412 bp = null; 7413 } 7414 } 7415 } 7416 7417 if (bp == null) { 7418 bp = new BasePermission(p.info.name, p.info.packageName, 7419 BasePermission.TYPE_NORMAL); 7420 permissionMap.put(p.info.name, bp); 7421 } 7422 7423 if (bp.perm == null) { 7424 if (bp.sourcePackage == null 7425 || bp.sourcePackage.equals(p.info.packageName)) { 7426 BasePermission tree = findPermissionTreeLP(p.info.name); 7427 if (tree == null 7428 || tree.sourcePackage.equals(p.info.packageName)) { 7429 bp.packageSetting = pkgSetting; 7430 bp.perm = p; 7431 bp.uid = pkg.applicationInfo.uid; 7432 bp.sourcePackage = p.info.packageName; 7433 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7434 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7435 if (r == null) { 7436 r = new StringBuilder(256); 7437 } else { 7438 r.append(' '); 7439 } 7440 r.append(p.info.name); 7441 } 7442 } else { 7443 Slog.w(TAG, "Permission " + p.info.name + " from package " 7444 + p.info.packageName + " ignored: base tree " 7445 + tree.name + " is from package " 7446 + tree.sourcePackage); 7447 } 7448 } else { 7449 Slog.w(TAG, "Permission " + p.info.name + " from package " 7450 + p.info.packageName + " ignored: original from " 7451 + bp.sourcePackage); 7452 } 7453 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7454 if (r == null) { 7455 r = new StringBuilder(256); 7456 } else { 7457 r.append(' '); 7458 } 7459 r.append("DUP:"); 7460 r.append(p.info.name); 7461 } 7462 if (bp.perm == p) { 7463 bp.protectionLevel = p.info.protectionLevel; 7464 } 7465 } 7466 7467 if (r != null) { 7468 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7469 } 7470 7471 N = pkg.instrumentation.size(); 7472 r = null; 7473 for (i=0; i<N; i++) { 7474 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7475 a.info.packageName = pkg.applicationInfo.packageName; 7476 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7477 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7478 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7479 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7480 a.info.dataDir = pkg.applicationInfo.dataDir; 7481 7482 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7483 // need other information about the application, like the ABI and what not ? 7484 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7485 mInstrumentation.put(a.getComponentName(), a); 7486 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7487 if (r == null) { 7488 r = new StringBuilder(256); 7489 } else { 7490 r.append(' '); 7491 } 7492 r.append(a.info.name); 7493 } 7494 } 7495 if (r != null) { 7496 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7497 } 7498 7499 if (pkg.protectedBroadcasts != null) { 7500 N = pkg.protectedBroadcasts.size(); 7501 for (i=0; i<N; i++) { 7502 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7503 } 7504 } 7505 7506 pkgSetting.setTimeStamp(scanFileTime); 7507 7508 // Create idmap files for pairs of (packages, overlay packages). 7509 // Note: "android", ie framework-res.apk, is handled by native layers. 7510 if (pkg.mOverlayTarget != null) { 7511 // This is an overlay package. 7512 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7513 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7514 mOverlays.put(pkg.mOverlayTarget, 7515 new ArrayMap<String, PackageParser.Package>()); 7516 } 7517 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7518 map.put(pkg.packageName, pkg); 7519 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7520 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7521 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7522 "scanPackageLI failed to createIdmap"); 7523 } 7524 } 7525 } else if (mOverlays.containsKey(pkg.packageName) && 7526 !pkg.packageName.equals("android")) { 7527 // This is a regular package, with one or more known overlay packages. 7528 createIdmapsForPackageLI(pkg); 7529 } 7530 } 7531 7532 return pkg; 7533 } 7534 7535 /** 7536 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7537 * is derived purely on the basis of the contents of {@code scanFile} and 7538 * {@code cpuAbiOverride}. 7539 * 7540 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7541 */ 7542 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7543 String cpuAbiOverride, boolean extractLibs) 7544 throws PackageManagerException { 7545 // TODO: We can probably be smarter about this stuff. For installed apps, 7546 // we can calculate this information at install time once and for all. For 7547 // system apps, we can probably assume that this information doesn't change 7548 // after the first boot scan. As things stand, we do lots of unnecessary work. 7549 7550 // Give ourselves some initial paths; we'll come back for another 7551 // pass once we've determined ABI below. 7552 setNativeLibraryPaths(pkg); 7553 7554 // We would never need to extract libs for forward-locked and external packages, 7555 // since the container service will do it for us. We shouldn't attempt to 7556 // extract libs from system app when it was not updated. 7557 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7558 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7559 extractLibs = false; 7560 } 7561 7562 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7563 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7564 7565 NativeLibraryHelper.Handle handle = null; 7566 try { 7567 handle = NativeLibraryHelper.Handle.create(scanFile); 7568 // TODO(multiArch): This can be null for apps that didn't go through the 7569 // usual installation process. We can calculate it again, like we 7570 // do during install time. 7571 // 7572 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7573 // unnecessary. 7574 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7575 7576 // Null out the abis so that they can be recalculated. 7577 pkg.applicationInfo.primaryCpuAbi = null; 7578 pkg.applicationInfo.secondaryCpuAbi = null; 7579 if (isMultiArch(pkg.applicationInfo)) { 7580 // Warn if we've set an abiOverride for multi-lib packages.. 7581 // By definition, we need to copy both 32 and 64 bit libraries for 7582 // such packages. 7583 if (pkg.cpuAbiOverride != null 7584 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7585 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7586 } 7587 7588 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7589 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7590 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7591 if (extractLibs) { 7592 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7593 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7594 useIsaSpecificSubdirs); 7595 } else { 7596 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7597 } 7598 } 7599 7600 maybeThrowExceptionForMultiArchCopy( 7601 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7602 7603 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7604 if (extractLibs) { 7605 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7606 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7607 useIsaSpecificSubdirs); 7608 } else { 7609 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7610 } 7611 } 7612 7613 maybeThrowExceptionForMultiArchCopy( 7614 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7615 7616 if (abi64 >= 0) { 7617 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7618 } 7619 7620 if (abi32 >= 0) { 7621 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7622 if (abi64 >= 0) { 7623 pkg.applicationInfo.secondaryCpuAbi = abi; 7624 } else { 7625 pkg.applicationInfo.primaryCpuAbi = abi; 7626 } 7627 } 7628 } else { 7629 String[] abiList = (cpuAbiOverride != null) ? 7630 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7631 7632 // Enable gross and lame hacks for apps that are built with old 7633 // SDK tools. We must scan their APKs for renderscript bitcode and 7634 // not launch them if it's present. Don't bother checking on devices 7635 // that don't have 64 bit support. 7636 boolean needsRenderScriptOverride = false; 7637 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7638 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7639 abiList = Build.SUPPORTED_32_BIT_ABIS; 7640 needsRenderScriptOverride = true; 7641 } 7642 7643 final int copyRet; 7644 if (extractLibs) { 7645 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7646 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7647 } else { 7648 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7649 } 7650 7651 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7652 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7653 "Error unpackaging native libs for app, errorCode=" + copyRet); 7654 } 7655 7656 if (copyRet >= 0) { 7657 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7658 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7659 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7660 } else if (needsRenderScriptOverride) { 7661 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7662 } 7663 } 7664 } catch (IOException ioe) { 7665 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7666 } finally { 7667 IoUtils.closeQuietly(handle); 7668 } 7669 7670 // Now that we've calculated the ABIs and determined if it's an internal app, 7671 // we will go ahead and populate the nativeLibraryPath. 7672 setNativeLibraryPaths(pkg); 7673 } 7674 7675 /** 7676 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7677 * i.e, so that all packages can be run inside a single process if required. 7678 * 7679 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7680 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7681 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7682 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7683 * updating a package that belongs to a shared user. 7684 * 7685 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7686 * adds unnecessary complexity. 7687 */ 7688 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7689 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt, 7690 boolean bootComplete) { 7691 String requiredInstructionSet = null; 7692 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7693 requiredInstructionSet = VMRuntime.getInstructionSet( 7694 scannedPackage.applicationInfo.primaryCpuAbi); 7695 } 7696 7697 PackageSetting requirer = null; 7698 for (PackageSetting ps : packagesForUser) { 7699 // If packagesForUser contains scannedPackage, we skip it. This will happen 7700 // when scannedPackage is an update of an existing package. Without this check, 7701 // we will never be able to change the ABI of any package belonging to a shared 7702 // user, even if it's compatible with other packages. 7703 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7704 if (ps.primaryCpuAbiString == null) { 7705 continue; 7706 } 7707 7708 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7709 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7710 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7711 // this but there's not much we can do. 7712 String errorMessage = "Instruction set mismatch, " 7713 + ((requirer == null) ? "[caller]" : requirer) 7714 + " requires " + requiredInstructionSet + " whereas " + ps 7715 + " requires " + instructionSet; 7716 Slog.w(TAG, errorMessage); 7717 } 7718 7719 if (requiredInstructionSet == null) { 7720 requiredInstructionSet = instructionSet; 7721 requirer = ps; 7722 } 7723 } 7724 } 7725 7726 if (requiredInstructionSet != null) { 7727 String adjustedAbi; 7728 if (requirer != null) { 7729 // requirer != null implies that either scannedPackage was null or that scannedPackage 7730 // did not require an ABI, in which case we have to adjust scannedPackage to match 7731 // the ABI of the set (which is the same as requirer's ABI) 7732 adjustedAbi = requirer.primaryCpuAbiString; 7733 if (scannedPackage != null) { 7734 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7735 } 7736 } else { 7737 // requirer == null implies that we're updating all ABIs in the set to 7738 // match scannedPackage. 7739 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7740 } 7741 7742 for (PackageSetting ps : packagesForUser) { 7743 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7744 if (ps.primaryCpuAbiString != null) { 7745 continue; 7746 } 7747 7748 ps.primaryCpuAbiString = adjustedAbi; 7749 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7750 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7751 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7752 7753 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7754 null /* instruction sets */, forceDexOpt, deferDexOpt, true, 7755 bootComplete, false /*useJit*/); 7756 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7757 ps.primaryCpuAbiString = null; 7758 ps.pkg.applicationInfo.primaryCpuAbi = null; 7759 return; 7760 } else { 7761 mInstaller.rmdex(ps.codePathString, 7762 getDexCodeInstructionSet(getPreferredInstructionSet())); 7763 } 7764 } 7765 } 7766 } 7767 } 7768 } 7769 7770 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7771 synchronized (mPackages) { 7772 mResolverReplaced = true; 7773 // Set up information for custom user intent resolution activity. 7774 mResolveActivity.applicationInfo = pkg.applicationInfo; 7775 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7776 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7777 mResolveActivity.processName = pkg.applicationInfo.packageName; 7778 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7779 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7780 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7781 mResolveActivity.theme = 0; 7782 mResolveActivity.exported = true; 7783 mResolveActivity.enabled = true; 7784 mResolveInfo.activityInfo = mResolveActivity; 7785 mResolveInfo.priority = 0; 7786 mResolveInfo.preferredOrder = 0; 7787 mResolveInfo.match = 0; 7788 mResolveComponentName = mCustomResolverComponentName; 7789 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7790 mResolveComponentName); 7791 } 7792 } 7793 7794 private static String calculateBundledApkRoot(final String codePathString) { 7795 final File codePath = new File(codePathString); 7796 final File codeRoot; 7797 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7798 codeRoot = Environment.getRootDirectory(); 7799 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7800 codeRoot = Environment.getOemDirectory(); 7801 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7802 codeRoot = Environment.getVendorDirectory(); 7803 } else { 7804 // Unrecognized code path; take its top real segment as the apk root: 7805 // e.g. /something/app/blah.apk => /something 7806 try { 7807 File f = codePath.getCanonicalFile(); 7808 File parent = f.getParentFile(); // non-null because codePath is a file 7809 File tmp; 7810 while ((tmp = parent.getParentFile()) != null) { 7811 f = parent; 7812 parent = tmp; 7813 } 7814 codeRoot = f; 7815 Slog.w(TAG, "Unrecognized code path " 7816 + codePath + " - using " + codeRoot); 7817 } catch (IOException e) { 7818 // Can't canonicalize the code path -- shenanigans? 7819 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7820 return Environment.getRootDirectory().getPath(); 7821 } 7822 } 7823 return codeRoot.getPath(); 7824 } 7825 7826 /** 7827 * Derive and set the location of native libraries for the given package, 7828 * which varies depending on where and how the package was installed. 7829 */ 7830 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7831 final ApplicationInfo info = pkg.applicationInfo; 7832 final String codePath = pkg.codePath; 7833 final File codeFile = new File(codePath); 7834 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7835 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 7836 7837 info.nativeLibraryRootDir = null; 7838 info.nativeLibraryRootRequiresIsa = false; 7839 info.nativeLibraryDir = null; 7840 info.secondaryNativeLibraryDir = null; 7841 7842 if (isApkFile(codeFile)) { 7843 // Monolithic install 7844 if (bundledApp) { 7845 // If "/system/lib64/apkname" exists, assume that is the per-package 7846 // native library directory to use; otherwise use "/system/lib/apkname". 7847 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7848 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7849 getPrimaryInstructionSet(info)); 7850 7851 // This is a bundled system app so choose the path based on the ABI. 7852 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7853 // is just the default path. 7854 final String apkName = deriveCodePathName(codePath); 7855 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7856 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7857 apkName).getAbsolutePath(); 7858 7859 if (info.secondaryCpuAbi != null) { 7860 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7861 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7862 secondaryLibDir, apkName).getAbsolutePath(); 7863 } 7864 } else if (asecApp) { 7865 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7866 .getAbsolutePath(); 7867 } else { 7868 final String apkName = deriveCodePathName(codePath); 7869 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7870 .getAbsolutePath(); 7871 } 7872 7873 info.nativeLibraryRootRequiresIsa = false; 7874 info.nativeLibraryDir = info.nativeLibraryRootDir; 7875 } else { 7876 // Cluster install 7877 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7878 info.nativeLibraryRootRequiresIsa = true; 7879 7880 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7881 getPrimaryInstructionSet(info)).getAbsolutePath(); 7882 7883 if (info.secondaryCpuAbi != null) { 7884 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7885 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7886 } 7887 } 7888 } 7889 7890 /** 7891 * Calculate the abis and roots for a bundled app. These can uniquely 7892 * be determined from the contents of the system partition, i.e whether 7893 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7894 * of this information, and instead assume that the system was built 7895 * sensibly. 7896 */ 7897 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7898 PackageSetting pkgSetting) { 7899 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7900 7901 // If "/system/lib64/apkname" exists, assume that is the per-package 7902 // native library directory to use; otherwise use "/system/lib/apkname". 7903 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7904 setBundledAppAbi(pkg, apkRoot, apkName); 7905 // pkgSetting might be null during rescan following uninstall of updates 7906 // to a bundled app, so accommodate that possibility. The settings in 7907 // that case will be established later from the parsed package. 7908 // 7909 // If the settings aren't null, sync them up with what we've just derived. 7910 // note that apkRoot isn't stored in the package settings. 7911 if (pkgSetting != null) { 7912 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7913 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7914 } 7915 } 7916 7917 /** 7918 * Deduces the ABI of a bundled app and sets the relevant fields on the 7919 * parsed pkg object. 7920 * 7921 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7922 * under which system libraries are installed. 7923 * @param apkName the name of the installed package. 7924 */ 7925 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7926 final File codeFile = new File(pkg.codePath); 7927 7928 final boolean has64BitLibs; 7929 final boolean has32BitLibs; 7930 if (isApkFile(codeFile)) { 7931 // Monolithic install 7932 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7933 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7934 } else { 7935 // Cluster install 7936 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7937 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7938 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7939 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7940 has64BitLibs = (new File(rootDir, isa)).exists(); 7941 } else { 7942 has64BitLibs = false; 7943 } 7944 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7945 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7946 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7947 has32BitLibs = (new File(rootDir, isa)).exists(); 7948 } else { 7949 has32BitLibs = false; 7950 } 7951 } 7952 7953 if (has64BitLibs && !has32BitLibs) { 7954 // The package has 64 bit libs, but not 32 bit libs. Its primary 7955 // ABI should be 64 bit. We can safely assume here that the bundled 7956 // native libraries correspond to the most preferred ABI in the list. 7957 7958 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7959 pkg.applicationInfo.secondaryCpuAbi = null; 7960 } else if (has32BitLibs && !has64BitLibs) { 7961 // The package has 32 bit libs but not 64 bit libs. Its primary 7962 // ABI should be 32 bit. 7963 7964 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7965 pkg.applicationInfo.secondaryCpuAbi = null; 7966 } else if (has32BitLibs && has64BitLibs) { 7967 // The application has both 64 and 32 bit bundled libraries. We check 7968 // here that the app declares multiArch support, and warn if it doesn't. 7969 // 7970 // We will be lenient here and record both ABIs. The primary will be the 7971 // ABI that's higher on the list, i.e, a device that's configured to prefer 7972 // 64 bit apps will see a 64 bit primary ABI, 7973 7974 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7975 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7976 } 7977 7978 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7979 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7980 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7981 } else { 7982 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7983 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7984 } 7985 } else { 7986 pkg.applicationInfo.primaryCpuAbi = null; 7987 pkg.applicationInfo.secondaryCpuAbi = null; 7988 } 7989 } 7990 7991 private void killApplication(String pkgName, int appId, String reason) { 7992 // Request the ActivityManager to kill the process(only for existing packages) 7993 // so that we do not end up in a confused state while the user is still using the older 7994 // version of the application while the new one gets installed. 7995 IActivityManager am = ActivityManagerNative.getDefault(); 7996 if (am != null) { 7997 try { 7998 am.killApplicationWithAppId(pkgName, appId, reason); 7999 } catch (RemoteException e) { 8000 } 8001 } 8002 } 8003 8004 void removePackageLI(PackageSetting ps, boolean chatty) { 8005 if (DEBUG_INSTALL) { 8006 if (chatty) 8007 Log.d(TAG, "Removing package " + ps.name); 8008 } 8009 8010 // writer 8011 synchronized (mPackages) { 8012 mPackages.remove(ps.name); 8013 final PackageParser.Package pkg = ps.pkg; 8014 if (pkg != null) { 8015 cleanPackageDataStructuresLILPw(pkg, chatty); 8016 } 8017 } 8018 } 8019 8020 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8021 if (DEBUG_INSTALL) { 8022 if (chatty) 8023 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8024 } 8025 8026 // writer 8027 synchronized (mPackages) { 8028 mPackages.remove(pkg.applicationInfo.packageName); 8029 cleanPackageDataStructuresLILPw(pkg, chatty); 8030 } 8031 } 8032 8033 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8034 int N = pkg.providers.size(); 8035 StringBuilder r = null; 8036 int i; 8037 for (i=0; i<N; i++) { 8038 PackageParser.Provider p = pkg.providers.get(i); 8039 mProviders.removeProvider(p); 8040 if (p.info.authority == null) { 8041 8042 /* There was another ContentProvider with this authority when 8043 * this app was installed so this authority is null, 8044 * Ignore it as we don't have to unregister the provider. 8045 */ 8046 continue; 8047 } 8048 String names[] = p.info.authority.split(";"); 8049 for (int j = 0; j < names.length; j++) { 8050 if (mProvidersByAuthority.get(names[j]) == p) { 8051 mProvidersByAuthority.remove(names[j]); 8052 if (DEBUG_REMOVE) { 8053 if (chatty) 8054 Log.d(TAG, "Unregistered content provider: " + names[j] 8055 + ", className = " + p.info.name + ", isSyncable = " 8056 + p.info.isSyncable); 8057 } 8058 } 8059 } 8060 if (DEBUG_REMOVE && chatty) { 8061 if (r == null) { 8062 r = new StringBuilder(256); 8063 } else { 8064 r.append(' '); 8065 } 8066 r.append(p.info.name); 8067 } 8068 } 8069 if (r != null) { 8070 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8071 } 8072 8073 N = pkg.services.size(); 8074 r = null; 8075 for (i=0; i<N; i++) { 8076 PackageParser.Service s = pkg.services.get(i); 8077 mServices.removeService(s); 8078 if (chatty) { 8079 if (r == null) { 8080 r = new StringBuilder(256); 8081 } else { 8082 r.append(' '); 8083 } 8084 r.append(s.info.name); 8085 } 8086 } 8087 if (r != null) { 8088 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8089 } 8090 8091 N = pkg.receivers.size(); 8092 r = null; 8093 for (i=0; i<N; i++) { 8094 PackageParser.Activity a = pkg.receivers.get(i); 8095 mReceivers.removeActivity(a, "receiver"); 8096 if (DEBUG_REMOVE && chatty) { 8097 if (r == null) { 8098 r = new StringBuilder(256); 8099 } else { 8100 r.append(' '); 8101 } 8102 r.append(a.info.name); 8103 } 8104 } 8105 if (r != null) { 8106 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8107 } 8108 8109 N = pkg.activities.size(); 8110 r = null; 8111 for (i=0; i<N; i++) { 8112 PackageParser.Activity a = pkg.activities.get(i); 8113 mActivities.removeActivity(a, "activity"); 8114 if (DEBUG_REMOVE && chatty) { 8115 if (r == null) { 8116 r = new StringBuilder(256); 8117 } else { 8118 r.append(' '); 8119 } 8120 r.append(a.info.name); 8121 } 8122 } 8123 if (r != null) { 8124 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8125 } 8126 8127 N = pkg.permissions.size(); 8128 r = null; 8129 for (i=0; i<N; i++) { 8130 PackageParser.Permission p = pkg.permissions.get(i); 8131 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8132 if (bp == null) { 8133 bp = mSettings.mPermissionTrees.get(p.info.name); 8134 } 8135 if (bp != null && bp.perm == p) { 8136 bp.perm = null; 8137 if (DEBUG_REMOVE && chatty) { 8138 if (r == null) { 8139 r = new StringBuilder(256); 8140 } else { 8141 r.append(' '); 8142 } 8143 r.append(p.info.name); 8144 } 8145 } 8146 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8147 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8148 if (appOpPerms != null) { 8149 appOpPerms.remove(pkg.packageName); 8150 } 8151 } 8152 } 8153 if (r != null) { 8154 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8155 } 8156 8157 N = pkg.requestedPermissions.size(); 8158 r = null; 8159 for (i=0; i<N; i++) { 8160 String perm = pkg.requestedPermissions.get(i); 8161 BasePermission bp = mSettings.mPermissions.get(perm); 8162 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8163 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8164 if (appOpPerms != null) { 8165 appOpPerms.remove(pkg.packageName); 8166 if (appOpPerms.isEmpty()) { 8167 mAppOpPermissionPackages.remove(perm); 8168 } 8169 } 8170 } 8171 } 8172 if (r != null) { 8173 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8174 } 8175 8176 N = pkg.instrumentation.size(); 8177 r = null; 8178 for (i=0; i<N; i++) { 8179 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8180 mInstrumentation.remove(a.getComponentName()); 8181 if (DEBUG_REMOVE && chatty) { 8182 if (r == null) { 8183 r = new StringBuilder(256); 8184 } else { 8185 r.append(' '); 8186 } 8187 r.append(a.info.name); 8188 } 8189 } 8190 if (r != null) { 8191 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8192 } 8193 8194 r = null; 8195 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8196 // Only system apps can hold shared libraries. 8197 if (pkg.libraryNames != null) { 8198 for (i=0; i<pkg.libraryNames.size(); i++) { 8199 String name = pkg.libraryNames.get(i); 8200 SharedLibraryEntry cur = mSharedLibraries.get(name); 8201 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8202 mSharedLibraries.remove(name); 8203 if (DEBUG_REMOVE && chatty) { 8204 if (r == null) { 8205 r = new StringBuilder(256); 8206 } else { 8207 r.append(' '); 8208 } 8209 r.append(name); 8210 } 8211 } 8212 } 8213 } 8214 } 8215 if (r != null) { 8216 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8217 } 8218 } 8219 8220 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8221 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8222 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8223 return true; 8224 } 8225 } 8226 return false; 8227 } 8228 8229 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8230 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8231 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8232 8233 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8234 int flags) { 8235 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8236 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8237 } 8238 8239 private void updatePermissionsLPw(String changingPkg, 8240 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8241 // Make sure there are no dangling permission trees. 8242 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8243 while (it.hasNext()) { 8244 final BasePermission bp = it.next(); 8245 if (bp.packageSetting == null) { 8246 // We may not yet have parsed the package, so just see if 8247 // we still know about its settings. 8248 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8249 } 8250 if (bp.packageSetting == null) { 8251 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8252 + " from package " + bp.sourcePackage); 8253 it.remove(); 8254 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8255 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8256 Slog.i(TAG, "Removing old permission tree: " + bp.name 8257 + " from package " + bp.sourcePackage); 8258 flags |= UPDATE_PERMISSIONS_ALL; 8259 it.remove(); 8260 } 8261 } 8262 } 8263 8264 // Make sure all dynamic permissions have been assigned to a package, 8265 // and make sure there are no dangling permissions. 8266 it = mSettings.mPermissions.values().iterator(); 8267 while (it.hasNext()) { 8268 final BasePermission bp = it.next(); 8269 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8270 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8271 + bp.name + " pkg=" + bp.sourcePackage 8272 + " info=" + bp.pendingInfo); 8273 if (bp.packageSetting == null && bp.pendingInfo != null) { 8274 final BasePermission tree = findPermissionTreeLP(bp.name); 8275 if (tree != null && tree.perm != null) { 8276 bp.packageSetting = tree.packageSetting; 8277 bp.perm = new PackageParser.Permission(tree.perm.owner, 8278 new PermissionInfo(bp.pendingInfo)); 8279 bp.perm.info.packageName = tree.perm.info.packageName; 8280 bp.perm.info.name = bp.name; 8281 bp.uid = tree.uid; 8282 } 8283 } 8284 } 8285 if (bp.packageSetting == null) { 8286 // We may not yet have parsed the package, so just see if 8287 // we still know about its settings. 8288 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8289 } 8290 if (bp.packageSetting == null) { 8291 Slog.w(TAG, "Removing dangling permission: " + bp.name 8292 + " from package " + bp.sourcePackage); 8293 it.remove(); 8294 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8295 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8296 Slog.i(TAG, "Removing old permission: " + bp.name 8297 + " from package " + bp.sourcePackage); 8298 flags |= UPDATE_PERMISSIONS_ALL; 8299 it.remove(); 8300 } 8301 } 8302 } 8303 8304 // Now update the permissions for all packages, in particular 8305 // replace the granted permissions of the system packages. 8306 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8307 for (PackageParser.Package pkg : mPackages.values()) { 8308 if (pkg != pkgInfo) { 8309 // Only replace for packages on requested volume 8310 final String volumeUuid = getVolumeUuidForPackage(pkg); 8311 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8312 && Objects.equals(replaceVolumeUuid, volumeUuid); 8313 grantPermissionsLPw(pkg, replace, changingPkg); 8314 } 8315 } 8316 } 8317 8318 if (pkgInfo != null) { 8319 // Only replace for packages on requested volume 8320 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8321 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8322 && Objects.equals(replaceVolumeUuid, volumeUuid); 8323 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8324 } 8325 } 8326 8327 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8328 String packageOfInterest) { 8329 // IMPORTANT: There are two types of permissions: install and runtime. 8330 // Install time permissions are granted when the app is installed to 8331 // all device users and users added in the future. Runtime permissions 8332 // are granted at runtime explicitly to specific users. Normal and signature 8333 // protected permissions are install time permissions. Dangerous permissions 8334 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8335 // otherwise they are runtime permissions. This function does not manage 8336 // runtime permissions except for the case an app targeting Lollipop MR1 8337 // being upgraded to target a newer SDK, in which case dangerous permissions 8338 // are transformed from install time to runtime ones. 8339 8340 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8341 if (ps == null) { 8342 return; 8343 } 8344 8345 PermissionsState permissionsState = ps.getPermissionsState(); 8346 PermissionsState origPermissions = permissionsState; 8347 8348 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8349 8350 boolean runtimePermissionsRevoked = false; 8351 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8352 8353 boolean changedInstallPermission = false; 8354 8355 if (replace) { 8356 ps.installPermissionsFixed = false; 8357 if (!ps.isSharedUser()) { 8358 origPermissions = new PermissionsState(permissionsState); 8359 permissionsState.reset(); 8360 } else { 8361 // We need to know only about runtime permission changes since the 8362 // calling code always writes the install permissions state but 8363 // the runtime ones are written only if changed. The only cases of 8364 // changed runtime permissions here are promotion of an install to 8365 // runtime and revocation of a runtime from a shared user. 8366 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8367 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8368 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8369 runtimePermissionsRevoked = true; 8370 } 8371 } 8372 } 8373 8374 permissionsState.setGlobalGids(mGlobalGids); 8375 8376 final int N = pkg.requestedPermissions.size(); 8377 for (int i=0; i<N; i++) { 8378 final String name = pkg.requestedPermissions.get(i); 8379 final BasePermission bp = mSettings.mPermissions.get(name); 8380 8381 if (DEBUG_INSTALL) { 8382 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8383 } 8384 8385 if (bp == null || bp.packageSetting == null) { 8386 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8387 Slog.w(TAG, "Unknown permission " + name 8388 + " in package " + pkg.packageName); 8389 } 8390 continue; 8391 } 8392 8393 final String perm = bp.name; 8394 boolean allowedSig = false; 8395 int grant = GRANT_DENIED; 8396 8397 // Keep track of app op permissions. 8398 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8399 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8400 if (pkgs == null) { 8401 pkgs = new ArraySet<>(); 8402 mAppOpPermissionPackages.put(bp.name, pkgs); 8403 } 8404 pkgs.add(pkg.packageName); 8405 } 8406 8407 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8408 switch (level) { 8409 case PermissionInfo.PROTECTION_NORMAL: { 8410 // For all apps normal permissions are install time ones. 8411 grant = GRANT_INSTALL; 8412 } break; 8413 8414 case PermissionInfo.PROTECTION_DANGEROUS: { 8415 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8416 // For legacy apps dangerous permissions are install time ones. 8417 grant = GRANT_INSTALL_LEGACY; 8418 } else if (origPermissions.hasInstallPermission(bp.name)) { 8419 // For legacy apps that became modern, install becomes runtime. 8420 grant = GRANT_UPGRADE; 8421 } else if (mPromoteSystemApps 8422 && isSystemApp(ps) 8423 && mExistingSystemPackages.contains(ps.name)) { 8424 // For legacy system apps, install becomes runtime. 8425 // We cannot check hasInstallPermission() for system apps since those 8426 // permissions were granted implicitly and not persisted pre-M. 8427 grant = GRANT_UPGRADE; 8428 } else { 8429 // For modern apps keep runtime permissions unchanged. 8430 grant = GRANT_RUNTIME; 8431 } 8432 } break; 8433 8434 case PermissionInfo.PROTECTION_SIGNATURE: { 8435 // For all apps signature permissions are install time ones. 8436 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8437 if (allowedSig) { 8438 grant = GRANT_INSTALL; 8439 } 8440 } break; 8441 } 8442 8443 if (DEBUG_INSTALL) { 8444 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8445 } 8446 8447 if (grant != GRANT_DENIED) { 8448 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8449 // If this is an existing, non-system package, then 8450 // we can't add any new permissions to it. 8451 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8452 // Except... if this is a permission that was added 8453 // to the platform (note: need to only do this when 8454 // updating the platform). 8455 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8456 grant = GRANT_DENIED; 8457 } 8458 } 8459 } 8460 8461 switch (grant) { 8462 case GRANT_INSTALL: { 8463 // Revoke this as runtime permission to handle the case of 8464 // a runtime permission being downgraded to an install one. 8465 for (int userId : UserManagerService.getInstance().getUserIds()) { 8466 if (origPermissions.getRuntimePermissionState( 8467 bp.name, userId) != null) { 8468 // Revoke the runtime permission and clear the flags. 8469 origPermissions.revokeRuntimePermission(bp, userId); 8470 origPermissions.updatePermissionFlags(bp, userId, 8471 PackageManager.MASK_PERMISSION_FLAGS, 0); 8472 // If we revoked a permission permission, we have to write. 8473 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8474 changedRuntimePermissionUserIds, userId); 8475 } 8476 } 8477 // Grant an install permission. 8478 if (permissionsState.grantInstallPermission(bp) != 8479 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8480 changedInstallPermission = true; 8481 } 8482 } break; 8483 8484 case GRANT_INSTALL_LEGACY: { 8485 // Grant an install permission. 8486 if (permissionsState.grantInstallPermission(bp) != 8487 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8488 changedInstallPermission = true; 8489 } 8490 } break; 8491 8492 case GRANT_RUNTIME: { 8493 // Grant previously granted runtime permissions. 8494 for (int userId : UserManagerService.getInstance().getUserIds()) { 8495 PermissionState permissionState = origPermissions 8496 .getRuntimePermissionState(bp.name, userId); 8497 final int flags = permissionState != null 8498 ? permissionState.getFlags() : 0; 8499 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8500 if (permissionsState.grantRuntimePermission(bp, userId) == 8501 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8502 // If we cannot put the permission as it was, we have to write. 8503 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8504 changedRuntimePermissionUserIds, userId); 8505 } 8506 } 8507 // Propagate the permission flags. 8508 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8509 } 8510 } break; 8511 8512 case GRANT_UPGRADE: { 8513 // Grant runtime permissions for a previously held install permission. 8514 PermissionState permissionState = origPermissions 8515 .getInstallPermissionState(bp.name); 8516 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8517 8518 if (origPermissions.revokeInstallPermission(bp) 8519 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8520 // We will be transferring the permission flags, so clear them. 8521 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8522 PackageManager.MASK_PERMISSION_FLAGS, 0); 8523 changedInstallPermission = true; 8524 } 8525 8526 // If the permission is not to be promoted to runtime we ignore it and 8527 // also its other flags as they are not applicable to install permissions. 8528 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8529 for (int userId : currentUserIds) { 8530 if (permissionsState.grantRuntimePermission(bp, userId) != 8531 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8532 // Transfer the permission flags. 8533 permissionsState.updatePermissionFlags(bp, userId, 8534 flags, flags); 8535 // If we granted the permission, we have to write. 8536 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8537 changedRuntimePermissionUserIds, userId); 8538 } 8539 } 8540 } 8541 } break; 8542 8543 default: { 8544 if (packageOfInterest == null 8545 || packageOfInterest.equals(pkg.packageName)) { 8546 Slog.w(TAG, "Not granting permission " + perm 8547 + " to package " + pkg.packageName 8548 + " because it was previously installed without"); 8549 } 8550 } break; 8551 } 8552 } else { 8553 if (permissionsState.revokeInstallPermission(bp) != 8554 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8555 // Also drop the permission flags. 8556 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8557 PackageManager.MASK_PERMISSION_FLAGS, 0); 8558 changedInstallPermission = true; 8559 Slog.i(TAG, "Un-granting permission " + perm 8560 + " from package " + pkg.packageName 8561 + " (protectionLevel=" + bp.protectionLevel 8562 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8563 + ")"); 8564 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8565 // Don't print warning for app op permissions, since it is fine for them 8566 // not to be granted, there is a UI for the user to decide. 8567 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8568 Slog.w(TAG, "Not granting permission " + perm 8569 + " to package " + pkg.packageName 8570 + " (protectionLevel=" + bp.protectionLevel 8571 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8572 + ")"); 8573 } 8574 } 8575 } 8576 } 8577 8578 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8579 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8580 // This is the first that we have heard about this package, so the 8581 // permissions we have now selected are fixed until explicitly 8582 // changed. 8583 ps.installPermissionsFixed = true; 8584 } 8585 8586 // Persist the runtime permissions state for users with changes. If permissions 8587 // were revoked because no app in the shared user declares them we have to 8588 // write synchronously to avoid losing runtime permissions state. 8589 for (int userId : changedRuntimePermissionUserIds) { 8590 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8591 } 8592 } 8593 8594 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8595 boolean allowed = false; 8596 final int NP = PackageParser.NEW_PERMISSIONS.length; 8597 for (int ip=0; ip<NP; ip++) { 8598 final PackageParser.NewPermissionInfo npi 8599 = PackageParser.NEW_PERMISSIONS[ip]; 8600 if (npi.name.equals(perm) 8601 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8602 allowed = true; 8603 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8604 + pkg.packageName); 8605 break; 8606 } 8607 } 8608 return allowed; 8609 } 8610 8611 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8612 BasePermission bp, PermissionsState origPermissions) { 8613 boolean allowed; 8614 allowed = (compareSignatures( 8615 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8616 == PackageManager.SIGNATURE_MATCH) 8617 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8618 == PackageManager.SIGNATURE_MATCH); 8619 if (!allowed && (bp.protectionLevel 8620 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8621 if (isSystemApp(pkg)) { 8622 // For updated system applications, a system permission 8623 // is granted only if it had been defined by the original application. 8624 if (pkg.isUpdatedSystemApp()) { 8625 final PackageSetting sysPs = mSettings 8626 .getDisabledSystemPkgLPr(pkg.packageName); 8627 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8628 // If the original was granted this permission, we take 8629 // that grant decision as read and propagate it to the 8630 // update. 8631 if (sysPs.isPrivileged()) { 8632 allowed = true; 8633 } 8634 } else { 8635 // The system apk may have been updated with an older 8636 // version of the one on the data partition, but which 8637 // granted a new system permission that it didn't have 8638 // before. In this case we do want to allow the app to 8639 // now get the new permission if the ancestral apk is 8640 // privileged to get it. 8641 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8642 for (int j=0; 8643 j<sysPs.pkg.requestedPermissions.size(); j++) { 8644 if (perm.equals( 8645 sysPs.pkg.requestedPermissions.get(j))) { 8646 allowed = true; 8647 break; 8648 } 8649 } 8650 } 8651 } 8652 } else { 8653 allowed = isPrivilegedApp(pkg); 8654 } 8655 } 8656 } 8657 if (!allowed) { 8658 if (!allowed && (bp.protectionLevel 8659 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8660 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8661 // If this was a previously normal/dangerous permission that got moved 8662 // to a system permission as part of the runtime permission redesign, then 8663 // we still want to blindly grant it to old apps. 8664 allowed = true; 8665 } 8666 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8667 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8668 // If this permission is to be granted to the system installer and 8669 // this app is an installer, then it gets the permission. 8670 allowed = true; 8671 } 8672 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8673 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8674 // If this permission is to be granted to the system verifier and 8675 // this app is a verifier, then it gets the permission. 8676 allowed = true; 8677 } 8678 if (!allowed && (bp.protectionLevel 8679 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8680 && isSystemApp(pkg)) { 8681 // Any pre-installed system app is allowed to get this permission. 8682 allowed = true; 8683 } 8684 if (!allowed && (bp.protectionLevel 8685 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8686 // For development permissions, a development permission 8687 // is granted only if it was already granted. 8688 allowed = origPermissions.hasInstallPermission(perm); 8689 } 8690 } 8691 return allowed; 8692 } 8693 8694 final class ActivityIntentResolver 8695 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8696 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8697 boolean defaultOnly, int userId) { 8698 if (!sUserManager.exists(userId)) return null; 8699 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8700 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8701 } 8702 8703 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8704 int userId) { 8705 if (!sUserManager.exists(userId)) return null; 8706 mFlags = flags; 8707 return super.queryIntent(intent, resolvedType, 8708 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8709 } 8710 8711 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8712 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8713 if (!sUserManager.exists(userId)) return null; 8714 if (packageActivities == null) { 8715 return null; 8716 } 8717 mFlags = flags; 8718 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8719 final int N = packageActivities.size(); 8720 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8721 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8722 8723 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8724 for (int i = 0; i < N; ++i) { 8725 intentFilters = packageActivities.get(i).intents; 8726 if (intentFilters != null && intentFilters.size() > 0) { 8727 PackageParser.ActivityIntentInfo[] array = 8728 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8729 intentFilters.toArray(array); 8730 listCut.add(array); 8731 } 8732 } 8733 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8734 } 8735 8736 public final void addActivity(PackageParser.Activity a, String type) { 8737 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8738 mActivities.put(a.getComponentName(), a); 8739 if (DEBUG_SHOW_INFO) 8740 Log.v( 8741 TAG, " " + type + " " + 8742 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8743 if (DEBUG_SHOW_INFO) 8744 Log.v(TAG, " Class=" + a.info.name); 8745 final int NI = a.intents.size(); 8746 for (int j=0; j<NI; j++) { 8747 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8748 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8749 intent.setPriority(0); 8750 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8751 + a.className + " with priority > 0, forcing to 0"); 8752 } 8753 if (DEBUG_SHOW_INFO) { 8754 Log.v(TAG, " IntentFilter:"); 8755 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8756 } 8757 if (!intent.debugCheck()) { 8758 Log.w(TAG, "==> For Activity " + a.info.name); 8759 } 8760 addFilter(intent); 8761 } 8762 } 8763 8764 public final void removeActivity(PackageParser.Activity a, String type) { 8765 mActivities.remove(a.getComponentName()); 8766 if (DEBUG_SHOW_INFO) { 8767 Log.v(TAG, " " + type + " " 8768 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8769 : a.info.name) + ":"); 8770 Log.v(TAG, " Class=" + a.info.name); 8771 } 8772 final int NI = a.intents.size(); 8773 for (int j=0; j<NI; j++) { 8774 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8775 if (DEBUG_SHOW_INFO) { 8776 Log.v(TAG, " IntentFilter:"); 8777 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8778 } 8779 removeFilter(intent); 8780 } 8781 } 8782 8783 @Override 8784 protected boolean allowFilterResult( 8785 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8786 ActivityInfo filterAi = filter.activity.info; 8787 for (int i=dest.size()-1; i>=0; i--) { 8788 ActivityInfo destAi = dest.get(i).activityInfo; 8789 if (destAi.name == filterAi.name 8790 && destAi.packageName == filterAi.packageName) { 8791 return false; 8792 } 8793 } 8794 return true; 8795 } 8796 8797 @Override 8798 protected ActivityIntentInfo[] newArray(int size) { 8799 return new ActivityIntentInfo[size]; 8800 } 8801 8802 @Override 8803 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8804 if (!sUserManager.exists(userId)) return true; 8805 PackageParser.Package p = filter.activity.owner; 8806 if (p != null) { 8807 PackageSetting ps = (PackageSetting)p.mExtras; 8808 if (ps != null) { 8809 // System apps are never considered stopped for purposes of 8810 // filtering, because there may be no way for the user to 8811 // actually re-launch them. 8812 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8813 && ps.getStopped(userId); 8814 } 8815 } 8816 return false; 8817 } 8818 8819 @Override 8820 protected boolean isPackageForFilter(String packageName, 8821 PackageParser.ActivityIntentInfo info) { 8822 return packageName.equals(info.activity.owner.packageName); 8823 } 8824 8825 @Override 8826 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8827 int match, int userId) { 8828 if (!sUserManager.exists(userId)) return null; 8829 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8830 return null; 8831 } 8832 final PackageParser.Activity activity = info.activity; 8833 if (mSafeMode && (activity.info.applicationInfo.flags 8834 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8835 return null; 8836 } 8837 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8838 if (ps == null) { 8839 return null; 8840 } 8841 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8842 ps.readUserState(userId), userId); 8843 if (ai == null) { 8844 return null; 8845 } 8846 final ResolveInfo res = new ResolveInfo(); 8847 res.activityInfo = ai; 8848 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8849 res.filter = info; 8850 } 8851 if (info != null) { 8852 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8853 } 8854 res.priority = info.getPriority(); 8855 res.preferredOrder = activity.owner.mPreferredOrder; 8856 //System.out.println("Result: " + res.activityInfo.className + 8857 // " = " + res.priority); 8858 res.match = match; 8859 res.isDefault = info.hasDefault; 8860 res.labelRes = info.labelRes; 8861 res.nonLocalizedLabel = info.nonLocalizedLabel; 8862 if (userNeedsBadging(userId)) { 8863 res.noResourceId = true; 8864 } else { 8865 res.icon = info.icon; 8866 } 8867 res.iconResourceId = info.icon; 8868 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8869 return res; 8870 } 8871 8872 @Override 8873 protected void sortResults(List<ResolveInfo> results) { 8874 Collections.sort(results, mResolvePrioritySorter); 8875 } 8876 8877 @Override 8878 protected void dumpFilter(PrintWriter out, String prefix, 8879 PackageParser.ActivityIntentInfo filter) { 8880 out.print(prefix); out.print( 8881 Integer.toHexString(System.identityHashCode(filter.activity))); 8882 out.print(' '); 8883 filter.activity.printComponentShortName(out); 8884 out.print(" filter "); 8885 out.println(Integer.toHexString(System.identityHashCode(filter))); 8886 } 8887 8888 @Override 8889 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8890 return filter.activity; 8891 } 8892 8893 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8894 PackageParser.Activity activity = (PackageParser.Activity)label; 8895 out.print(prefix); out.print( 8896 Integer.toHexString(System.identityHashCode(activity))); 8897 out.print(' '); 8898 activity.printComponentShortName(out); 8899 if (count > 1) { 8900 out.print(" ("); out.print(count); out.print(" filters)"); 8901 } 8902 out.println(); 8903 } 8904 8905// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8906// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8907// final List<ResolveInfo> retList = Lists.newArrayList(); 8908// while (i.hasNext()) { 8909// final ResolveInfo resolveInfo = i.next(); 8910// if (isEnabledLP(resolveInfo.activityInfo)) { 8911// retList.add(resolveInfo); 8912// } 8913// } 8914// return retList; 8915// } 8916 8917 // Keys are String (activity class name), values are Activity. 8918 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8919 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8920 private int mFlags; 8921 } 8922 8923 private final class ServiceIntentResolver 8924 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8925 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8926 boolean defaultOnly, int userId) { 8927 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8928 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8929 } 8930 8931 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8932 int userId) { 8933 if (!sUserManager.exists(userId)) return null; 8934 mFlags = flags; 8935 return super.queryIntent(intent, resolvedType, 8936 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8937 } 8938 8939 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8940 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8941 if (!sUserManager.exists(userId)) return null; 8942 if (packageServices == null) { 8943 return null; 8944 } 8945 mFlags = flags; 8946 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8947 final int N = packageServices.size(); 8948 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8949 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8950 8951 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8952 for (int i = 0; i < N; ++i) { 8953 intentFilters = packageServices.get(i).intents; 8954 if (intentFilters != null && intentFilters.size() > 0) { 8955 PackageParser.ServiceIntentInfo[] array = 8956 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8957 intentFilters.toArray(array); 8958 listCut.add(array); 8959 } 8960 } 8961 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8962 } 8963 8964 public final void addService(PackageParser.Service s) { 8965 mServices.put(s.getComponentName(), s); 8966 if (DEBUG_SHOW_INFO) { 8967 Log.v(TAG, " " 8968 + (s.info.nonLocalizedLabel != null 8969 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8970 Log.v(TAG, " Class=" + s.info.name); 8971 } 8972 final int NI = s.intents.size(); 8973 int j; 8974 for (j=0; j<NI; j++) { 8975 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8976 if (DEBUG_SHOW_INFO) { 8977 Log.v(TAG, " IntentFilter:"); 8978 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8979 } 8980 if (!intent.debugCheck()) { 8981 Log.w(TAG, "==> For Service " + s.info.name); 8982 } 8983 addFilter(intent); 8984 } 8985 } 8986 8987 public final void removeService(PackageParser.Service s) { 8988 mServices.remove(s.getComponentName()); 8989 if (DEBUG_SHOW_INFO) { 8990 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8991 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8992 Log.v(TAG, " Class=" + s.info.name); 8993 } 8994 final int NI = s.intents.size(); 8995 int j; 8996 for (j=0; j<NI; j++) { 8997 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8998 if (DEBUG_SHOW_INFO) { 8999 Log.v(TAG, " IntentFilter:"); 9000 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9001 } 9002 removeFilter(intent); 9003 } 9004 } 9005 9006 @Override 9007 protected boolean allowFilterResult( 9008 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9009 ServiceInfo filterSi = filter.service.info; 9010 for (int i=dest.size()-1; i>=0; i--) { 9011 ServiceInfo destAi = dest.get(i).serviceInfo; 9012 if (destAi.name == filterSi.name 9013 && destAi.packageName == filterSi.packageName) { 9014 return false; 9015 } 9016 } 9017 return true; 9018 } 9019 9020 @Override 9021 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9022 return new PackageParser.ServiceIntentInfo[size]; 9023 } 9024 9025 @Override 9026 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9027 if (!sUserManager.exists(userId)) return true; 9028 PackageParser.Package p = filter.service.owner; 9029 if (p != null) { 9030 PackageSetting ps = (PackageSetting)p.mExtras; 9031 if (ps != null) { 9032 // System apps are never considered stopped for purposes of 9033 // filtering, because there may be no way for the user to 9034 // actually re-launch them. 9035 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9036 && ps.getStopped(userId); 9037 } 9038 } 9039 return false; 9040 } 9041 9042 @Override 9043 protected boolean isPackageForFilter(String packageName, 9044 PackageParser.ServiceIntentInfo info) { 9045 return packageName.equals(info.service.owner.packageName); 9046 } 9047 9048 @Override 9049 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9050 int match, int userId) { 9051 if (!sUserManager.exists(userId)) return null; 9052 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9053 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9054 return null; 9055 } 9056 final PackageParser.Service service = info.service; 9057 if (mSafeMode && (service.info.applicationInfo.flags 9058 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9059 return null; 9060 } 9061 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9062 if (ps == null) { 9063 return null; 9064 } 9065 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9066 ps.readUserState(userId), userId); 9067 if (si == null) { 9068 return null; 9069 } 9070 final ResolveInfo res = new ResolveInfo(); 9071 res.serviceInfo = si; 9072 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9073 res.filter = filter; 9074 } 9075 res.priority = info.getPriority(); 9076 res.preferredOrder = service.owner.mPreferredOrder; 9077 res.match = match; 9078 res.isDefault = info.hasDefault; 9079 res.labelRes = info.labelRes; 9080 res.nonLocalizedLabel = info.nonLocalizedLabel; 9081 res.icon = info.icon; 9082 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9083 return res; 9084 } 9085 9086 @Override 9087 protected void sortResults(List<ResolveInfo> results) { 9088 Collections.sort(results, mResolvePrioritySorter); 9089 } 9090 9091 @Override 9092 protected void dumpFilter(PrintWriter out, String prefix, 9093 PackageParser.ServiceIntentInfo filter) { 9094 out.print(prefix); out.print( 9095 Integer.toHexString(System.identityHashCode(filter.service))); 9096 out.print(' '); 9097 filter.service.printComponentShortName(out); 9098 out.print(" filter "); 9099 out.println(Integer.toHexString(System.identityHashCode(filter))); 9100 } 9101 9102 @Override 9103 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9104 return filter.service; 9105 } 9106 9107 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9108 PackageParser.Service service = (PackageParser.Service)label; 9109 out.print(prefix); out.print( 9110 Integer.toHexString(System.identityHashCode(service))); 9111 out.print(' '); 9112 service.printComponentShortName(out); 9113 if (count > 1) { 9114 out.print(" ("); out.print(count); out.print(" filters)"); 9115 } 9116 out.println(); 9117 } 9118 9119// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9120// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9121// final List<ResolveInfo> retList = Lists.newArrayList(); 9122// while (i.hasNext()) { 9123// final ResolveInfo resolveInfo = (ResolveInfo) i; 9124// if (isEnabledLP(resolveInfo.serviceInfo)) { 9125// retList.add(resolveInfo); 9126// } 9127// } 9128// return retList; 9129// } 9130 9131 // Keys are String (activity class name), values are Activity. 9132 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9133 = new ArrayMap<ComponentName, PackageParser.Service>(); 9134 private int mFlags; 9135 }; 9136 9137 private final class ProviderIntentResolver 9138 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9139 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9140 boolean defaultOnly, int userId) { 9141 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9142 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9143 } 9144 9145 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9146 int userId) { 9147 if (!sUserManager.exists(userId)) 9148 return null; 9149 mFlags = flags; 9150 return super.queryIntent(intent, resolvedType, 9151 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9152 } 9153 9154 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9155 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9156 if (!sUserManager.exists(userId)) 9157 return null; 9158 if (packageProviders == null) { 9159 return null; 9160 } 9161 mFlags = flags; 9162 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9163 final int N = packageProviders.size(); 9164 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9165 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9166 9167 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9168 for (int i = 0; i < N; ++i) { 9169 intentFilters = packageProviders.get(i).intents; 9170 if (intentFilters != null && intentFilters.size() > 0) { 9171 PackageParser.ProviderIntentInfo[] array = 9172 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9173 intentFilters.toArray(array); 9174 listCut.add(array); 9175 } 9176 } 9177 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9178 } 9179 9180 public final void addProvider(PackageParser.Provider p) { 9181 if (mProviders.containsKey(p.getComponentName())) { 9182 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9183 return; 9184 } 9185 9186 mProviders.put(p.getComponentName(), p); 9187 if (DEBUG_SHOW_INFO) { 9188 Log.v(TAG, " " 9189 + (p.info.nonLocalizedLabel != null 9190 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9191 Log.v(TAG, " Class=" + p.info.name); 9192 } 9193 final int NI = p.intents.size(); 9194 int j; 9195 for (j = 0; j < NI; j++) { 9196 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9197 if (DEBUG_SHOW_INFO) { 9198 Log.v(TAG, " IntentFilter:"); 9199 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9200 } 9201 if (!intent.debugCheck()) { 9202 Log.w(TAG, "==> For Provider " + p.info.name); 9203 } 9204 addFilter(intent); 9205 } 9206 } 9207 9208 public final void removeProvider(PackageParser.Provider p) { 9209 mProviders.remove(p.getComponentName()); 9210 if (DEBUG_SHOW_INFO) { 9211 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9212 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9213 Log.v(TAG, " Class=" + p.info.name); 9214 } 9215 final int NI = p.intents.size(); 9216 int j; 9217 for (j = 0; j < NI; j++) { 9218 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9219 if (DEBUG_SHOW_INFO) { 9220 Log.v(TAG, " IntentFilter:"); 9221 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9222 } 9223 removeFilter(intent); 9224 } 9225 } 9226 9227 @Override 9228 protected boolean allowFilterResult( 9229 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9230 ProviderInfo filterPi = filter.provider.info; 9231 for (int i = dest.size() - 1; i >= 0; i--) { 9232 ProviderInfo destPi = dest.get(i).providerInfo; 9233 if (destPi.name == filterPi.name 9234 && destPi.packageName == filterPi.packageName) { 9235 return false; 9236 } 9237 } 9238 return true; 9239 } 9240 9241 @Override 9242 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9243 return new PackageParser.ProviderIntentInfo[size]; 9244 } 9245 9246 @Override 9247 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9248 if (!sUserManager.exists(userId)) 9249 return true; 9250 PackageParser.Package p = filter.provider.owner; 9251 if (p != null) { 9252 PackageSetting ps = (PackageSetting) p.mExtras; 9253 if (ps != null) { 9254 // System apps are never considered stopped for purposes of 9255 // filtering, because there may be no way for the user to 9256 // actually re-launch them. 9257 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9258 && ps.getStopped(userId); 9259 } 9260 } 9261 return false; 9262 } 9263 9264 @Override 9265 protected boolean isPackageForFilter(String packageName, 9266 PackageParser.ProviderIntentInfo info) { 9267 return packageName.equals(info.provider.owner.packageName); 9268 } 9269 9270 @Override 9271 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9272 int match, int userId) { 9273 if (!sUserManager.exists(userId)) 9274 return null; 9275 final PackageParser.ProviderIntentInfo info = filter; 9276 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9277 return null; 9278 } 9279 final PackageParser.Provider provider = info.provider; 9280 if (mSafeMode && (provider.info.applicationInfo.flags 9281 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9282 return null; 9283 } 9284 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9285 if (ps == null) { 9286 return null; 9287 } 9288 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9289 ps.readUserState(userId), userId); 9290 if (pi == null) { 9291 return null; 9292 } 9293 final ResolveInfo res = new ResolveInfo(); 9294 res.providerInfo = pi; 9295 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9296 res.filter = filter; 9297 } 9298 res.priority = info.getPriority(); 9299 res.preferredOrder = provider.owner.mPreferredOrder; 9300 res.match = match; 9301 res.isDefault = info.hasDefault; 9302 res.labelRes = info.labelRes; 9303 res.nonLocalizedLabel = info.nonLocalizedLabel; 9304 res.icon = info.icon; 9305 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9306 return res; 9307 } 9308 9309 @Override 9310 protected void sortResults(List<ResolveInfo> results) { 9311 Collections.sort(results, mResolvePrioritySorter); 9312 } 9313 9314 @Override 9315 protected void dumpFilter(PrintWriter out, String prefix, 9316 PackageParser.ProviderIntentInfo filter) { 9317 out.print(prefix); 9318 out.print( 9319 Integer.toHexString(System.identityHashCode(filter.provider))); 9320 out.print(' '); 9321 filter.provider.printComponentShortName(out); 9322 out.print(" filter "); 9323 out.println(Integer.toHexString(System.identityHashCode(filter))); 9324 } 9325 9326 @Override 9327 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9328 return filter.provider; 9329 } 9330 9331 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9332 PackageParser.Provider provider = (PackageParser.Provider)label; 9333 out.print(prefix); out.print( 9334 Integer.toHexString(System.identityHashCode(provider))); 9335 out.print(' '); 9336 provider.printComponentShortName(out); 9337 if (count > 1) { 9338 out.print(" ("); out.print(count); out.print(" filters)"); 9339 } 9340 out.println(); 9341 } 9342 9343 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9344 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9345 private int mFlags; 9346 }; 9347 9348 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9349 new Comparator<ResolveInfo>() { 9350 public int compare(ResolveInfo r1, ResolveInfo r2) { 9351 int v1 = r1.priority; 9352 int v2 = r2.priority; 9353 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9354 if (v1 != v2) { 9355 return (v1 > v2) ? -1 : 1; 9356 } 9357 v1 = r1.preferredOrder; 9358 v2 = r2.preferredOrder; 9359 if (v1 != v2) { 9360 return (v1 > v2) ? -1 : 1; 9361 } 9362 if (r1.isDefault != r2.isDefault) { 9363 return r1.isDefault ? -1 : 1; 9364 } 9365 v1 = r1.match; 9366 v2 = r2.match; 9367 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9368 if (v1 != v2) { 9369 return (v1 > v2) ? -1 : 1; 9370 } 9371 if (r1.system != r2.system) { 9372 return r1.system ? -1 : 1; 9373 } 9374 return 0; 9375 } 9376 }; 9377 9378 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9379 new Comparator<ProviderInfo>() { 9380 public int compare(ProviderInfo p1, ProviderInfo p2) { 9381 final int v1 = p1.initOrder; 9382 final int v2 = p2.initOrder; 9383 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9384 } 9385 }; 9386 9387 final void sendPackageBroadcast(final String action, final String pkg, 9388 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9389 final int[] userIds) { 9390 mHandler.post(new Runnable() { 9391 @Override 9392 public void run() { 9393 try { 9394 final IActivityManager am = ActivityManagerNative.getDefault(); 9395 if (am == null) return; 9396 final int[] resolvedUserIds; 9397 if (userIds == null) { 9398 resolvedUserIds = am.getRunningUserIds(); 9399 } else { 9400 resolvedUserIds = userIds; 9401 } 9402 for (int id : resolvedUserIds) { 9403 final Intent intent = new Intent(action, 9404 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9405 if (extras != null) { 9406 intent.putExtras(extras); 9407 } 9408 if (targetPkg != null) { 9409 intent.setPackage(targetPkg); 9410 } 9411 // Modify the UID when posting to other users 9412 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9413 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9414 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9415 intent.putExtra(Intent.EXTRA_UID, uid); 9416 } 9417 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9418 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9419 if (DEBUG_BROADCASTS) { 9420 RuntimeException here = new RuntimeException("here"); 9421 here.fillInStackTrace(); 9422 Slog.d(TAG, "Sending to user " + id + ": " 9423 + intent.toShortString(false, true, false, false) 9424 + " " + intent.getExtras(), here); 9425 } 9426 am.broadcastIntent(null, intent, null, finishedReceiver, 9427 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9428 null, finishedReceiver != null, false, id); 9429 } 9430 } catch (RemoteException ex) { 9431 } 9432 } 9433 }); 9434 } 9435 9436 /** 9437 * Check if the external storage media is available. This is true if there 9438 * is a mounted external storage medium or if the external storage is 9439 * emulated. 9440 */ 9441 private boolean isExternalMediaAvailable() { 9442 return mMediaMounted || Environment.isExternalStorageEmulated(); 9443 } 9444 9445 @Override 9446 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9447 // writer 9448 synchronized (mPackages) { 9449 if (!isExternalMediaAvailable()) { 9450 // If the external storage is no longer mounted at this point, 9451 // the caller may not have been able to delete all of this 9452 // packages files and can not delete any more. Bail. 9453 return null; 9454 } 9455 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9456 if (lastPackage != null) { 9457 pkgs.remove(lastPackage); 9458 } 9459 if (pkgs.size() > 0) { 9460 return pkgs.get(0); 9461 } 9462 } 9463 return null; 9464 } 9465 9466 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9467 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9468 userId, andCode ? 1 : 0, packageName); 9469 if (mSystemReady) { 9470 msg.sendToTarget(); 9471 } else { 9472 if (mPostSystemReadyMessages == null) { 9473 mPostSystemReadyMessages = new ArrayList<>(); 9474 } 9475 mPostSystemReadyMessages.add(msg); 9476 } 9477 } 9478 9479 void startCleaningPackages() { 9480 // reader 9481 synchronized (mPackages) { 9482 if (!isExternalMediaAvailable()) { 9483 return; 9484 } 9485 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9486 return; 9487 } 9488 } 9489 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9490 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9491 IActivityManager am = ActivityManagerNative.getDefault(); 9492 if (am != null) { 9493 try { 9494 am.startService(null, intent, null, mContext.getOpPackageName(), 9495 UserHandle.USER_OWNER); 9496 } catch (RemoteException e) { 9497 } 9498 } 9499 } 9500 9501 @Override 9502 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9503 int installFlags, String installerPackageName, VerificationParams verificationParams, 9504 String packageAbiOverride) { 9505 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9506 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9507 } 9508 9509 @Override 9510 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9511 int installFlags, String installerPackageName, VerificationParams verificationParams, 9512 String packageAbiOverride, int userId) { 9513 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9514 9515 final int callingUid = Binder.getCallingUid(); 9516 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9517 9518 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9519 try { 9520 if (observer != null) { 9521 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9522 } 9523 } catch (RemoteException re) { 9524 } 9525 return; 9526 } 9527 9528 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9529 installFlags |= PackageManager.INSTALL_FROM_ADB; 9530 9531 } else { 9532 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9533 // about installerPackageName. 9534 9535 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9536 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9537 } 9538 9539 UserHandle user; 9540 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9541 user = UserHandle.ALL; 9542 } else { 9543 user = new UserHandle(userId); 9544 } 9545 9546 // Only system components can circumvent runtime permissions when installing. 9547 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9548 && mContext.checkCallingOrSelfPermission(Manifest.permission 9549 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9550 throw new SecurityException("You need the " 9551 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9552 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9553 } 9554 9555 verificationParams.setInstallerUid(callingUid); 9556 9557 final File originFile = new File(originPath); 9558 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9559 9560 final Message msg = mHandler.obtainMessage(INIT_COPY); 9561 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9562 null, verificationParams, user, packageAbiOverride, null); 9563 mHandler.sendMessage(msg); 9564 } 9565 9566 void installStage(String packageName, File stagedDir, String stagedCid, 9567 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9568 String installerPackageName, int installerUid, UserHandle user) { 9569 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9570 params.referrerUri, installerUid, null); 9571 verifParams.setInstallerUid(installerUid); 9572 9573 final OriginInfo origin; 9574 if (stagedDir != null) { 9575 origin = OriginInfo.fromStagedFile(stagedDir); 9576 } else { 9577 origin = OriginInfo.fromStagedContainer(stagedCid); 9578 } 9579 9580 final Message msg = mHandler.obtainMessage(INIT_COPY); 9581 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9582 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9583 params.grantedRuntimePermissions); 9584 mHandler.sendMessage(msg); 9585 } 9586 9587 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9588 Bundle extras = new Bundle(1); 9589 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9590 9591 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9592 packageName, extras, null, null, new int[] {userId}); 9593 try { 9594 IActivityManager am = ActivityManagerNative.getDefault(); 9595 final boolean isSystem = 9596 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9597 if (isSystem && am.isUserRunning(userId, false)) { 9598 // The just-installed/enabled app is bundled on the system, so presumed 9599 // to be able to run automatically without needing an explicit launch. 9600 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9601 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9602 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9603 .setPackage(packageName); 9604 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9605 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9606 } 9607 } catch (RemoteException e) { 9608 // shouldn't happen 9609 Slog.w(TAG, "Unable to bootstrap installed package", e); 9610 } 9611 } 9612 9613 @Override 9614 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9615 int userId) { 9616 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9617 PackageSetting pkgSetting; 9618 final int uid = Binder.getCallingUid(); 9619 enforceCrossUserPermission(uid, userId, true, true, 9620 "setApplicationHiddenSetting for user " + userId); 9621 9622 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9623 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9624 return false; 9625 } 9626 9627 long callingId = Binder.clearCallingIdentity(); 9628 try { 9629 boolean sendAdded = false; 9630 boolean sendRemoved = false; 9631 // writer 9632 synchronized (mPackages) { 9633 pkgSetting = mSettings.mPackages.get(packageName); 9634 if (pkgSetting == null) { 9635 return false; 9636 } 9637 if (pkgSetting.getHidden(userId) != hidden) { 9638 pkgSetting.setHidden(hidden, userId); 9639 mSettings.writePackageRestrictionsLPr(userId); 9640 if (hidden) { 9641 sendRemoved = true; 9642 } else { 9643 sendAdded = true; 9644 } 9645 } 9646 } 9647 if (sendAdded) { 9648 sendPackageAddedForUser(packageName, pkgSetting, userId); 9649 return true; 9650 } 9651 if (sendRemoved) { 9652 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9653 "hiding pkg"); 9654 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9655 return true; 9656 } 9657 } finally { 9658 Binder.restoreCallingIdentity(callingId); 9659 } 9660 return false; 9661 } 9662 9663 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9664 int userId) { 9665 final PackageRemovedInfo info = new PackageRemovedInfo(); 9666 info.removedPackage = packageName; 9667 info.removedUsers = new int[] {userId}; 9668 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9669 info.sendBroadcast(false, false, false); 9670 } 9671 9672 /** 9673 * Returns true if application is not found or there was an error. Otherwise it returns 9674 * the hidden state of the package for the given user. 9675 */ 9676 @Override 9677 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9678 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9679 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9680 false, "getApplicationHidden for user " + userId); 9681 PackageSetting pkgSetting; 9682 long callingId = Binder.clearCallingIdentity(); 9683 try { 9684 // writer 9685 synchronized (mPackages) { 9686 pkgSetting = mSettings.mPackages.get(packageName); 9687 if (pkgSetting == null) { 9688 return true; 9689 } 9690 return pkgSetting.getHidden(userId); 9691 } 9692 } finally { 9693 Binder.restoreCallingIdentity(callingId); 9694 } 9695 } 9696 9697 /** 9698 * @hide 9699 */ 9700 @Override 9701 public int installExistingPackageAsUser(String packageName, int userId) { 9702 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9703 null); 9704 PackageSetting pkgSetting; 9705 final int uid = Binder.getCallingUid(); 9706 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9707 + userId); 9708 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9709 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9710 } 9711 9712 long callingId = Binder.clearCallingIdentity(); 9713 try { 9714 boolean sendAdded = false; 9715 9716 // writer 9717 synchronized (mPackages) { 9718 pkgSetting = mSettings.mPackages.get(packageName); 9719 if (pkgSetting == null) { 9720 return PackageManager.INSTALL_FAILED_INVALID_URI; 9721 } 9722 if (!pkgSetting.getInstalled(userId)) { 9723 pkgSetting.setInstalled(true, userId); 9724 pkgSetting.setHidden(false, userId); 9725 mSettings.writePackageRestrictionsLPr(userId); 9726 sendAdded = true; 9727 } 9728 } 9729 9730 if (sendAdded) { 9731 sendPackageAddedForUser(packageName, pkgSetting, userId); 9732 } 9733 } finally { 9734 Binder.restoreCallingIdentity(callingId); 9735 } 9736 9737 return PackageManager.INSTALL_SUCCEEDED; 9738 } 9739 9740 boolean isUserRestricted(int userId, String restrictionKey) { 9741 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9742 if (restrictions.getBoolean(restrictionKey, false)) { 9743 Log.w(TAG, "User is restricted: " + restrictionKey); 9744 return true; 9745 } 9746 return false; 9747 } 9748 9749 @Override 9750 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9751 mContext.enforceCallingOrSelfPermission( 9752 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9753 "Only package verification agents can verify applications"); 9754 9755 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9756 final PackageVerificationResponse response = new PackageVerificationResponse( 9757 verificationCode, Binder.getCallingUid()); 9758 msg.arg1 = id; 9759 msg.obj = response; 9760 mHandler.sendMessage(msg); 9761 } 9762 9763 @Override 9764 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9765 long millisecondsToDelay) { 9766 mContext.enforceCallingOrSelfPermission( 9767 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9768 "Only package verification agents can extend verification timeouts"); 9769 9770 final PackageVerificationState state = mPendingVerification.get(id); 9771 final PackageVerificationResponse response = new PackageVerificationResponse( 9772 verificationCodeAtTimeout, Binder.getCallingUid()); 9773 9774 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9775 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9776 } 9777 if (millisecondsToDelay < 0) { 9778 millisecondsToDelay = 0; 9779 } 9780 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9781 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9782 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9783 } 9784 9785 if ((state != null) && !state.timeoutExtended()) { 9786 state.extendTimeout(); 9787 9788 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9789 msg.arg1 = id; 9790 msg.obj = response; 9791 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9792 } 9793 } 9794 9795 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9796 int verificationCode, UserHandle user) { 9797 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9798 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9799 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9800 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9801 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9802 9803 mContext.sendBroadcastAsUser(intent, user, 9804 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9805 } 9806 9807 private ComponentName matchComponentForVerifier(String packageName, 9808 List<ResolveInfo> receivers) { 9809 ActivityInfo targetReceiver = null; 9810 9811 final int NR = receivers.size(); 9812 for (int i = 0; i < NR; i++) { 9813 final ResolveInfo info = receivers.get(i); 9814 if (info.activityInfo == null) { 9815 continue; 9816 } 9817 9818 if (packageName.equals(info.activityInfo.packageName)) { 9819 targetReceiver = info.activityInfo; 9820 break; 9821 } 9822 } 9823 9824 if (targetReceiver == null) { 9825 return null; 9826 } 9827 9828 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9829 } 9830 9831 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9832 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9833 if (pkgInfo.verifiers.length == 0) { 9834 return null; 9835 } 9836 9837 final int N = pkgInfo.verifiers.length; 9838 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9839 for (int i = 0; i < N; i++) { 9840 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9841 9842 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9843 receivers); 9844 if (comp == null) { 9845 continue; 9846 } 9847 9848 final int verifierUid = getUidForVerifier(verifierInfo); 9849 if (verifierUid == -1) { 9850 continue; 9851 } 9852 9853 if (DEBUG_VERIFY) { 9854 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9855 + " with the correct signature"); 9856 } 9857 sufficientVerifiers.add(comp); 9858 verificationState.addSufficientVerifier(verifierUid); 9859 } 9860 9861 return sufficientVerifiers; 9862 } 9863 9864 private int getUidForVerifier(VerifierInfo verifierInfo) { 9865 synchronized (mPackages) { 9866 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9867 if (pkg == null) { 9868 return -1; 9869 } else if (pkg.mSignatures.length != 1) { 9870 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9871 + " has more than one signature; ignoring"); 9872 return -1; 9873 } 9874 9875 /* 9876 * If the public key of the package's signature does not match 9877 * our expected public key, then this is a different package and 9878 * we should skip. 9879 */ 9880 9881 final byte[] expectedPublicKey; 9882 try { 9883 final Signature verifierSig = pkg.mSignatures[0]; 9884 final PublicKey publicKey = verifierSig.getPublicKey(); 9885 expectedPublicKey = publicKey.getEncoded(); 9886 } catch (CertificateException e) { 9887 return -1; 9888 } 9889 9890 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9891 9892 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9893 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9894 + " does not have the expected public key; ignoring"); 9895 return -1; 9896 } 9897 9898 return pkg.applicationInfo.uid; 9899 } 9900 } 9901 9902 @Override 9903 public void finishPackageInstall(int token) { 9904 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9905 9906 if (DEBUG_INSTALL) { 9907 Slog.v(TAG, "BM finishing package install for " + token); 9908 } 9909 9910 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9911 mHandler.sendMessage(msg); 9912 } 9913 9914 /** 9915 * Get the verification agent timeout. 9916 * 9917 * @return verification timeout in milliseconds 9918 */ 9919 private long getVerificationTimeout() { 9920 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9921 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9922 DEFAULT_VERIFICATION_TIMEOUT); 9923 } 9924 9925 /** 9926 * Get the default verification agent response code. 9927 * 9928 * @return default verification response code 9929 */ 9930 private int getDefaultVerificationResponse() { 9931 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9932 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9933 DEFAULT_VERIFICATION_RESPONSE); 9934 } 9935 9936 /** 9937 * Check whether or not package verification has been enabled. 9938 * 9939 * @return true if verification should be performed 9940 */ 9941 private boolean isVerificationEnabled(int userId, int installFlags) { 9942 if (!DEFAULT_VERIFY_ENABLE) { 9943 return false; 9944 } 9945 9946 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9947 9948 // Check if installing from ADB 9949 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9950 // Do not run verification in a test harness environment 9951 if (ActivityManager.isRunningInTestHarness()) { 9952 return false; 9953 } 9954 if (ensureVerifyAppsEnabled) { 9955 return true; 9956 } 9957 // Check if the developer does not want package verification for ADB installs 9958 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9959 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9960 return false; 9961 } 9962 } 9963 9964 if (ensureVerifyAppsEnabled) { 9965 return true; 9966 } 9967 9968 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9969 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9970 } 9971 9972 @Override 9973 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9974 throws RemoteException { 9975 mContext.enforceCallingOrSelfPermission( 9976 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9977 "Only intentfilter verification agents can verify applications"); 9978 9979 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9980 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9981 Binder.getCallingUid(), verificationCode, failedDomains); 9982 msg.arg1 = id; 9983 msg.obj = response; 9984 mHandler.sendMessage(msg); 9985 } 9986 9987 @Override 9988 public int getIntentVerificationStatus(String packageName, int userId) { 9989 synchronized (mPackages) { 9990 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9991 } 9992 } 9993 9994 @Override 9995 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9996 mContext.enforceCallingOrSelfPermission( 9997 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9998 9999 boolean result = false; 10000 synchronized (mPackages) { 10001 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10002 } 10003 if (result) { 10004 scheduleWritePackageRestrictionsLocked(userId); 10005 } 10006 return result; 10007 } 10008 10009 @Override 10010 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10011 synchronized (mPackages) { 10012 return mSettings.getIntentFilterVerificationsLPr(packageName); 10013 } 10014 } 10015 10016 @Override 10017 public List<IntentFilter> getAllIntentFilters(String packageName) { 10018 if (TextUtils.isEmpty(packageName)) { 10019 return Collections.<IntentFilter>emptyList(); 10020 } 10021 synchronized (mPackages) { 10022 PackageParser.Package pkg = mPackages.get(packageName); 10023 if (pkg == null || pkg.activities == null) { 10024 return Collections.<IntentFilter>emptyList(); 10025 } 10026 final int count = pkg.activities.size(); 10027 ArrayList<IntentFilter> result = new ArrayList<>(); 10028 for (int n=0; n<count; n++) { 10029 PackageParser.Activity activity = pkg.activities.get(n); 10030 if (activity.intents != null || activity.intents.size() > 0) { 10031 result.addAll(activity.intents); 10032 } 10033 } 10034 return result; 10035 } 10036 } 10037 10038 @Override 10039 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10040 mContext.enforceCallingOrSelfPermission( 10041 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10042 10043 synchronized (mPackages) { 10044 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10045 if (packageName != null) { 10046 result |= updateIntentVerificationStatus(packageName, 10047 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10048 userId); 10049 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10050 packageName, userId); 10051 } 10052 return result; 10053 } 10054 } 10055 10056 @Override 10057 public String getDefaultBrowserPackageName(int userId) { 10058 synchronized (mPackages) { 10059 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10060 } 10061 } 10062 10063 /** 10064 * Get the "allow unknown sources" setting. 10065 * 10066 * @return the current "allow unknown sources" setting 10067 */ 10068 private int getUnknownSourcesSettings() { 10069 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10070 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10071 -1); 10072 } 10073 10074 @Override 10075 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10076 final int uid = Binder.getCallingUid(); 10077 // writer 10078 synchronized (mPackages) { 10079 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10080 if (targetPackageSetting == null) { 10081 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10082 } 10083 10084 PackageSetting installerPackageSetting; 10085 if (installerPackageName != null) { 10086 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10087 if (installerPackageSetting == null) { 10088 throw new IllegalArgumentException("Unknown installer package: " 10089 + installerPackageName); 10090 } 10091 } else { 10092 installerPackageSetting = null; 10093 } 10094 10095 Signature[] callerSignature; 10096 Object obj = mSettings.getUserIdLPr(uid); 10097 if (obj != null) { 10098 if (obj instanceof SharedUserSetting) { 10099 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10100 } else if (obj instanceof PackageSetting) { 10101 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10102 } else { 10103 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10104 } 10105 } else { 10106 throw new SecurityException("Unknown calling uid " + uid); 10107 } 10108 10109 // Verify: can't set installerPackageName to a package that is 10110 // not signed with the same cert as the caller. 10111 if (installerPackageSetting != null) { 10112 if (compareSignatures(callerSignature, 10113 installerPackageSetting.signatures.mSignatures) 10114 != PackageManager.SIGNATURE_MATCH) { 10115 throw new SecurityException( 10116 "Caller does not have same cert as new installer package " 10117 + installerPackageName); 10118 } 10119 } 10120 10121 // Verify: if target already has an installer package, it must 10122 // be signed with the same cert as the caller. 10123 if (targetPackageSetting.installerPackageName != null) { 10124 PackageSetting setting = mSettings.mPackages.get( 10125 targetPackageSetting.installerPackageName); 10126 // If the currently set package isn't valid, then it's always 10127 // okay to change it. 10128 if (setting != null) { 10129 if (compareSignatures(callerSignature, 10130 setting.signatures.mSignatures) 10131 != PackageManager.SIGNATURE_MATCH) { 10132 throw new SecurityException( 10133 "Caller does not have same cert as old installer package " 10134 + targetPackageSetting.installerPackageName); 10135 } 10136 } 10137 } 10138 10139 // Okay! 10140 targetPackageSetting.installerPackageName = installerPackageName; 10141 scheduleWriteSettingsLocked(); 10142 } 10143 } 10144 10145 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10146 // Queue up an async operation since the package installation may take a little while. 10147 mHandler.post(new Runnable() { 10148 public void run() { 10149 mHandler.removeCallbacks(this); 10150 // Result object to be returned 10151 PackageInstalledInfo res = new PackageInstalledInfo(); 10152 res.returnCode = currentStatus; 10153 res.uid = -1; 10154 res.pkg = null; 10155 res.removedInfo = new PackageRemovedInfo(); 10156 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10157 args.doPreInstall(res.returnCode); 10158 synchronized (mInstallLock) { 10159 installPackageLI(args, res); 10160 } 10161 args.doPostInstall(res.returnCode, res.uid); 10162 } 10163 10164 // A restore should be performed at this point if (a) the install 10165 // succeeded, (b) the operation is not an update, and (c) the new 10166 // package has not opted out of backup participation. 10167 final boolean update = res.removedInfo.removedPackage != null; 10168 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10169 boolean doRestore = !update 10170 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10171 10172 // Set up the post-install work request bookkeeping. This will be used 10173 // and cleaned up by the post-install event handling regardless of whether 10174 // there's a restore pass performed. Token values are >= 1. 10175 int token; 10176 if (mNextInstallToken < 0) mNextInstallToken = 1; 10177 token = mNextInstallToken++; 10178 10179 PostInstallData data = new PostInstallData(args, res); 10180 mRunningInstalls.put(token, data); 10181 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10182 10183 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10184 // Pass responsibility to the Backup Manager. It will perform a 10185 // restore if appropriate, then pass responsibility back to the 10186 // Package Manager to run the post-install observer callbacks 10187 // and broadcasts. 10188 IBackupManager bm = IBackupManager.Stub.asInterface( 10189 ServiceManager.getService(Context.BACKUP_SERVICE)); 10190 if (bm != null) { 10191 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10192 + " to BM for possible restore"); 10193 try { 10194 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10195 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10196 } else { 10197 doRestore = false; 10198 } 10199 } catch (RemoteException e) { 10200 // can't happen; the backup manager is local 10201 } catch (Exception e) { 10202 Slog.e(TAG, "Exception trying to enqueue restore", e); 10203 doRestore = false; 10204 } 10205 } else { 10206 Slog.e(TAG, "Backup Manager not found!"); 10207 doRestore = false; 10208 } 10209 } 10210 10211 if (!doRestore) { 10212 // No restore possible, or the Backup Manager was mysteriously not 10213 // available -- just fire the post-install work request directly. 10214 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10215 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10216 mHandler.sendMessage(msg); 10217 } 10218 } 10219 }); 10220 } 10221 10222 private abstract class HandlerParams { 10223 private static final int MAX_RETRIES = 4; 10224 10225 /** 10226 * Number of times startCopy() has been attempted and had a non-fatal 10227 * error. 10228 */ 10229 private int mRetries = 0; 10230 10231 /** User handle for the user requesting the information or installation. */ 10232 private final UserHandle mUser; 10233 10234 HandlerParams(UserHandle user) { 10235 mUser = user; 10236 } 10237 10238 UserHandle getUser() { 10239 return mUser; 10240 } 10241 10242 final boolean startCopy() { 10243 boolean res; 10244 try { 10245 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10246 10247 if (++mRetries > MAX_RETRIES) { 10248 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10249 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10250 handleServiceError(); 10251 return false; 10252 } else { 10253 handleStartCopy(); 10254 res = true; 10255 } 10256 } catch (RemoteException e) { 10257 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10258 mHandler.sendEmptyMessage(MCS_RECONNECT); 10259 res = false; 10260 } 10261 handleReturnCode(); 10262 return res; 10263 } 10264 10265 final void serviceError() { 10266 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10267 handleServiceError(); 10268 handleReturnCode(); 10269 } 10270 10271 abstract void handleStartCopy() throws RemoteException; 10272 abstract void handleServiceError(); 10273 abstract void handleReturnCode(); 10274 } 10275 10276 class MeasureParams extends HandlerParams { 10277 private final PackageStats mStats; 10278 private boolean mSuccess; 10279 10280 private final IPackageStatsObserver mObserver; 10281 10282 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10283 super(new UserHandle(stats.userHandle)); 10284 mObserver = observer; 10285 mStats = stats; 10286 } 10287 10288 @Override 10289 public String toString() { 10290 return "MeasureParams{" 10291 + Integer.toHexString(System.identityHashCode(this)) 10292 + " " + mStats.packageName + "}"; 10293 } 10294 10295 @Override 10296 void handleStartCopy() throws RemoteException { 10297 synchronized (mInstallLock) { 10298 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10299 } 10300 10301 if (mSuccess) { 10302 final boolean mounted; 10303 if (Environment.isExternalStorageEmulated()) { 10304 mounted = true; 10305 } else { 10306 final String status = Environment.getExternalStorageState(); 10307 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10308 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10309 } 10310 10311 if (mounted) { 10312 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10313 10314 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10315 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10316 10317 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10318 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10319 10320 // Always subtract cache size, since it's a subdirectory 10321 mStats.externalDataSize -= mStats.externalCacheSize; 10322 10323 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10324 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10325 10326 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10327 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10328 } 10329 } 10330 } 10331 10332 @Override 10333 void handleReturnCode() { 10334 if (mObserver != null) { 10335 try { 10336 mObserver.onGetStatsCompleted(mStats, mSuccess); 10337 } catch (RemoteException e) { 10338 Slog.i(TAG, "Observer no longer exists."); 10339 } 10340 } 10341 } 10342 10343 @Override 10344 void handleServiceError() { 10345 Slog.e(TAG, "Could not measure application " + mStats.packageName 10346 + " external storage"); 10347 } 10348 } 10349 10350 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10351 throws RemoteException { 10352 long result = 0; 10353 for (File path : paths) { 10354 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10355 } 10356 return result; 10357 } 10358 10359 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10360 for (File path : paths) { 10361 try { 10362 mcs.clearDirectory(path.getAbsolutePath()); 10363 } catch (RemoteException e) { 10364 } 10365 } 10366 } 10367 10368 static class OriginInfo { 10369 /** 10370 * Location where install is coming from, before it has been 10371 * copied/renamed into place. This could be a single monolithic APK 10372 * file, or a cluster directory. This location may be untrusted. 10373 */ 10374 final File file; 10375 final String cid; 10376 10377 /** 10378 * Flag indicating that {@link #file} or {@link #cid} has already been 10379 * staged, meaning downstream users don't need to defensively copy the 10380 * contents. 10381 */ 10382 final boolean staged; 10383 10384 /** 10385 * Flag indicating that {@link #file} or {@link #cid} is an already 10386 * installed app that is being moved. 10387 */ 10388 final boolean existing; 10389 10390 final String resolvedPath; 10391 final File resolvedFile; 10392 10393 static OriginInfo fromNothing() { 10394 return new OriginInfo(null, null, false, false); 10395 } 10396 10397 static OriginInfo fromUntrustedFile(File file) { 10398 return new OriginInfo(file, null, false, false); 10399 } 10400 10401 static OriginInfo fromExistingFile(File file) { 10402 return new OriginInfo(file, null, false, true); 10403 } 10404 10405 static OriginInfo fromStagedFile(File file) { 10406 return new OriginInfo(file, null, true, false); 10407 } 10408 10409 static OriginInfo fromStagedContainer(String cid) { 10410 return new OriginInfo(null, cid, true, false); 10411 } 10412 10413 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10414 this.file = file; 10415 this.cid = cid; 10416 this.staged = staged; 10417 this.existing = existing; 10418 10419 if (cid != null) { 10420 resolvedPath = PackageHelper.getSdDir(cid); 10421 resolvedFile = new File(resolvedPath); 10422 } else if (file != null) { 10423 resolvedPath = file.getAbsolutePath(); 10424 resolvedFile = file; 10425 } else { 10426 resolvedPath = null; 10427 resolvedFile = null; 10428 } 10429 } 10430 } 10431 10432 class MoveInfo { 10433 final int moveId; 10434 final String fromUuid; 10435 final String toUuid; 10436 final String packageName; 10437 final String dataAppName; 10438 final int appId; 10439 final String seinfo; 10440 10441 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10442 String dataAppName, int appId, String seinfo) { 10443 this.moveId = moveId; 10444 this.fromUuid = fromUuid; 10445 this.toUuid = toUuid; 10446 this.packageName = packageName; 10447 this.dataAppName = dataAppName; 10448 this.appId = appId; 10449 this.seinfo = seinfo; 10450 } 10451 } 10452 10453 class InstallParams extends HandlerParams { 10454 final OriginInfo origin; 10455 final MoveInfo move; 10456 final IPackageInstallObserver2 observer; 10457 int installFlags; 10458 final String installerPackageName; 10459 final String volumeUuid; 10460 final VerificationParams verificationParams; 10461 private InstallArgs mArgs; 10462 private int mRet; 10463 final String packageAbiOverride; 10464 final String[] grantedRuntimePermissions; 10465 10466 10467 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10468 int installFlags, String installerPackageName, String volumeUuid, 10469 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10470 String[] grantedPermissions) { 10471 super(user); 10472 this.origin = origin; 10473 this.move = move; 10474 this.observer = observer; 10475 this.installFlags = installFlags; 10476 this.installerPackageName = installerPackageName; 10477 this.volumeUuid = volumeUuid; 10478 this.verificationParams = verificationParams; 10479 this.packageAbiOverride = packageAbiOverride; 10480 this.grantedRuntimePermissions = grantedPermissions; 10481 } 10482 10483 @Override 10484 public String toString() { 10485 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10486 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10487 } 10488 10489 public ManifestDigest getManifestDigest() { 10490 if (verificationParams == null) { 10491 return null; 10492 } 10493 return verificationParams.getManifestDigest(); 10494 } 10495 10496 private int installLocationPolicy(PackageInfoLite pkgLite) { 10497 String packageName = pkgLite.packageName; 10498 int installLocation = pkgLite.installLocation; 10499 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10500 // reader 10501 synchronized (mPackages) { 10502 PackageParser.Package pkg = mPackages.get(packageName); 10503 if (pkg != null) { 10504 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10505 // Check for downgrading. 10506 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10507 try { 10508 checkDowngrade(pkg, pkgLite); 10509 } catch (PackageManagerException e) { 10510 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10511 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10512 } 10513 } 10514 // Check for updated system application. 10515 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10516 if (onSd) { 10517 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10518 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10519 } 10520 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10521 } else { 10522 if (onSd) { 10523 // Install flag overrides everything. 10524 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10525 } 10526 // If current upgrade specifies particular preference 10527 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10528 // Application explicitly specified internal. 10529 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10530 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10531 // App explictly prefers external. Let policy decide 10532 } else { 10533 // Prefer previous location 10534 if (isExternal(pkg)) { 10535 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10536 } 10537 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10538 } 10539 } 10540 } else { 10541 // Invalid install. Return error code 10542 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10543 } 10544 } 10545 } 10546 // All the special cases have been taken care of. 10547 // Return result based on recommended install location. 10548 if (onSd) { 10549 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10550 } 10551 return pkgLite.recommendedInstallLocation; 10552 } 10553 10554 /* 10555 * Invoke remote method to get package information and install 10556 * location values. Override install location based on default 10557 * policy if needed and then create install arguments based 10558 * on the install location. 10559 */ 10560 public void handleStartCopy() throws RemoteException { 10561 int ret = PackageManager.INSTALL_SUCCEEDED; 10562 10563 // If we're already staged, we've firmly committed to an install location 10564 if (origin.staged) { 10565 if (origin.file != null) { 10566 installFlags |= PackageManager.INSTALL_INTERNAL; 10567 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10568 } else if (origin.cid != null) { 10569 installFlags |= PackageManager.INSTALL_EXTERNAL; 10570 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10571 } else { 10572 throw new IllegalStateException("Invalid stage location"); 10573 } 10574 } 10575 10576 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10577 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10578 10579 PackageInfoLite pkgLite = null; 10580 10581 if (onInt && onSd) { 10582 // Check if both bits are set. 10583 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10584 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10585 } else { 10586 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10587 packageAbiOverride); 10588 10589 /* 10590 * If we have too little free space, try to free cache 10591 * before giving up. 10592 */ 10593 if (!origin.staged && pkgLite.recommendedInstallLocation 10594 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10595 // TODO: focus freeing disk space on the target device 10596 final StorageManager storage = StorageManager.from(mContext); 10597 final long lowThreshold = storage.getStorageLowBytes( 10598 Environment.getDataDirectory()); 10599 10600 final long sizeBytes = mContainerService.calculateInstalledSize( 10601 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10602 10603 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10604 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10605 installFlags, packageAbiOverride); 10606 } 10607 10608 /* 10609 * The cache free must have deleted the file we 10610 * downloaded to install. 10611 * 10612 * TODO: fix the "freeCache" call to not delete 10613 * the file we care about. 10614 */ 10615 if (pkgLite.recommendedInstallLocation 10616 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10617 pkgLite.recommendedInstallLocation 10618 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10619 } 10620 } 10621 } 10622 10623 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10624 int loc = pkgLite.recommendedInstallLocation; 10625 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10626 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10627 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10628 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10629 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10630 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10631 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10632 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10633 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10634 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10635 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10636 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10637 } else { 10638 // Override with defaults if needed. 10639 loc = installLocationPolicy(pkgLite); 10640 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10641 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10642 } else if (!onSd && !onInt) { 10643 // Override install location with flags 10644 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10645 // Set the flag to install on external media. 10646 installFlags |= PackageManager.INSTALL_EXTERNAL; 10647 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10648 } else { 10649 // Make sure the flag for installing on external 10650 // media is unset 10651 installFlags |= PackageManager.INSTALL_INTERNAL; 10652 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10653 } 10654 } 10655 } 10656 } 10657 10658 final InstallArgs args = createInstallArgs(this); 10659 mArgs = args; 10660 10661 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10662 /* 10663 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10664 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10665 */ 10666 int userIdentifier = getUser().getIdentifier(); 10667 if (userIdentifier == UserHandle.USER_ALL 10668 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10669 userIdentifier = UserHandle.USER_OWNER; 10670 } 10671 10672 /* 10673 * Determine if we have any installed package verifiers. If we 10674 * do, then we'll defer to them to verify the packages. 10675 */ 10676 final int requiredUid = mRequiredVerifierPackage == null ? -1 10677 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10678 if (!origin.existing && requiredUid != -1 10679 && isVerificationEnabled(userIdentifier, installFlags)) { 10680 final Intent verification = new Intent( 10681 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10682 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10683 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10684 PACKAGE_MIME_TYPE); 10685 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10686 10687 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10688 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10689 0 /* TODO: Which userId? */); 10690 10691 if (DEBUG_VERIFY) { 10692 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10693 + verification.toString() + " with " + pkgLite.verifiers.length 10694 + " optional verifiers"); 10695 } 10696 10697 final int verificationId = mPendingVerificationToken++; 10698 10699 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10700 10701 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10702 installerPackageName); 10703 10704 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10705 installFlags); 10706 10707 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10708 pkgLite.packageName); 10709 10710 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10711 pkgLite.versionCode); 10712 10713 if (verificationParams != null) { 10714 if (verificationParams.getVerificationURI() != null) { 10715 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10716 verificationParams.getVerificationURI()); 10717 } 10718 if (verificationParams.getOriginatingURI() != null) { 10719 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10720 verificationParams.getOriginatingURI()); 10721 } 10722 if (verificationParams.getReferrer() != null) { 10723 verification.putExtra(Intent.EXTRA_REFERRER, 10724 verificationParams.getReferrer()); 10725 } 10726 if (verificationParams.getOriginatingUid() >= 0) { 10727 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10728 verificationParams.getOriginatingUid()); 10729 } 10730 if (verificationParams.getInstallerUid() >= 0) { 10731 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10732 verificationParams.getInstallerUid()); 10733 } 10734 } 10735 10736 final PackageVerificationState verificationState = new PackageVerificationState( 10737 requiredUid, args); 10738 10739 mPendingVerification.append(verificationId, verificationState); 10740 10741 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10742 receivers, verificationState); 10743 10744 // Apps installed for "all" users use the device owner to verify the app 10745 UserHandle verifierUser = getUser(); 10746 if (verifierUser == UserHandle.ALL) { 10747 verifierUser = UserHandle.OWNER; 10748 } 10749 10750 /* 10751 * If any sufficient verifiers were listed in the package 10752 * manifest, attempt to ask them. 10753 */ 10754 if (sufficientVerifiers != null) { 10755 final int N = sufficientVerifiers.size(); 10756 if (N == 0) { 10757 Slog.i(TAG, "Additional verifiers required, but none installed."); 10758 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10759 } else { 10760 for (int i = 0; i < N; i++) { 10761 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10762 10763 final Intent sufficientIntent = new Intent(verification); 10764 sufficientIntent.setComponent(verifierComponent); 10765 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10766 } 10767 } 10768 } 10769 10770 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10771 mRequiredVerifierPackage, receivers); 10772 if (ret == PackageManager.INSTALL_SUCCEEDED 10773 && mRequiredVerifierPackage != null) { 10774 /* 10775 * Send the intent to the required verification agent, 10776 * but only start the verification timeout after the 10777 * target BroadcastReceivers have run. 10778 */ 10779 verification.setComponent(requiredVerifierComponent); 10780 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10781 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10782 new BroadcastReceiver() { 10783 @Override 10784 public void onReceive(Context context, Intent intent) { 10785 final Message msg = mHandler 10786 .obtainMessage(CHECK_PENDING_VERIFICATION); 10787 msg.arg1 = verificationId; 10788 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10789 } 10790 }, null, 0, null, null); 10791 10792 /* 10793 * We don't want the copy to proceed until verification 10794 * succeeds, so null out this field. 10795 */ 10796 mArgs = null; 10797 } 10798 } else { 10799 /* 10800 * No package verification is enabled, so immediately start 10801 * the remote call to initiate copy using temporary file. 10802 */ 10803 ret = args.copyApk(mContainerService, true); 10804 } 10805 } 10806 10807 mRet = ret; 10808 } 10809 10810 @Override 10811 void handleReturnCode() { 10812 // If mArgs is null, then MCS couldn't be reached. When it 10813 // reconnects, it will try again to install. At that point, this 10814 // will succeed. 10815 if (mArgs != null) { 10816 processPendingInstall(mArgs, mRet); 10817 } 10818 } 10819 10820 @Override 10821 void handleServiceError() { 10822 mArgs = createInstallArgs(this); 10823 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10824 } 10825 10826 public boolean isForwardLocked() { 10827 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10828 } 10829 } 10830 10831 /** 10832 * Used during creation of InstallArgs 10833 * 10834 * @param installFlags package installation flags 10835 * @return true if should be installed on external storage 10836 */ 10837 private static boolean installOnExternalAsec(int installFlags) { 10838 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10839 return false; 10840 } 10841 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10842 return true; 10843 } 10844 return false; 10845 } 10846 10847 /** 10848 * Used during creation of InstallArgs 10849 * 10850 * @param installFlags package installation flags 10851 * @return true if should be installed as forward locked 10852 */ 10853 private static boolean installForwardLocked(int installFlags) { 10854 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10855 } 10856 10857 private InstallArgs createInstallArgs(InstallParams params) { 10858 if (params.move != null) { 10859 return new MoveInstallArgs(params); 10860 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10861 return new AsecInstallArgs(params); 10862 } else { 10863 return new FileInstallArgs(params); 10864 } 10865 } 10866 10867 /** 10868 * Create args that describe an existing installed package. Typically used 10869 * when cleaning up old installs, or used as a move source. 10870 */ 10871 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10872 String resourcePath, String[] instructionSets) { 10873 final boolean isInAsec; 10874 if (installOnExternalAsec(installFlags)) { 10875 /* Apps on SD card are always in ASEC containers. */ 10876 isInAsec = true; 10877 } else if (installForwardLocked(installFlags) 10878 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10879 /* 10880 * Forward-locked apps are only in ASEC containers if they're the 10881 * new style 10882 */ 10883 isInAsec = true; 10884 } else { 10885 isInAsec = false; 10886 } 10887 10888 if (isInAsec) { 10889 return new AsecInstallArgs(codePath, instructionSets, 10890 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10891 } else { 10892 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10893 } 10894 } 10895 10896 static abstract class InstallArgs { 10897 /** @see InstallParams#origin */ 10898 final OriginInfo origin; 10899 /** @see InstallParams#move */ 10900 final MoveInfo move; 10901 10902 final IPackageInstallObserver2 observer; 10903 // Always refers to PackageManager flags only 10904 final int installFlags; 10905 final String installerPackageName; 10906 final String volumeUuid; 10907 final ManifestDigest manifestDigest; 10908 final UserHandle user; 10909 final String abiOverride; 10910 final String[] installGrantPermissions; 10911 10912 // The list of instruction sets supported by this app. This is currently 10913 // only used during the rmdex() phase to clean up resources. We can get rid of this 10914 // if we move dex files under the common app path. 10915 /* nullable */ String[] instructionSets; 10916 10917 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10918 int installFlags, String installerPackageName, String volumeUuid, 10919 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10920 String abiOverride, String[] installGrantPermissions) { 10921 this.origin = origin; 10922 this.move = move; 10923 this.installFlags = installFlags; 10924 this.observer = observer; 10925 this.installerPackageName = installerPackageName; 10926 this.volumeUuid = volumeUuid; 10927 this.manifestDigest = manifestDigest; 10928 this.user = user; 10929 this.instructionSets = instructionSets; 10930 this.abiOverride = abiOverride; 10931 this.installGrantPermissions = installGrantPermissions; 10932 } 10933 10934 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10935 abstract int doPreInstall(int status); 10936 10937 /** 10938 * Rename package into final resting place. All paths on the given 10939 * scanned package should be updated to reflect the rename. 10940 */ 10941 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10942 abstract int doPostInstall(int status, int uid); 10943 10944 /** @see PackageSettingBase#codePathString */ 10945 abstract String getCodePath(); 10946 /** @see PackageSettingBase#resourcePathString */ 10947 abstract String getResourcePath(); 10948 10949 // Need installer lock especially for dex file removal. 10950 abstract void cleanUpResourcesLI(); 10951 abstract boolean doPostDeleteLI(boolean delete); 10952 10953 /** 10954 * Called before the source arguments are copied. This is used mostly 10955 * for MoveParams when it needs to read the source file to put it in the 10956 * destination. 10957 */ 10958 int doPreCopy() { 10959 return PackageManager.INSTALL_SUCCEEDED; 10960 } 10961 10962 /** 10963 * Called after the source arguments are copied. This is used mostly for 10964 * MoveParams when it needs to read the source file to put it in the 10965 * destination. 10966 * 10967 * @return 10968 */ 10969 int doPostCopy(int uid) { 10970 return PackageManager.INSTALL_SUCCEEDED; 10971 } 10972 10973 protected boolean isFwdLocked() { 10974 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10975 } 10976 10977 protected boolean isExternalAsec() { 10978 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10979 } 10980 10981 UserHandle getUser() { 10982 return user; 10983 } 10984 } 10985 10986 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10987 if (!allCodePaths.isEmpty()) { 10988 if (instructionSets == null) { 10989 throw new IllegalStateException("instructionSet == null"); 10990 } 10991 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10992 for (String codePath : allCodePaths) { 10993 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10994 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10995 if (retCode < 0) { 10996 Slog.w(TAG, "Couldn't remove dex file for package: " 10997 + " at location " + codePath + ", retcode=" + retCode); 10998 // we don't consider this to be a failure of the core package deletion 10999 } 11000 } 11001 } 11002 } 11003 } 11004 11005 /** 11006 * Logic to handle installation of non-ASEC applications, including copying 11007 * and renaming logic. 11008 */ 11009 class FileInstallArgs extends InstallArgs { 11010 private File codeFile; 11011 private File resourceFile; 11012 11013 // Example topology: 11014 // /data/app/com.example/base.apk 11015 // /data/app/com.example/split_foo.apk 11016 // /data/app/com.example/lib/arm/libfoo.so 11017 // /data/app/com.example/lib/arm64/libfoo.so 11018 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11019 11020 /** New install */ 11021 FileInstallArgs(InstallParams params) { 11022 super(params.origin, params.move, params.observer, params.installFlags, 11023 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11024 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11025 params.grantedRuntimePermissions); 11026 if (isFwdLocked()) { 11027 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11028 } 11029 } 11030 11031 /** Existing install */ 11032 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11033 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11034 null, null); 11035 this.codeFile = (codePath != null) ? new File(codePath) : null; 11036 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11037 } 11038 11039 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11040 if (origin.staged) { 11041 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11042 codeFile = origin.file; 11043 resourceFile = origin.file; 11044 return PackageManager.INSTALL_SUCCEEDED; 11045 } 11046 11047 try { 11048 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11049 codeFile = tempDir; 11050 resourceFile = tempDir; 11051 } catch (IOException e) { 11052 Slog.w(TAG, "Failed to create copy file: " + e); 11053 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11054 } 11055 11056 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11057 @Override 11058 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11059 if (!FileUtils.isValidExtFilename(name)) { 11060 throw new IllegalArgumentException("Invalid filename: " + name); 11061 } 11062 try { 11063 final File file = new File(codeFile, name); 11064 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11065 O_RDWR | O_CREAT, 0644); 11066 Os.chmod(file.getAbsolutePath(), 0644); 11067 return new ParcelFileDescriptor(fd); 11068 } catch (ErrnoException e) { 11069 throw new RemoteException("Failed to open: " + e.getMessage()); 11070 } 11071 } 11072 }; 11073 11074 int ret = PackageManager.INSTALL_SUCCEEDED; 11075 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11076 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11077 Slog.e(TAG, "Failed to copy package"); 11078 return ret; 11079 } 11080 11081 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11082 NativeLibraryHelper.Handle handle = null; 11083 try { 11084 handle = NativeLibraryHelper.Handle.create(codeFile); 11085 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11086 abiOverride); 11087 } catch (IOException e) { 11088 Slog.e(TAG, "Copying native libraries failed", e); 11089 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11090 } finally { 11091 IoUtils.closeQuietly(handle); 11092 } 11093 11094 return ret; 11095 } 11096 11097 int doPreInstall(int status) { 11098 if (status != PackageManager.INSTALL_SUCCEEDED) { 11099 cleanUp(); 11100 } 11101 return status; 11102 } 11103 11104 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11105 if (status != PackageManager.INSTALL_SUCCEEDED) { 11106 cleanUp(); 11107 return false; 11108 } 11109 11110 final File targetDir = codeFile.getParentFile(); 11111 final File beforeCodeFile = codeFile; 11112 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11113 11114 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11115 try { 11116 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11117 } catch (ErrnoException e) { 11118 Slog.w(TAG, "Failed to rename", e); 11119 return false; 11120 } 11121 11122 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11123 Slog.w(TAG, "Failed to restorecon"); 11124 return false; 11125 } 11126 11127 // Reflect the rename internally 11128 codeFile = afterCodeFile; 11129 resourceFile = afterCodeFile; 11130 11131 // Reflect the rename in scanned details 11132 pkg.codePath = afterCodeFile.getAbsolutePath(); 11133 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11134 pkg.baseCodePath); 11135 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11136 pkg.splitCodePaths); 11137 11138 // Reflect the rename in app info 11139 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11140 pkg.applicationInfo.setCodePath(pkg.codePath); 11141 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11142 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11143 pkg.applicationInfo.setResourcePath(pkg.codePath); 11144 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11145 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11146 11147 return true; 11148 } 11149 11150 int doPostInstall(int status, int uid) { 11151 if (status != PackageManager.INSTALL_SUCCEEDED) { 11152 cleanUp(); 11153 } 11154 return status; 11155 } 11156 11157 @Override 11158 String getCodePath() { 11159 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11160 } 11161 11162 @Override 11163 String getResourcePath() { 11164 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11165 } 11166 11167 private boolean cleanUp() { 11168 if (codeFile == null || !codeFile.exists()) { 11169 return false; 11170 } 11171 11172 if (codeFile.isDirectory()) { 11173 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11174 } else { 11175 codeFile.delete(); 11176 } 11177 11178 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11179 resourceFile.delete(); 11180 } 11181 11182 return true; 11183 } 11184 11185 void cleanUpResourcesLI() { 11186 // Try enumerating all code paths before deleting 11187 List<String> allCodePaths = Collections.EMPTY_LIST; 11188 if (codeFile != null && codeFile.exists()) { 11189 try { 11190 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11191 allCodePaths = pkg.getAllCodePaths(); 11192 } catch (PackageParserException e) { 11193 // Ignored; we tried our best 11194 } 11195 } 11196 11197 cleanUp(); 11198 removeDexFiles(allCodePaths, instructionSets); 11199 } 11200 11201 boolean doPostDeleteLI(boolean delete) { 11202 // XXX err, shouldn't we respect the delete flag? 11203 cleanUpResourcesLI(); 11204 return true; 11205 } 11206 } 11207 11208 private boolean isAsecExternal(String cid) { 11209 final String asecPath = PackageHelper.getSdFilesystem(cid); 11210 return !asecPath.startsWith(mAsecInternalPath); 11211 } 11212 11213 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11214 PackageManagerException { 11215 if (copyRet < 0) { 11216 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11217 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11218 throw new PackageManagerException(copyRet, message); 11219 } 11220 } 11221 } 11222 11223 /** 11224 * Extract the MountService "container ID" from the full code path of an 11225 * .apk. 11226 */ 11227 static String cidFromCodePath(String fullCodePath) { 11228 int eidx = fullCodePath.lastIndexOf("/"); 11229 String subStr1 = fullCodePath.substring(0, eidx); 11230 int sidx = subStr1.lastIndexOf("/"); 11231 return subStr1.substring(sidx+1, eidx); 11232 } 11233 11234 /** 11235 * Logic to handle installation of ASEC applications, including copying and 11236 * renaming logic. 11237 */ 11238 class AsecInstallArgs extends InstallArgs { 11239 static final String RES_FILE_NAME = "pkg.apk"; 11240 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11241 11242 String cid; 11243 String packagePath; 11244 String resourcePath; 11245 11246 /** New install */ 11247 AsecInstallArgs(InstallParams params) { 11248 super(params.origin, params.move, params.observer, params.installFlags, 11249 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11250 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11251 params.grantedRuntimePermissions); 11252 } 11253 11254 /** Existing install */ 11255 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11256 boolean isExternal, boolean isForwardLocked) { 11257 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11258 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11259 instructionSets, null, null); 11260 // Hackily pretend we're still looking at a full code path 11261 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11262 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11263 } 11264 11265 // Extract cid from fullCodePath 11266 int eidx = fullCodePath.lastIndexOf("/"); 11267 String subStr1 = fullCodePath.substring(0, eidx); 11268 int sidx = subStr1.lastIndexOf("/"); 11269 cid = subStr1.substring(sidx+1, eidx); 11270 setMountPath(subStr1); 11271 } 11272 11273 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11274 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11275 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11276 instructionSets, null, null); 11277 this.cid = cid; 11278 setMountPath(PackageHelper.getSdDir(cid)); 11279 } 11280 11281 void createCopyFile() { 11282 cid = mInstallerService.allocateExternalStageCidLegacy(); 11283 } 11284 11285 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11286 if (origin.staged) { 11287 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11288 cid = origin.cid; 11289 setMountPath(PackageHelper.getSdDir(cid)); 11290 return PackageManager.INSTALL_SUCCEEDED; 11291 } 11292 11293 if (temp) { 11294 createCopyFile(); 11295 } else { 11296 /* 11297 * Pre-emptively destroy the container since it's destroyed if 11298 * copying fails due to it existing anyway. 11299 */ 11300 PackageHelper.destroySdDir(cid); 11301 } 11302 11303 final String newMountPath = imcs.copyPackageToContainer( 11304 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11305 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11306 11307 if (newMountPath != null) { 11308 setMountPath(newMountPath); 11309 return PackageManager.INSTALL_SUCCEEDED; 11310 } else { 11311 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11312 } 11313 } 11314 11315 @Override 11316 String getCodePath() { 11317 return packagePath; 11318 } 11319 11320 @Override 11321 String getResourcePath() { 11322 return resourcePath; 11323 } 11324 11325 int doPreInstall(int status) { 11326 if (status != PackageManager.INSTALL_SUCCEEDED) { 11327 // Destroy container 11328 PackageHelper.destroySdDir(cid); 11329 } else { 11330 boolean mounted = PackageHelper.isContainerMounted(cid); 11331 if (!mounted) { 11332 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11333 Process.SYSTEM_UID); 11334 if (newMountPath != null) { 11335 setMountPath(newMountPath); 11336 } else { 11337 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11338 } 11339 } 11340 } 11341 return status; 11342 } 11343 11344 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11345 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11346 String newMountPath = null; 11347 if (PackageHelper.isContainerMounted(cid)) { 11348 // Unmount the container 11349 if (!PackageHelper.unMountSdDir(cid)) { 11350 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11351 return false; 11352 } 11353 } 11354 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11355 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11356 " which might be stale. Will try to clean up."); 11357 // Clean up the stale container and proceed to recreate. 11358 if (!PackageHelper.destroySdDir(newCacheId)) { 11359 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11360 return false; 11361 } 11362 // Successfully cleaned up stale container. Try to rename again. 11363 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11364 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11365 + " inspite of cleaning it up."); 11366 return false; 11367 } 11368 } 11369 if (!PackageHelper.isContainerMounted(newCacheId)) { 11370 Slog.w(TAG, "Mounting container " + newCacheId); 11371 newMountPath = PackageHelper.mountSdDir(newCacheId, 11372 getEncryptKey(), Process.SYSTEM_UID); 11373 } else { 11374 newMountPath = PackageHelper.getSdDir(newCacheId); 11375 } 11376 if (newMountPath == null) { 11377 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11378 return false; 11379 } 11380 Log.i(TAG, "Succesfully renamed " + cid + 11381 " to " + newCacheId + 11382 " at new path: " + newMountPath); 11383 cid = newCacheId; 11384 11385 final File beforeCodeFile = new File(packagePath); 11386 setMountPath(newMountPath); 11387 final File afterCodeFile = new File(packagePath); 11388 11389 // Reflect the rename in scanned details 11390 pkg.codePath = afterCodeFile.getAbsolutePath(); 11391 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11392 pkg.baseCodePath); 11393 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11394 pkg.splitCodePaths); 11395 11396 // Reflect the rename in app info 11397 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11398 pkg.applicationInfo.setCodePath(pkg.codePath); 11399 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11400 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11401 pkg.applicationInfo.setResourcePath(pkg.codePath); 11402 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11403 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11404 11405 return true; 11406 } 11407 11408 private void setMountPath(String mountPath) { 11409 final File mountFile = new File(mountPath); 11410 11411 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11412 if (monolithicFile.exists()) { 11413 packagePath = monolithicFile.getAbsolutePath(); 11414 if (isFwdLocked()) { 11415 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11416 } else { 11417 resourcePath = packagePath; 11418 } 11419 } else { 11420 packagePath = mountFile.getAbsolutePath(); 11421 resourcePath = packagePath; 11422 } 11423 } 11424 11425 int doPostInstall(int status, int uid) { 11426 if (status != PackageManager.INSTALL_SUCCEEDED) { 11427 cleanUp(); 11428 } else { 11429 final int groupOwner; 11430 final String protectedFile; 11431 if (isFwdLocked()) { 11432 groupOwner = UserHandle.getSharedAppGid(uid); 11433 protectedFile = RES_FILE_NAME; 11434 } else { 11435 groupOwner = -1; 11436 protectedFile = null; 11437 } 11438 11439 if (uid < Process.FIRST_APPLICATION_UID 11440 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11441 Slog.e(TAG, "Failed to finalize " + cid); 11442 PackageHelper.destroySdDir(cid); 11443 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11444 } 11445 11446 boolean mounted = PackageHelper.isContainerMounted(cid); 11447 if (!mounted) { 11448 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11449 } 11450 } 11451 return status; 11452 } 11453 11454 private void cleanUp() { 11455 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11456 11457 // Destroy secure container 11458 PackageHelper.destroySdDir(cid); 11459 } 11460 11461 private List<String> getAllCodePaths() { 11462 final File codeFile = new File(getCodePath()); 11463 if (codeFile != null && codeFile.exists()) { 11464 try { 11465 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11466 return pkg.getAllCodePaths(); 11467 } catch (PackageParserException e) { 11468 // Ignored; we tried our best 11469 } 11470 } 11471 return Collections.EMPTY_LIST; 11472 } 11473 11474 void cleanUpResourcesLI() { 11475 // Enumerate all code paths before deleting 11476 cleanUpResourcesLI(getAllCodePaths()); 11477 } 11478 11479 private void cleanUpResourcesLI(List<String> allCodePaths) { 11480 cleanUp(); 11481 removeDexFiles(allCodePaths, instructionSets); 11482 } 11483 11484 String getPackageName() { 11485 return getAsecPackageName(cid); 11486 } 11487 11488 boolean doPostDeleteLI(boolean delete) { 11489 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11490 final List<String> allCodePaths = getAllCodePaths(); 11491 boolean mounted = PackageHelper.isContainerMounted(cid); 11492 if (mounted) { 11493 // Unmount first 11494 if (PackageHelper.unMountSdDir(cid)) { 11495 mounted = false; 11496 } 11497 } 11498 if (!mounted && delete) { 11499 cleanUpResourcesLI(allCodePaths); 11500 } 11501 return !mounted; 11502 } 11503 11504 @Override 11505 int doPreCopy() { 11506 if (isFwdLocked()) { 11507 if (!PackageHelper.fixSdPermissions(cid, 11508 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11509 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11510 } 11511 } 11512 11513 return PackageManager.INSTALL_SUCCEEDED; 11514 } 11515 11516 @Override 11517 int doPostCopy(int uid) { 11518 if (isFwdLocked()) { 11519 if (uid < Process.FIRST_APPLICATION_UID 11520 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11521 RES_FILE_NAME)) { 11522 Slog.e(TAG, "Failed to finalize " + cid); 11523 PackageHelper.destroySdDir(cid); 11524 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11525 } 11526 } 11527 11528 return PackageManager.INSTALL_SUCCEEDED; 11529 } 11530 } 11531 11532 /** 11533 * Logic to handle movement of existing installed applications. 11534 */ 11535 class MoveInstallArgs extends InstallArgs { 11536 private File codeFile; 11537 private File resourceFile; 11538 11539 /** New install */ 11540 MoveInstallArgs(InstallParams params) { 11541 super(params.origin, params.move, params.observer, params.installFlags, 11542 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11543 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11544 params.grantedRuntimePermissions); 11545 } 11546 11547 int copyApk(IMediaContainerService imcs, boolean temp) { 11548 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11549 + move.fromUuid + " to " + move.toUuid); 11550 synchronized (mInstaller) { 11551 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11552 move.dataAppName, move.appId, move.seinfo) != 0) { 11553 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11554 } 11555 } 11556 11557 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11558 resourceFile = codeFile; 11559 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11560 11561 return PackageManager.INSTALL_SUCCEEDED; 11562 } 11563 11564 int doPreInstall(int status) { 11565 if (status != PackageManager.INSTALL_SUCCEEDED) { 11566 cleanUp(move.toUuid); 11567 } 11568 return status; 11569 } 11570 11571 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11572 if (status != PackageManager.INSTALL_SUCCEEDED) { 11573 cleanUp(move.toUuid); 11574 return false; 11575 } 11576 11577 // Reflect the move in app info 11578 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11579 pkg.applicationInfo.setCodePath(pkg.codePath); 11580 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11581 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11582 pkg.applicationInfo.setResourcePath(pkg.codePath); 11583 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11584 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11585 11586 return true; 11587 } 11588 11589 int doPostInstall(int status, int uid) { 11590 if (status == PackageManager.INSTALL_SUCCEEDED) { 11591 cleanUp(move.fromUuid); 11592 } else { 11593 cleanUp(move.toUuid); 11594 } 11595 return status; 11596 } 11597 11598 @Override 11599 String getCodePath() { 11600 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11601 } 11602 11603 @Override 11604 String getResourcePath() { 11605 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11606 } 11607 11608 private boolean cleanUp(String volumeUuid) { 11609 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11610 move.dataAppName); 11611 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11612 synchronized (mInstallLock) { 11613 // Clean up both app data and code 11614 removeDataDirsLI(volumeUuid, move.packageName); 11615 if (codeFile.isDirectory()) { 11616 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11617 } else { 11618 codeFile.delete(); 11619 } 11620 } 11621 return true; 11622 } 11623 11624 void cleanUpResourcesLI() { 11625 throw new UnsupportedOperationException(); 11626 } 11627 11628 boolean doPostDeleteLI(boolean delete) { 11629 throw new UnsupportedOperationException(); 11630 } 11631 } 11632 11633 static String getAsecPackageName(String packageCid) { 11634 int idx = packageCid.lastIndexOf("-"); 11635 if (idx == -1) { 11636 return packageCid; 11637 } 11638 return packageCid.substring(0, idx); 11639 } 11640 11641 // Utility method used to create code paths based on package name and available index. 11642 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11643 String idxStr = ""; 11644 int idx = 1; 11645 // Fall back to default value of idx=1 if prefix is not 11646 // part of oldCodePath 11647 if (oldCodePath != null) { 11648 String subStr = oldCodePath; 11649 // Drop the suffix right away 11650 if (suffix != null && subStr.endsWith(suffix)) { 11651 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11652 } 11653 // If oldCodePath already contains prefix find out the 11654 // ending index to either increment or decrement. 11655 int sidx = subStr.lastIndexOf(prefix); 11656 if (sidx != -1) { 11657 subStr = subStr.substring(sidx + prefix.length()); 11658 if (subStr != null) { 11659 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11660 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11661 } 11662 try { 11663 idx = Integer.parseInt(subStr); 11664 if (idx <= 1) { 11665 idx++; 11666 } else { 11667 idx--; 11668 } 11669 } catch(NumberFormatException e) { 11670 } 11671 } 11672 } 11673 } 11674 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11675 return prefix + idxStr; 11676 } 11677 11678 private File getNextCodePath(File targetDir, String packageName) { 11679 int suffix = 1; 11680 File result; 11681 do { 11682 result = new File(targetDir, packageName + "-" + suffix); 11683 suffix++; 11684 } while (result.exists()); 11685 return result; 11686 } 11687 11688 // Utility method that returns the relative package path with respect 11689 // to the installation directory. Like say for /data/data/com.test-1.apk 11690 // string com.test-1 is returned. 11691 static String deriveCodePathName(String codePath) { 11692 if (codePath == null) { 11693 return null; 11694 } 11695 final File codeFile = new File(codePath); 11696 final String name = codeFile.getName(); 11697 if (codeFile.isDirectory()) { 11698 return name; 11699 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11700 final int lastDot = name.lastIndexOf('.'); 11701 return name.substring(0, lastDot); 11702 } else { 11703 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11704 return null; 11705 } 11706 } 11707 11708 class PackageInstalledInfo { 11709 String name; 11710 int uid; 11711 // The set of users that originally had this package installed. 11712 int[] origUsers; 11713 // The set of users that now have this package installed. 11714 int[] newUsers; 11715 PackageParser.Package pkg; 11716 int returnCode; 11717 String returnMsg; 11718 PackageRemovedInfo removedInfo; 11719 11720 public void setError(int code, String msg) { 11721 returnCode = code; 11722 returnMsg = msg; 11723 Slog.w(TAG, msg); 11724 } 11725 11726 public void setError(String msg, PackageParserException e) { 11727 returnCode = e.error; 11728 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11729 Slog.w(TAG, msg, e); 11730 } 11731 11732 public void setError(String msg, PackageManagerException e) { 11733 returnCode = e.error; 11734 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11735 Slog.w(TAG, msg, e); 11736 } 11737 11738 // In some error cases we want to convey more info back to the observer 11739 String origPackage; 11740 String origPermission; 11741 } 11742 11743 /* 11744 * Install a non-existing package. 11745 */ 11746 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11747 UserHandle user, String installerPackageName, String volumeUuid, 11748 PackageInstalledInfo res) { 11749 // Remember this for later, in case we need to rollback this install 11750 String pkgName = pkg.packageName; 11751 11752 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11753 final boolean dataDirExists = Environment 11754 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11755 synchronized(mPackages) { 11756 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11757 // A package with the same name is already installed, though 11758 // it has been renamed to an older name. The package we 11759 // are trying to install should be installed as an update to 11760 // the existing one, but that has not been requested, so bail. 11761 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11762 + " without first uninstalling package running as " 11763 + mSettings.mRenamedPackages.get(pkgName)); 11764 return; 11765 } 11766 if (mPackages.containsKey(pkgName)) { 11767 // Don't allow installation over an existing package with the same name. 11768 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11769 + " without first uninstalling."); 11770 return; 11771 } 11772 } 11773 11774 try { 11775 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11776 System.currentTimeMillis(), user); 11777 11778 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11779 // delete the partially installed application. the data directory will have to be 11780 // restored if it was already existing 11781 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11782 // remove package from internal structures. Note that we want deletePackageX to 11783 // delete the package data and cache directories that it created in 11784 // scanPackageLocked, unless those directories existed before we even tried to 11785 // install. 11786 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11787 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11788 res.removedInfo, true); 11789 } 11790 11791 } catch (PackageManagerException e) { 11792 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11793 } 11794 } 11795 11796 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11797 // Can't rotate keys during boot or if sharedUser. 11798 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11799 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11800 return false; 11801 } 11802 // app is using upgradeKeySets; make sure all are valid 11803 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11804 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11805 for (int i = 0; i < upgradeKeySets.length; i++) { 11806 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11807 Slog.wtf(TAG, "Package " 11808 + (oldPs.name != null ? oldPs.name : "<null>") 11809 + " contains upgrade-key-set reference to unknown key-set: " 11810 + upgradeKeySets[i] 11811 + " reverting to signatures check."); 11812 return false; 11813 } 11814 } 11815 return true; 11816 } 11817 11818 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11819 // Upgrade keysets are being used. Determine if new package has a superset of the 11820 // required keys. 11821 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11822 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11823 for (int i = 0; i < upgradeKeySets.length; i++) { 11824 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11825 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11826 return true; 11827 } 11828 } 11829 return false; 11830 } 11831 11832 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11833 UserHandle user, String installerPackageName, String volumeUuid, 11834 PackageInstalledInfo res) { 11835 final PackageParser.Package oldPackage; 11836 final String pkgName = pkg.packageName; 11837 final int[] allUsers; 11838 final boolean[] perUserInstalled; 11839 11840 // First find the old package info and check signatures 11841 synchronized(mPackages) { 11842 oldPackage = mPackages.get(pkgName); 11843 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11844 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11845 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11846 if(!checkUpgradeKeySetLP(ps, pkg)) { 11847 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11848 "New package not signed by keys specified by upgrade-keysets: " 11849 + pkgName); 11850 return; 11851 } 11852 } else { 11853 // default to original signature matching 11854 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11855 != PackageManager.SIGNATURE_MATCH) { 11856 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11857 "New package has a different signature: " + pkgName); 11858 return; 11859 } 11860 } 11861 11862 // In case of rollback, remember per-user/profile install state 11863 allUsers = sUserManager.getUserIds(); 11864 perUserInstalled = new boolean[allUsers.length]; 11865 for (int i = 0; i < allUsers.length; i++) { 11866 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11867 } 11868 } 11869 11870 boolean sysPkg = (isSystemApp(oldPackage)); 11871 if (sysPkg) { 11872 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11873 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11874 } else { 11875 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11876 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11877 } 11878 } 11879 11880 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11881 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11882 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11883 String volumeUuid, PackageInstalledInfo res) { 11884 String pkgName = deletedPackage.packageName; 11885 boolean deletedPkg = true; 11886 boolean updatedSettings = false; 11887 11888 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11889 + deletedPackage); 11890 long origUpdateTime; 11891 if (pkg.mExtras != null) { 11892 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11893 } else { 11894 origUpdateTime = 0; 11895 } 11896 11897 // First delete the existing package while retaining the data directory 11898 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11899 res.removedInfo, true)) { 11900 // If the existing package wasn't successfully deleted 11901 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11902 deletedPkg = false; 11903 } else { 11904 // Successfully deleted the old package; proceed with replace. 11905 11906 // If deleted package lived in a container, give users a chance to 11907 // relinquish resources before killing. 11908 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11909 if (DEBUG_INSTALL) { 11910 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11911 } 11912 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11913 final ArrayList<String> pkgList = new ArrayList<String>(1); 11914 pkgList.add(deletedPackage.applicationInfo.packageName); 11915 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11916 } 11917 11918 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11919 try { 11920 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11921 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11922 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11923 perUserInstalled, res, user); 11924 updatedSettings = true; 11925 } catch (PackageManagerException e) { 11926 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11927 } 11928 } 11929 11930 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11931 // remove package from internal structures. Note that we want deletePackageX to 11932 // delete the package data and cache directories that it created in 11933 // scanPackageLocked, unless those directories existed before we even tried to 11934 // install. 11935 if(updatedSettings) { 11936 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11937 deletePackageLI( 11938 pkgName, null, true, allUsers, perUserInstalled, 11939 PackageManager.DELETE_KEEP_DATA, 11940 res.removedInfo, true); 11941 } 11942 // Since we failed to install the new package we need to restore the old 11943 // package that we deleted. 11944 if (deletedPkg) { 11945 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11946 File restoreFile = new File(deletedPackage.codePath); 11947 // Parse old package 11948 boolean oldExternal = isExternal(deletedPackage); 11949 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11950 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11951 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11952 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11953 try { 11954 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11955 } catch (PackageManagerException e) { 11956 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11957 + e.getMessage()); 11958 return; 11959 } 11960 // Restore of old package succeeded. Update permissions. 11961 // writer 11962 synchronized (mPackages) { 11963 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11964 UPDATE_PERMISSIONS_ALL); 11965 // can downgrade to reader 11966 mSettings.writeLPr(); 11967 } 11968 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11969 } 11970 } 11971 } 11972 11973 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11974 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11975 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11976 String volumeUuid, PackageInstalledInfo res) { 11977 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11978 + ", old=" + deletedPackage); 11979 boolean disabledSystem = false; 11980 boolean updatedSettings = false; 11981 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11982 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11983 != 0) { 11984 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11985 } 11986 String packageName = deletedPackage.packageName; 11987 if (packageName == null) { 11988 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11989 "Attempt to delete null packageName."); 11990 return; 11991 } 11992 PackageParser.Package oldPkg; 11993 PackageSetting oldPkgSetting; 11994 // reader 11995 synchronized (mPackages) { 11996 oldPkg = mPackages.get(packageName); 11997 oldPkgSetting = mSettings.mPackages.get(packageName); 11998 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11999 (oldPkgSetting == null)) { 12000 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12001 "Couldn't find package:" + packageName + " information"); 12002 return; 12003 } 12004 } 12005 12006 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12007 12008 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12009 res.removedInfo.removedPackage = packageName; 12010 // Remove existing system package 12011 removePackageLI(oldPkgSetting, true); 12012 // writer 12013 synchronized (mPackages) { 12014 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12015 if (!disabledSystem && deletedPackage != null) { 12016 // We didn't need to disable the .apk as a current system package, 12017 // which means we are replacing another update that is already 12018 // installed. We need to make sure to delete the older one's .apk. 12019 res.removedInfo.args = createInstallArgsForExisting(0, 12020 deletedPackage.applicationInfo.getCodePath(), 12021 deletedPackage.applicationInfo.getResourcePath(), 12022 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12023 } else { 12024 res.removedInfo.args = null; 12025 } 12026 } 12027 12028 // Successfully disabled the old package. Now proceed with re-installation 12029 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12030 12031 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12032 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12033 12034 PackageParser.Package newPackage = null; 12035 try { 12036 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 12037 if (newPackage.mExtras != null) { 12038 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12039 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12040 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12041 12042 // is the update attempting to change shared user? that isn't going to work... 12043 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12044 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12045 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12046 + " to " + newPkgSetting.sharedUser); 12047 updatedSettings = true; 12048 } 12049 } 12050 12051 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12052 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12053 perUserInstalled, res, user); 12054 updatedSettings = true; 12055 } 12056 12057 } catch (PackageManagerException e) { 12058 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12059 } 12060 12061 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12062 // Re installation failed. Restore old information 12063 // Remove new pkg information 12064 if (newPackage != null) { 12065 removeInstalledPackageLI(newPackage, true); 12066 } 12067 // Add back the old system package 12068 try { 12069 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12070 } catch (PackageManagerException e) { 12071 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12072 } 12073 // Restore the old system information in Settings 12074 synchronized (mPackages) { 12075 if (disabledSystem) { 12076 mSettings.enableSystemPackageLPw(packageName); 12077 } 12078 if (updatedSettings) { 12079 mSettings.setInstallerPackageName(packageName, 12080 oldPkgSetting.installerPackageName); 12081 } 12082 mSettings.writeLPr(); 12083 } 12084 } 12085 } 12086 12087 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12088 // Collect all used permissions in the UID 12089 ArraySet<String> usedPermissions = new ArraySet<>(); 12090 final int packageCount = su.packages.size(); 12091 for (int i = 0; i < packageCount; i++) { 12092 PackageSetting ps = su.packages.valueAt(i); 12093 if (ps.pkg == null) { 12094 continue; 12095 } 12096 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12097 for (int j = 0; j < requestedPermCount; j++) { 12098 String permission = ps.pkg.requestedPermissions.get(j); 12099 BasePermission bp = mSettings.mPermissions.get(permission); 12100 if (bp != null) { 12101 usedPermissions.add(permission); 12102 } 12103 } 12104 } 12105 12106 PermissionsState permissionsState = su.getPermissionsState(); 12107 // Prune install permissions 12108 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12109 final int installPermCount = installPermStates.size(); 12110 for (int i = installPermCount - 1; i >= 0; i--) { 12111 PermissionState permissionState = installPermStates.get(i); 12112 if (!usedPermissions.contains(permissionState.getName())) { 12113 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12114 if (bp != null) { 12115 permissionsState.revokeInstallPermission(bp); 12116 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12117 PackageManager.MASK_PERMISSION_FLAGS, 0); 12118 } 12119 } 12120 } 12121 12122 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12123 12124 // Prune runtime permissions 12125 for (int userId : allUserIds) { 12126 List<PermissionState> runtimePermStates = permissionsState 12127 .getRuntimePermissionStates(userId); 12128 final int runtimePermCount = runtimePermStates.size(); 12129 for (int i = runtimePermCount - 1; i >= 0; i--) { 12130 PermissionState permissionState = runtimePermStates.get(i); 12131 if (!usedPermissions.contains(permissionState.getName())) { 12132 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12133 if (bp != null) { 12134 permissionsState.revokeRuntimePermission(bp, userId); 12135 permissionsState.updatePermissionFlags(bp, userId, 12136 PackageManager.MASK_PERMISSION_FLAGS, 0); 12137 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12138 runtimePermissionChangedUserIds, userId); 12139 } 12140 } 12141 } 12142 } 12143 12144 return runtimePermissionChangedUserIds; 12145 } 12146 12147 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12148 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12149 UserHandle user) { 12150 String pkgName = newPackage.packageName; 12151 synchronized (mPackages) { 12152 //write settings. the installStatus will be incomplete at this stage. 12153 //note that the new package setting would have already been 12154 //added to mPackages. It hasn't been persisted yet. 12155 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12156 mSettings.writeLPr(); 12157 } 12158 12159 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12160 12161 synchronized (mPackages) { 12162 updatePermissionsLPw(newPackage.packageName, newPackage, 12163 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12164 ? UPDATE_PERMISSIONS_ALL : 0)); 12165 // For system-bundled packages, we assume that installing an upgraded version 12166 // of the package implies that the user actually wants to run that new code, 12167 // so we enable the package. 12168 PackageSetting ps = mSettings.mPackages.get(pkgName); 12169 if (ps != null) { 12170 if (isSystemApp(newPackage)) { 12171 // NB: implicit assumption that system package upgrades apply to all users 12172 if (DEBUG_INSTALL) { 12173 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12174 } 12175 if (res.origUsers != null) { 12176 for (int userHandle : res.origUsers) { 12177 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12178 userHandle, installerPackageName); 12179 } 12180 } 12181 // Also convey the prior install/uninstall state 12182 if (allUsers != null && perUserInstalled != null) { 12183 for (int i = 0; i < allUsers.length; i++) { 12184 if (DEBUG_INSTALL) { 12185 Slog.d(TAG, " user " + allUsers[i] 12186 + " => " + perUserInstalled[i]); 12187 } 12188 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12189 } 12190 // these install state changes will be persisted in the 12191 // upcoming call to mSettings.writeLPr(). 12192 } 12193 } 12194 // It's implied that when a user requests installation, they want the app to be 12195 // installed and enabled. 12196 int userId = user.getIdentifier(); 12197 if (userId != UserHandle.USER_ALL) { 12198 ps.setInstalled(true, userId); 12199 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12200 } 12201 } 12202 res.name = pkgName; 12203 res.uid = newPackage.applicationInfo.uid; 12204 res.pkg = newPackage; 12205 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12206 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12207 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12208 //to update install status 12209 mSettings.writeLPr(); 12210 } 12211 } 12212 12213 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12214 final int installFlags = args.installFlags; 12215 final String installerPackageName = args.installerPackageName; 12216 final String volumeUuid = args.volumeUuid; 12217 final File tmpPackageFile = new File(args.getCodePath()); 12218 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12219 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12220 || (args.volumeUuid != null)); 12221 boolean replace = false; 12222 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12223 if (args.move != null) { 12224 // moving a complete application; perfom an initial scan on the new install location 12225 scanFlags |= SCAN_INITIAL; 12226 } 12227 // Result object to be returned 12228 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12229 12230 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12231 // Retrieve PackageSettings and parse package 12232 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12233 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12234 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12235 PackageParser pp = new PackageParser(); 12236 pp.setSeparateProcesses(mSeparateProcesses); 12237 pp.setDisplayMetrics(mMetrics); 12238 12239 final PackageParser.Package pkg; 12240 try { 12241 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12242 } catch (PackageParserException e) { 12243 res.setError("Failed parse during installPackageLI", e); 12244 return; 12245 } 12246 12247 // Mark that we have an install time CPU ABI override. 12248 pkg.cpuAbiOverride = args.abiOverride; 12249 12250 String pkgName = res.name = pkg.packageName; 12251 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12252 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12253 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12254 return; 12255 } 12256 } 12257 12258 try { 12259 pp.collectCertificates(pkg, parseFlags); 12260 pp.collectManifestDigest(pkg); 12261 } catch (PackageParserException e) { 12262 res.setError("Failed collect during installPackageLI", e); 12263 return; 12264 } 12265 12266 /* If the installer passed in a manifest digest, compare it now. */ 12267 if (args.manifestDigest != null) { 12268 if (DEBUG_INSTALL) { 12269 final String parsedManifest = pkg.manifestDigest == null ? "null" 12270 : pkg.manifestDigest.toString(); 12271 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12272 + parsedManifest); 12273 } 12274 12275 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12276 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12277 return; 12278 } 12279 } else if (DEBUG_INSTALL) { 12280 final String parsedManifest = pkg.manifestDigest == null 12281 ? "null" : pkg.manifestDigest.toString(); 12282 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12283 } 12284 12285 // Get rid of all references to package scan path via parser. 12286 pp = null; 12287 String oldCodePath = null; 12288 boolean systemApp = false; 12289 synchronized (mPackages) { 12290 // Check if installing already existing package 12291 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12292 String oldName = mSettings.mRenamedPackages.get(pkgName); 12293 if (pkg.mOriginalPackages != null 12294 && pkg.mOriginalPackages.contains(oldName) 12295 && mPackages.containsKey(oldName)) { 12296 // This package is derived from an original package, 12297 // and this device has been updating from that original 12298 // name. We must continue using the original name, so 12299 // rename the new package here. 12300 pkg.setPackageName(oldName); 12301 pkgName = pkg.packageName; 12302 replace = true; 12303 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12304 + oldName + " pkgName=" + pkgName); 12305 } else if (mPackages.containsKey(pkgName)) { 12306 // This package, under its official name, already exists 12307 // on the device; we should replace it. 12308 replace = true; 12309 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12310 } 12311 12312 // Prevent apps opting out from runtime permissions 12313 if (replace) { 12314 PackageParser.Package oldPackage = mPackages.get(pkgName); 12315 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12316 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12317 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12318 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12319 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12320 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12321 + " doesn't support runtime permissions but the old" 12322 + " target SDK " + oldTargetSdk + " does."); 12323 return; 12324 } 12325 } 12326 } 12327 12328 PackageSetting ps = mSettings.mPackages.get(pkgName); 12329 if (ps != null) { 12330 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12331 12332 // Quick sanity check that we're signed correctly if updating; 12333 // we'll check this again later when scanning, but we want to 12334 // bail early here before tripping over redefined permissions. 12335 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12336 if (!checkUpgradeKeySetLP(ps, pkg)) { 12337 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12338 + pkg.packageName + " upgrade keys do not match the " 12339 + "previously installed version"); 12340 return; 12341 } 12342 } else { 12343 try { 12344 verifySignaturesLP(ps, pkg); 12345 } catch (PackageManagerException e) { 12346 res.setError(e.error, e.getMessage()); 12347 return; 12348 } 12349 } 12350 12351 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12352 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12353 systemApp = (ps.pkg.applicationInfo.flags & 12354 ApplicationInfo.FLAG_SYSTEM) != 0; 12355 } 12356 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12357 } 12358 12359 // Check whether the newly-scanned package wants to define an already-defined perm 12360 int N = pkg.permissions.size(); 12361 for (int i = N-1; i >= 0; i--) { 12362 PackageParser.Permission perm = pkg.permissions.get(i); 12363 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12364 if (bp != null) { 12365 // If the defining package is signed with our cert, it's okay. This 12366 // also includes the "updating the same package" case, of course. 12367 // "updating same package" could also involve key-rotation. 12368 final boolean sigsOk; 12369 if (bp.sourcePackage.equals(pkg.packageName) 12370 && (bp.packageSetting instanceof PackageSetting) 12371 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12372 scanFlags))) { 12373 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12374 } else { 12375 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12376 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12377 } 12378 if (!sigsOk) { 12379 // If the owning package is the system itself, we log but allow 12380 // install to proceed; we fail the install on all other permission 12381 // redefinitions. 12382 if (!bp.sourcePackage.equals("android")) { 12383 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12384 + pkg.packageName + " attempting to redeclare permission " 12385 + perm.info.name + " already owned by " + bp.sourcePackage); 12386 res.origPermission = perm.info.name; 12387 res.origPackage = bp.sourcePackage; 12388 return; 12389 } else { 12390 Slog.w(TAG, "Package " + pkg.packageName 12391 + " attempting to redeclare system permission " 12392 + perm.info.name + "; ignoring new declaration"); 12393 pkg.permissions.remove(i); 12394 } 12395 } 12396 } 12397 } 12398 12399 } 12400 12401 if (systemApp && onExternal) { 12402 // Disable updates to system apps on sdcard 12403 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12404 "Cannot install updates to system apps on sdcard"); 12405 return; 12406 } 12407 12408 if (args.move != null) { 12409 // We did an in-place move, so dex is ready to roll 12410 scanFlags |= SCAN_NO_DEX; 12411 scanFlags |= SCAN_MOVE; 12412 12413 synchronized (mPackages) { 12414 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12415 if (ps == null) { 12416 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12417 "Missing settings for moved package " + pkgName); 12418 } 12419 12420 // We moved the entire application as-is, so bring over the 12421 // previously derived ABI information. 12422 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12423 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12424 } 12425 12426 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12427 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12428 scanFlags |= SCAN_NO_DEX; 12429 12430 try { 12431 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12432 true /* extract libs */); 12433 } catch (PackageManagerException pme) { 12434 Slog.e(TAG, "Error deriving application ABI", pme); 12435 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12436 return; 12437 } 12438 12439 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12440 int result = mPackageDexOptimizer 12441 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12442 false /* defer */, false /* inclDependencies */, 12443 true /*bootComplete*/, false /*useJit*/); 12444 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12445 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12446 return; 12447 } 12448 } 12449 12450 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12451 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12452 return; 12453 } 12454 12455 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12456 12457 if (replace) { 12458 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12459 installerPackageName, volumeUuid, res); 12460 } else { 12461 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12462 args.user, installerPackageName, volumeUuid, res); 12463 } 12464 synchronized (mPackages) { 12465 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12466 if (ps != null) { 12467 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12468 } 12469 } 12470 } 12471 12472 private void startIntentFilterVerifications(int userId, boolean replacing, 12473 PackageParser.Package pkg) { 12474 if (mIntentFilterVerifierComponent == null) { 12475 Slog.w(TAG, "No IntentFilter verification will not be done as " 12476 + "there is no IntentFilterVerifier available!"); 12477 return; 12478 } 12479 12480 final int verifierUid = getPackageUid( 12481 mIntentFilterVerifierComponent.getPackageName(), 12482 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12483 12484 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12485 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12486 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12487 mHandler.sendMessage(msg); 12488 } 12489 12490 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12491 PackageParser.Package pkg) { 12492 int size = pkg.activities.size(); 12493 if (size == 0) { 12494 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12495 "No activity, so no need to verify any IntentFilter!"); 12496 return; 12497 } 12498 12499 final boolean hasDomainURLs = hasDomainURLs(pkg); 12500 if (!hasDomainURLs) { 12501 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12502 "No domain URLs, so no need to verify any IntentFilter!"); 12503 return; 12504 } 12505 12506 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12507 + " if any IntentFilter from the " + size 12508 + " Activities needs verification ..."); 12509 12510 int count = 0; 12511 final String packageName = pkg.packageName; 12512 12513 synchronized (mPackages) { 12514 // If this is a new install and we see that we've already run verification for this 12515 // package, we have nothing to do: it means the state was restored from backup. 12516 if (!replacing) { 12517 IntentFilterVerificationInfo ivi = 12518 mSettings.getIntentFilterVerificationLPr(packageName); 12519 if (ivi != null) { 12520 if (DEBUG_DOMAIN_VERIFICATION) { 12521 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12522 + ivi.getStatusString()); 12523 } 12524 return; 12525 } 12526 } 12527 12528 // If any filters need to be verified, then all need to be. 12529 boolean needToVerify = false; 12530 for (PackageParser.Activity a : pkg.activities) { 12531 for (ActivityIntentInfo filter : a.intents) { 12532 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12533 if (DEBUG_DOMAIN_VERIFICATION) { 12534 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12535 } 12536 needToVerify = true; 12537 break; 12538 } 12539 } 12540 } 12541 12542 if (needToVerify) { 12543 final int verificationId = mIntentFilterVerificationToken++; 12544 for (PackageParser.Activity a : pkg.activities) { 12545 for (ActivityIntentInfo filter : a.intents) { 12546 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12547 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12548 "Verification needed for IntentFilter:" + filter.toString()); 12549 mIntentFilterVerifier.addOneIntentFilterVerification( 12550 verifierUid, userId, verificationId, filter, packageName); 12551 count++; 12552 } 12553 } 12554 } 12555 } 12556 } 12557 12558 if (count > 0) { 12559 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12560 + " IntentFilter verification" + (count > 1 ? "s" : "") 12561 + " for userId:" + userId); 12562 mIntentFilterVerifier.startVerifications(userId); 12563 } else { 12564 if (DEBUG_DOMAIN_VERIFICATION) { 12565 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12566 } 12567 } 12568 } 12569 12570 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12571 final ComponentName cn = filter.activity.getComponentName(); 12572 final String packageName = cn.getPackageName(); 12573 12574 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12575 packageName); 12576 if (ivi == null) { 12577 return true; 12578 } 12579 int status = ivi.getStatus(); 12580 switch (status) { 12581 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12582 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12583 return true; 12584 12585 default: 12586 // Nothing to do 12587 return false; 12588 } 12589 } 12590 12591 private static boolean isMultiArch(PackageSetting ps) { 12592 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12593 } 12594 12595 private static boolean isMultiArch(ApplicationInfo info) { 12596 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12597 } 12598 12599 private static boolean isExternal(PackageParser.Package pkg) { 12600 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12601 } 12602 12603 private static boolean isExternal(PackageSetting ps) { 12604 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12605 } 12606 12607 private static boolean isExternal(ApplicationInfo info) { 12608 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12609 } 12610 12611 private static boolean isSystemApp(PackageParser.Package pkg) { 12612 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12613 } 12614 12615 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12616 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12617 } 12618 12619 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12620 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12621 } 12622 12623 private static boolean isSystemApp(PackageSetting ps) { 12624 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12625 } 12626 12627 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12628 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12629 } 12630 12631 private int packageFlagsToInstallFlags(PackageSetting ps) { 12632 int installFlags = 0; 12633 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12634 // This existing package was an external ASEC install when we have 12635 // the external flag without a UUID 12636 installFlags |= PackageManager.INSTALL_EXTERNAL; 12637 } 12638 if (ps.isForwardLocked()) { 12639 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12640 } 12641 return installFlags; 12642 } 12643 12644 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 12645 if (isExternal(pkg)) { 12646 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12647 return StorageManager.UUID_PRIMARY_PHYSICAL; 12648 } else { 12649 return pkg.volumeUuid; 12650 } 12651 } else { 12652 return StorageManager.UUID_PRIVATE_INTERNAL; 12653 } 12654 } 12655 12656 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12657 if (isExternal(pkg)) { 12658 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12659 return mSettings.getExternalVersion(); 12660 } else { 12661 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12662 } 12663 } else { 12664 return mSettings.getInternalVersion(); 12665 } 12666 } 12667 12668 private void deleteTempPackageFiles() { 12669 final FilenameFilter filter = new FilenameFilter() { 12670 public boolean accept(File dir, String name) { 12671 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12672 } 12673 }; 12674 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12675 file.delete(); 12676 } 12677 } 12678 12679 @Override 12680 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12681 int flags) { 12682 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12683 flags); 12684 } 12685 12686 @Override 12687 public void deletePackage(final String packageName, 12688 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12689 mContext.enforceCallingOrSelfPermission( 12690 android.Manifest.permission.DELETE_PACKAGES, null); 12691 Preconditions.checkNotNull(packageName); 12692 Preconditions.checkNotNull(observer); 12693 final int uid = Binder.getCallingUid(); 12694 if (UserHandle.getUserId(uid) != userId) { 12695 mContext.enforceCallingPermission( 12696 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12697 "deletePackage for user " + userId); 12698 } 12699 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12700 try { 12701 observer.onPackageDeleted(packageName, 12702 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12703 } catch (RemoteException re) { 12704 } 12705 return; 12706 } 12707 12708 boolean uninstallBlocked = false; 12709 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12710 int[] users = sUserManager.getUserIds(); 12711 for (int i = 0; i < users.length; ++i) { 12712 if (getBlockUninstallForUser(packageName, users[i])) { 12713 uninstallBlocked = true; 12714 break; 12715 } 12716 } 12717 } else { 12718 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12719 } 12720 if (uninstallBlocked) { 12721 try { 12722 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12723 null); 12724 } catch (RemoteException re) { 12725 } 12726 return; 12727 } 12728 12729 if (DEBUG_REMOVE) { 12730 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12731 } 12732 // Queue up an async operation since the package deletion may take a little while. 12733 mHandler.post(new Runnable() { 12734 public void run() { 12735 mHandler.removeCallbacks(this); 12736 final int returnCode = deletePackageX(packageName, userId, flags); 12737 if (observer != null) { 12738 try { 12739 observer.onPackageDeleted(packageName, returnCode, null); 12740 } catch (RemoteException e) { 12741 Log.i(TAG, "Observer no longer exists."); 12742 } //end catch 12743 } //end if 12744 } //end run 12745 }); 12746 } 12747 12748 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12749 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12750 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12751 try { 12752 if (dpm != null) { 12753 if (dpm.isDeviceOwner(packageName)) { 12754 return true; 12755 } 12756 int[] users; 12757 if (userId == UserHandle.USER_ALL) { 12758 users = sUserManager.getUserIds(); 12759 } else { 12760 users = new int[]{userId}; 12761 } 12762 for (int i = 0; i < users.length; ++i) { 12763 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12764 return true; 12765 } 12766 } 12767 } 12768 } catch (RemoteException e) { 12769 } 12770 return false; 12771 } 12772 12773 /** 12774 * This method is an internal method that could be get invoked either 12775 * to delete an installed package or to clean up a failed installation. 12776 * After deleting an installed package, a broadcast is sent to notify any 12777 * listeners that the package has been installed. For cleaning up a failed 12778 * installation, the broadcast is not necessary since the package's 12779 * installation wouldn't have sent the initial broadcast either 12780 * The key steps in deleting a package are 12781 * deleting the package information in internal structures like mPackages, 12782 * deleting the packages base directories through installd 12783 * updating mSettings to reflect current status 12784 * persisting settings for later use 12785 * sending a broadcast if necessary 12786 */ 12787 private int deletePackageX(String packageName, int userId, int flags) { 12788 final PackageRemovedInfo info = new PackageRemovedInfo(); 12789 final boolean res; 12790 12791 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12792 ? UserHandle.ALL : new UserHandle(userId); 12793 12794 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12795 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12796 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12797 } 12798 12799 boolean removedForAllUsers = false; 12800 boolean systemUpdate = false; 12801 12802 // for the uninstall-updates case and restricted profiles, remember the per- 12803 // userhandle installed state 12804 int[] allUsers; 12805 boolean[] perUserInstalled; 12806 synchronized (mPackages) { 12807 PackageSetting ps = mSettings.mPackages.get(packageName); 12808 allUsers = sUserManager.getUserIds(); 12809 perUserInstalled = new boolean[allUsers.length]; 12810 for (int i = 0; i < allUsers.length; i++) { 12811 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12812 } 12813 } 12814 12815 synchronized (mInstallLock) { 12816 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12817 res = deletePackageLI(packageName, removeForUser, 12818 true, allUsers, perUserInstalled, 12819 flags | REMOVE_CHATTY, info, true); 12820 systemUpdate = info.isRemovedPackageSystemUpdate; 12821 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12822 removedForAllUsers = true; 12823 } 12824 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12825 + " removedForAllUsers=" + removedForAllUsers); 12826 } 12827 12828 if (res) { 12829 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12830 12831 // If the removed package was a system update, the old system package 12832 // was re-enabled; we need to broadcast this information 12833 if (systemUpdate) { 12834 Bundle extras = new Bundle(1); 12835 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12836 ? info.removedAppId : info.uid); 12837 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12838 12839 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12840 extras, null, null, null); 12841 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12842 extras, null, null, null); 12843 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12844 null, packageName, null, null); 12845 } 12846 } 12847 // Force a gc here. 12848 Runtime.getRuntime().gc(); 12849 // Delete the resources here after sending the broadcast to let 12850 // other processes clean up before deleting resources. 12851 if (info.args != null) { 12852 synchronized (mInstallLock) { 12853 info.args.doPostDeleteLI(true); 12854 } 12855 } 12856 12857 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12858 } 12859 12860 class PackageRemovedInfo { 12861 String removedPackage; 12862 int uid = -1; 12863 int removedAppId = -1; 12864 int[] removedUsers = null; 12865 boolean isRemovedPackageSystemUpdate = false; 12866 // Clean up resources deleted packages. 12867 InstallArgs args = null; 12868 12869 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12870 Bundle extras = new Bundle(1); 12871 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12872 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12873 if (replacing) { 12874 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12875 } 12876 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12877 if (removedPackage != null) { 12878 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12879 extras, null, null, removedUsers); 12880 if (fullRemove && !replacing) { 12881 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12882 extras, null, null, removedUsers); 12883 } 12884 } 12885 if (removedAppId >= 0) { 12886 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12887 removedUsers); 12888 } 12889 } 12890 } 12891 12892 /* 12893 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12894 * flag is not set, the data directory is removed as well. 12895 * make sure this flag is set for partially installed apps. If not its meaningless to 12896 * delete a partially installed application. 12897 */ 12898 private void removePackageDataLI(PackageSetting ps, 12899 int[] allUserHandles, boolean[] perUserInstalled, 12900 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12901 String packageName = ps.name; 12902 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12903 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12904 // Retrieve object to delete permissions for shared user later on 12905 final PackageSetting deletedPs; 12906 // reader 12907 synchronized (mPackages) { 12908 deletedPs = mSettings.mPackages.get(packageName); 12909 if (outInfo != null) { 12910 outInfo.removedPackage = packageName; 12911 outInfo.removedUsers = deletedPs != null 12912 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12913 : null; 12914 } 12915 } 12916 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12917 removeDataDirsLI(ps.volumeUuid, packageName); 12918 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12919 } 12920 // writer 12921 synchronized (mPackages) { 12922 if (deletedPs != null) { 12923 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12924 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12925 clearDefaultBrowserIfNeeded(packageName); 12926 if (outInfo != null) { 12927 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12928 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12929 } 12930 updatePermissionsLPw(deletedPs.name, null, 0); 12931 if (deletedPs.sharedUser != null) { 12932 // Remove permissions associated with package. Since runtime 12933 // permissions are per user we have to kill the removed package 12934 // or packages running under the shared user of the removed 12935 // package if revoking the permissions requested only by the removed 12936 // package is successful and this causes a change in gids. 12937 for (int userId : UserManagerService.getInstance().getUserIds()) { 12938 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12939 userId); 12940 if (userIdToKill == UserHandle.USER_ALL 12941 || userIdToKill >= UserHandle.USER_OWNER) { 12942 // If gids changed for this user, kill all affected packages. 12943 mHandler.post(new Runnable() { 12944 @Override 12945 public void run() { 12946 // This has to happen with no lock held. 12947 killApplication(deletedPs.name, deletedPs.appId, 12948 KILL_APP_REASON_GIDS_CHANGED); 12949 } 12950 }); 12951 break; 12952 } 12953 } 12954 } 12955 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12956 } 12957 // make sure to preserve per-user disabled state if this removal was just 12958 // a downgrade of a system app to the factory package 12959 if (allUserHandles != null && perUserInstalled != null) { 12960 if (DEBUG_REMOVE) { 12961 Slog.d(TAG, "Propagating install state across downgrade"); 12962 } 12963 for (int i = 0; i < allUserHandles.length; i++) { 12964 if (DEBUG_REMOVE) { 12965 Slog.d(TAG, " user " + allUserHandles[i] 12966 + " => " + perUserInstalled[i]); 12967 } 12968 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12969 } 12970 } 12971 } 12972 // can downgrade to reader 12973 if (writeSettings) { 12974 // Save settings now 12975 mSettings.writeLPr(); 12976 } 12977 } 12978 if (outInfo != null) { 12979 // A user ID was deleted here. Go through all users and remove it 12980 // from KeyStore. 12981 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12982 } 12983 } 12984 12985 static boolean locationIsPrivileged(File path) { 12986 try { 12987 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12988 .getCanonicalPath(); 12989 return path.getCanonicalPath().startsWith(privilegedAppDir); 12990 } catch (IOException e) { 12991 Slog.e(TAG, "Unable to access code path " + path); 12992 } 12993 return false; 12994 } 12995 12996 /* 12997 * Tries to delete system package. 12998 */ 12999 private boolean deleteSystemPackageLI(PackageSetting newPs, 13000 int[] allUserHandles, boolean[] perUserInstalled, 13001 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13002 final boolean applyUserRestrictions 13003 = (allUserHandles != null) && (perUserInstalled != null); 13004 PackageSetting disabledPs = null; 13005 // Confirm if the system package has been updated 13006 // An updated system app can be deleted. This will also have to restore 13007 // the system pkg from system partition 13008 // reader 13009 synchronized (mPackages) { 13010 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13011 } 13012 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13013 + " disabledPs=" + disabledPs); 13014 if (disabledPs == null) { 13015 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13016 return false; 13017 } else if (DEBUG_REMOVE) { 13018 Slog.d(TAG, "Deleting system pkg from data partition"); 13019 } 13020 if (DEBUG_REMOVE) { 13021 if (applyUserRestrictions) { 13022 Slog.d(TAG, "Remembering install states:"); 13023 for (int i = 0; i < allUserHandles.length; i++) { 13024 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13025 } 13026 } 13027 } 13028 // Delete the updated package 13029 outInfo.isRemovedPackageSystemUpdate = true; 13030 if (disabledPs.versionCode < newPs.versionCode) { 13031 // Delete data for downgrades 13032 flags &= ~PackageManager.DELETE_KEEP_DATA; 13033 } else { 13034 // Preserve data by setting flag 13035 flags |= PackageManager.DELETE_KEEP_DATA; 13036 } 13037 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13038 allUserHandles, perUserInstalled, outInfo, writeSettings); 13039 if (!ret) { 13040 return false; 13041 } 13042 // writer 13043 synchronized (mPackages) { 13044 // Reinstate the old system package 13045 mSettings.enableSystemPackageLPw(newPs.name); 13046 // Remove any native libraries from the upgraded package. 13047 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13048 } 13049 // Install the system package 13050 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13051 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13052 if (locationIsPrivileged(disabledPs.codePath)) { 13053 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13054 } 13055 13056 final PackageParser.Package newPkg; 13057 try { 13058 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13059 } catch (PackageManagerException e) { 13060 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13061 return false; 13062 } 13063 13064 // writer 13065 synchronized (mPackages) { 13066 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13067 13068 // Propagate the permissions state as we do not want to drop on the floor 13069 // runtime permissions. The update permissions method below will take 13070 // care of removing obsolete permissions and grant install permissions. 13071 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13072 updatePermissionsLPw(newPkg.packageName, newPkg, 13073 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13074 13075 if (applyUserRestrictions) { 13076 if (DEBUG_REMOVE) { 13077 Slog.d(TAG, "Propagating install state across reinstall"); 13078 } 13079 for (int i = 0; i < allUserHandles.length; i++) { 13080 if (DEBUG_REMOVE) { 13081 Slog.d(TAG, " user " + allUserHandles[i] 13082 + " => " + perUserInstalled[i]); 13083 } 13084 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13085 13086 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13087 } 13088 // Regardless of writeSettings we need to ensure that this restriction 13089 // state propagation is persisted 13090 mSettings.writeAllUsersPackageRestrictionsLPr(); 13091 } 13092 // can downgrade to reader here 13093 if (writeSettings) { 13094 mSettings.writeLPr(); 13095 } 13096 } 13097 return true; 13098 } 13099 13100 private boolean deleteInstalledPackageLI(PackageSetting ps, 13101 boolean deleteCodeAndResources, int flags, 13102 int[] allUserHandles, boolean[] perUserInstalled, 13103 PackageRemovedInfo outInfo, boolean writeSettings) { 13104 if (outInfo != null) { 13105 outInfo.uid = ps.appId; 13106 } 13107 13108 // Delete package data from internal structures and also remove data if flag is set 13109 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13110 13111 // Delete application code and resources 13112 if (deleteCodeAndResources && (outInfo != null)) { 13113 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13114 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13115 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13116 } 13117 return true; 13118 } 13119 13120 @Override 13121 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13122 int userId) { 13123 mContext.enforceCallingOrSelfPermission( 13124 android.Manifest.permission.DELETE_PACKAGES, null); 13125 synchronized (mPackages) { 13126 PackageSetting ps = mSettings.mPackages.get(packageName); 13127 if (ps == null) { 13128 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13129 return false; 13130 } 13131 if (!ps.getInstalled(userId)) { 13132 // Can't block uninstall for an app that is not installed or enabled. 13133 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13134 return false; 13135 } 13136 ps.setBlockUninstall(blockUninstall, userId); 13137 mSettings.writePackageRestrictionsLPr(userId); 13138 } 13139 return true; 13140 } 13141 13142 @Override 13143 public boolean getBlockUninstallForUser(String packageName, int userId) { 13144 synchronized (mPackages) { 13145 PackageSetting ps = mSettings.mPackages.get(packageName); 13146 if (ps == null) { 13147 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13148 return false; 13149 } 13150 return ps.getBlockUninstall(userId); 13151 } 13152 } 13153 13154 /* 13155 * This method handles package deletion in general 13156 */ 13157 private boolean deletePackageLI(String packageName, UserHandle user, 13158 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13159 int flags, PackageRemovedInfo outInfo, 13160 boolean writeSettings) { 13161 if (packageName == null) { 13162 Slog.w(TAG, "Attempt to delete null packageName."); 13163 return false; 13164 } 13165 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13166 PackageSetting ps; 13167 boolean dataOnly = false; 13168 int removeUser = -1; 13169 int appId = -1; 13170 synchronized (mPackages) { 13171 ps = mSettings.mPackages.get(packageName); 13172 if (ps == null) { 13173 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13174 return false; 13175 } 13176 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13177 && user.getIdentifier() != UserHandle.USER_ALL) { 13178 // The caller is asking that the package only be deleted for a single 13179 // user. To do this, we just mark its uninstalled state and delete 13180 // its data. If this is a system app, we only allow this to happen if 13181 // they have set the special DELETE_SYSTEM_APP which requests different 13182 // semantics than normal for uninstalling system apps. 13183 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13184 final int userId = user.getIdentifier(); 13185 ps.setUserState(userId, 13186 COMPONENT_ENABLED_STATE_DEFAULT, 13187 false, //installed 13188 true, //stopped 13189 true, //notLaunched 13190 false, //hidden 13191 null, null, null, 13192 false, // blockUninstall 13193 ps.readUserState(userId).domainVerificationStatus, 0); 13194 if (!isSystemApp(ps)) { 13195 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13196 // Other user still have this package installed, so all 13197 // we need to do is clear this user's data and save that 13198 // it is uninstalled. 13199 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13200 removeUser = user.getIdentifier(); 13201 appId = ps.appId; 13202 scheduleWritePackageRestrictionsLocked(removeUser); 13203 } else { 13204 // We need to set it back to 'installed' so the uninstall 13205 // broadcasts will be sent correctly. 13206 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13207 ps.setInstalled(true, user.getIdentifier()); 13208 } 13209 } else { 13210 // This is a system app, so we assume that the 13211 // other users still have this package installed, so all 13212 // we need to do is clear this user's data and save that 13213 // it is uninstalled. 13214 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13215 removeUser = user.getIdentifier(); 13216 appId = ps.appId; 13217 scheduleWritePackageRestrictionsLocked(removeUser); 13218 } 13219 } 13220 } 13221 13222 if (removeUser >= 0) { 13223 // From above, we determined that we are deleting this only 13224 // for a single user. Continue the work here. 13225 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13226 if (outInfo != null) { 13227 outInfo.removedPackage = packageName; 13228 outInfo.removedAppId = appId; 13229 outInfo.removedUsers = new int[] {removeUser}; 13230 } 13231 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13232 removeKeystoreDataIfNeeded(removeUser, appId); 13233 schedulePackageCleaning(packageName, removeUser, false); 13234 synchronized (mPackages) { 13235 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13236 scheduleWritePackageRestrictionsLocked(removeUser); 13237 } 13238 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13239 } 13240 return true; 13241 } 13242 13243 if (dataOnly) { 13244 // Delete application data first 13245 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13246 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13247 return true; 13248 } 13249 13250 boolean ret = false; 13251 if (isSystemApp(ps)) { 13252 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13253 // When an updated system application is deleted we delete the existing resources as well and 13254 // fall back to existing code in system partition 13255 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13256 flags, outInfo, writeSettings); 13257 } else { 13258 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13259 // Kill application pre-emptively especially for apps on sd. 13260 killApplication(packageName, ps.appId, "uninstall pkg"); 13261 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13262 allUserHandles, perUserInstalled, 13263 outInfo, writeSettings); 13264 } 13265 13266 return ret; 13267 } 13268 13269 private final class ClearStorageConnection implements ServiceConnection { 13270 IMediaContainerService mContainerService; 13271 13272 @Override 13273 public void onServiceConnected(ComponentName name, IBinder service) { 13274 synchronized (this) { 13275 mContainerService = IMediaContainerService.Stub.asInterface(service); 13276 notifyAll(); 13277 } 13278 } 13279 13280 @Override 13281 public void onServiceDisconnected(ComponentName name) { 13282 } 13283 } 13284 13285 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13286 final boolean mounted; 13287 if (Environment.isExternalStorageEmulated()) { 13288 mounted = true; 13289 } else { 13290 final String status = Environment.getExternalStorageState(); 13291 13292 mounted = status.equals(Environment.MEDIA_MOUNTED) 13293 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13294 } 13295 13296 if (!mounted) { 13297 return; 13298 } 13299 13300 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13301 int[] users; 13302 if (userId == UserHandle.USER_ALL) { 13303 users = sUserManager.getUserIds(); 13304 } else { 13305 users = new int[] { userId }; 13306 } 13307 final ClearStorageConnection conn = new ClearStorageConnection(); 13308 if (mContext.bindServiceAsUser( 13309 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13310 try { 13311 for (int curUser : users) { 13312 long timeout = SystemClock.uptimeMillis() + 5000; 13313 synchronized (conn) { 13314 long now = SystemClock.uptimeMillis(); 13315 while (conn.mContainerService == null && now < timeout) { 13316 try { 13317 conn.wait(timeout - now); 13318 } catch (InterruptedException e) { 13319 } 13320 } 13321 } 13322 if (conn.mContainerService == null) { 13323 return; 13324 } 13325 13326 final UserEnvironment userEnv = new UserEnvironment(curUser); 13327 clearDirectory(conn.mContainerService, 13328 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13329 if (allData) { 13330 clearDirectory(conn.mContainerService, 13331 userEnv.buildExternalStorageAppDataDirs(packageName)); 13332 clearDirectory(conn.mContainerService, 13333 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13334 } 13335 } 13336 } finally { 13337 mContext.unbindService(conn); 13338 } 13339 } 13340 } 13341 13342 @Override 13343 public void clearApplicationUserData(final String packageName, 13344 final IPackageDataObserver observer, final int userId) { 13345 mContext.enforceCallingOrSelfPermission( 13346 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13347 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13348 // Queue up an async operation since the package deletion may take a little while. 13349 mHandler.post(new Runnable() { 13350 public void run() { 13351 mHandler.removeCallbacks(this); 13352 final boolean succeeded; 13353 synchronized (mInstallLock) { 13354 succeeded = clearApplicationUserDataLI(packageName, userId); 13355 } 13356 clearExternalStorageDataSync(packageName, userId, true); 13357 if (succeeded) { 13358 // invoke DeviceStorageMonitor's update method to clear any notifications 13359 DeviceStorageMonitorInternal 13360 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13361 if (dsm != null) { 13362 dsm.checkMemory(); 13363 } 13364 } 13365 if(observer != null) { 13366 try { 13367 observer.onRemoveCompleted(packageName, succeeded); 13368 } catch (RemoteException e) { 13369 Log.i(TAG, "Observer no longer exists."); 13370 } 13371 } //end if observer 13372 } //end run 13373 }); 13374 } 13375 13376 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13377 if (packageName == null) { 13378 Slog.w(TAG, "Attempt to delete null packageName."); 13379 return false; 13380 } 13381 13382 // Try finding details about the requested package 13383 PackageParser.Package pkg; 13384 synchronized (mPackages) { 13385 pkg = mPackages.get(packageName); 13386 if (pkg == null) { 13387 final PackageSetting ps = mSettings.mPackages.get(packageName); 13388 if (ps != null) { 13389 pkg = ps.pkg; 13390 } 13391 } 13392 13393 if (pkg == null) { 13394 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13395 return false; 13396 } 13397 13398 PackageSetting ps = (PackageSetting) pkg.mExtras; 13399 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13400 } 13401 13402 // Always delete data directories for package, even if we found no other 13403 // record of app. This helps users recover from UID mismatches without 13404 // resorting to a full data wipe. 13405 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13406 if (retCode < 0) { 13407 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13408 return false; 13409 } 13410 13411 final int appId = pkg.applicationInfo.uid; 13412 removeKeystoreDataIfNeeded(userId, appId); 13413 13414 // Create a native library symlink only if we have native libraries 13415 // and if the native libraries are 32 bit libraries. We do not provide 13416 // this symlink for 64 bit libraries. 13417 if (pkg.applicationInfo.primaryCpuAbi != null && 13418 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13419 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13420 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13421 nativeLibPath, userId) < 0) { 13422 Slog.w(TAG, "Failed linking native library dir"); 13423 return false; 13424 } 13425 } 13426 13427 return true; 13428 } 13429 13430 /** 13431 * Reverts user permission state changes (permissions and flags) in 13432 * all packages for a given user. 13433 * 13434 * @param userId The device user for which to do a reset. 13435 */ 13436 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13437 final int packageCount = mPackages.size(); 13438 for (int i = 0; i < packageCount; i++) { 13439 PackageParser.Package pkg = mPackages.valueAt(i); 13440 PackageSetting ps = (PackageSetting) pkg.mExtras; 13441 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13442 } 13443 } 13444 13445 /** 13446 * Reverts user permission state changes (permissions and flags). 13447 * 13448 * @param ps The package for which to reset. 13449 * @param userId The device user for which to do a reset. 13450 */ 13451 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13452 final PackageSetting ps, final int userId) { 13453 if (ps.pkg == null) { 13454 return; 13455 } 13456 13457 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13458 | FLAG_PERMISSION_USER_FIXED 13459 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13460 13461 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13462 | FLAG_PERMISSION_POLICY_FIXED; 13463 13464 boolean writeInstallPermissions = false; 13465 boolean writeRuntimePermissions = false; 13466 13467 final int permissionCount = ps.pkg.requestedPermissions.size(); 13468 for (int i = 0; i < permissionCount; i++) { 13469 String permission = ps.pkg.requestedPermissions.get(i); 13470 13471 BasePermission bp = mSettings.mPermissions.get(permission); 13472 if (bp == null) { 13473 continue; 13474 } 13475 13476 // If shared user we just reset the state to which only this app contributed. 13477 if (ps.sharedUser != null) { 13478 boolean used = false; 13479 final int packageCount = ps.sharedUser.packages.size(); 13480 for (int j = 0; j < packageCount; j++) { 13481 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13482 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13483 && pkg.pkg.requestedPermissions.contains(permission)) { 13484 used = true; 13485 break; 13486 } 13487 } 13488 if (used) { 13489 continue; 13490 } 13491 } 13492 13493 PermissionsState permissionsState = ps.getPermissionsState(); 13494 13495 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13496 13497 // Always clear the user settable flags. 13498 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13499 bp.name) != null; 13500 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13501 if (hasInstallState) { 13502 writeInstallPermissions = true; 13503 } else { 13504 writeRuntimePermissions = true; 13505 } 13506 } 13507 13508 // Below is only runtime permission handling. 13509 if (!bp.isRuntime()) { 13510 continue; 13511 } 13512 13513 // Never clobber system or policy. 13514 if ((oldFlags & policyOrSystemFlags) != 0) { 13515 continue; 13516 } 13517 13518 // If this permission was granted by default, make sure it is. 13519 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13520 if (permissionsState.grantRuntimePermission(bp, userId) 13521 != PERMISSION_OPERATION_FAILURE) { 13522 writeRuntimePermissions = true; 13523 } 13524 } else { 13525 // Otherwise, reset the permission. 13526 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13527 switch (revokeResult) { 13528 case PERMISSION_OPERATION_SUCCESS: { 13529 writeRuntimePermissions = true; 13530 } break; 13531 13532 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13533 writeRuntimePermissions = true; 13534 final int appId = ps.appId; 13535 mHandler.post(new Runnable() { 13536 @Override 13537 public void run() { 13538 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13539 } 13540 }); 13541 } break; 13542 } 13543 } 13544 } 13545 13546 // Synchronously write as we are taking permissions away. 13547 if (writeRuntimePermissions) { 13548 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13549 } 13550 13551 // Synchronously write as we are taking permissions away. 13552 if (writeInstallPermissions) { 13553 mSettings.writeLPr(); 13554 } 13555 } 13556 13557 /** 13558 * Remove entries from the keystore daemon. Will only remove it if the 13559 * {@code appId} is valid. 13560 */ 13561 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13562 if (appId < 0) { 13563 return; 13564 } 13565 13566 final KeyStore keyStore = KeyStore.getInstance(); 13567 if (keyStore != null) { 13568 if (userId == UserHandle.USER_ALL) { 13569 for (final int individual : sUserManager.getUserIds()) { 13570 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13571 } 13572 } else { 13573 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13574 } 13575 } else { 13576 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13577 } 13578 } 13579 13580 @Override 13581 public void deleteApplicationCacheFiles(final String packageName, 13582 final IPackageDataObserver observer) { 13583 mContext.enforceCallingOrSelfPermission( 13584 android.Manifest.permission.DELETE_CACHE_FILES, null); 13585 // Queue up an async operation since the package deletion may take a little while. 13586 final int userId = UserHandle.getCallingUserId(); 13587 mHandler.post(new Runnable() { 13588 public void run() { 13589 mHandler.removeCallbacks(this); 13590 final boolean succeded; 13591 synchronized (mInstallLock) { 13592 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13593 } 13594 clearExternalStorageDataSync(packageName, userId, false); 13595 if (observer != null) { 13596 try { 13597 observer.onRemoveCompleted(packageName, succeded); 13598 } catch (RemoteException e) { 13599 Log.i(TAG, "Observer no longer exists."); 13600 } 13601 } //end if observer 13602 } //end run 13603 }); 13604 } 13605 13606 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13607 if (packageName == null) { 13608 Slog.w(TAG, "Attempt to delete null packageName."); 13609 return false; 13610 } 13611 PackageParser.Package p; 13612 synchronized (mPackages) { 13613 p = mPackages.get(packageName); 13614 } 13615 if (p == null) { 13616 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13617 return false; 13618 } 13619 final ApplicationInfo applicationInfo = p.applicationInfo; 13620 if (applicationInfo == null) { 13621 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13622 return false; 13623 } 13624 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13625 if (retCode < 0) { 13626 Slog.w(TAG, "Couldn't remove cache files for package: " 13627 + packageName + " u" + userId); 13628 return false; 13629 } 13630 return true; 13631 } 13632 13633 @Override 13634 public void getPackageSizeInfo(final String packageName, int userHandle, 13635 final IPackageStatsObserver observer) { 13636 mContext.enforceCallingOrSelfPermission( 13637 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13638 if (packageName == null) { 13639 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13640 } 13641 13642 PackageStats stats = new PackageStats(packageName, userHandle); 13643 13644 /* 13645 * Queue up an async operation since the package measurement may take a 13646 * little while. 13647 */ 13648 Message msg = mHandler.obtainMessage(INIT_COPY); 13649 msg.obj = new MeasureParams(stats, observer); 13650 mHandler.sendMessage(msg); 13651 } 13652 13653 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13654 PackageStats pStats) { 13655 if (packageName == null) { 13656 Slog.w(TAG, "Attempt to get size of null packageName."); 13657 return false; 13658 } 13659 PackageParser.Package p; 13660 boolean dataOnly = false; 13661 String libDirRoot = null; 13662 String asecPath = null; 13663 PackageSetting ps = null; 13664 synchronized (mPackages) { 13665 p = mPackages.get(packageName); 13666 ps = mSettings.mPackages.get(packageName); 13667 if(p == null) { 13668 dataOnly = true; 13669 if((ps == null) || (ps.pkg == null)) { 13670 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13671 return false; 13672 } 13673 p = ps.pkg; 13674 } 13675 if (ps != null) { 13676 libDirRoot = ps.legacyNativeLibraryPathString; 13677 } 13678 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 13679 final long token = Binder.clearCallingIdentity(); 13680 try { 13681 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13682 if (secureContainerId != null) { 13683 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13684 } 13685 } finally { 13686 Binder.restoreCallingIdentity(token); 13687 } 13688 } 13689 } 13690 String publicSrcDir = null; 13691 if(!dataOnly) { 13692 final ApplicationInfo applicationInfo = p.applicationInfo; 13693 if (applicationInfo == null) { 13694 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13695 return false; 13696 } 13697 if (p.isForwardLocked()) { 13698 publicSrcDir = applicationInfo.getBaseResourcePath(); 13699 } 13700 } 13701 // TODO: extend to measure size of split APKs 13702 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13703 // not just the first level. 13704 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13705 // just the primary. 13706 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13707 13708 String apkPath; 13709 File packageDir = new File(p.codePath); 13710 13711 if (packageDir.isDirectory() && p.canHaveOatDir()) { 13712 apkPath = packageDir.getAbsolutePath(); 13713 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 13714 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 13715 libDirRoot = null; 13716 } 13717 } else { 13718 apkPath = p.baseCodePath; 13719 } 13720 13721 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 13722 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13723 if (res < 0) { 13724 return false; 13725 } 13726 13727 // Fix-up for forward-locked applications in ASEC containers. 13728 if (!isExternal(p)) { 13729 pStats.codeSize += pStats.externalCodeSize; 13730 pStats.externalCodeSize = 0L; 13731 } 13732 13733 return true; 13734 } 13735 13736 13737 @Override 13738 public void addPackageToPreferred(String packageName) { 13739 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13740 } 13741 13742 @Override 13743 public void removePackageFromPreferred(String packageName) { 13744 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13745 } 13746 13747 @Override 13748 public List<PackageInfo> getPreferredPackages(int flags) { 13749 return new ArrayList<PackageInfo>(); 13750 } 13751 13752 private int getUidTargetSdkVersionLockedLPr(int uid) { 13753 Object obj = mSettings.getUserIdLPr(uid); 13754 if (obj instanceof SharedUserSetting) { 13755 final SharedUserSetting sus = (SharedUserSetting) obj; 13756 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13757 final Iterator<PackageSetting> it = sus.packages.iterator(); 13758 while (it.hasNext()) { 13759 final PackageSetting ps = it.next(); 13760 if (ps.pkg != null) { 13761 int v = ps.pkg.applicationInfo.targetSdkVersion; 13762 if (v < vers) vers = v; 13763 } 13764 } 13765 return vers; 13766 } else if (obj instanceof PackageSetting) { 13767 final PackageSetting ps = (PackageSetting) obj; 13768 if (ps.pkg != null) { 13769 return ps.pkg.applicationInfo.targetSdkVersion; 13770 } 13771 } 13772 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13773 } 13774 13775 @Override 13776 public void addPreferredActivity(IntentFilter filter, int match, 13777 ComponentName[] set, ComponentName activity, int userId) { 13778 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13779 "Adding preferred"); 13780 } 13781 13782 private void addPreferredActivityInternal(IntentFilter filter, int match, 13783 ComponentName[] set, ComponentName activity, boolean always, int userId, 13784 String opname) { 13785 // writer 13786 int callingUid = Binder.getCallingUid(); 13787 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13788 if (filter.countActions() == 0) { 13789 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13790 return; 13791 } 13792 synchronized (mPackages) { 13793 if (mContext.checkCallingOrSelfPermission( 13794 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13795 != PackageManager.PERMISSION_GRANTED) { 13796 if (getUidTargetSdkVersionLockedLPr(callingUid) 13797 < Build.VERSION_CODES.FROYO) { 13798 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13799 + callingUid); 13800 return; 13801 } 13802 mContext.enforceCallingOrSelfPermission( 13803 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13804 } 13805 13806 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13807 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13808 + userId + ":"); 13809 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13810 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13811 scheduleWritePackageRestrictionsLocked(userId); 13812 } 13813 } 13814 13815 @Override 13816 public void replacePreferredActivity(IntentFilter filter, int match, 13817 ComponentName[] set, ComponentName activity, int userId) { 13818 if (filter.countActions() != 1) { 13819 throw new IllegalArgumentException( 13820 "replacePreferredActivity expects filter to have only 1 action."); 13821 } 13822 if (filter.countDataAuthorities() != 0 13823 || filter.countDataPaths() != 0 13824 || filter.countDataSchemes() > 1 13825 || filter.countDataTypes() != 0) { 13826 throw new IllegalArgumentException( 13827 "replacePreferredActivity expects filter to have no data authorities, " + 13828 "paths, or types; and at most one scheme."); 13829 } 13830 13831 final int callingUid = Binder.getCallingUid(); 13832 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13833 synchronized (mPackages) { 13834 if (mContext.checkCallingOrSelfPermission( 13835 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13836 != PackageManager.PERMISSION_GRANTED) { 13837 if (getUidTargetSdkVersionLockedLPr(callingUid) 13838 < Build.VERSION_CODES.FROYO) { 13839 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13840 + Binder.getCallingUid()); 13841 return; 13842 } 13843 mContext.enforceCallingOrSelfPermission( 13844 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13845 } 13846 13847 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13848 if (pir != null) { 13849 // Get all of the existing entries that exactly match this filter. 13850 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13851 if (existing != null && existing.size() == 1) { 13852 PreferredActivity cur = existing.get(0); 13853 if (DEBUG_PREFERRED) { 13854 Slog.i(TAG, "Checking replace of preferred:"); 13855 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13856 if (!cur.mPref.mAlways) { 13857 Slog.i(TAG, " -- CUR; not mAlways!"); 13858 } else { 13859 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13860 Slog.i(TAG, " -- CUR: mSet=" 13861 + Arrays.toString(cur.mPref.mSetComponents)); 13862 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13863 Slog.i(TAG, " -- NEW: mMatch=" 13864 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13865 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13866 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13867 } 13868 } 13869 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13870 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13871 && cur.mPref.sameSet(set)) { 13872 // Setting the preferred activity to what it happens to be already 13873 if (DEBUG_PREFERRED) { 13874 Slog.i(TAG, "Replacing with same preferred activity " 13875 + cur.mPref.mShortComponent + " for user " 13876 + userId + ":"); 13877 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13878 } 13879 return; 13880 } 13881 } 13882 13883 if (existing != null) { 13884 if (DEBUG_PREFERRED) { 13885 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13886 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13887 } 13888 for (int i = 0; i < existing.size(); i++) { 13889 PreferredActivity pa = existing.get(i); 13890 if (DEBUG_PREFERRED) { 13891 Slog.i(TAG, "Removing existing preferred activity " 13892 + pa.mPref.mComponent + ":"); 13893 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13894 } 13895 pir.removeFilter(pa); 13896 } 13897 } 13898 } 13899 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13900 "Replacing preferred"); 13901 } 13902 } 13903 13904 @Override 13905 public void clearPackagePreferredActivities(String packageName) { 13906 final int uid = Binder.getCallingUid(); 13907 // writer 13908 synchronized (mPackages) { 13909 PackageParser.Package pkg = mPackages.get(packageName); 13910 if (pkg == null || pkg.applicationInfo.uid != uid) { 13911 if (mContext.checkCallingOrSelfPermission( 13912 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13913 != PackageManager.PERMISSION_GRANTED) { 13914 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13915 < Build.VERSION_CODES.FROYO) { 13916 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13917 + Binder.getCallingUid()); 13918 return; 13919 } 13920 mContext.enforceCallingOrSelfPermission( 13921 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13922 } 13923 } 13924 13925 int user = UserHandle.getCallingUserId(); 13926 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13927 scheduleWritePackageRestrictionsLocked(user); 13928 } 13929 } 13930 } 13931 13932 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13933 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13934 ArrayList<PreferredActivity> removed = null; 13935 boolean changed = false; 13936 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13937 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13938 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13939 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13940 continue; 13941 } 13942 Iterator<PreferredActivity> it = pir.filterIterator(); 13943 while (it.hasNext()) { 13944 PreferredActivity pa = it.next(); 13945 // Mark entry for removal only if it matches the package name 13946 // and the entry is of type "always". 13947 if (packageName == null || 13948 (pa.mPref.mComponent.getPackageName().equals(packageName) 13949 && pa.mPref.mAlways)) { 13950 if (removed == null) { 13951 removed = new ArrayList<PreferredActivity>(); 13952 } 13953 removed.add(pa); 13954 } 13955 } 13956 if (removed != null) { 13957 for (int j=0; j<removed.size(); j++) { 13958 PreferredActivity pa = removed.get(j); 13959 pir.removeFilter(pa); 13960 } 13961 changed = true; 13962 } 13963 } 13964 return changed; 13965 } 13966 13967 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13968 private void clearIntentFilterVerificationsLPw(int userId) { 13969 final int packageCount = mPackages.size(); 13970 for (int i = 0; i < packageCount; i++) { 13971 PackageParser.Package pkg = mPackages.valueAt(i); 13972 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13973 } 13974 } 13975 13976 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13977 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13978 if (userId == UserHandle.USER_ALL) { 13979 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13980 sUserManager.getUserIds())) { 13981 for (int oneUserId : sUserManager.getUserIds()) { 13982 scheduleWritePackageRestrictionsLocked(oneUserId); 13983 } 13984 } 13985 } else { 13986 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13987 scheduleWritePackageRestrictionsLocked(userId); 13988 } 13989 } 13990 } 13991 13992 void clearDefaultBrowserIfNeeded(String packageName) { 13993 for (int oneUserId : sUserManager.getUserIds()) { 13994 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13995 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13996 if (packageName.equals(defaultBrowserPackageName)) { 13997 setDefaultBrowserPackageName(null, oneUserId); 13998 } 13999 } 14000 } 14001 14002 @Override 14003 public void resetApplicationPreferences(int userId) { 14004 mContext.enforceCallingOrSelfPermission( 14005 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14006 // writer 14007 synchronized (mPackages) { 14008 final long identity = Binder.clearCallingIdentity(); 14009 try { 14010 clearPackagePreferredActivitiesLPw(null, userId); 14011 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14012 // TODO: We have to reset the default SMS and Phone. This requires 14013 // significant refactoring to keep all default apps in the package 14014 // manager (cleaner but more work) or have the services provide 14015 // callbacks to the package manager to request a default app reset. 14016 applyFactoryDefaultBrowserLPw(userId); 14017 clearIntentFilterVerificationsLPw(userId); 14018 primeDomainVerificationsLPw(userId); 14019 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14020 scheduleWritePackageRestrictionsLocked(userId); 14021 } finally { 14022 Binder.restoreCallingIdentity(identity); 14023 } 14024 } 14025 } 14026 14027 @Override 14028 public int getPreferredActivities(List<IntentFilter> outFilters, 14029 List<ComponentName> outActivities, String packageName) { 14030 14031 int num = 0; 14032 final int userId = UserHandle.getCallingUserId(); 14033 // reader 14034 synchronized (mPackages) { 14035 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14036 if (pir != null) { 14037 final Iterator<PreferredActivity> it = pir.filterIterator(); 14038 while (it.hasNext()) { 14039 final PreferredActivity pa = it.next(); 14040 if (packageName == null 14041 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14042 && pa.mPref.mAlways)) { 14043 if (outFilters != null) { 14044 outFilters.add(new IntentFilter(pa)); 14045 } 14046 if (outActivities != null) { 14047 outActivities.add(pa.mPref.mComponent); 14048 } 14049 } 14050 } 14051 } 14052 } 14053 14054 return num; 14055 } 14056 14057 @Override 14058 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14059 int userId) { 14060 int callingUid = Binder.getCallingUid(); 14061 if (callingUid != Process.SYSTEM_UID) { 14062 throw new SecurityException( 14063 "addPersistentPreferredActivity can only be run by the system"); 14064 } 14065 if (filter.countActions() == 0) { 14066 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14067 return; 14068 } 14069 synchronized (mPackages) { 14070 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14071 " :"); 14072 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14073 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14074 new PersistentPreferredActivity(filter, activity)); 14075 scheduleWritePackageRestrictionsLocked(userId); 14076 } 14077 } 14078 14079 @Override 14080 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14081 int callingUid = Binder.getCallingUid(); 14082 if (callingUid != Process.SYSTEM_UID) { 14083 throw new SecurityException( 14084 "clearPackagePersistentPreferredActivities can only be run by the system"); 14085 } 14086 ArrayList<PersistentPreferredActivity> removed = null; 14087 boolean changed = false; 14088 synchronized (mPackages) { 14089 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14090 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14091 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14092 .valueAt(i); 14093 if (userId != thisUserId) { 14094 continue; 14095 } 14096 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14097 while (it.hasNext()) { 14098 PersistentPreferredActivity ppa = it.next(); 14099 // Mark entry for removal only if it matches the package name. 14100 if (ppa.mComponent.getPackageName().equals(packageName)) { 14101 if (removed == null) { 14102 removed = new ArrayList<PersistentPreferredActivity>(); 14103 } 14104 removed.add(ppa); 14105 } 14106 } 14107 if (removed != null) { 14108 for (int j=0; j<removed.size(); j++) { 14109 PersistentPreferredActivity ppa = removed.get(j); 14110 ppir.removeFilter(ppa); 14111 } 14112 changed = true; 14113 } 14114 } 14115 14116 if (changed) { 14117 scheduleWritePackageRestrictionsLocked(userId); 14118 } 14119 } 14120 } 14121 14122 /** 14123 * Common machinery for picking apart a restored XML blob and passing 14124 * it to a caller-supplied functor to be applied to the running system. 14125 */ 14126 private void restoreFromXml(XmlPullParser parser, int userId, 14127 String expectedStartTag, BlobXmlRestorer functor) 14128 throws IOException, XmlPullParserException { 14129 int type; 14130 while ((type = parser.next()) != XmlPullParser.START_TAG 14131 && type != XmlPullParser.END_DOCUMENT) { 14132 } 14133 if (type != XmlPullParser.START_TAG) { 14134 // oops didn't find a start tag?! 14135 if (DEBUG_BACKUP) { 14136 Slog.e(TAG, "Didn't find start tag during restore"); 14137 } 14138 return; 14139 } 14140 14141 // this is supposed to be TAG_PREFERRED_BACKUP 14142 if (!expectedStartTag.equals(parser.getName())) { 14143 if (DEBUG_BACKUP) { 14144 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14145 } 14146 return; 14147 } 14148 14149 // skip interfering stuff, then we're aligned with the backing implementation 14150 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14151 functor.apply(parser, userId); 14152 } 14153 14154 private interface BlobXmlRestorer { 14155 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14156 } 14157 14158 /** 14159 * Non-Binder method, support for the backup/restore mechanism: write the 14160 * full set of preferred activities in its canonical XML format. Returns the 14161 * XML output as a byte array, or null if there is none. 14162 */ 14163 @Override 14164 public byte[] getPreferredActivityBackup(int userId) { 14165 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14166 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14167 } 14168 14169 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14170 try { 14171 final XmlSerializer serializer = new FastXmlSerializer(); 14172 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14173 serializer.startDocument(null, true); 14174 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14175 14176 synchronized (mPackages) { 14177 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14178 } 14179 14180 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14181 serializer.endDocument(); 14182 serializer.flush(); 14183 } catch (Exception e) { 14184 if (DEBUG_BACKUP) { 14185 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14186 } 14187 return null; 14188 } 14189 14190 return dataStream.toByteArray(); 14191 } 14192 14193 @Override 14194 public void restorePreferredActivities(byte[] backup, int userId) { 14195 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14196 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14197 } 14198 14199 try { 14200 final XmlPullParser parser = Xml.newPullParser(); 14201 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14202 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14203 new BlobXmlRestorer() { 14204 @Override 14205 public void apply(XmlPullParser parser, int userId) 14206 throws XmlPullParserException, IOException { 14207 synchronized (mPackages) { 14208 mSettings.readPreferredActivitiesLPw(parser, userId); 14209 } 14210 } 14211 } ); 14212 } catch (Exception e) { 14213 if (DEBUG_BACKUP) { 14214 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14215 } 14216 } 14217 } 14218 14219 /** 14220 * Non-Binder method, support for the backup/restore mechanism: write the 14221 * default browser (etc) settings in its canonical XML format. Returns the default 14222 * browser XML representation as a byte array, or null if there is none. 14223 */ 14224 @Override 14225 public byte[] getDefaultAppsBackup(int userId) { 14226 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14227 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14228 } 14229 14230 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14231 try { 14232 final XmlSerializer serializer = new FastXmlSerializer(); 14233 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14234 serializer.startDocument(null, true); 14235 serializer.startTag(null, TAG_DEFAULT_APPS); 14236 14237 synchronized (mPackages) { 14238 mSettings.writeDefaultAppsLPr(serializer, userId); 14239 } 14240 14241 serializer.endTag(null, TAG_DEFAULT_APPS); 14242 serializer.endDocument(); 14243 serializer.flush(); 14244 } catch (Exception e) { 14245 if (DEBUG_BACKUP) { 14246 Slog.e(TAG, "Unable to write default apps for backup", e); 14247 } 14248 return null; 14249 } 14250 14251 return dataStream.toByteArray(); 14252 } 14253 14254 @Override 14255 public void restoreDefaultApps(byte[] backup, int userId) { 14256 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14257 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14258 } 14259 14260 try { 14261 final XmlPullParser parser = Xml.newPullParser(); 14262 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14263 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14264 new BlobXmlRestorer() { 14265 @Override 14266 public void apply(XmlPullParser parser, int userId) 14267 throws XmlPullParserException, IOException { 14268 synchronized (mPackages) { 14269 mSettings.readDefaultAppsLPw(parser, userId); 14270 } 14271 } 14272 } ); 14273 } catch (Exception e) { 14274 if (DEBUG_BACKUP) { 14275 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14276 } 14277 } 14278 } 14279 14280 @Override 14281 public byte[] getIntentFilterVerificationBackup(int userId) { 14282 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14283 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14284 } 14285 14286 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14287 try { 14288 final XmlSerializer serializer = new FastXmlSerializer(); 14289 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14290 serializer.startDocument(null, true); 14291 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14292 14293 synchronized (mPackages) { 14294 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14295 } 14296 14297 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14298 serializer.endDocument(); 14299 serializer.flush(); 14300 } catch (Exception e) { 14301 if (DEBUG_BACKUP) { 14302 Slog.e(TAG, "Unable to write default apps for backup", e); 14303 } 14304 return null; 14305 } 14306 14307 return dataStream.toByteArray(); 14308 } 14309 14310 @Override 14311 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14312 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14313 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14314 } 14315 14316 try { 14317 final XmlPullParser parser = Xml.newPullParser(); 14318 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14319 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14320 new BlobXmlRestorer() { 14321 @Override 14322 public void apply(XmlPullParser parser, int userId) 14323 throws XmlPullParserException, IOException { 14324 synchronized (mPackages) { 14325 mSettings.readAllDomainVerificationsLPr(parser, userId); 14326 mSettings.writeLPr(); 14327 } 14328 } 14329 } ); 14330 } catch (Exception e) { 14331 if (DEBUG_BACKUP) { 14332 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14333 } 14334 } 14335 } 14336 14337 @Override 14338 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14339 int sourceUserId, int targetUserId, int flags) { 14340 mContext.enforceCallingOrSelfPermission( 14341 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14342 int callingUid = Binder.getCallingUid(); 14343 enforceOwnerRights(ownerPackage, callingUid); 14344 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14345 if (intentFilter.countActions() == 0) { 14346 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14347 return; 14348 } 14349 synchronized (mPackages) { 14350 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14351 ownerPackage, targetUserId, flags); 14352 CrossProfileIntentResolver resolver = 14353 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14354 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14355 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14356 if (existing != null) { 14357 int size = existing.size(); 14358 for (int i = 0; i < size; i++) { 14359 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14360 return; 14361 } 14362 } 14363 } 14364 resolver.addFilter(newFilter); 14365 scheduleWritePackageRestrictionsLocked(sourceUserId); 14366 } 14367 } 14368 14369 @Override 14370 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14371 mContext.enforceCallingOrSelfPermission( 14372 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14373 int callingUid = Binder.getCallingUid(); 14374 enforceOwnerRights(ownerPackage, callingUid); 14375 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14376 synchronized (mPackages) { 14377 CrossProfileIntentResolver resolver = 14378 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14379 ArraySet<CrossProfileIntentFilter> set = 14380 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14381 for (CrossProfileIntentFilter filter : set) { 14382 if (filter.getOwnerPackage().equals(ownerPackage)) { 14383 resolver.removeFilter(filter); 14384 } 14385 } 14386 scheduleWritePackageRestrictionsLocked(sourceUserId); 14387 } 14388 } 14389 14390 // Enforcing that callingUid is owning pkg on userId 14391 private void enforceOwnerRights(String pkg, int callingUid) { 14392 // The system owns everything. 14393 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14394 return; 14395 } 14396 int callingUserId = UserHandle.getUserId(callingUid); 14397 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14398 if (pi == null) { 14399 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14400 + callingUserId); 14401 } 14402 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14403 throw new SecurityException("Calling uid " + callingUid 14404 + " does not own package " + pkg); 14405 } 14406 } 14407 14408 @Override 14409 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14410 Intent intent = new Intent(Intent.ACTION_MAIN); 14411 intent.addCategory(Intent.CATEGORY_HOME); 14412 14413 final int callingUserId = UserHandle.getCallingUserId(); 14414 List<ResolveInfo> list = queryIntentActivities(intent, null, 14415 PackageManager.GET_META_DATA, callingUserId); 14416 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14417 true, false, false, callingUserId); 14418 14419 allHomeCandidates.clear(); 14420 if (list != null) { 14421 for (ResolveInfo ri : list) { 14422 allHomeCandidates.add(ri); 14423 } 14424 } 14425 return (preferred == null || preferred.activityInfo == null) 14426 ? null 14427 : new ComponentName(preferred.activityInfo.packageName, 14428 preferred.activityInfo.name); 14429 } 14430 14431 @Override 14432 public void setApplicationEnabledSetting(String appPackageName, 14433 int newState, int flags, int userId, String callingPackage) { 14434 if (!sUserManager.exists(userId)) return; 14435 if (callingPackage == null) { 14436 callingPackage = Integer.toString(Binder.getCallingUid()); 14437 } 14438 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14439 } 14440 14441 @Override 14442 public void setComponentEnabledSetting(ComponentName componentName, 14443 int newState, int flags, int userId) { 14444 if (!sUserManager.exists(userId)) return; 14445 setEnabledSetting(componentName.getPackageName(), 14446 componentName.getClassName(), newState, flags, userId, null); 14447 } 14448 14449 private void setEnabledSetting(final String packageName, String className, int newState, 14450 final int flags, int userId, String callingPackage) { 14451 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14452 || newState == COMPONENT_ENABLED_STATE_ENABLED 14453 || newState == COMPONENT_ENABLED_STATE_DISABLED 14454 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14455 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14456 throw new IllegalArgumentException("Invalid new component state: " 14457 + newState); 14458 } 14459 PackageSetting pkgSetting; 14460 final int uid = Binder.getCallingUid(); 14461 final int permission = mContext.checkCallingOrSelfPermission( 14462 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14463 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14464 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14465 boolean sendNow = false; 14466 boolean isApp = (className == null); 14467 String componentName = isApp ? packageName : className; 14468 int packageUid = -1; 14469 ArrayList<String> components; 14470 14471 // writer 14472 synchronized (mPackages) { 14473 pkgSetting = mSettings.mPackages.get(packageName); 14474 if (pkgSetting == null) { 14475 if (className == null) { 14476 throw new IllegalArgumentException( 14477 "Unknown package: " + packageName); 14478 } 14479 throw new IllegalArgumentException( 14480 "Unknown component: " + packageName 14481 + "/" + className); 14482 } 14483 // Allow root and verify that userId is not being specified by a different user 14484 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14485 throw new SecurityException( 14486 "Permission Denial: attempt to change component state from pid=" 14487 + Binder.getCallingPid() 14488 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14489 } 14490 if (className == null) { 14491 // We're dealing with an application/package level state change 14492 if (pkgSetting.getEnabled(userId) == newState) { 14493 // Nothing to do 14494 return; 14495 } 14496 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14497 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14498 // Don't care about who enables an app. 14499 callingPackage = null; 14500 } 14501 pkgSetting.setEnabled(newState, userId, callingPackage); 14502 // pkgSetting.pkg.mSetEnabled = newState; 14503 } else { 14504 // We're dealing with a component level state change 14505 // First, verify that this is a valid class name. 14506 PackageParser.Package pkg = pkgSetting.pkg; 14507 if (pkg == null || !pkg.hasComponentClassName(className)) { 14508 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14509 throw new IllegalArgumentException("Component class " + className 14510 + " does not exist in " + packageName); 14511 } else { 14512 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14513 + className + " does not exist in " + packageName); 14514 } 14515 } 14516 switch (newState) { 14517 case COMPONENT_ENABLED_STATE_ENABLED: 14518 if (!pkgSetting.enableComponentLPw(className, userId)) { 14519 return; 14520 } 14521 break; 14522 case COMPONENT_ENABLED_STATE_DISABLED: 14523 if (!pkgSetting.disableComponentLPw(className, userId)) { 14524 return; 14525 } 14526 break; 14527 case COMPONENT_ENABLED_STATE_DEFAULT: 14528 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14529 return; 14530 } 14531 break; 14532 default: 14533 Slog.e(TAG, "Invalid new component state: " + newState); 14534 return; 14535 } 14536 } 14537 scheduleWritePackageRestrictionsLocked(userId); 14538 components = mPendingBroadcasts.get(userId, packageName); 14539 final boolean newPackage = components == null; 14540 if (newPackage) { 14541 components = new ArrayList<String>(); 14542 } 14543 if (!components.contains(componentName)) { 14544 components.add(componentName); 14545 } 14546 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14547 sendNow = true; 14548 // Purge entry from pending broadcast list if another one exists already 14549 // since we are sending one right away. 14550 mPendingBroadcasts.remove(userId, packageName); 14551 } else { 14552 if (newPackage) { 14553 mPendingBroadcasts.put(userId, packageName, components); 14554 } 14555 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14556 // Schedule a message 14557 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14558 } 14559 } 14560 } 14561 14562 long callingId = Binder.clearCallingIdentity(); 14563 try { 14564 if (sendNow) { 14565 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14566 sendPackageChangedBroadcast(packageName, 14567 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14568 } 14569 } finally { 14570 Binder.restoreCallingIdentity(callingId); 14571 } 14572 } 14573 14574 private void sendPackageChangedBroadcast(String packageName, 14575 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14576 if (DEBUG_INSTALL) 14577 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14578 + componentNames); 14579 Bundle extras = new Bundle(4); 14580 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14581 String nameList[] = new String[componentNames.size()]; 14582 componentNames.toArray(nameList); 14583 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14584 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14585 extras.putInt(Intent.EXTRA_UID, packageUid); 14586 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14587 new int[] {UserHandle.getUserId(packageUid)}); 14588 } 14589 14590 @Override 14591 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14592 if (!sUserManager.exists(userId)) return; 14593 final int uid = Binder.getCallingUid(); 14594 final int permission = mContext.checkCallingOrSelfPermission( 14595 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14596 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14597 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14598 // writer 14599 synchronized (mPackages) { 14600 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14601 allowedByPermission, uid, userId)) { 14602 scheduleWritePackageRestrictionsLocked(userId); 14603 } 14604 } 14605 } 14606 14607 @Override 14608 public String getInstallerPackageName(String packageName) { 14609 // reader 14610 synchronized (mPackages) { 14611 return mSettings.getInstallerPackageNameLPr(packageName); 14612 } 14613 } 14614 14615 @Override 14616 public int getApplicationEnabledSetting(String packageName, int userId) { 14617 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14618 int uid = Binder.getCallingUid(); 14619 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14620 // reader 14621 synchronized (mPackages) { 14622 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14623 } 14624 } 14625 14626 @Override 14627 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14628 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14629 int uid = Binder.getCallingUid(); 14630 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14631 // reader 14632 synchronized (mPackages) { 14633 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14634 } 14635 } 14636 14637 @Override 14638 public void enterSafeMode() { 14639 enforceSystemOrRoot("Only the system can request entering safe mode"); 14640 14641 if (!mSystemReady) { 14642 mSafeMode = true; 14643 } 14644 } 14645 14646 @Override 14647 public void systemReady() { 14648 mSystemReady = true; 14649 14650 // Read the compatibilty setting when the system is ready. 14651 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14652 mContext.getContentResolver(), 14653 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14654 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14655 if (DEBUG_SETTINGS) { 14656 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14657 } 14658 14659 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14660 14661 synchronized (mPackages) { 14662 // Verify that all of the preferred activity components actually 14663 // exist. It is possible for applications to be updated and at 14664 // that point remove a previously declared activity component that 14665 // had been set as a preferred activity. We try to clean this up 14666 // the next time we encounter that preferred activity, but it is 14667 // possible for the user flow to never be able to return to that 14668 // situation so here we do a sanity check to make sure we haven't 14669 // left any junk around. 14670 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14671 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14672 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14673 removed.clear(); 14674 for (PreferredActivity pa : pir.filterSet()) { 14675 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14676 removed.add(pa); 14677 } 14678 } 14679 if (removed.size() > 0) { 14680 for (int r=0; r<removed.size(); r++) { 14681 PreferredActivity pa = removed.get(r); 14682 Slog.w(TAG, "Removing dangling preferred activity: " 14683 + pa.mPref.mComponent); 14684 pir.removeFilter(pa); 14685 } 14686 mSettings.writePackageRestrictionsLPr( 14687 mSettings.mPreferredActivities.keyAt(i)); 14688 } 14689 } 14690 14691 for (int userId : UserManagerService.getInstance().getUserIds()) { 14692 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14693 grantPermissionsUserIds = ArrayUtils.appendInt( 14694 grantPermissionsUserIds, userId); 14695 } 14696 } 14697 } 14698 sUserManager.systemReady(); 14699 14700 // If we upgraded grant all default permissions before kicking off. 14701 for (int userId : grantPermissionsUserIds) { 14702 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14703 } 14704 14705 // Kick off any messages waiting for system ready 14706 if (mPostSystemReadyMessages != null) { 14707 for (Message msg : mPostSystemReadyMessages) { 14708 msg.sendToTarget(); 14709 } 14710 mPostSystemReadyMessages = null; 14711 } 14712 14713 // Watch for external volumes that come and go over time 14714 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14715 storage.registerListener(mStorageListener); 14716 14717 mInstallerService.systemReady(); 14718 mPackageDexOptimizer.systemReady(); 14719 14720 MountServiceInternal mountServiceInternal = LocalServices.getService( 14721 MountServiceInternal.class); 14722 mountServiceInternal.addExternalStoragePolicy( 14723 new MountServiceInternal.ExternalStorageMountPolicy() { 14724 @Override 14725 public int getMountMode(int uid, String packageName) { 14726 if (Process.isIsolated(uid)) { 14727 return Zygote.MOUNT_EXTERNAL_NONE; 14728 } 14729 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14730 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14731 } 14732 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14733 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14734 } 14735 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14736 return Zygote.MOUNT_EXTERNAL_READ; 14737 } 14738 return Zygote.MOUNT_EXTERNAL_WRITE; 14739 } 14740 14741 @Override 14742 public boolean hasExternalStorage(int uid, String packageName) { 14743 return true; 14744 } 14745 }); 14746 } 14747 14748 @Override 14749 public boolean isSafeMode() { 14750 return mSafeMode; 14751 } 14752 14753 @Override 14754 public boolean hasSystemUidErrors() { 14755 return mHasSystemUidErrors; 14756 } 14757 14758 static String arrayToString(int[] array) { 14759 StringBuffer buf = new StringBuffer(128); 14760 buf.append('['); 14761 if (array != null) { 14762 for (int i=0; i<array.length; i++) { 14763 if (i > 0) buf.append(", "); 14764 buf.append(array[i]); 14765 } 14766 } 14767 buf.append(']'); 14768 return buf.toString(); 14769 } 14770 14771 static class DumpState { 14772 public static final int DUMP_LIBS = 1 << 0; 14773 public static final int DUMP_FEATURES = 1 << 1; 14774 public static final int DUMP_RESOLVERS = 1 << 2; 14775 public static final int DUMP_PERMISSIONS = 1 << 3; 14776 public static final int DUMP_PACKAGES = 1 << 4; 14777 public static final int DUMP_SHARED_USERS = 1 << 5; 14778 public static final int DUMP_MESSAGES = 1 << 6; 14779 public static final int DUMP_PROVIDERS = 1 << 7; 14780 public static final int DUMP_VERIFIERS = 1 << 8; 14781 public static final int DUMP_PREFERRED = 1 << 9; 14782 public static final int DUMP_PREFERRED_XML = 1 << 10; 14783 public static final int DUMP_KEYSETS = 1 << 11; 14784 public static final int DUMP_VERSION = 1 << 12; 14785 public static final int DUMP_INSTALLS = 1 << 13; 14786 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14787 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14788 14789 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14790 14791 private int mTypes; 14792 14793 private int mOptions; 14794 14795 private boolean mTitlePrinted; 14796 14797 private SharedUserSetting mSharedUser; 14798 14799 public boolean isDumping(int type) { 14800 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14801 return true; 14802 } 14803 14804 return (mTypes & type) != 0; 14805 } 14806 14807 public void setDump(int type) { 14808 mTypes |= type; 14809 } 14810 14811 public boolean isOptionEnabled(int option) { 14812 return (mOptions & option) != 0; 14813 } 14814 14815 public void setOptionEnabled(int option) { 14816 mOptions |= option; 14817 } 14818 14819 public boolean onTitlePrinted() { 14820 final boolean printed = mTitlePrinted; 14821 mTitlePrinted = true; 14822 return printed; 14823 } 14824 14825 public boolean getTitlePrinted() { 14826 return mTitlePrinted; 14827 } 14828 14829 public void setTitlePrinted(boolean enabled) { 14830 mTitlePrinted = enabled; 14831 } 14832 14833 public SharedUserSetting getSharedUser() { 14834 return mSharedUser; 14835 } 14836 14837 public void setSharedUser(SharedUserSetting user) { 14838 mSharedUser = user; 14839 } 14840 } 14841 14842 @Override 14843 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14844 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14845 != PackageManager.PERMISSION_GRANTED) { 14846 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14847 + Binder.getCallingPid() 14848 + ", uid=" + Binder.getCallingUid() 14849 + " without permission " 14850 + android.Manifest.permission.DUMP); 14851 return; 14852 } 14853 14854 DumpState dumpState = new DumpState(); 14855 boolean fullPreferred = false; 14856 boolean checkin = false; 14857 14858 String packageName = null; 14859 ArraySet<String> permissionNames = null; 14860 14861 int opti = 0; 14862 while (opti < args.length) { 14863 String opt = args[opti]; 14864 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14865 break; 14866 } 14867 opti++; 14868 14869 if ("-a".equals(opt)) { 14870 // Right now we only know how to print all. 14871 } else if ("-h".equals(opt)) { 14872 pw.println("Package manager dump options:"); 14873 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14874 pw.println(" --checkin: dump for a checkin"); 14875 pw.println(" -f: print details of intent filters"); 14876 pw.println(" -h: print this help"); 14877 pw.println(" cmd may be one of:"); 14878 pw.println(" l[ibraries]: list known shared libraries"); 14879 pw.println(" f[ibraries]: list device features"); 14880 pw.println(" k[eysets]: print known keysets"); 14881 pw.println(" r[esolvers]: dump intent resolvers"); 14882 pw.println(" perm[issions]: dump permissions"); 14883 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14884 pw.println(" pref[erred]: print preferred package settings"); 14885 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14886 pw.println(" prov[iders]: dump content providers"); 14887 pw.println(" p[ackages]: dump installed packages"); 14888 pw.println(" s[hared-users]: dump shared user IDs"); 14889 pw.println(" m[essages]: print collected runtime messages"); 14890 pw.println(" v[erifiers]: print package verifier info"); 14891 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14892 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14893 pw.println(" version: print database version info"); 14894 pw.println(" write: write current settings now"); 14895 pw.println(" installs: details about install sessions"); 14896 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 14897 pw.println(" <package.name>: info about given package"); 14898 return; 14899 } else if ("--checkin".equals(opt)) { 14900 checkin = true; 14901 } else if ("-f".equals(opt)) { 14902 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14903 } else { 14904 pw.println("Unknown argument: " + opt + "; use -h for help"); 14905 } 14906 } 14907 14908 // Is the caller requesting to dump a particular piece of data? 14909 if (opti < args.length) { 14910 String cmd = args[opti]; 14911 opti++; 14912 // Is this a package name? 14913 if ("android".equals(cmd) || cmd.contains(".")) { 14914 packageName = cmd; 14915 // When dumping a single package, we always dump all of its 14916 // filter information since the amount of data will be reasonable. 14917 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14918 } else if ("check-permission".equals(cmd)) { 14919 if (opti >= args.length) { 14920 pw.println("Error: check-permission missing permission argument"); 14921 return; 14922 } 14923 String perm = args[opti]; 14924 opti++; 14925 if (opti >= args.length) { 14926 pw.println("Error: check-permission missing package argument"); 14927 return; 14928 } 14929 String pkg = args[opti]; 14930 opti++; 14931 int user = UserHandle.getUserId(Binder.getCallingUid()); 14932 if (opti < args.length) { 14933 try { 14934 user = Integer.parseInt(args[opti]); 14935 } catch (NumberFormatException e) { 14936 pw.println("Error: check-permission user argument is not a number: " 14937 + args[opti]); 14938 return; 14939 } 14940 } 14941 pw.println(checkPermission(perm, pkg, user)); 14942 return; 14943 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14944 dumpState.setDump(DumpState.DUMP_LIBS); 14945 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14946 dumpState.setDump(DumpState.DUMP_FEATURES); 14947 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14948 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14949 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14950 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14951 } else if ("permission".equals(cmd)) { 14952 if (opti >= args.length) { 14953 pw.println("Error: permission requires permission name"); 14954 return; 14955 } 14956 permissionNames = new ArraySet<>(); 14957 while (opti < args.length) { 14958 permissionNames.add(args[opti]); 14959 opti++; 14960 } 14961 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14962 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14963 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14964 dumpState.setDump(DumpState.DUMP_PREFERRED); 14965 } else if ("preferred-xml".equals(cmd)) { 14966 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14967 if (opti < args.length && "--full".equals(args[opti])) { 14968 fullPreferred = true; 14969 opti++; 14970 } 14971 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14972 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14973 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14974 dumpState.setDump(DumpState.DUMP_PACKAGES); 14975 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14976 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14977 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14978 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14979 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14980 dumpState.setDump(DumpState.DUMP_MESSAGES); 14981 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14982 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14983 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14984 || "intent-filter-verifiers".equals(cmd)) { 14985 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14986 } else if ("version".equals(cmd)) { 14987 dumpState.setDump(DumpState.DUMP_VERSION); 14988 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14989 dumpState.setDump(DumpState.DUMP_KEYSETS); 14990 } else if ("installs".equals(cmd)) { 14991 dumpState.setDump(DumpState.DUMP_INSTALLS); 14992 } else if ("write".equals(cmd)) { 14993 synchronized (mPackages) { 14994 mSettings.writeLPr(); 14995 pw.println("Settings written."); 14996 return; 14997 } 14998 } 14999 } 15000 15001 if (checkin) { 15002 pw.println("vers,1"); 15003 } 15004 15005 // reader 15006 synchronized (mPackages) { 15007 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15008 if (!checkin) { 15009 if (dumpState.onTitlePrinted()) 15010 pw.println(); 15011 pw.println("Database versions:"); 15012 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15013 } 15014 } 15015 15016 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15017 if (!checkin) { 15018 if (dumpState.onTitlePrinted()) 15019 pw.println(); 15020 pw.println("Verifiers:"); 15021 pw.print(" Required: "); 15022 pw.print(mRequiredVerifierPackage); 15023 pw.print(" (uid="); 15024 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15025 pw.println(")"); 15026 } else if (mRequiredVerifierPackage != null) { 15027 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15028 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15029 } 15030 } 15031 15032 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15033 packageName == null) { 15034 if (mIntentFilterVerifierComponent != null) { 15035 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15036 if (!checkin) { 15037 if (dumpState.onTitlePrinted()) 15038 pw.println(); 15039 pw.println("Intent Filter Verifier:"); 15040 pw.print(" Using: "); 15041 pw.print(verifierPackageName); 15042 pw.print(" (uid="); 15043 pw.print(getPackageUid(verifierPackageName, 0)); 15044 pw.println(")"); 15045 } else if (verifierPackageName != null) { 15046 pw.print("ifv,"); pw.print(verifierPackageName); 15047 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15048 } 15049 } else { 15050 pw.println(); 15051 pw.println("No Intent Filter Verifier available!"); 15052 } 15053 } 15054 15055 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15056 boolean printedHeader = false; 15057 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15058 while (it.hasNext()) { 15059 String name = it.next(); 15060 SharedLibraryEntry ent = mSharedLibraries.get(name); 15061 if (!checkin) { 15062 if (!printedHeader) { 15063 if (dumpState.onTitlePrinted()) 15064 pw.println(); 15065 pw.println("Libraries:"); 15066 printedHeader = true; 15067 } 15068 pw.print(" "); 15069 } else { 15070 pw.print("lib,"); 15071 } 15072 pw.print(name); 15073 if (!checkin) { 15074 pw.print(" -> "); 15075 } 15076 if (ent.path != null) { 15077 if (!checkin) { 15078 pw.print("(jar) "); 15079 pw.print(ent.path); 15080 } else { 15081 pw.print(",jar,"); 15082 pw.print(ent.path); 15083 } 15084 } else { 15085 if (!checkin) { 15086 pw.print("(apk) "); 15087 pw.print(ent.apk); 15088 } else { 15089 pw.print(",apk,"); 15090 pw.print(ent.apk); 15091 } 15092 } 15093 pw.println(); 15094 } 15095 } 15096 15097 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15098 if (dumpState.onTitlePrinted()) 15099 pw.println(); 15100 if (!checkin) { 15101 pw.println("Features:"); 15102 } 15103 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15104 while (it.hasNext()) { 15105 String name = it.next(); 15106 if (!checkin) { 15107 pw.print(" "); 15108 } else { 15109 pw.print("feat,"); 15110 } 15111 pw.println(name); 15112 } 15113 } 15114 15115 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15116 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15117 : "Activity Resolver Table:", " ", packageName, 15118 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15119 dumpState.setTitlePrinted(true); 15120 } 15121 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15122 : "Receiver Resolver Table:", " ", packageName, 15123 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15124 dumpState.setTitlePrinted(true); 15125 } 15126 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15127 : "Service Resolver Table:", " ", packageName, 15128 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15129 dumpState.setTitlePrinted(true); 15130 } 15131 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15132 : "Provider Resolver Table:", " ", packageName, 15133 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15134 dumpState.setTitlePrinted(true); 15135 } 15136 } 15137 15138 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15139 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15140 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15141 int user = mSettings.mPreferredActivities.keyAt(i); 15142 if (pir.dump(pw, 15143 dumpState.getTitlePrinted() 15144 ? "\nPreferred Activities User " + user + ":" 15145 : "Preferred Activities User " + user + ":", " ", 15146 packageName, true, false)) { 15147 dumpState.setTitlePrinted(true); 15148 } 15149 } 15150 } 15151 15152 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15153 pw.flush(); 15154 FileOutputStream fout = new FileOutputStream(fd); 15155 BufferedOutputStream str = new BufferedOutputStream(fout); 15156 XmlSerializer serializer = new FastXmlSerializer(); 15157 try { 15158 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15159 serializer.startDocument(null, true); 15160 serializer.setFeature( 15161 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15162 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15163 serializer.endDocument(); 15164 serializer.flush(); 15165 } catch (IllegalArgumentException e) { 15166 pw.println("Failed writing: " + e); 15167 } catch (IllegalStateException e) { 15168 pw.println("Failed writing: " + e); 15169 } catch (IOException e) { 15170 pw.println("Failed writing: " + e); 15171 } 15172 } 15173 15174 if (!checkin 15175 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15176 && packageName == null) { 15177 pw.println(); 15178 int count = mSettings.mPackages.size(); 15179 if (count == 0) { 15180 pw.println("No applications!"); 15181 pw.println(); 15182 } else { 15183 final String prefix = " "; 15184 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15185 if (allPackageSettings.size() == 0) { 15186 pw.println("No domain preferred apps!"); 15187 pw.println(); 15188 } else { 15189 pw.println("App verification status:"); 15190 pw.println(); 15191 count = 0; 15192 for (PackageSetting ps : allPackageSettings) { 15193 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15194 if (ivi == null || ivi.getPackageName() == null) continue; 15195 pw.println(prefix + "Package: " + ivi.getPackageName()); 15196 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15197 pw.println(prefix + "Status: " + ivi.getStatusString()); 15198 pw.println(); 15199 count++; 15200 } 15201 if (count == 0) { 15202 pw.println(prefix + "No app verification established."); 15203 pw.println(); 15204 } 15205 for (int userId : sUserManager.getUserIds()) { 15206 pw.println("App linkages for user " + userId + ":"); 15207 pw.println(); 15208 count = 0; 15209 for (PackageSetting ps : allPackageSettings) { 15210 final long status = ps.getDomainVerificationStatusForUser(userId); 15211 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15212 continue; 15213 } 15214 pw.println(prefix + "Package: " + ps.name); 15215 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15216 String statusStr = IntentFilterVerificationInfo. 15217 getStatusStringFromValue(status); 15218 pw.println(prefix + "Status: " + statusStr); 15219 pw.println(); 15220 count++; 15221 } 15222 if (count == 0) { 15223 pw.println(prefix + "No configured app linkages."); 15224 pw.println(); 15225 } 15226 } 15227 } 15228 } 15229 } 15230 15231 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15232 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15233 if (packageName == null && permissionNames == null) { 15234 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15235 if (iperm == 0) { 15236 if (dumpState.onTitlePrinted()) 15237 pw.println(); 15238 pw.println("AppOp Permissions:"); 15239 } 15240 pw.print(" AppOp Permission "); 15241 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15242 pw.println(":"); 15243 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15244 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15245 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15246 } 15247 } 15248 } 15249 } 15250 15251 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15252 boolean printedSomething = false; 15253 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15254 if (packageName != null && !packageName.equals(p.info.packageName)) { 15255 continue; 15256 } 15257 if (!printedSomething) { 15258 if (dumpState.onTitlePrinted()) 15259 pw.println(); 15260 pw.println("Registered ContentProviders:"); 15261 printedSomething = true; 15262 } 15263 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15264 pw.print(" "); pw.println(p.toString()); 15265 } 15266 printedSomething = false; 15267 for (Map.Entry<String, PackageParser.Provider> entry : 15268 mProvidersByAuthority.entrySet()) { 15269 PackageParser.Provider p = entry.getValue(); 15270 if (packageName != null && !packageName.equals(p.info.packageName)) { 15271 continue; 15272 } 15273 if (!printedSomething) { 15274 if (dumpState.onTitlePrinted()) 15275 pw.println(); 15276 pw.println("ContentProvider Authorities:"); 15277 printedSomething = true; 15278 } 15279 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15280 pw.print(" "); pw.println(p.toString()); 15281 if (p.info != null && p.info.applicationInfo != null) { 15282 final String appInfo = p.info.applicationInfo.toString(); 15283 pw.print(" applicationInfo="); pw.println(appInfo); 15284 } 15285 } 15286 } 15287 15288 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15289 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15290 } 15291 15292 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15293 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15294 } 15295 15296 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15297 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15298 } 15299 15300 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15301 // XXX should handle packageName != null by dumping only install data that 15302 // the given package is involved with. 15303 if (dumpState.onTitlePrinted()) pw.println(); 15304 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15305 } 15306 15307 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15308 if (dumpState.onTitlePrinted()) pw.println(); 15309 mSettings.dumpReadMessagesLPr(pw, dumpState); 15310 15311 pw.println(); 15312 pw.println("Package warning messages:"); 15313 BufferedReader in = null; 15314 String line = null; 15315 try { 15316 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15317 while ((line = in.readLine()) != null) { 15318 if (line.contains("ignored: updated version")) continue; 15319 pw.println(line); 15320 } 15321 } catch (IOException ignored) { 15322 } finally { 15323 IoUtils.closeQuietly(in); 15324 } 15325 } 15326 15327 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15328 BufferedReader in = null; 15329 String line = null; 15330 try { 15331 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15332 while ((line = in.readLine()) != null) { 15333 if (line.contains("ignored: updated version")) continue; 15334 pw.print("msg,"); 15335 pw.println(line); 15336 } 15337 } catch (IOException ignored) { 15338 } finally { 15339 IoUtils.closeQuietly(in); 15340 } 15341 } 15342 } 15343 } 15344 15345 private String dumpDomainString(String packageName) { 15346 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15347 List<IntentFilter> filters = getAllIntentFilters(packageName); 15348 15349 ArraySet<String> result = new ArraySet<>(); 15350 if (iviList.size() > 0) { 15351 for (IntentFilterVerificationInfo ivi : iviList) { 15352 for (String host : ivi.getDomains()) { 15353 result.add(host); 15354 } 15355 } 15356 } 15357 if (filters != null && filters.size() > 0) { 15358 for (IntentFilter filter : filters) { 15359 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15360 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15361 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15362 result.addAll(filter.getHostsList()); 15363 } 15364 } 15365 } 15366 15367 StringBuilder sb = new StringBuilder(result.size() * 16); 15368 for (String domain : result) { 15369 if (sb.length() > 0) sb.append(" "); 15370 sb.append(domain); 15371 } 15372 return sb.toString(); 15373 } 15374 15375 // ------- apps on sdcard specific code ------- 15376 static final boolean DEBUG_SD_INSTALL = false; 15377 15378 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15379 15380 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15381 15382 private boolean mMediaMounted = false; 15383 15384 static String getEncryptKey() { 15385 try { 15386 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15387 SD_ENCRYPTION_KEYSTORE_NAME); 15388 if (sdEncKey == null) { 15389 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15390 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15391 if (sdEncKey == null) { 15392 Slog.e(TAG, "Failed to create encryption keys"); 15393 return null; 15394 } 15395 } 15396 return sdEncKey; 15397 } catch (NoSuchAlgorithmException nsae) { 15398 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15399 return null; 15400 } catch (IOException ioe) { 15401 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15402 return null; 15403 } 15404 } 15405 15406 /* 15407 * Update media status on PackageManager. 15408 */ 15409 @Override 15410 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15411 int callingUid = Binder.getCallingUid(); 15412 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15413 throw new SecurityException("Media status can only be updated by the system"); 15414 } 15415 // reader; this apparently protects mMediaMounted, but should probably 15416 // be a different lock in that case. 15417 synchronized (mPackages) { 15418 Log.i(TAG, "Updating external media status from " 15419 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15420 + (mediaStatus ? "mounted" : "unmounted")); 15421 if (DEBUG_SD_INSTALL) 15422 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15423 + ", mMediaMounted=" + mMediaMounted); 15424 if (mediaStatus == mMediaMounted) { 15425 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15426 : 0, -1); 15427 mHandler.sendMessage(msg); 15428 return; 15429 } 15430 mMediaMounted = mediaStatus; 15431 } 15432 // Queue up an async operation since the package installation may take a 15433 // little while. 15434 mHandler.post(new Runnable() { 15435 public void run() { 15436 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15437 } 15438 }); 15439 } 15440 15441 /** 15442 * Called by MountService when the initial ASECs to scan are available. 15443 * Should block until all the ASEC containers are finished being scanned. 15444 */ 15445 public void scanAvailableAsecs() { 15446 updateExternalMediaStatusInner(true, false, false); 15447 if (mShouldRestoreconData) { 15448 SELinuxMMAC.setRestoreconDone(); 15449 mShouldRestoreconData = false; 15450 } 15451 } 15452 15453 /* 15454 * Collect information of applications on external media, map them against 15455 * existing containers and update information based on current mount status. 15456 * Please note that we always have to report status if reportStatus has been 15457 * set to true especially when unloading packages. 15458 */ 15459 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15460 boolean externalStorage) { 15461 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15462 int[] uidArr = EmptyArray.INT; 15463 15464 final String[] list = PackageHelper.getSecureContainerList(); 15465 if (ArrayUtils.isEmpty(list)) { 15466 Log.i(TAG, "No secure containers found"); 15467 } else { 15468 // Process list of secure containers and categorize them 15469 // as active or stale based on their package internal state. 15470 15471 // reader 15472 synchronized (mPackages) { 15473 for (String cid : list) { 15474 // Leave stages untouched for now; installer service owns them 15475 if (PackageInstallerService.isStageName(cid)) continue; 15476 15477 if (DEBUG_SD_INSTALL) 15478 Log.i(TAG, "Processing container " + cid); 15479 String pkgName = getAsecPackageName(cid); 15480 if (pkgName == null) { 15481 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15482 continue; 15483 } 15484 if (DEBUG_SD_INSTALL) 15485 Log.i(TAG, "Looking for pkg : " + pkgName); 15486 15487 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15488 if (ps == null) { 15489 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15490 continue; 15491 } 15492 15493 /* 15494 * Skip packages that are not external if we're unmounting 15495 * external storage. 15496 */ 15497 if (externalStorage && !isMounted && !isExternal(ps)) { 15498 continue; 15499 } 15500 15501 final AsecInstallArgs args = new AsecInstallArgs(cid, 15502 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15503 // The package status is changed only if the code path 15504 // matches between settings and the container id. 15505 if (ps.codePathString != null 15506 && ps.codePathString.startsWith(args.getCodePath())) { 15507 if (DEBUG_SD_INSTALL) { 15508 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15509 + " at code path: " + ps.codePathString); 15510 } 15511 15512 // We do have a valid package installed on sdcard 15513 processCids.put(args, ps.codePathString); 15514 final int uid = ps.appId; 15515 if (uid != -1) { 15516 uidArr = ArrayUtils.appendInt(uidArr, uid); 15517 } 15518 } else { 15519 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15520 + ps.codePathString); 15521 } 15522 } 15523 } 15524 15525 Arrays.sort(uidArr); 15526 } 15527 15528 // Process packages with valid entries. 15529 if (isMounted) { 15530 if (DEBUG_SD_INSTALL) 15531 Log.i(TAG, "Loading packages"); 15532 loadMediaPackages(processCids, uidArr, externalStorage); 15533 startCleaningPackages(); 15534 mInstallerService.onSecureContainersAvailable(); 15535 } else { 15536 if (DEBUG_SD_INSTALL) 15537 Log.i(TAG, "Unloading packages"); 15538 unloadMediaPackages(processCids, uidArr, reportStatus); 15539 } 15540 } 15541 15542 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15543 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15544 final int size = infos.size(); 15545 final String[] packageNames = new String[size]; 15546 final int[] packageUids = new int[size]; 15547 for (int i = 0; i < size; i++) { 15548 final ApplicationInfo info = infos.get(i); 15549 packageNames[i] = info.packageName; 15550 packageUids[i] = info.uid; 15551 } 15552 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15553 finishedReceiver); 15554 } 15555 15556 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15557 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15558 sendResourcesChangedBroadcast(mediaStatus, replacing, 15559 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15560 } 15561 15562 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15563 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15564 int size = pkgList.length; 15565 if (size > 0) { 15566 // Send broadcasts here 15567 Bundle extras = new Bundle(); 15568 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15569 if (uidArr != null) { 15570 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15571 } 15572 if (replacing) { 15573 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15574 } 15575 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15576 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15577 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15578 } 15579 } 15580 15581 /* 15582 * Look at potentially valid container ids from processCids If package 15583 * information doesn't match the one on record or package scanning fails, 15584 * the cid is added to list of removeCids. We currently don't delete stale 15585 * containers. 15586 */ 15587 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 15588 boolean externalStorage) { 15589 ArrayList<String> pkgList = new ArrayList<String>(); 15590 Set<AsecInstallArgs> keys = processCids.keySet(); 15591 15592 for (AsecInstallArgs args : keys) { 15593 String codePath = processCids.get(args); 15594 if (DEBUG_SD_INSTALL) 15595 Log.i(TAG, "Loading container : " + args.cid); 15596 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15597 try { 15598 // Make sure there are no container errors first. 15599 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15600 Slog.e(TAG, "Failed to mount cid : " + args.cid 15601 + " when installing from sdcard"); 15602 continue; 15603 } 15604 // Check code path here. 15605 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15606 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15607 + " does not match one in settings " + codePath); 15608 continue; 15609 } 15610 // Parse package 15611 int parseFlags = mDefParseFlags; 15612 if (args.isExternalAsec()) { 15613 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15614 } 15615 if (args.isFwdLocked()) { 15616 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15617 } 15618 15619 synchronized (mInstallLock) { 15620 PackageParser.Package pkg = null; 15621 try { 15622 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15623 } catch (PackageManagerException e) { 15624 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15625 } 15626 // Scan the package 15627 if (pkg != null) { 15628 /* 15629 * TODO why is the lock being held? doPostInstall is 15630 * called in other places without the lock. This needs 15631 * to be straightened out. 15632 */ 15633 // writer 15634 synchronized (mPackages) { 15635 retCode = PackageManager.INSTALL_SUCCEEDED; 15636 pkgList.add(pkg.packageName); 15637 // Post process args 15638 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15639 pkg.applicationInfo.uid); 15640 } 15641 } else { 15642 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15643 } 15644 } 15645 15646 } finally { 15647 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15648 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15649 } 15650 } 15651 } 15652 // writer 15653 synchronized (mPackages) { 15654 // If the platform SDK has changed since the last time we booted, 15655 // we need to re-grant app permission to catch any new ones that 15656 // appear. This is really a hack, and means that apps can in some 15657 // cases get permissions that the user didn't initially explicitly 15658 // allow... it would be nice to have some better way to handle 15659 // this situation. 15660 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 15661 : mSettings.getInternalVersion(); 15662 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 15663 : StorageManager.UUID_PRIVATE_INTERNAL; 15664 15665 int updateFlags = UPDATE_PERMISSIONS_ALL; 15666 if (ver.sdkVersion != mSdkVersion) { 15667 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15668 + mSdkVersion + "; regranting permissions for external"); 15669 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15670 } 15671 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 15672 15673 // Yay, everything is now upgraded 15674 ver.forceCurrent(); 15675 15676 // can downgrade to reader 15677 // Persist settings 15678 mSettings.writeLPr(); 15679 } 15680 // Send a broadcast to let everyone know we are done processing 15681 if (pkgList.size() > 0) { 15682 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15683 } 15684 } 15685 15686 /* 15687 * Utility method to unload a list of specified containers 15688 */ 15689 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15690 // Just unmount all valid containers. 15691 for (AsecInstallArgs arg : cidArgs) { 15692 synchronized (mInstallLock) { 15693 arg.doPostDeleteLI(false); 15694 } 15695 } 15696 } 15697 15698 /* 15699 * Unload packages mounted on external media. This involves deleting package 15700 * data from internal structures, sending broadcasts about diabled packages, 15701 * gc'ing to free up references, unmounting all secure containers 15702 * corresponding to packages on external media, and posting a 15703 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15704 * that we always have to post this message if status has been requested no 15705 * matter what. 15706 */ 15707 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15708 final boolean reportStatus) { 15709 if (DEBUG_SD_INSTALL) 15710 Log.i(TAG, "unloading media packages"); 15711 ArrayList<String> pkgList = new ArrayList<String>(); 15712 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15713 final Set<AsecInstallArgs> keys = processCids.keySet(); 15714 for (AsecInstallArgs args : keys) { 15715 String pkgName = args.getPackageName(); 15716 if (DEBUG_SD_INSTALL) 15717 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15718 // Delete package internally 15719 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15720 synchronized (mInstallLock) { 15721 boolean res = deletePackageLI(pkgName, null, false, null, null, 15722 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15723 if (res) { 15724 pkgList.add(pkgName); 15725 } else { 15726 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15727 failedList.add(args); 15728 } 15729 } 15730 } 15731 15732 // reader 15733 synchronized (mPackages) { 15734 // We didn't update the settings after removing each package; 15735 // write them now for all packages. 15736 mSettings.writeLPr(); 15737 } 15738 15739 // We have to absolutely send UPDATED_MEDIA_STATUS only 15740 // after confirming that all the receivers processed the ordered 15741 // broadcast when packages get disabled, force a gc to clean things up. 15742 // and unload all the containers. 15743 if (pkgList.size() > 0) { 15744 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15745 new IIntentReceiver.Stub() { 15746 public void performReceive(Intent intent, int resultCode, String data, 15747 Bundle extras, boolean ordered, boolean sticky, 15748 int sendingUser) throws RemoteException { 15749 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15750 reportStatus ? 1 : 0, 1, keys); 15751 mHandler.sendMessage(msg); 15752 } 15753 }); 15754 } else { 15755 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15756 keys); 15757 mHandler.sendMessage(msg); 15758 } 15759 } 15760 15761 private void loadPrivatePackages(final VolumeInfo vol) { 15762 mHandler.post(new Runnable() { 15763 @Override 15764 public void run() { 15765 loadPrivatePackagesInner(vol); 15766 } 15767 }); 15768 } 15769 15770 private void loadPrivatePackagesInner(VolumeInfo vol) { 15771 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15772 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15773 15774 final VersionInfo ver; 15775 final List<PackageSetting> packages; 15776 synchronized (mPackages) { 15777 ver = mSettings.findOrCreateVersion(vol.fsUuid); 15778 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15779 } 15780 15781 for (PackageSetting ps : packages) { 15782 synchronized (mInstallLock) { 15783 final PackageParser.Package pkg; 15784 try { 15785 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15786 loaded.add(pkg.applicationInfo); 15787 } catch (PackageManagerException e) { 15788 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15789 } 15790 15791 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15792 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15793 } 15794 } 15795 } 15796 15797 synchronized (mPackages) { 15798 int updateFlags = UPDATE_PERMISSIONS_ALL; 15799 if (ver.sdkVersion != mSdkVersion) { 15800 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15801 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15802 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15803 } 15804 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 15805 15806 // Yay, everything is now upgraded 15807 ver.forceCurrent(); 15808 15809 mSettings.writeLPr(); 15810 } 15811 15812 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15813 sendResourcesChangedBroadcast(true, false, loaded, null); 15814 } 15815 15816 private void unloadPrivatePackages(final VolumeInfo vol) { 15817 mHandler.post(new Runnable() { 15818 @Override 15819 public void run() { 15820 unloadPrivatePackagesInner(vol); 15821 } 15822 }); 15823 } 15824 15825 private void unloadPrivatePackagesInner(VolumeInfo vol) { 15826 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15827 synchronized (mInstallLock) { 15828 synchronized (mPackages) { 15829 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15830 for (PackageSetting ps : packages) { 15831 if (ps.pkg == null) continue; 15832 15833 final ApplicationInfo info = ps.pkg.applicationInfo; 15834 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15835 if (deletePackageLI(ps.name, null, false, null, null, 15836 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15837 unloaded.add(info); 15838 } else { 15839 Slog.w(TAG, "Failed to unload " + ps.codePath); 15840 } 15841 } 15842 15843 mSettings.writeLPr(); 15844 } 15845 } 15846 15847 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15848 sendResourcesChangedBroadcast(false, false, unloaded, null); 15849 } 15850 15851 /** 15852 * Examine all users present on given mounted volume, and destroy data 15853 * belonging to users that are no longer valid, or whose user ID has been 15854 * recycled. 15855 */ 15856 private void reconcileUsers(String volumeUuid) { 15857 final File[] files = FileUtils 15858 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15859 for (File file : files) { 15860 if (!file.isDirectory()) continue; 15861 15862 final int userId; 15863 final UserInfo info; 15864 try { 15865 userId = Integer.parseInt(file.getName()); 15866 info = sUserManager.getUserInfo(userId); 15867 } catch (NumberFormatException e) { 15868 Slog.w(TAG, "Invalid user directory " + file); 15869 continue; 15870 } 15871 15872 boolean destroyUser = false; 15873 if (info == null) { 15874 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15875 + " because no matching user was found"); 15876 destroyUser = true; 15877 } else { 15878 try { 15879 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15880 } catch (IOException e) { 15881 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15882 + " because we failed to enforce serial number: " + e); 15883 destroyUser = true; 15884 } 15885 } 15886 15887 if (destroyUser) { 15888 synchronized (mInstallLock) { 15889 mInstaller.removeUserDataDirs(volumeUuid, userId); 15890 } 15891 } 15892 } 15893 15894 final UserManager um = mContext.getSystemService(UserManager.class); 15895 for (UserInfo user : um.getUsers()) { 15896 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15897 if (userDir.exists()) continue; 15898 15899 try { 15900 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15901 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15902 } catch (IOException e) { 15903 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15904 } 15905 } 15906 } 15907 15908 /** 15909 * Examine all apps present on given mounted volume, and destroy apps that 15910 * aren't expected, either due to uninstallation or reinstallation on 15911 * another volume. 15912 */ 15913 private void reconcileApps(String volumeUuid) { 15914 final File[] files = FileUtils 15915 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15916 for (File file : files) { 15917 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15918 && !PackageInstallerService.isStageName(file.getName()); 15919 if (!isPackage) { 15920 // Ignore entries which are not packages 15921 continue; 15922 } 15923 15924 boolean destroyApp = false; 15925 String packageName = null; 15926 try { 15927 final PackageLite pkg = PackageParser.parsePackageLite(file, 15928 PackageParser.PARSE_MUST_BE_APK); 15929 packageName = pkg.packageName; 15930 15931 synchronized (mPackages) { 15932 final PackageSetting ps = mSettings.mPackages.get(packageName); 15933 if (ps == null) { 15934 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15935 + volumeUuid + " because we found no install record"); 15936 destroyApp = true; 15937 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15938 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15939 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15940 destroyApp = true; 15941 } 15942 } 15943 15944 } catch (PackageParserException e) { 15945 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15946 destroyApp = true; 15947 } 15948 15949 if (destroyApp) { 15950 synchronized (mInstallLock) { 15951 if (packageName != null) { 15952 removeDataDirsLI(volumeUuid, packageName); 15953 } 15954 if (file.isDirectory()) { 15955 mInstaller.rmPackageDir(file.getAbsolutePath()); 15956 } else { 15957 file.delete(); 15958 } 15959 } 15960 } 15961 } 15962 } 15963 15964 private void unfreezePackage(String packageName) { 15965 synchronized (mPackages) { 15966 final PackageSetting ps = mSettings.mPackages.get(packageName); 15967 if (ps != null) { 15968 ps.frozen = false; 15969 } 15970 } 15971 } 15972 15973 @Override 15974 public int movePackage(final String packageName, final String volumeUuid) { 15975 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15976 15977 final int moveId = mNextMoveId.getAndIncrement(); 15978 try { 15979 movePackageInternal(packageName, volumeUuid, moveId); 15980 } catch (PackageManagerException e) { 15981 Slog.w(TAG, "Failed to move " + packageName, e); 15982 mMoveCallbacks.notifyStatusChanged(moveId, 15983 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15984 } 15985 return moveId; 15986 } 15987 15988 private void movePackageInternal(final String packageName, final String volumeUuid, 15989 final int moveId) throws PackageManagerException { 15990 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15991 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15992 final PackageManager pm = mContext.getPackageManager(); 15993 15994 final boolean currentAsec; 15995 final String currentVolumeUuid; 15996 final File codeFile; 15997 final String installerPackageName; 15998 final String packageAbiOverride; 15999 final int appId; 16000 final String seinfo; 16001 final String label; 16002 16003 // reader 16004 synchronized (mPackages) { 16005 final PackageParser.Package pkg = mPackages.get(packageName); 16006 final PackageSetting ps = mSettings.mPackages.get(packageName); 16007 if (pkg == null || ps == null) { 16008 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16009 } 16010 16011 if (pkg.applicationInfo.isSystemApp()) { 16012 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16013 "Cannot move system application"); 16014 } 16015 16016 if (pkg.applicationInfo.isExternalAsec()) { 16017 currentAsec = true; 16018 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16019 } else if (pkg.applicationInfo.isForwardLocked()) { 16020 currentAsec = true; 16021 currentVolumeUuid = "forward_locked"; 16022 } else { 16023 currentAsec = false; 16024 currentVolumeUuid = ps.volumeUuid; 16025 16026 final File probe = new File(pkg.codePath); 16027 final File probeOat = new File(probe, "oat"); 16028 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16029 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16030 "Move only supported for modern cluster style installs"); 16031 } 16032 } 16033 16034 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16035 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16036 "Package already moved to " + volumeUuid); 16037 } 16038 16039 if (ps.frozen) { 16040 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16041 "Failed to move already frozen package"); 16042 } 16043 ps.frozen = true; 16044 16045 codeFile = new File(pkg.codePath); 16046 installerPackageName = ps.installerPackageName; 16047 packageAbiOverride = ps.cpuAbiOverrideString; 16048 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16049 seinfo = pkg.applicationInfo.seinfo; 16050 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16051 } 16052 16053 // Now that we're guarded by frozen state, kill app during move 16054 final long token = Binder.clearCallingIdentity(); 16055 try { 16056 killApplication(packageName, appId, "move pkg"); 16057 } finally { 16058 Binder.restoreCallingIdentity(token); 16059 } 16060 16061 final Bundle extras = new Bundle(); 16062 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16063 extras.putString(Intent.EXTRA_TITLE, label); 16064 mMoveCallbacks.notifyCreated(moveId, extras); 16065 16066 int installFlags; 16067 final boolean moveCompleteApp; 16068 final File measurePath; 16069 16070 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16071 installFlags = INSTALL_INTERNAL; 16072 moveCompleteApp = !currentAsec; 16073 measurePath = Environment.getDataAppDirectory(volumeUuid); 16074 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16075 installFlags = INSTALL_EXTERNAL; 16076 moveCompleteApp = false; 16077 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16078 } else { 16079 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16080 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16081 || !volume.isMountedWritable()) { 16082 unfreezePackage(packageName); 16083 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16084 "Move location not mounted private volume"); 16085 } 16086 16087 Preconditions.checkState(!currentAsec); 16088 16089 installFlags = INSTALL_INTERNAL; 16090 moveCompleteApp = true; 16091 measurePath = Environment.getDataAppDirectory(volumeUuid); 16092 } 16093 16094 final PackageStats stats = new PackageStats(null, -1); 16095 synchronized (mInstaller) { 16096 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16097 unfreezePackage(packageName); 16098 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16099 "Failed to measure package size"); 16100 } 16101 } 16102 16103 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16104 + stats.dataSize); 16105 16106 final long startFreeBytes = measurePath.getFreeSpace(); 16107 final long sizeBytes; 16108 if (moveCompleteApp) { 16109 sizeBytes = stats.codeSize + stats.dataSize; 16110 } else { 16111 sizeBytes = stats.codeSize; 16112 } 16113 16114 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16115 unfreezePackage(packageName); 16116 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16117 "Not enough free space to move"); 16118 } 16119 16120 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16121 16122 final CountDownLatch installedLatch = new CountDownLatch(1); 16123 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16124 @Override 16125 public void onUserActionRequired(Intent intent) throws RemoteException { 16126 throw new IllegalStateException(); 16127 } 16128 16129 @Override 16130 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16131 Bundle extras) throws RemoteException { 16132 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16133 + PackageManager.installStatusToString(returnCode, msg)); 16134 16135 installedLatch.countDown(); 16136 16137 // Regardless of success or failure of the move operation, 16138 // always unfreeze the package 16139 unfreezePackage(packageName); 16140 16141 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16142 switch (status) { 16143 case PackageInstaller.STATUS_SUCCESS: 16144 mMoveCallbacks.notifyStatusChanged(moveId, 16145 PackageManager.MOVE_SUCCEEDED); 16146 break; 16147 case PackageInstaller.STATUS_FAILURE_STORAGE: 16148 mMoveCallbacks.notifyStatusChanged(moveId, 16149 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16150 break; 16151 default: 16152 mMoveCallbacks.notifyStatusChanged(moveId, 16153 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16154 break; 16155 } 16156 } 16157 }; 16158 16159 final MoveInfo move; 16160 if (moveCompleteApp) { 16161 // Kick off a thread to report progress estimates 16162 new Thread() { 16163 @Override 16164 public void run() { 16165 while (true) { 16166 try { 16167 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16168 break; 16169 } 16170 } catch (InterruptedException ignored) { 16171 } 16172 16173 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16174 final int progress = 10 + (int) MathUtils.constrain( 16175 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16176 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16177 } 16178 } 16179 }.start(); 16180 16181 final String dataAppName = codeFile.getName(); 16182 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16183 dataAppName, appId, seinfo); 16184 } else { 16185 move = null; 16186 } 16187 16188 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16189 16190 final Message msg = mHandler.obtainMessage(INIT_COPY); 16191 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16192 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 16193 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16194 mHandler.sendMessage(msg); 16195 } 16196 16197 @Override 16198 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16199 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16200 16201 final int realMoveId = mNextMoveId.getAndIncrement(); 16202 final Bundle extras = new Bundle(); 16203 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16204 mMoveCallbacks.notifyCreated(realMoveId, extras); 16205 16206 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16207 @Override 16208 public void onCreated(int moveId, Bundle extras) { 16209 // Ignored 16210 } 16211 16212 @Override 16213 public void onStatusChanged(int moveId, int status, long estMillis) { 16214 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16215 } 16216 }; 16217 16218 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16219 storage.setPrimaryStorageUuid(volumeUuid, callback); 16220 return realMoveId; 16221 } 16222 16223 @Override 16224 public int getMoveStatus(int moveId) { 16225 mContext.enforceCallingOrSelfPermission( 16226 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16227 return mMoveCallbacks.mLastStatus.get(moveId); 16228 } 16229 16230 @Override 16231 public void registerMoveCallback(IPackageMoveObserver callback) { 16232 mContext.enforceCallingOrSelfPermission( 16233 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16234 mMoveCallbacks.register(callback); 16235 } 16236 16237 @Override 16238 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16239 mContext.enforceCallingOrSelfPermission( 16240 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16241 mMoveCallbacks.unregister(callback); 16242 } 16243 16244 @Override 16245 public boolean setInstallLocation(int loc) { 16246 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16247 null); 16248 if (getInstallLocation() == loc) { 16249 return true; 16250 } 16251 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16252 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16253 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16254 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16255 return true; 16256 } 16257 return false; 16258 } 16259 16260 @Override 16261 public int getInstallLocation() { 16262 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16263 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16264 PackageHelper.APP_INSTALL_AUTO); 16265 } 16266 16267 /** Called by UserManagerService */ 16268 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16269 mDirtyUsers.remove(userHandle); 16270 mSettings.removeUserLPw(userHandle); 16271 mPendingBroadcasts.remove(userHandle); 16272 if (mInstaller != null) { 16273 // Technically, we shouldn't be doing this with the package lock 16274 // held. However, this is very rare, and there is already so much 16275 // other disk I/O going on, that we'll let it slide for now. 16276 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16277 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16278 final String volumeUuid = vol.getFsUuid(); 16279 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16280 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16281 } 16282 } 16283 mUserNeedsBadging.delete(userHandle); 16284 removeUnusedPackagesLILPw(userManager, userHandle); 16285 } 16286 16287 /** 16288 * We're removing userHandle and would like to remove any downloaded packages 16289 * that are no longer in use by any other user. 16290 * @param userHandle the user being removed 16291 */ 16292 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16293 final boolean DEBUG_CLEAN_APKS = false; 16294 int [] users = userManager.getUserIdsLPr(); 16295 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16296 while (psit.hasNext()) { 16297 PackageSetting ps = psit.next(); 16298 if (ps.pkg == null) { 16299 continue; 16300 } 16301 final String packageName = ps.pkg.packageName; 16302 // Skip over if system app 16303 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16304 continue; 16305 } 16306 if (DEBUG_CLEAN_APKS) { 16307 Slog.i(TAG, "Checking package " + packageName); 16308 } 16309 boolean keep = false; 16310 for (int i = 0; i < users.length; i++) { 16311 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16312 keep = true; 16313 if (DEBUG_CLEAN_APKS) { 16314 Slog.i(TAG, " Keeping package " + packageName + " for user " 16315 + users[i]); 16316 } 16317 break; 16318 } 16319 } 16320 if (!keep) { 16321 if (DEBUG_CLEAN_APKS) { 16322 Slog.i(TAG, " Removing package " + packageName); 16323 } 16324 mHandler.post(new Runnable() { 16325 public void run() { 16326 deletePackageX(packageName, userHandle, 0); 16327 } //end run 16328 }); 16329 } 16330 } 16331 } 16332 16333 /** Called by UserManagerService */ 16334 void createNewUserLILPw(int userHandle) { 16335 if (mInstaller != null) { 16336 mInstaller.createUserConfig(userHandle); 16337 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16338 applyFactoryDefaultBrowserLPw(userHandle); 16339 primeDomainVerificationsLPw(userHandle); 16340 } 16341 } 16342 16343 void newUserCreated(final int userHandle) { 16344 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16345 } 16346 16347 @Override 16348 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16349 mContext.enforceCallingOrSelfPermission( 16350 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16351 "Only package verification agents can read the verifier device identity"); 16352 16353 synchronized (mPackages) { 16354 return mSettings.getVerifierDeviceIdentityLPw(); 16355 } 16356 } 16357 16358 @Override 16359 public void setPermissionEnforced(String permission, boolean enforced) { 16360 // TODO: Now that we no longer change GID for storage, this should to away. 16361 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16362 "setPermissionEnforced"); 16363 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16364 synchronized (mPackages) { 16365 if (mSettings.mReadExternalStorageEnforced == null 16366 || mSettings.mReadExternalStorageEnforced != enforced) { 16367 mSettings.mReadExternalStorageEnforced = enforced; 16368 mSettings.writeLPr(); 16369 } 16370 } 16371 // kill any non-foreground processes so we restart them and 16372 // grant/revoke the GID. 16373 final IActivityManager am = ActivityManagerNative.getDefault(); 16374 if (am != null) { 16375 final long token = Binder.clearCallingIdentity(); 16376 try { 16377 am.killProcessesBelowForeground("setPermissionEnforcement"); 16378 } catch (RemoteException e) { 16379 } finally { 16380 Binder.restoreCallingIdentity(token); 16381 } 16382 } 16383 } else { 16384 throw new IllegalArgumentException("No selective enforcement for " + permission); 16385 } 16386 } 16387 16388 @Override 16389 @Deprecated 16390 public boolean isPermissionEnforced(String permission) { 16391 return true; 16392 } 16393 16394 @Override 16395 public boolean isStorageLow() { 16396 final long token = Binder.clearCallingIdentity(); 16397 try { 16398 final DeviceStorageMonitorInternal 16399 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16400 if (dsm != null) { 16401 return dsm.isMemoryLow(); 16402 } else { 16403 return false; 16404 } 16405 } finally { 16406 Binder.restoreCallingIdentity(token); 16407 } 16408 } 16409 16410 @Override 16411 public IPackageInstaller getPackageInstaller() { 16412 return mInstallerService; 16413 } 16414 16415 private boolean userNeedsBadging(int userId) { 16416 int index = mUserNeedsBadging.indexOfKey(userId); 16417 if (index < 0) { 16418 final UserInfo userInfo; 16419 final long token = Binder.clearCallingIdentity(); 16420 try { 16421 userInfo = sUserManager.getUserInfo(userId); 16422 } finally { 16423 Binder.restoreCallingIdentity(token); 16424 } 16425 final boolean b; 16426 if (userInfo != null && userInfo.isManagedProfile()) { 16427 b = true; 16428 } else { 16429 b = false; 16430 } 16431 mUserNeedsBadging.put(userId, b); 16432 return b; 16433 } 16434 return mUserNeedsBadging.valueAt(index); 16435 } 16436 16437 @Override 16438 public KeySet getKeySetByAlias(String packageName, String alias) { 16439 if (packageName == null || alias == null) { 16440 return null; 16441 } 16442 synchronized(mPackages) { 16443 final PackageParser.Package pkg = mPackages.get(packageName); 16444 if (pkg == null) { 16445 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16446 throw new IllegalArgumentException("Unknown package: " + packageName); 16447 } 16448 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16449 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16450 } 16451 } 16452 16453 @Override 16454 public KeySet getSigningKeySet(String packageName) { 16455 if (packageName == null) { 16456 return null; 16457 } 16458 synchronized(mPackages) { 16459 final PackageParser.Package pkg = mPackages.get(packageName); 16460 if (pkg == null) { 16461 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16462 throw new IllegalArgumentException("Unknown package: " + packageName); 16463 } 16464 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16465 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16466 throw new SecurityException("May not access signing KeySet of other apps."); 16467 } 16468 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16469 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16470 } 16471 } 16472 16473 @Override 16474 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16475 if (packageName == null || ks == null) { 16476 return false; 16477 } 16478 synchronized(mPackages) { 16479 final PackageParser.Package pkg = mPackages.get(packageName); 16480 if (pkg == null) { 16481 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16482 throw new IllegalArgumentException("Unknown package: " + packageName); 16483 } 16484 IBinder ksh = ks.getToken(); 16485 if (ksh instanceof KeySetHandle) { 16486 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16487 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16488 } 16489 return false; 16490 } 16491 } 16492 16493 @Override 16494 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16495 if (packageName == null || ks == null) { 16496 return false; 16497 } 16498 synchronized(mPackages) { 16499 final PackageParser.Package pkg = mPackages.get(packageName); 16500 if (pkg == null) { 16501 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16502 throw new IllegalArgumentException("Unknown package: " + packageName); 16503 } 16504 IBinder ksh = ks.getToken(); 16505 if (ksh instanceof KeySetHandle) { 16506 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16507 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16508 } 16509 return false; 16510 } 16511 } 16512 16513 public void getUsageStatsIfNoPackageUsageInfo() { 16514 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16515 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16516 if (usm == null) { 16517 throw new IllegalStateException("UsageStatsManager must be initialized"); 16518 } 16519 long now = System.currentTimeMillis(); 16520 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16521 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16522 String packageName = entry.getKey(); 16523 PackageParser.Package pkg = mPackages.get(packageName); 16524 if (pkg == null) { 16525 continue; 16526 } 16527 UsageStats usage = entry.getValue(); 16528 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16529 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16530 } 16531 } 16532 } 16533 16534 /** 16535 * Check and throw if the given before/after packages would be considered a 16536 * downgrade. 16537 */ 16538 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16539 throws PackageManagerException { 16540 if (after.versionCode < before.mVersionCode) { 16541 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16542 "Update version code " + after.versionCode + " is older than current " 16543 + before.mVersionCode); 16544 } else if (after.versionCode == before.mVersionCode) { 16545 if (after.baseRevisionCode < before.baseRevisionCode) { 16546 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16547 "Update base revision code " + after.baseRevisionCode 16548 + " is older than current " + before.baseRevisionCode); 16549 } 16550 16551 if (!ArrayUtils.isEmpty(after.splitNames)) { 16552 for (int i = 0; i < after.splitNames.length; i++) { 16553 final String splitName = after.splitNames[i]; 16554 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16555 if (j != -1) { 16556 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16557 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16558 "Update split " + splitName + " revision code " 16559 + after.splitRevisionCodes[i] + " is older than current " 16560 + before.splitRevisionCodes[j]); 16561 } 16562 } 16563 } 16564 } 16565 } 16566 } 16567 16568 private static class MoveCallbacks extends Handler { 16569 private static final int MSG_CREATED = 1; 16570 private static final int MSG_STATUS_CHANGED = 2; 16571 16572 private final RemoteCallbackList<IPackageMoveObserver> 16573 mCallbacks = new RemoteCallbackList<>(); 16574 16575 private final SparseIntArray mLastStatus = new SparseIntArray(); 16576 16577 public MoveCallbacks(Looper looper) { 16578 super(looper); 16579 } 16580 16581 public void register(IPackageMoveObserver callback) { 16582 mCallbacks.register(callback); 16583 } 16584 16585 public void unregister(IPackageMoveObserver callback) { 16586 mCallbacks.unregister(callback); 16587 } 16588 16589 @Override 16590 public void handleMessage(Message msg) { 16591 final SomeArgs args = (SomeArgs) msg.obj; 16592 final int n = mCallbacks.beginBroadcast(); 16593 for (int i = 0; i < n; i++) { 16594 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16595 try { 16596 invokeCallback(callback, msg.what, args); 16597 } catch (RemoteException ignored) { 16598 } 16599 } 16600 mCallbacks.finishBroadcast(); 16601 args.recycle(); 16602 } 16603 16604 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16605 throws RemoteException { 16606 switch (what) { 16607 case MSG_CREATED: { 16608 callback.onCreated(args.argi1, (Bundle) args.arg2); 16609 break; 16610 } 16611 case MSG_STATUS_CHANGED: { 16612 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16613 break; 16614 } 16615 } 16616 } 16617 16618 private void notifyCreated(int moveId, Bundle extras) { 16619 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16620 16621 final SomeArgs args = SomeArgs.obtain(); 16622 args.argi1 = moveId; 16623 args.arg2 = extras; 16624 obtainMessage(MSG_CREATED, args).sendToTarget(); 16625 } 16626 16627 private void notifyStatusChanged(int moveId, int status) { 16628 notifyStatusChanged(moveId, status, -1); 16629 } 16630 16631 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16632 Slog.v(TAG, "Move " + moveId + " status " + status); 16633 16634 final SomeArgs args = SomeArgs.obtain(); 16635 args.argi1 = moveId; 16636 args.argi2 = status; 16637 args.arg3 = estMillis; 16638 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16639 16640 synchronized (mLastStatus) { 16641 mLastStatus.put(moveId, status); 16642 } 16643 } 16644 } 16645 16646 private final class OnPermissionChangeListeners extends Handler { 16647 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16648 16649 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16650 new RemoteCallbackList<>(); 16651 16652 public OnPermissionChangeListeners(Looper looper) { 16653 super(looper); 16654 } 16655 16656 @Override 16657 public void handleMessage(Message msg) { 16658 switch (msg.what) { 16659 case MSG_ON_PERMISSIONS_CHANGED: { 16660 final int uid = msg.arg1; 16661 handleOnPermissionsChanged(uid); 16662 } break; 16663 } 16664 } 16665 16666 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16667 mPermissionListeners.register(listener); 16668 16669 } 16670 16671 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16672 mPermissionListeners.unregister(listener); 16673 } 16674 16675 public void onPermissionsChanged(int uid) { 16676 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16677 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16678 } 16679 } 16680 16681 private void handleOnPermissionsChanged(int uid) { 16682 final int count = mPermissionListeners.beginBroadcast(); 16683 try { 16684 for (int i = 0; i < count; i++) { 16685 IOnPermissionsChangeListener callback = mPermissionListeners 16686 .getBroadcastItem(i); 16687 try { 16688 callback.onPermissionsChanged(uid); 16689 } catch (RemoteException e) { 16690 Log.e(TAG, "Permission listener is dead", e); 16691 } 16692 } 16693 } finally { 16694 mPermissionListeners.finishBroadcast(); 16695 } 16696 } 16697 } 16698 16699 private class PackageManagerInternalImpl extends PackageManagerInternal { 16700 @Override 16701 public void setLocationPackagesProvider(PackagesProvider provider) { 16702 synchronized (mPackages) { 16703 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16704 } 16705 } 16706 16707 @Override 16708 public void setImePackagesProvider(PackagesProvider provider) { 16709 synchronized (mPackages) { 16710 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16711 } 16712 } 16713 16714 @Override 16715 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16716 synchronized (mPackages) { 16717 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16718 } 16719 } 16720 16721 @Override 16722 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16723 synchronized (mPackages) { 16724 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16725 } 16726 } 16727 16728 @Override 16729 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16730 synchronized (mPackages) { 16731 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16732 } 16733 } 16734 16735 @Override 16736 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16737 synchronized (mPackages) { 16738 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16739 } 16740 } 16741 16742 @Override 16743 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16744 synchronized (mPackages) { 16745 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16746 } 16747 } 16748 16749 @Override 16750 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16751 synchronized (mPackages) { 16752 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16753 packageName, userId); 16754 } 16755 } 16756 16757 @Override 16758 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16759 synchronized (mPackages) { 16760 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16761 packageName, userId); 16762 } 16763 } 16764 @Override 16765 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16766 synchronized (mPackages) { 16767 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16768 packageName, userId); 16769 } 16770 } 16771 } 16772 16773 @Override 16774 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16775 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16776 synchronized (mPackages) { 16777 final long identity = Binder.clearCallingIdentity(); 16778 try { 16779 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16780 packageNames, userId); 16781 } finally { 16782 Binder.restoreCallingIdentity(identity); 16783 } 16784 } 16785 } 16786 16787 private static void enforceSystemOrPhoneCaller(String tag) { 16788 int callingUid = Binder.getCallingUid(); 16789 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16790 throw new SecurityException( 16791 "Cannot call " + tag + " from UID " + callingUid); 16792 } 16793 } 16794} 16795