PackageManagerService.java revision 8d027e6d523d13a9cf2a5cf4ef901cc3e78b901d
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 60import static android.content.pm.PackageManager.MATCH_ALL; 61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 65import static android.content.pm.PackageManager.PERMISSION_DENIED; 66import static android.content.pm.PackageManager.PERMISSION_GRANTED; 67import static android.content.pm.PackageParser.isApkFile; 68import static android.os.Process.PACKAGE_INFO_GID; 69import static android.os.Process.SYSTEM_UID; 70import static android.system.OsConstants.O_CREAT; 71import static android.system.OsConstants.O_RDWR; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 76import static com.android.internal.util.ArrayUtils.appendInt; 77import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 80import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 81import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 85 86import android.Manifest; 87import android.app.ActivityManager; 88import android.app.ActivityManagerNative; 89import android.app.AppGlobals; 90import android.app.IActivityManager; 91import android.app.admin.IDevicePolicyManager; 92import android.app.backup.IBackupManager; 93import android.app.usage.UsageStats; 94import android.app.usage.UsageStatsManager; 95import android.content.BroadcastReceiver; 96import android.content.ComponentName; 97import android.content.Context; 98import android.content.IIntentReceiver; 99import android.content.Intent; 100import android.content.IntentFilter; 101import android.content.IntentSender; 102import android.content.IntentSender.SendIntentException; 103import android.content.ServiceConnection; 104import android.content.pm.ActivityInfo; 105import android.content.pm.ApplicationInfo; 106import android.content.pm.FeatureInfo; 107import android.content.pm.IOnPermissionsChangeListener; 108import android.content.pm.IPackageDataObserver; 109import android.content.pm.IPackageDeleteObserver; 110import android.content.pm.IPackageDeleteObserver2; 111import android.content.pm.IPackageInstallObserver2; 112import android.content.pm.IPackageInstaller; 113import android.content.pm.IPackageManager; 114import android.content.pm.IPackageMoveObserver; 115import android.content.pm.IPackageStatsObserver; 116import android.content.pm.InstrumentationInfo; 117import android.content.pm.IntentFilterVerificationInfo; 118import android.content.pm.KeySet; 119import android.content.pm.ManifestDigest; 120import android.content.pm.PackageCleanItem; 121import android.content.pm.PackageInfo; 122import android.content.pm.PackageInfoLite; 123import android.content.pm.PackageInstaller; 124import android.content.pm.PackageManager; 125import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 126import android.content.pm.PackageManagerInternal; 127import android.content.pm.PackageParser; 128import android.content.pm.PackageParser.ActivityIntentInfo; 129import android.content.pm.PackageParser.PackageLite; 130import android.content.pm.PackageParser.PackageParserException; 131import android.content.pm.PackageStats; 132import android.content.pm.PackageUserState; 133import android.content.pm.ParceledListSlice; 134import android.content.pm.PermissionGroupInfo; 135import android.content.pm.PermissionInfo; 136import android.content.pm.ProviderInfo; 137import android.content.pm.ResolveInfo; 138import android.content.pm.ServiceInfo; 139import android.content.pm.Signature; 140import android.content.pm.UserInfo; 141import android.content.pm.VerificationParams; 142import android.content.pm.VerifierDeviceIdentity; 143import android.content.pm.VerifierInfo; 144import android.content.res.Resources; 145import android.hardware.display.DisplayManager; 146import android.net.Uri; 147import android.os.Debug; 148import android.os.Binder; 149import android.os.Build; 150import android.os.Bundle; 151import android.os.Environment; 152import android.os.Environment.UserEnvironment; 153import android.os.FileUtils; 154import android.os.Handler; 155import android.os.IBinder; 156import android.os.Looper; 157import android.os.Message; 158import android.os.Parcel; 159import android.os.ParcelFileDescriptor; 160import android.os.Process; 161import android.os.RemoteCallbackList; 162import android.os.RemoteException; 163import android.os.SELinux; 164import android.os.ServiceManager; 165import android.os.SystemClock; 166import android.os.SystemProperties; 167import android.os.UserHandle; 168import android.os.UserManager; 169import android.os.storage.IMountService; 170import android.os.storage.MountServiceInternal; 171import android.os.storage.StorageEventListener; 172import android.os.storage.StorageManager; 173import android.os.storage.VolumeInfo; 174import android.os.storage.VolumeRecord; 175import android.security.KeyStore; 176import android.security.SystemKeyStore; 177import android.system.ErrnoException; 178import android.system.Os; 179import android.system.StructStat; 180import android.text.TextUtils; 181import android.text.format.DateUtils; 182import android.util.ArrayMap; 183import android.util.ArraySet; 184import android.util.AtomicFile; 185import android.util.DisplayMetrics; 186import android.util.EventLog; 187import android.util.ExceptionUtils; 188import android.util.Log; 189import android.util.LogPrinter; 190import android.util.MathUtils; 191import android.util.PrintStreamPrinter; 192import android.util.Slog; 193import android.util.SparseArray; 194import android.util.SparseBooleanArray; 195import android.util.SparseIntArray; 196import android.util.Xml; 197import android.view.Display; 198 199import dalvik.system.DexFile; 200import dalvik.system.VMRuntime; 201 202import libcore.io.IoUtils; 203import libcore.util.EmptyArray; 204 205import com.android.internal.R; 206import com.android.internal.annotations.GuardedBy; 207import com.android.internal.app.IMediaContainerService; 208import com.android.internal.app.ResolverActivity; 209import com.android.internal.content.NativeLibraryHelper; 210import com.android.internal.content.PackageHelper; 211import com.android.internal.os.IParcelFileDescriptorFactory; 212import com.android.internal.os.SomeArgs; 213import com.android.internal.os.Zygote; 214import com.android.internal.util.ArrayUtils; 215import com.android.internal.util.FastPrintWriter; 216import com.android.internal.util.FastXmlSerializer; 217import com.android.internal.util.IndentingPrintWriter; 218import com.android.internal.util.Preconditions; 219import com.android.server.EventLogTags; 220import com.android.server.FgThread; 221import com.android.server.IntentResolver; 222import com.android.server.LocalServices; 223import com.android.server.ServiceThread; 224import com.android.server.SystemConfig; 225import com.android.server.Watchdog; 226import com.android.server.pm.PermissionsState.PermissionState; 227import com.android.server.pm.Settings.DatabaseVersion; 228import com.android.server.pm.Settings.VersionInfo; 229import com.android.server.storage.DeviceStorageMonitorInternal; 230 231import org.xmlpull.v1.XmlPullParser; 232import org.xmlpull.v1.XmlPullParserException; 233import org.xmlpull.v1.XmlSerializer; 234 235import java.io.BufferedInputStream; 236import java.io.BufferedOutputStream; 237import java.io.BufferedReader; 238import java.io.ByteArrayInputStream; 239import java.io.ByteArrayOutputStream; 240import java.io.File; 241import java.io.FileDescriptor; 242import java.io.FileNotFoundException; 243import java.io.FileOutputStream; 244import java.io.FileReader; 245import java.io.FilenameFilter; 246import java.io.IOException; 247import java.io.InputStream; 248import java.io.PrintWriter; 249import java.nio.charset.StandardCharsets; 250import java.security.NoSuchAlgorithmException; 251import java.security.PublicKey; 252import java.security.cert.CertificateEncodingException; 253import java.security.cert.CertificateException; 254import java.text.SimpleDateFormat; 255import java.util.ArrayList; 256import java.util.Arrays; 257import java.util.Collection; 258import java.util.Collections; 259import java.util.Comparator; 260import java.util.Date; 261import java.util.Iterator; 262import java.util.List; 263import java.util.Map; 264import java.util.Objects; 265import java.util.Set; 266import java.util.concurrent.CountDownLatch; 267import java.util.concurrent.TimeUnit; 268import java.util.concurrent.atomic.AtomicBoolean; 269import java.util.concurrent.atomic.AtomicInteger; 270import java.util.concurrent.atomic.AtomicLong; 271 272/** 273 * Keep track of all those .apks everywhere. 274 * 275 * This is very central to the platform's security; please run the unit 276 * tests whenever making modifications here: 277 * 278mmm frameworks/base/tests/AndroidTests 279adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 280adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 281 * 282 * {@hide} 283 */ 284public class PackageManagerService extends IPackageManager.Stub { 285 static final String TAG = "PackageManager"; 286 static final boolean DEBUG_SETTINGS = false; 287 static final boolean DEBUG_PREFERRED = false; 288 static final boolean DEBUG_UPGRADE = false; 289 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 290 private static final boolean DEBUG_BACKUP = false; 291 private static final boolean DEBUG_INSTALL = false; 292 private static final boolean DEBUG_REMOVE = false; 293 private static final boolean DEBUG_BROADCASTS = false; 294 private static final boolean DEBUG_SHOW_INFO = false; 295 private static final boolean DEBUG_PACKAGE_INFO = false; 296 private static final boolean DEBUG_INTENT_MATCHING = false; 297 private static final boolean DEBUG_PACKAGE_SCANNING = false; 298 private static final boolean DEBUG_VERIFY = false; 299 private static final boolean DEBUG_DEXOPT = false; 300 private static final boolean DEBUG_ABI_SELECTION = false; 301 302 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 303 304 private static final int RADIO_UID = Process.PHONE_UID; 305 private static final int LOG_UID = Process.LOG_UID; 306 private static final int NFC_UID = Process.NFC_UID; 307 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 308 private static final int SHELL_UID = Process.SHELL_UID; 309 310 // Cap the size of permission trees that 3rd party apps can define 311 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 312 313 // Suffix used during package installation when copying/moving 314 // package apks to install directory. 315 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 316 317 static final int SCAN_NO_DEX = 1<<1; 318 static final int SCAN_FORCE_DEX = 1<<2; 319 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 320 static final int SCAN_NEW_INSTALL = 1<<4; 321 static final int SCAN_NO_PATHS = 1<<5; 322 static final int SCAN_UPDATE_TIME = 1<<6; 323 static final int SCAN_DEFER_DEX = 1<<7; 324 static final int SCAN_BOOTING = 1<<8; 325 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 326 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 327 static final int SCAN_REPLACING = 1<<11; 328 static final int SCAN_REQUIRE_KNOWN = 1<<12; 329 static final int SCAN_MOVE = 1<<13; 330 static final int SCAN_INITIAL = 1<<14; 331 332 static final int REMOVE_CHATTY = 1<<16; 333 334 private static final int[] EMPTY_INT_ARRAY = new int[0]; 335 336 /** 337 * Timeout (in milliseconds) after which the watchdog should declare that 338 * our handler thread is wedged. The usual default for such things is one 339 * minute but we sometimes do very lengthy I/O operations on this thread, 340 * such as installing multi-gigabyte applications, so ours needs to be longer. 341 */ 342 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 343 344 /** 345 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 346 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 347 * settings entry if available, otherwise we use the hardcoded default. If it's been 348 * more than this long since the last fstrim, we force one during the boot sequence. 349 * 350 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 351 * one gets run at the next available charging+idle time. This final mandatory 352 * no-fstrim check kicks in only of the other scheduling criteria is never met. 353 */ 354 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 355 356 /** 357 * Whether verification is enabled by default. 358 */ 359 private static final boolean DEFAULT_VERIFY_ENABLE = true; 360 361 /** 362 * The default maximum time to wait for the verification agent to return in 363 * milliseconds. 364 */ 365 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 366 367 /** 368 * The default response for package verification timeout. 369 * 370 * This can be either PackageManager.VERIFICATION_ALLOW or 371 * PackageManager.VERIFICATION_REJECT. 372 */ 373 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 374 375 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 376 377 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 378 DEFAULT_CONTAINER_PACKAGE, 379 "com.android.defcontainer.DefaultContainerService"); 380 381 private static final String KILL_APP_REASON_GIDS_CHANGED = 382 "permission grant or revoke changed gids"; 383 384 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 385 "permissions revoked"; 386 387 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 388 389 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 390 391 /** Permission grant: not grant the permission. */ 392 private static final int GRANT_DENIED = 1; 393 394 /** Permission grant: grant the permission as an install permission. */ 395 private static final int GRANT_INSTALL = 2; 396 397 /** Permission grant: grant the permission as an install permission for a legacy app. */ 398 private static final int GRANT_INSTALL_LEGACY = 3; 399 400 /** Permission grant: grant the permission as a runtime one. */ 401 private static final int GRANT_RUNTIME = 4; 402 403 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 404 private static final int GRANT_UPGRADE = 5; 405 406 /** Canonical intent used to identify what counts as a "web browser" app */ 407 private static final Intent sBrowserIntent; 408 static { 409 sBrowserIntent = new Intent(); 410 sBrowserIntent.setAction(Intent.ACTION_VIEW); 411 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 412 sBrowserIntent.setData(Uri.parse("http:")); 413 } 414 415 final ServiceThread mHandlerThread; 416 417 final PackageHandler mHandler; 418 419 /** 420 * Messages for {@link #mHandler} that need to wait for system ready before 421 * being dispatched. 422 */ 423 private ArrayList<Message> mPostSystemReadyMessages; 424 425 final int mSdkVersion = Build.VERSION.SDK_INT; 426 427 final Context mContext; 428 final boolean mFactoryTest; 429 final boolean mOnlyCore; 430 final boolean mLazyDexOpt; 431 final long mDexOptLRUThresholdInMills; 432 final DisplayMetrics mMetrics; 433 final int mDefParseFlags; 434 final String[] mSeparateProcesses; 435 final boolean mIsUpgrade; 436 437 // This is where all application persistent data goes. 438 final File mAppDataDir; 439 440 // This is where all application persistent data goes for secondary users. 441 final File mUserAppDataDir; 442 443 /** The location for ASEC container files on internal storage. */ 444 final String mAsecInternalPath; 445 446 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 447 // LOCK HELD. Can be called with mInstallLock held. 448 @GuardedBy("mInstallLock") 449 final Installer mInstaller; 450 451 /** Directory where installed third-party apps stored */ 452 final File mAppInstallDir; 453 454 /** 455 * Directory to which applications installed internally have their 456 * 32 bit native libraries copied. 457 */ 458 private File mAppLib32InstallDir; 459 460 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 461 // apps. 462 final File mDrmAppPrivateInstallDir; 463 464 // ---------------------------------------------------------------- 465 466 // Lock for state used when installing and doing other long running 467 // operations. Methods that must be called with this lock held have 468 // the suffix "LI". 469 final Object mInstallLock = new Object(); 470 471 // ---------------------------------------------------------------- 472 473 // Keys are String (package name), values are Package. This also serves 474 // as the lock for the global state. Methods that must be called with 475 // this lock held have the prefix "LP". 476 @GuardedBy("mPackages") 477 final ArrayMap<String, PackageParser.Package> mPackages = 478 new ArrayMap<String, PackageParser.Package>(); 479 480 // Tracks available target package names -> overlay package paths. 481 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 482 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 483 484 /** 485 * Tracks new system packages [received in an OTA] that we expect to 486 * find updated user-installed versions. Keys are package name, values 487 * are package location. 488 */ 489 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 490 491 /** 492 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 493 */ 494 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 495 /** 496 * Whether or not system app permissions should be promoted from install to runtime. 497 */ 498 boolean mPromoteSystemApps; 499 500 final Settings mSettings; 501 boolean mRestoredSettings; 502 503 // System configuration read by SystemConfig. 504 final int[] mGlobalGids; 505 final SparseArray<ArraySet<String>> mSystemPermissions; 506 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 507 508 // If mac_permissions.xml was found for seinfo labeling. 509 boolean mFoundPolicyFile; 510 511 // If a recursive restorecon of /data/data/<pkg> is needed. 512 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 513 514 public static final class SharedLibraryEntry { 515 public final String path; 516 public final String apk; 517 518 SharedLibraryEntry(String _path, String _apk) { 519 path = _path; 520 apk = _apk; 521 } 522 } 523 524 // Currently known shared libraries. 525 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 526 new ArrayMap<String, SharedLibraryEntry>(); 527 528 // All available activities, for your resolving pleasure. 529 final ActivityIntentResolver mActivities = 530 new ActivityIntentResolver(); 531 532 // All available receivers, for your resolving pleasure. 533 final ActivityIntentResolver mReceivers = 534 new ActivityIntentResolver(); 535 536 // All available services, for your resolving pleasure. 537 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 538 539 // All available providers, for your resolving pleasure. 540 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 541 542 // Mapping from provider base names (first directory in content URI codePath) 543 // to the provider information. 544 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 545 new ArrayMap<String, PackageParser.Provider>(); 546 547 // Mapping from instrumentation class names to info about them. 548 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 549 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 550 551 // Mapping from permission names to info about them. 552 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 553 new ArrayMap<String, PackageParser.PermissionGroup>(); 554 555 // Packages whose data we have transfered into another package, thus 556 // should no longer exist. 557 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 558 559 // Broadcast actions that are only available to the system. 560 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 561 562 /** List of packages waiting for verification. */ 563 final SparseArray<PackageVerificationState> mPendingVerification 564 = new SparseArray<PackageVerificationState>(); 565 566 /** Set of packages associated with each app op permission. */ 567 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 568 569 final PackageInstallerService mInstallerService; 570 571 private final PackageDexOptimizer mPackageDexOptimizer; 572 573 private AtomicInteger mNextMoveId = new AtomicInteger(); 574 private final MoveCallbacks mMoveCallbacks; 575 576 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 577 578 // Cache of users who need badging. 579 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 580 581 /** Token for keys in mPendingVerification. */ 582 private int mPendingVerificationToken = 0; 583 584 volatile boolean mSystemReady; 585 volatile boolean mSafeMode; 586 volatile boolean mHasSystemUidErrors; 587 588 ApplicationInfo mAndroidApplication; 589 final ActivityInfo mResolveActivity = new ActivityInfo(); 590 final ResolveInfo mResolveInfo = new ResolveInfo(); 591 ComponentName mResolveComponentName; 592 PackageParser.Package mPlatformPackage; 593 ComponentName mCustomResolverComponentName; 594 595 boolean mResolverReplaced = false; 596 597 private final ComponentName mIntentFilterVerifierComponent; 598 private int mIntentFilterVerificationToken = 0; 599 600 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 601 = new SparseArray<IntentFilterVerificationState>(); 602 603 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 604 new DefaultPermissionGrantPolicy(this); 605 606 private static class IFVerificationParams { 607 PackageParser.Package pkg; 608 boolean replacing; 609 int userId; 610 int verifierUid; 611 612 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 613 int _userId, int _verifierUid) { 614 pkg = _pkg; 615 replacing = _replacing; 616 userId = _userId; 617 replacing = _replacing; 618 verifierUid = _verifierUid; 619 } 620 } 621 622 private interface IntentFilterVerifier<T extends IntentFilter> { 623 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 624 T filter, String packageName); 625 void startVerifications(int userId); 626 void receiveVerificationResponse(int verificationId); 627 } 628 629 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 630 private Context mContext; 631 private ComponentName mIntentFilterVerifierComponent; 632 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 633 634 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 635 mContext = context; 636 mIntentFilterVerifierComponent = verifierComponent; 637 } 638 639 private String getDefaultScheme() { 640 return IntentFilter.SCHEME_HTTPS; 641 } 642 643 @Override 644 public void startVerifications(int userId) { 645 // Launch verifications requests 646 int count = mCurrentIntentFilterVerifications.size(); 647 for (int n=0; n<count; n++) { 648 int verificationId = mCurrentIntentFilterVerifications.get(n); 649 final IntentFilterVerificationState ivs = 650 mIntentFilterVerificationStates.get(verificationId); 651 652 String packageName = ivs.getPackageName(); 653 654 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 655 final int filterCount = filters.size(); 656 ArraySet<String> domainsSet = new ArraySet<>(); 657 for (int m=0; m<filterCount; m++) { 658 PackageParser.ActivityIntentInfo filter = filters.get(m); 659 domainsSet.addAll(filter.getHostsList()); 660 } 661 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 662 synchronized (mPackages) { 663 if (mSettings.createIntentFilterVerificationIfNeededLPw( 664 packageName, domainsList) != null) { 665 scheduleWriteSettingsLocked(); 666 } 667 } 668 sendVerificationRequest(userId, verificationId, ivs); 669 } 670 mCurrentIntentFilterVerifications.clear(); 671 } 672 673 private void sendVerificationRequest(int userId, int verificationId, 674 IntentFilterVerificationState ivs) { 675 676 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 677 verificationIntent.putExtra( 678 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 679 verificationId); 680 verificationIntent.putExtra( 681 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 682 getDefaultScheme()); 683 verificationIntent.putExtra( 684 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 685 ivs.getHostsString()); 686 verificationIntent.putExtra( 687 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 688 ivs.getPackageName()); 689 verificationIntent.setComponent(mIntentFilterVerifierComponent); 690 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 691 692 UserHandle user = new UserHandle(userId); 693 mContext.sendBroadcastAsUser(verificationIntent, user); 694 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 695 "Sending IntentFilter verification broadcast"); 696 } 697 698 public void receiveVerificationResponse(int verificationId) { 699 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 700 701 final boolean verified = ivs.isVerified(); 702 703 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 704 final int count = filters.size(); 705 if (DEBUG_DOMAIN_VERIFICATION) { 706 Slog.i(TAG, "Received verification response " + verificationId 707 + " for " + count + " filters, verified=" + verified); 708 } 709 for (int n=0; n<count; n++) { 710 PackageParser.ActivityIntentInfo filter = filters.get(n); 711 filter.setVerified(verified); 712 713 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 714 + " verified with result:" + verified + " and hosts:" 715 + ivs.getHostsString()); 716 } 717 718 mIntentFilterVerificationStates.remove(verificationId); 719 720 final String packageName = ivs.getPackageName(); 721 IntentFilterVerificationInfo ivi = null; 722 723 synchronized (mPackages) { 724 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 725 } 726 if (ivi == null) { 727 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 728 + verificationId + " packageName:" + packageName); 729 return; 730 } 731 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 732 "Updating IntentFilterVerificationInfo for package " + packageName 733 +" verificationId:" + verificationId); 734 735 synchronized (mPackages) { 736 if (verified) { 737 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 738 } else { 739 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 740 } 741 scheduleWriteSettingsLocked(); 742 743 final int userId = ivs.getUserId(); 744 if (userId != UserHandle.USER_ALL) { 745 final int userStatus = 746 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 747 748 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 749 boolean needUpdate = false; 750 751 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 752 // already been set by the User thru the Disambiguation dialog 753 switch (userStatus) { 754 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 755 if (verified) { 756 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 757 } else { 758 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 759 } 760 needUpdate = true; 761 break; 762 763 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 764 if (verified) { 765 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 766 needUpdate = true; 767 } 768 break; 769 770 default: 771 // Nothing to do 772 } 773 774 if (needUpdate) { 775 mSettings.updateIntentFilterVerificationStatusLPw( 776 packageName, updatedStatus, userId); 777 scheduleWritePackageRestrictionsLocked(userId); 778 } 779 } 780 } 781 } 782 783 @Override 784 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 785 ActivityIntentInfo filter, String packageName) { 786 if (!hasValidDomains(filter)) { 787 return false; 788 } 789 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 790 if (ivs == null) { 791 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 792 packageName); 793 } 794 if (DEBUG_DOMAIN_VERIFICATION) { 795 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 796 } 797 ivs.addFilter(filter); 798 return true; 799 } 800 801 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 802 int userId, int verificationId, String packageName) { 803 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 804 verifierUid, userId, packageName); 805 ivs.setPendingState(); 806 synchronized (mPackages) { 807 mIntentFilterVerificationStates.append(verificationId, ivs); 808 mCurrentIntentFilterVerifications.add(verificationId); 809 } 810 return ivs; 811 } 812 } 813 814 private static boolean hasValidDomains(ActivityIntentInfo filter) { 815 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 816 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 817 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 818 } 819 820 private IntentFilterVerifier mIntentFilterVerifier; 821 822 // Set of pending broadcasts for aggregating enable/disable of components. 823 static class PendingPackageBroadcasts { 824 // for each user id, a map of <package name -> components within that package> 825 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 826 827 public PendingPackageBroadcasts() { 828 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 829 } 830 831 public ArrayList<String> get(int userId, String packageName) { 832 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 833 return packages.get(packageName); 834 } 835 836 public void put(int userId, String packageName, ArrayList<String> components) { 837 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 838 packages.put(packageName, components); 839 } 840 841 public void remove(int userId, String packageName) { 842 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 843 if (packages != null) { 844 packages.remove(packageName); 845 } 846 } 847 848 public void remove(int userId) { 849 mUidMap.remove(userId); 850 } 851 852 public int userIdCount() { 853 return mUidMap.size(); 854 } 855 856 public int userIdAt(int n) { 857 return mUidMap.keyAt(n); 858 } 859 860 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 861 return mUidMap.get(userId); 862 } 863 864 public int size() { 865 // total number of pending broadcast entries across all userIds 866 int num = 0; 867 for (int i = 0; i< mUidMap.size(); i++) { 868 num += mUidMap.valueAt(i).size(); 869 } 870 return num; 871 } 872 873 public void clear() { 874 mUidMap.clear(); 875 } 876 877 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 878 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 879 if (map == null) { 880 map = new ArrayMap<String, ArrayList<String>>(); 881 mUidMap.put(userId, map); 882 } 883 return map; 884 } 885 } 886 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 887 888 // Service Connection to remote media container service to copy 889 // package uri's from external media onto secure containers 890 // or internal storage. 891 private IMediaContainerService mContainerService = null; 892 893 static final int SEND_PENDING_BROADCAST = 1; 894 static final int MCS_BOUND = 3; 895 static final int END_COPY = 4; 896 static final int INIT_COPY = 5; 897 static final int MCS_UNBIND = 6; 898 static final int START_CLEANING_PACKAGE = 7; 899 static final int FIND_INSTALL_LOC = 8; 900 static final int POST_INSTALL = 9; 901 static final int MCS_RECONNECT = 10; 902 static final int MCS_GIVE_UP = 11; 903 static final int UPDATED_MEDIA_STATUS = 12; 904 static final int WRITE_SETTINGS = 13; 905 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 906 static final int PACKAGE_VERIFIED = 15; 907 static final int CHECK_PENDING_VERIFICATION = 16; 908 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 909 static final int INTENT_FILTER_VERIFIED = 18; 910 911 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 912 913 // Delay time in millisecs 914 static final int BROADCAST_DELAY = 10 * 1000; 915 916 static UserManagerService sUserManager; 917 918 // Stores a list of users whose package restrictions file needs to be updated 919 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 920 921 final private DefaultContainerConnection mDefContainerConn = 922 new DefaultContainerConnection(); 923 class DefaultContainerConnection implements ServiceConnection { 924 public void onServiceConnected(ComponentName name, IBinder service) { 925 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 926 IMediaContainerService imcs = 927 IMediaContainerService.Stub.asInterface(service); 928 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 929 } 930 931 public void onServiceDisconnected(ComponentName name) { 932 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 933 } 934 } 935 936 // Recordkeeping of restore-after-install operations that are currently in flight 937 // between the Package Manager and the Backup Manager 938 class PostInstallData { 939 public InstallArgs args; 940 public PackageInstalledInfo res; 941 942 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 943 args = _a; 944 res = _r; 945 } 946 } 947 948 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 949 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 950 951 // XML tags for backup/restore of various bits of state 952 private static final String TAG_PREFERRED_BACKUP = "pa"; 953 private static final String TAG_DEFAULT_APPS = "da"; 954 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 955 956 final String mRequiredVerifierPackage; 957 final String mRequiredInstallerPackage; 958 959 private final PackageUsage mPackageUsage = new PackageUsage(); 960 961 private class PackageUsage { 962 private static final int WRITE_INTERVAL 963 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 964 965 private final Object mFileLock = new Object(); 966 private final AtomicLong mLastWritten = new AtomicLong(0); 967 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 968 969 private boolean mIsHistoricalPackageUsageAvailable = true; 970 971 boolean isHistoricalPackageUsageAvailable() { 972 return mIsHistoricalPackageUsageAvailable; 973 } 974 975 void write(boolean force) { 976 if (force) { 977 writeInternal(); 978 return; 979 } 980 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 981 && !DEBUG_DEXOPT) { 982 return; 983 } 984 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 985 new Thread("PackageUsage_DiskWriter") { 986 @Override 987 public void run() { 988 try { 989 writeInternal(); 990 } finally { 991 mBackgroundWriteRunning.set(false); 992 } 993 } 994 }.start(); 995 } 996 } 997 998 private void writeInternal() { 999 synchronized (mPackages) { 1000 synchronized (mFileLock) { 1001 AtomicFile file = getFile(); 1002 FileOutputStream f = null; 1003 try { 1004 f = file.startWrite(); 1005 BufferedOutputStream out = new BufferedOutputStream(f); 1006 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1007 StringBuilder sb = new StringBuilder(); 1008 for (PackageParser.Package pkg : mPackages.values()) { 1009 if (pkg.mLastPackageUsageTimeInMills == 0) { 1010 continue; 1011 } 1012 sb.setLength(0); 1013 sb.append(pkg.packageName); 1014 sb.append(' '); 1015 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1016 sb.append('\n'); 1017 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1018 } 1019 out.flush(); 1020 file.finishWrite(f); 1021 } catch (IOException e) { 1022 if (f != null) { 1023 file.failWrite(f); 1024 } 1025 Log.e(TAG, "Failed to write package usage times", e); 1026 } 1027 } 1028 } 1029 mLastWritten.set(SystemClock.elapsedRealtime()); 1030 } 1031 1032 void readLP() { 1033 synchronized (mFileLock) { 1034 AtomicFile file = getFile(); 1035 BufferedInputStream in = null; 1036 try { 1037 in = new BufferedInputStream(file.openRead()); 1038 StringBuffer sb = new StringBuffer(); 1039 while (true) { 1040 String packageName = readToken(in, sb, ' '); 1041 if (packageName == null) { 1042 break; 1043 } 1044 String timeInMillisString = readToken(in, sb, '\n'); 1045 if (timeInMillisString == null) { 1046 throw new IOException("Failed to find last usage time for package " 1047 + packageName); 1048 } 1049 PackageParser.Package pkg = mPackages.get(packageName); 1050 if (pkg == null) { 1051 continue; 1052 } 1053 long timeInMillis; 1054 try { 1055 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1056 } catch (NumberFormatException e) { 1057 throw new IOException("Failed to parse " + timeInMillisString 1058 + " as a long.", e); 1059 } 1060 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1061 } 1062 } catch (FileNotFoundException expected) { 1063 mIsHistoricalPackageUsageAvailable = false; 1064 } catch (IOException e) { 1065 Log.w(TAG, "Failed to read package usage times", e); 1066 } finally { 1067 IoUtils.closeQuietly(in); 1068 } 1069 } 1070 mLastWritten.set(SystemClock.elapsedRealtime()); 1071 } 1072 1073 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1074 throws IOException { 1075 sb.setLength(0); 1076 while (true) { 1077 int ch = in.read(); 1078 if (ch == -1) { 1079 if (sb.length() == 0) { 1080 return null; 1081 } 1082 throw new IOException("Unexpected EOF"); 1083 } 1084 if (ch == endOfToken) { 1085 return sb.toString(); 1086 } 1087 sb.append((char)ch); 1088 } 1089 } 1090 1091 private AtomicFile getFile() { 1092 File dataDir = Environment.getDataDirectory(); 1093 File systemDir = new File(dataDir, "system"); 1094 File fname = new File(systemDir, "package-usage.list"); 1095 return new AtomicFile(fname); 1096 } 1097 } 1098 1099 class PackageHandler extends Handler { 1100 private boolean mBound = false; 1101 final ArrayList<HandlerParams> mPendingInstalls = 1102 new ArrayList<HandlerParams>(); 1103 1104 private boolean connectToService() { 1105 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1106 " DefaultContainerService"); 1107 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1108 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1109 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1110 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1112 mBound = true; 1113 return true; 1114 } 1115 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1116 return false; 1117 } 1118 1119 private void disconnectService() { 1120 mContainerService = null; 1121 mBound = false; 1122 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1123 mContext.unbindService(mDefContainerConn); 1124 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1125 } 1126 1127 PackageHandler(Looper looper) { 1128 super(looper); 1129 } 1130 1131 public void handleMessage(Message msg) { 1132 try { 1133 doHandleMessage(msg); 1134 } finally { 1135 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1136 } 1137 } 1138 1139 void doHandleMessage(Message msg) { 1140 switch (msg.what) { 1141 case INIT_COPY: { 1142 HandlerParams params = (HandlerParams) msg.obj; 1143 int idx = mPendingInstalls.size(); 1144 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1145 // If a bind was already initiated we dont really 1146 // need to do anything. The pending install 1147 // will be processed later on. 1148 if (!mBound) { 1149 // If this is the only one pending we might 1150 // have to bind to the service again. 1151 if (!connectToService()) { 1152 Slog.e(TAG, "Failed to bind to media container service"); 1153 params.serviceError(); 1154 return; 1155 } else { 1156 // Once we bind to the service, the first 1157 // pending request will be processed. 1158 mPendingInstalls.add(idx, params); 1159 } 1160 } else { 1161 mPendingInstalls.add(idx, params); 1162 // Already bound to the service. Just make 1163 // sure we trigger off processing the first request. 1164 if (idx == 0) { 1165 mHandler.sendEmptyMessage(MCS_BOUND); 1166 } 1167 } 1168 break; 1169 } 1170 case MCS_BOUND: { 1171 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1172 if (msg.obj != null) { 1173 mContainerService = (IMediaContainerService) msg.obj; 1174 } 1175 if (mContainerService == null) { 1176 if (!mBound) { 1177 // Something seriously wrong since we are not bound and we are not 1178 // waiting for connection. Bail out. 1179 Slog.e(TAG, "Cannot bind to media container service"); 1180 for (HandlerParams params : mPendingInstalls) { 1181 // Indicate service bind error 1182 params.serviceError(); 1183 } 1184 mPendingInstalls.clear(); 1185 } else { 1186 Slog.w(TAG, "Waiting to connect to media container service"); 1187 } 1188 } else if (mPendingInstalls.size() > 0) { 1189 HandlerParams params = mPendingInstalls.get(0); 1190 if (params != null) { 1191 if (params.startCopy()) { 1192 // We are done... look for more work or to 1193 // go idle. 1194 if (DEBUG_SD_INSTALL) Log.i(TAG, 1195 "Checking for more work or unbind..."); 1196 // Delete pending install 1197 if (mPendingInstalls.size() > 0) { 1198 mPendingInstalls.remove(0); 1199 } 1200 if (mPendingInstalls.size() == 0) { 1201 if (mBound) { 1202 if (DEBUG_SD_INSTALL) Log.i(TAG, 1203 "Posting delayed MCS_UNBIND"); 1204 removeMessages(MCS_UNBIND); 1205 Message ubmsg = obtainMessage(MCS_UNBIND); 1206 // Unbind after a little delay, to avoid 1207 // continual thrashing. 1208 sendMessageDelayed(ubmsg, 10000); 1209 } 1210 } else { 1211 // There are more pending requests in queue. 1212 // Just post MCS_BOUND message to trigger processing 1213 // of next pending install. 1214 if (DEBUG_SD_INSTALL) Log.i(TAG, 1215 "Posting MCS_BOUND for next work"); 1216 mHandler.sendEmptyMessage(MCS_BOUND); 1217 } 1218 } 1219 } 1220 } else { 1221 // Should never happen ideally. 1222 Slog.w(TAG, "Empty queue"); 1223 } 1224 break; 1225 } 1226 case MCS_RECONNECT: { 1227 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1228 if (mPendingInstalls.size() > 0) { 1229 if (mBound) { 1230 disconnectService(); 1231 } 1232 if (!connectToService()) { 1233 Slog.e(TAG, "Failed to bind to media container service"); 1234 for (HandlerParams params : mPendingInstalls) { 1235 // Indicate service bind error 1236 params.serviceError(); 1237 } 1238 mPendingInstalls.clear(); 1239 } 1240 } 1241 break; 1242 } 1243 case MCS_UNBIND: { 1244 // If there is no actual work left, then time to unbind. 1245 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1246 1247 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1248 if (mBound) { 1249 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1250 1251 disconnectService(); 1252 } 1253 } else if (mPendingInstalls.size() > 0) { 1254 // There are more pending requests in queue. 1255 // Just post MCS_BOUND message to trigger processing 1256 // of next pending install. 1257 mHandler.sendEmptyMessage(MCS_BOUND); 1258 } 1259 1260 break; 1261 } 1262 case MCS_GIVE_UP: { 1263 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1264 mPendingInstalls.remove(0); 1265 break; 1266 } 1267 case SEND_PENDING_BROADCAST: { 1268 String packages[]; 1269 ArrayList<String> components[]; 1270 int size = 0; 1271 int uids[]; 1272 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1273 synchronized (mPackages) { 1274 if (mPendingBroadcasts == null) { 1275 return; 1276 } 1277 size = mPendingBroadcasts.size(); 1278 if (size <= 0) { 1279 // Nothing to be done. Just return 1280 return; 1281 } 1282 packages = new String[size]; 1283 components = new ArrayList[size]; 1284 uids = new int[size]; 1285 int i = 0; // filling out the above arrays 1286 1287 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1288 int packageUserId = mPendingBroadcasts.userIdAt(n); 1289 Iterator<Map.Entry<String, ArrayList<String>>> it 1290 = mPendingBroadcasts.packagesForUserId(packageUserId) 1291 .entrySet().iterator(); 1292 while (it.hasNext() && i < size) { 1293 Map.Entry<String, ArrayList<String>> ent = it.next(); 1294 packages[i] = ent.getKey(); 1295 components[i] = ent.getValue(); 1296 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1297 uids[i] = (ps != null) 1298 ? UserHandle.getUid(packageUserId, ps.appId) 1299 : -1; 1300 i++; 1301 } 1302 } 1303 size = i; 1304 mPendingBroadcasts.clear(); 1305 } 1306 // Send broadcasts 1307 for (int i = 0; i < size; i++) { 1308 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1309 } 1310 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1311 break; 1312 } 1313 case START_CLEANING_PACKAGE: { 1314 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1315 final String packageName = (String)msg.obj; 1316 final int userId = msg.arg1; 1317 final boolean andCode = msg.arg2 != 0; 1318 synchronized (mPackages) { 1319 if (userId == UserHandle.USER_ALL) { 1320 int[] users = sUserManager.getUserIds(); 1321 for (int user : users) { 1322 mSettings.addPackageToCleanLPw( 1323 new PackageCleanItem(user, packageName, andCode)); 1324 } 1325 } else { 1326 mSettings.addPackageToCleanLPw( 1327 new PackageCleanItem(userId, packageName, andCode)); 1328 } 1329 } 1330 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1331 startCleaningPackages(); 1332 } break; 1333 case POST_INSTALL: { 1334 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1335 PostInstallData data = mRunningInstalls.get(msg.arg1); 1336 mRunningInstalls.delete(msg.arg1); 1337 boolean deleteOld = false; 1338 1339 if (data != null) { 1340 InstallArgs args = data.args; 1341 PackageInstalledInfo res = data.res; 1342 1343 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1344 final String packageName = res.pkg.applicationInfo.packageName; 1345 res.removedInfo.sendBroadcast(false, true, false); 1346 Bundle extras = new Bundle(1); 1347 extras.putInt(Intent.EXTRA_UID, res.uid); 1348 1349 // Now that we successfully installed the package, grant runtime 1350 // permissions if requested before broadcasting the install. 1351 if ((args.installFlags 1352 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1353 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1354 args.installGrantPermissions); 1355 } 1356 1357 // Determine the set of users who are adding this 1358 // package for the first time vs. those who are seeing 1359 // an update. 1360 int[] firstUsers; 1361 int[] updateUsers = new int[0]; 1362 if (res.origUsers == null || res.origUsers.length == 0) { 1363 firstUsers = res.newUsers; 1364 } else { 1365 firstUsers = new int[0]; 1366 for (int i=0; i<res.newUsers.length; i++) { 1367 int user = res.newUsers[i]; 1368 boolean isNew = true; 1369 for (int j=0; j<res.origUsers.length; j++) { 1370 if (res.origUsers[j] == user) { 1371 isNew = false; 1372 break; 1373 } 1374 } 1375 if (isNew) { 1376 int[] newFirst = new int[firstUsers.length+1]; 1377 System.arraycopy(firstUsers, 0, newFirst, 0, 1378 firstUsers.length); 1379 newFirst[firstUsers.length] = user; 1380 firstUsers = newFirst; 1381 } else { 1382 int[] newUpdate = new int[updateUsers.length+1]; 1383 System.arraycopy(updateUsers, 0, newUpdate, 0, 1384 updateUsers.length); 1385 newUpdate[updateUsers.length] = user; 1386 updateUsers = newUpdate; 1387 } 1388 } 1389 } 1390 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1391 packageName, extras, null, null, firstUsers); 1392 final boolean update = res.removedInfo.removedPackage != null; 1393 if (update) { 1394 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1395 } 1396 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1397 packageName, extras, null, null, updateUsers); 1398 if (update) { 1399 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1400 packageName, extras, null, null, updateUsers); 1401 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1402 null, null, packageName, null, updateUsers); 1403 1404 // treat asec-hosted packages like removable media on upgrade 1405 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1406 if (DEBUG_INSTALL) { 1407 Slog.i(TAG, "upgrading pkg " + res.pkg 1408 + " is ASEC-hosted -> AVAILABLE"); 1409 } 1410 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1411 ArrayList<String> pkgList = new ArrayList<String>(1); 1412 pkgList.add(packageName); 1413 sendResourcesChangedBroadcast(true, true, 1414 pkgList,uidArray, null); 1415 } 1416 } 1417 if (res.removedInfo.args != null) { 1418 // Remove the replaced package's older resources safely now 1419 deleteOld = true; 1420 } 1421 1422 // If this app is a browser and it's newly-installed for some 1423 // users, clear any default-browser state in those users 1424 if (firstUsers.length > 0) { 1425 // the app's nature doesn't depend on the user, so we can just 1426 // check its browser nature in any user and generalize. 1427 if (packageIsBrowser(packageName, firstUsers[0])) { 1428 synchronized (mPackages) { 1429 for (int userId : firstUsers) { 1430 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1431 } 1432 } 1433 } 1434 } 1435 // Log current value of "unknown sources" setting 1436 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1437 getUnknownSourcesSettings()); 1438 } 1439 // Force a gc to clear up things 1440 Runtime.getRuntime().gc(); 1441 // We delete after a gc for applications on sdcard. 1442 if (deleteOld) { 1443 synchronized (mInstallLock) { 1444 res.removedInfo.args.doPostDeleteLI(true); 1445 } 1446 } 1447 if (args.observer != null) { 1448 try { 1449 Bundle extras = extrasForInstallResult(res); 1450 args.observer.onPackageInstalled(res.name, res.returnCode, 1451 res.returnMsg, extras); 1452 } catch (RemoteException e) { 1453 Slog.i(TAG, "Observer no longer exists."); 1454 } 1455 } 1456 } else { 1457 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1458 } 1459 } break; 1460 case UPDATED_MEDIA_STATUS: { 1461 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1462 boolean reportStatus = msg.arg1 == 1; 1463 boolean doGc = msg.arg2 == 1; 1464 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1465 if (doGc) { 1466 // Force a gc to clear up stale containers. 1467 Runtime.getRuntime().gc(); 1468 } 1469 if (msg.obj != null) { 1470 @SuppressWarnings("unchecked") 1471 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1472 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1473 // Unload containers 1474 unloadAllContainers(args); 1475 } 1476 if (reportStatus) { 1477 try { 1478 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1479 PackageHelper.getMountService().finishMediaUpdate(); 1480 } catch (RemoteException e) { 1481 Log.e(TAG, "MountService not running?"); 1482 } 1483 } 1484 } break; 1485 case WRITE_SETTINGS: { 1486 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1487 synchronized (mPackages) { 1488 removeMessages(WRITE_SETTINGS); 1489 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1490 mSettings.writeLPr(); 1491 mDirtyUsers.clear(); 1492 } 1493 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1494 } break; 1495 case WRITE_PACKAGE_RESTRICTIONS: { 1496 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1497 synchronized (mPackages) { 1498 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1499 for (int userId : mDirtyUsers) { 1500 mSettings.writePackageRestrictionsLPr(userId); 1501 } 1502 mDirtyUsers.clear(); 1503 } 1504 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1505 } break; 1506 case CHECK_PENDING_VERIFICATION: { 1507 final int verificationId = msg.arg1; 1508 final PackageVerificationState state = mPendingVerification.get(verificationId); 1509 1510 if ((state != null) && !state.timeoutExtended()) { 1511 final InstallArgs args = state.getInstallArgs(); 1512 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1513 1514 Slog.i(TAG, "Verification timed out for " + originUri); 1515 mPendingVerification.remove(verificationId); 1516 1517 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1518 1519 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1520 Slog.i(TAG, "Continuing with installation of " + originUri); 1521 state.setVerifierResponse(Binder.getCallingUid(), 1522 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1523 broadcastPackageVerified(verificationId, originUri, 1524 PackageManager.VERIFICATION_ALLOW, 1525 state.getInstallArgs().getUser()); 1526 try { 1527 ret = args.copyApk(mContainerService, true); 1528 } catch (RemoteException e) { 1529 Slog.e(TAG, "Could not contact the ContainerService"); 1530 } 1531 } else { 1532 broadcastPackageVerified(verificationId, originUri, 1533 PackageManager.VERIFICATION_REJECT, 1534 state.getInstallArgs().getUser()); 1535 } 1536 1537 processPendingInstall(args, ret); 1538 mHandler.sendEmptyMessage(MCS_UNBIND); 1539 } 1540 break; 1541 } 1542 case PACKAGE_VERIFIED: { 1543 final int verificationId = msg.arg1; 1544 1545 final PackageVerificationState state = mPendingVerification.get(verificationId); 1546 if (state == null) { 1547 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1548 break; 1549 } 1550 1551 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1552 1553 state.setVerifierResponse(response.callerUid, response.code); 1554 1555 if (state.isVerificationComplete()) { 1556 mPendingVerification.remove(verificationId); 1557 1558 final InstallArgs args = state.getInstallArgs(); 1559 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1560 1561 int ret; 1562 if (state.isInstallAllowed()) { 1563 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1564 broadcastPackageVerified(verificationId, originUri, 1565 response.code, state.getInstallArgs().getUser()); 1566 try { 1567 ret = args.copyApk(mContainerService, true); 1568 } catch (RemoteException e) { 1569 Slog.e(TAG, "Could not contact the ContainerService"); 1570 } 1571 } else { 1572 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1573 } 1574 1575 processPendingInstall(args, ret); 1576 1577 mHandler.sendEmptyMessage(MCS_UNBIND); 1578 } 1579 1580 break; 1581 } 1582 case START_INTENT_FILTER_VERIFICATIONS: { 1583 IFVerificationParams params = (IFVerificationParams) msg.obj; 1584 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1585 params.replacing, params.pkg); 1586 break; 1587 } 1588 case INTENT_FILTER_VERIFIED: { 1589 final int verificationId = msg.arg1; 1590 1591 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1592 verificationId); 1593 if (state == null) { 1594 Slog.w(TAG, "Invalid IntentFilter verification token " 1595 + verificationId + " received"); 1596 break; 1597 } 1598 1599 final int userId = state.getUserId(); 1600 1601 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1602 "Processing IntentFilter verification with token:" 1603 + verificationId + " and userId:" + userId); 1604 1605 final IntentFilterVerificationResponse response = 1606 (IntentFilterVerificationResponse) msg.obj; 1607 1608 state.setVerifierResponse(response.callerUid, response.code); 1609 1610 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1611 "IntentFilter verification with token:" + verificationId 1612 + " and userId:" + userId 1613 + " is settings verifier response with response code:" 1614 + response.code); 1615 1616 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1617 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1618 + response.getFailedDomainsString()); 1619 } 1620 1621 if (state.isVerificationComplete()) { 1622 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1623 } else { 1624 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1625 "IntentFilter verification with token:" + verificationId 1626 + " was not said to be complete"); 1627 } 1628 1629 break; 1630 } 1631 } 1632 } 1633 } 1634 1635 private StorageEventListener mStorageListener = new StorageEventListener() { 1636 @Override 1637 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1638 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1639 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1640 final String volumeUuid = vol.getFsUuid(); 1641 1642 // Clean up any users or apps that were removed or recreated 1643 // while this volume was missing 1644 reconcileUsers(volumeUuid); 1645 reconcileApps(volumeUuid); 1646 1647 // Clean up any install sessions that expired or were 1648 // cancelled while this volume was missing 1649 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1650 1651 loadPrivatePackages(vol); 1652 1653 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1654 unloadPrivatePackages(vol); 1655 } 1656 } 1657 1658 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1659 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1660 updateExternalMediaStatus(true, false); 1661 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1662 updateExternalMediaStatus(false, false); 1663 } 1664 } 1665 } 1666 1667 @Override 1668 public void onVolumeForgotten(String fsUuid) { 1669 if (TextUtils.isEmpty(fsUuid)) { 1670 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1671 return; 1672 } 1673 1674 // Remove any apps installed on the forgotten volume 1675 synchronized (mPackages) { 1676 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1677 for (PackageSetting ps : packages) { 1678 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1679 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1680 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1681 } 1682 1683 mSettings.onVolumeForgotten(fsUuid); 1684 mSettings.writeLPr(); 1685 } 1686 } 1687 }; 1688 1689 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1690 String[] grantedPermissions) { 1691 if (userId >= UserHandle.USER_OWNER) { 1692 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1693 } else if (userId == UserHandle.USER_ALL) { 1694 final int[] userIds; 1695 synchronized (mPackages) { 1696 userIds = UserManagerService.getInstance().getUserIds(); 1697 } 1698 for (int someUserId : userIds) { 1699 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1700 } 1701 } 1702 1703 // We could have touched GID membership, so flush out packages.list 1704 synchronized (mPackages) { 1705 mSettings.writePackageListLPr(); 1706 } 1707 } 1708 1709 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1710 String[] grantedPermissions) { 1711 SettingBase sb = (SettingBase) pkg.mExtras; 1712 if (sb == null) { 1713 return; 1714 } 1715 1716 PermissionsState permissionsState = sb.getPermissionsState(); 1717 1718 for (String permission : pkg.requestedPermissions) { 1719 BasePermission bp = mSettings.mPermissions.get(permission); 1720 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1721 || ArrayUtils.contains(grantedPermissions, permission))) { 1722 permissionsState.grantRuntimePermission(bp, userId); 1723 } 1724 } 1725 } 1726 1727 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1728 Bundle extras = null; 1729 switch (res.returnCode) { 1730 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1731 extras = new Bundle(); 1732 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1733 res.origPermission); 1734 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1735 res.origPackage); 1736 break; 1737 } 1738 case PackageManager.INSTALL_SUCCEEDED: { 1739 extras = new Bundle(); 1740 extras.putBoolean(Intent.EXTRA_REPLACING, 1741 res.removedInfo != null && res.removedInfo.removedPackage != null); 1742 break; 1743 } 1744 } 1745 return extras; 1746 } 1747 1748 void scheduleWriteSettingsLocked() { 1749 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1750 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1751 } 1752 } 1753 1754 void scheduleWritePackageRestrictionsLocked(int userId) { 1755 if (!sUserManager.exists(userId)) return; 1756 mDirtyUsers.add(userId); 1757 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1758 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1759 } 1760 } 1761 1762 public static PackageManagerService main(Context context, Installer installer, 1763 boolean factoryTest, boolean onlyCore) { 1764 PackageManagerService m = new PackageManagerService(context, installer, 1765 factoryTest, onlyCore); 1766 ServiceManager.addService("package", m); 1767 return m; 1768 } 1769 1770 static String[] splitString(String str, char sep) { 1771 int count = 1; 1772 int i = 0; 1773 while ((i=str.indexOf(sep, i)) >= 0) { 1774 count++; 1775 i++; 1776 } 1777 1778 String[] res = new String[count]; 1779 i=0; 1780 count = 0; 1781 int lastI=0; 1782 while ((i=str.indexOf(sep, i)) >= 0) { 1783 res[count] = str.substring(lastI, i); 1784 count++; 1785 i++; 1786 lastI = i; 1787 } 1788 res[count] = str.substring(lastI, str.length()); 1789 return res; 1790 } 1791 1792 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1793 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1794 Context.DISPLAY_SERVICE); 1795 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1796 } 1797 1798 public PackageManagerService(Context context, Installer installer, 1799 boolean factoryTest, boolean onlyCore) { 1800 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1801 SystemClock.uptimeMillis()); 1802 1803 if (mSdkVersion <= 0) { 1804 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1805 } 1806 1807 mContext = context; 1808 mFactoryTest = factoryTest; 1809 mOnlyCore = onlyCore; 1810 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1811 mMetrics = new DisplayMetrics(); 1812 mSettings = new Settings(mPackages); 1813 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1814 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1815 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1816 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1817 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1818 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1819 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1820 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1821 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1822 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1823 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1824 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1825 1826 // TODO: add a property to control this? 1827 long dexOptLRUThresholdInMinutes; 1828 if (mLazyDexOpt) { 1829 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1830 } else { 1831 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1832 } 1833 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1834 1835 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1836 if (separateProcesses != null && separateProcesses.length() > 0) { 1837 if ("*".equals(separateProcesses)) { 1838 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1839 mSeparateProcesses = null; 1840 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1841 } else { 1842 mDefParseFlags = 0; 1843 mSeparateProcesses = separateProcesses.split(","); 1844 Slog.w(TAG, "Running with debug.separate_processes: " 1845 + separateProcesses); 1846 } 1847 } else { 1848 mDefParseFlags = 0; 1849 mSeparateProcesses = null; 1850 } 1851 1852 mInstaller = installer; 1853 mPackageDexOptimizer = new PackageDexOptimizer(this); 1854 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1855 1856 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1857 FgThread.get().getLooper()); 1858 1859 getDefaultDisplayMetrics(context, mMetrics); 1860 1861 SystemConfig systemConfig = SystemConfig.getInstance(); 1862 mGlobalGids = systemConfig.getGlobalGids(); 1863 mSystemPermissions = systemConfig.getSystemPermissions(); 1864 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1865 1866 synchronized (mInstallLock) { 1867 // writer 1868 synchronized (mPackages) { 1869 mHandlerThread = new ServiceThread(TAG, 1870 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1871 mHandlerThread.start(); 1872 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1873 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1874 1875 File dataDir = Environment.getDataDirectory(); 1876 mAppDataDir = new File(dataDir, "data"); 1877 mAppInstallDir = new File(dataDir, "app"); 1878 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1879 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1880 mUserAppDataDir = new File(dataDir, "user"); 1881 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1882 1883 sUserManager = new UserManagerService(context, this, 1884 mInstallLock, mPackages); 1885 1886 // Propagate permission configuration in to package manager. 1887 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1888 = systemConfig.getPermissions(); 1889 for (int i=0; i<permConfig.size(); i++) { 1890 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1891 BasePermission bp = mSettings.mPermissions.get(perm.name); 1892 if (bp == null) { 1893 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1894 mSettings.mPermissions.put(perm.name, bp); 1895 } 1896 if (perm.gids != null) { 1897 bp.setGids(perm.gids, perm.perUser); 1898 } 1899 } 1900 1901 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1902 for (int i=0; i<libConfig.size(); i++) { 1903 mSharedLibraries.put(libConfig.keyAt(i), 1904 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1905 } 1906 1907 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1908 1909 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1910 mSdkVersion, mOnlyCore); 1911 1912 String customResolverActivity = Resources.getSystem().getString( 1913 R.string.config_customResolverActivity); 1914 if (TextUtils.isEmpty(customResolverActivity)) { 1915 customResolverActivity = null; 1916 } else { 1917 mCustomResolverComponentName = ComponentName.unflattenFromString( 1918 customResolverActivity); 1919 } 1920 1921 long startTime = SystemClock.uptimeMillis(); 1922 1923 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1924 startTime); 1925 1926 // Set flag to monitor and not change apk file paths when 1927 // scanning install directories. 1928 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1929 1930 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1931 1932 /** 1933 * Add everything in the in the boot class path to the 1934 * list of process files because dexopt will have been run 1935 * if necessary during zygote startup. 1936 */ 1937 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1938 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1939 1940 if (bootClassPath != null) { 1941 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1942 for (String element : bootClassPathElements) { 1943 alreadyDexOpted.add(element); 1944 } 1945 } else { 1946 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1947 } 1948 1949 if (systemServerClassPath != null) { 1950 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1951 for (String element : systemServerClassPathElements) { 1952 alreadyDexOpted.add(element); 1953 } 1954 } else { 1955 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1956 } 1957 1958 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1959 final String[] dexCodeInstructionSets = 1960 getDexCodeInstructionSets( 1961 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1962 1963 /** 1964 * Ensure all external libraries have had dexopt run on them. 1965 */ 1966 if (mSharedLibraries.size() > 0) { 1967 // NOTE: For now, we're compiling these system "shared libraries" 1968 // (and framework jars) into all available architectures. It's possible 1969 // to compile them only when we come across an app that uses them (there's 1970 // already logic for that in scanPackageLI) but that adds some complexity. 1971 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1972 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1973 final String lib = libEntry.path; 1974 if (lib == null) { 1975 continue; 1976 } 1977 1978 try { 1979 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1980 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1981 alreadyDexOpted.add(lib); 1982 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1983 } 1984 } catch (FileNotFoundException e) { 1985 Slog.w(TAG, "Library not found: " + lib); 1986 } catch (IOException e) { 1987 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1988 + e.getMessage()); 1989 } 1990 } 1991 } 1992 } 1993 1994 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1995 1996 // Gross hack for now: we know this file doesn't contain any 1997 // code, so don't dexopt it to avoid the resulting log spew. 1998 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1999 2000 // Gross hack for now: we know this file is only part of 2001 // the boot class path for art, so don't dexopt it to 2002 // avoid the resulting log spew. 2003 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2004 2005 /** 2006 * There are a number of commands implemented in Java, which 2007 * we currently need to do the dexopt on so that they can be 2008 * run from a non-root shell. 2009 */ 2010 String[] frameworkFiles = frameworkDir.list(); 2011 if (frameworkFiles != null) { 2012 // TODO: We could compile these only for the most preferred ABI. We should 2013 // first double check that the dex files for these commands are not referenced 2014 // by other system apps. 2015 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2016 for (int i=0; i<frameworkFiles.length; i++) { 2017 File libPath = new File(frameworkDir, frameworkFiles[i]); 2018 String path = libPath.getPath(); 2019 // Skip the file if we already did it. 2020 if (alreadyDexOpted.contains(path)) { 2021 continue; 2022 } 2023 // Skip the file if it is not a type we want to dexopt. 2024 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2025 continue; 2026 } 2027 try { 2028 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2029 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2030 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2031 } 2032 } catch (FileNotFoundException e) { 2033 Slog.w(TAG, "Jar not found: " + path); 2034 } catch (IOException e) { 2035 Slog.w(TAG, "Exception reading jar: " + path, e); 2036 } 2037 } 2038 } 2039 } 2040 2041 final VersionInfo ver = mSettings.getInternalVersion(); 2042 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2043 // when upgrading from pre-M, promote system app permissions from install to runtime 2044 mPromoteSystemApps = 2045 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2046 2047 // save off the names of pre-existing system packages prior to scanning; we don't 2048 // want to automatically grant runtime permissions for new system apps 2049 if (mPromoteSystemApps) { 2050 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2051 while (pkgSettingIter.hasNext()) { 2052 PackageSetting ps = pkgSettingIter.next(); 2053 if (isSystemApp(ps)) { 2054 mExistingSystemPackages.add(ps.name); 2055 } 2056 } 2057 } 2058 2059 // Collect vendor overlay packages. 2060 // (Do this before scanning any apps.) 2061 // For security and version matching reason, only consider 2062 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2063 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2064 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2065 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2066 2067 // Find base frameworks (resource packages without code). 2068 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2069 | PackageParser.PARSE_IS_SYSTEM_DIR 2070 | PackageParser.PARSE_IS_PRIVILEGED, 2071 scanFlags | SCAN_NO_DEX, 0); 2072 2073 // Collected privileged system packages. 2074 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2075 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2076 | PackageParser.PARSE_IS_SYSTEM_DIR 2077 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2078 2079 // Collect ordinary system packages. 2080 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2081 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2082 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2083 2084 // Collect all vendor packages. 2085 File vendorAppDir = new File("/vendor/app"); 2086 try { 2087 vendorAppDir = vendorAppDir.getCanonicalFile(); 2088 } catch (IOException e) { 2089 // failed to look up canonical path, continue with original one 2090 } 2091 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2092 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2093 2094 // Collect all OEM packages. 2095 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2096 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2097 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2098 2099 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2100 mInstaller.moveFiles(); 2101 2102 // Prune any system packages that no longer exist. 2103 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2104 if (!mOnlyCore) { 2105 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2106 while (psit.hasNext()) { 2107 PackageSetting ps = psit.next(); 2108 2109 /* 2110 * If this is not a system app, it can't be a 2111 * disable system app. 2112 */ 2113 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2114 continue; 2115 } 2116 2117 /* 2118 * If the package is scanned, it's not erased. 2119 */ 2120 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2121 if (scannedPkg != null) { 2122 /* 2123 * If the system app is both scanned and in the 2124 * disabled packages list, then it must have been 2125 * added via OTA. Remove it from the currently 2126 * scanned package so the previously user-installed 2127 * application can be scanned. 2128 */ 2129 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2130 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2131 + ps.name + "; removing system app. Last known codePath=" 2132 + ps.codePathString + ", installStatus=" + ps.installStatus 2133 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2134 + scannedPkg.mVersionCode); 2135 removePackageLI(ps, true); 2136 mExpectingBetter.put(ps.name, ps.codePath); 2137 } 2138 2139 continue; 2140 } 2141 2142 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2143 psit.remove(); 2144 logCriticalInfo(Log.WARN, "System package " + ps.name 2145 + " no longer exists; wiping its data"); 2146 removeDataDirsLI(null, ps.name); 2147 } else { 2148 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2149 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2150 possiblyDeletedUpdatedSystemApps.add(ps.name); 2151 } 2152 } 2153 } 2154 } 2155 2156 //look for any incomplete package installations 2157 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2158 //clean up list 2159 for(int i = 0; i < deletePkgsList.size(); i++) { 2160 //clean up here 2161 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2162 } 2163 //delete tmp files 2164 deleteTempPackageFiles(); 2165 2166 // Remove any shared userIDs that have no associated packages 2167 mSettings.pruneSharedUsersLPw(); 2168 2169 if (!mOnlyCore) { 2170 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2171 SystemClock.uptimeMillis()); 2172 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2173 2174 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2175 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2176 2177 /** 2178 * Remove disable package settings for any updated system 2179 * apps that were removed via an OTA. If they're not a 2180 * previously-updated app, remove them completely. 2181 * Otherwise, just revoke their system-level permissions. 2182 */ 2183 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2184 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2185 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2186 2187 String msg; 2188 if (deletedPkg == null) { 2189 msg = "Updated system package " + deletedAppName 2190 + " no longer exists; wiping its data"; 2191 removeDataDirsLI(null, deletedAppName); 2192 } else { 2193 msg = "Updated system app + " + deletedAppName 2194 + " no longer present; removing system privileges for " 2195 + deletedAppName; 2196 2197 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2198 2199 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2200 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2201 } 2202 logCriticalInfo(Log.WARN, msg); 2203 } 2204 2205 /** 2206 * Make sure all system apps that we expected to appear on 2207 * the userdata partition actually showed up. If they never 2208 * appeared, crawl back and revive the system version. 2209 */ 2210 for (int i = 0; i < mExpectingBetter.size(); i++) { 2211 final String packageName = mExpectingBetter.keyAt(i); 2212 if (!mPackages.containsKey(packageName)) { 2213 final File scanFile = mExpectingBetter.valueAt(i); 2214 2215 logCriticalInfo(Log.WARN, "Expected better " + packageName 2216 + " but never showed up; reverting to system"); 2217 2218 final int reparseFlags; 2219 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2220 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2221 | PackageParser.PARSE_IS_SYSTEM_DIR 2222 | PackageParser.PARSE_IS_PRIVILEGED; 2223 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2224 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2225 | PackageParser.PARSE_IS_SYSTEM_DIR; 2226 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2227 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2228 | PackageParser.PARSE_IS_SYSTEM_DIR; 2229 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2230 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2231 | PackageParser.PARSE_IS_SYSTEM_DIR; 2232 } else { 2233 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2234 continue; 2235 } 2236 2237 mSettings.enableSystemPackageLPw(packageName); 2238 2239 try { 2240 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2241 } catch (PackageManagerException e) { 2242 Slog.e(TAG, "Failed to parse original system package: " 2243 + e.getMessage()); 2244 } 2245 } 2246 } 2247 } 2248 mExpectingBetter.clear(); 2249 2250 // Now that we know all of the shared libraries, update all clients to have 2251 // the correct library paths. 2252 updateAllSharedLibrariesLPw(); 2253 2254 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2255 // NOTE: We ignore potential failures here during a system scan (like 2256 // the rest of the commands above) because there's precious little we 2257 // can do about it. A settings error is reported, though. 2258 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2259 false /* force dexopt */, false /* defer dexopt */); 2260 } 2261 2262 // Now that we know all the packages we are keeping, 2263 // read and update their last usage times. 2264 mPackageUsage.readLP(); 2265 2266 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2267 SystemClock.uptimeMillis()); 2268 Slog.i(TAG, "Time to scan packages: " 2269 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2270 + " seconds"); 2271 2272 // If the platform SDK has changed since the last time we booted, 2273 // we need to re-grant app permission to catch any new ones that 2274 // appear. This is really a hack, and means that apps can in some 2275 // cases get permissions that the user didn't initially explicitly 2276 // allow... it would be nice to have some better way to handle 2277 // this situation. 2278 int updateFlags = UPDATE_PERMISSIONS_ALL; 2279 if (ver.sdkVersion != mSdkVersion) { 2280 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2281 + mSdkVersion + "; regranting permissions for internal storage"); 2282 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2283 } 2284 updatePermissionsLPw(null, null, updateFlags); 2285 ver.sdkVersion = mSdkVersion; 2286 // clear only after permissions have been updated 2287 mExistingSystemPackages.clear(); 2288 mPromoteSystemApps = false; 2289 2290 // If this is the first boot, and it is a normal boot, then 2291 // we need to initialize the default preferred apps. 2292 if (!mRestoredSettings && !onlyCore) { 2293 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2294 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2295 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2296 } 2297 2298 // If this is first boot after an OTA, and a normal boot, then 2299 // we need to clear code cache directories. 2300 if (mIsUpgrade && !onlyCore) { 2301 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2302 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2303 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2304 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2305 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2306 } 2307 } 2308 ver.fingerprint = Build.FINGERPRINT; 2309 } 2310 2311 checkDefaultBrowser(); 2312 2313 // All the changes are done during package scanning. 2314 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2315 2316 // can downgrade to reader 2317 mSettings.writeLPr(); 2318 2319 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2320 SystemClock.uptimeMillis()); 2321 2322 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2323 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2324 2325 mInstallerService = new PackageInstallerService(context, this); 2326 2327 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2328 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2329 mIntentFilterVerifierComponent); 2330 2331 } // synchronized (mPackages) 2332 } // synchronized (mInstallLock) 2333 2334 // Now after opening every single application zip, make sure they 2335 // are all flushed. Not really needed, but keeps things nice and 2336 // tidy. 2337 Runtime.getRuntime().gc(); 2338 2339 // Expose private service for system components to use. 2340 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2341 } 2342 2343 @Override 2344 public boolean isFirstBoot() { 2345 return !mRestoredSettings; 2346 } 2347 2348 @Override 2349 public boolean isOnlyCoreApps() { 2350 return mOnlyCore; 2351 } 2352 2353 @Override 2354 public boolean isUpgrade() { 2355 return mIsUpgrade; 2356 } 2357 2358 private String getRequiredVerifierLPr() { 2359 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2360 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2361 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2362 2363 String requiredVerifier = null; 2364 2365 final int N = receivers.size(); 2366 for (int i = 0; i < N; i++) { 2367 final ResolveInfo info = receivers.get(i); 2368 2369 if (info.activityInfo == null) { 2370 continue; 2371 } 2372 2373 final String packageName = info.activityInfo.packageName; 2374 2375 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2376 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2377 continue; 2378 } 2379 2380 if (requiredVerifier != null) { 2381 throw new RuntimeException("There can be only one required verifier"); 2382 } 2383 2384 requiredVerifier = packageName; 2385 } 2386 2387 return requiredVerifier; 2388 } 2389 2390 private String getRequiredInstallerLPr() { 2391 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2392 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2393 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2394 2395 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2396 PACKAGE_MIME_TYPE, 0, 0); 2397 2398 String requiredInstaller = null; 2399 2400 final int N = installers.size(); 2401 for (int i = 0; i < N; i++) { 2402 final ResolveInfo info = installers.get(i); 2403 final String packageName = info.activityInfo.packageName; 2404 2405 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2406 continue; 2407 } 2408 2409 if (requiredInstaller != null) { 2410 throw new RuntimeException("There must be one required installer"); 2411 } 2412 2413 requiredInstaller = packageName; 2414 } 2415 2416 if (requiredInstaller == null) { 2417 throw new RuntimeException("There must be one required installer"); 2418 } 2419 2420 return requiredInstaller; 2421 } 2422 2423 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2424 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2425 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2426 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2427 2428 ComponentName verifierComponentName = null; 2429 2430 int priority = -1000; 2431 final int N = receivers.size(); 2432 for (int i = 0; i < N; i++) { 2433 final ResolveInfo info = receivers.get(i); 2434 2435 if (info.activityInfo == null) { 2436 continue; 2437 } 2438 2439 final String packageName = info.activityInfo.packageName; 2440 2441 final PackageSetting ps = mSettings.mPackages.get(packageName); 2442 if (ps == null) { 2443 continue; 2444 } 2445 2446 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2447 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2448 continue; 2449 } 2450 2451 // Select the IntentFilterVerifier with the highest priority 2452 if (priority < info.priority) { 2453 priority = info.priority; 2454 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2455 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2456 + verifierComponentName + " with priority: " + info.priority); 2457 } 2458 } 2459 2460 return verifierComponentName; 2461 } 2462 2463 private void primeDomainVerificationsLPw(int userId) { 2464 if (DEBUG_DOMAIN_VERIFICATION) { 2465 Slog.d(TAG, "Priming domain verifications in user " + userId); 2466 } 2467 2468 SystemConfig systemConfig = SystemConfig.getInstance(); 2469 ArraySet<String> packages = systemConfig.getLinkedApps(); 2470 ArraySet<String> domains = new ArraySet<String>(); 2471 2472 for (String packageName : packages) { 2473 PackageParser.Package pkg = mPackages.get(packageName); 2474 if (pkg != null) { 2475 if (!pkg.isSystemApp()) { 2476 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2477 continue; 2478 } 2479 2480 domains.clear(); 2481 for (PackageParser.Activity a : pkg.activities) { 2482 for (ActivityIntentInfo filter : a.intents) { 2483 if (hasValidDomains(filter)) { 2484 domains.addAll(filter.getHostsList()); 2485 } 2486 } 2487 } 2488 2489 if (domains.size() > 0) { 2490 if (DEBUG_DOMAIN_VERIFICATION) { 2491 Slog.v(TAG, " + " + packageName); 2492 } 2493 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2494 // state w.r.t. the formal app-linkage "no verification attempted" state; 2495 // and then 'always' in the per-user state actually used for intent resolution. 2496 final IntentFilterVerificationInfo ivi; 2497 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2498 new ArrayList<String>(domains)); 2499 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2500 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2501 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2502 } else { 2503 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2504 + "' does not handle web links"); 2505 } 2506 } else { 2507 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2508 } 2509 } 2510 2511 scheduleWritePackageRestrictionsLocked(userId); 2512 scheduleWriteSettingsLocked(); 2513 } 2514 2515 private void applyFactoryDefaultBrowserLPw(int userId) { 2516 // The default browser app's package name is stored in a string resource, 2517 // with a product-specific overlay used for vendor customization. 2518 String browserPkg = mContext.getResources().getString( 2519 com.android.internal.R.string.default_browser); 2520 if (!TextUtils.isEmpty(browserPkg)) { 2521 // non-empty string => required to be a known package 2522 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2523 if (ps == null) { 2524 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2525 browserPkg = null; 2526 } else { 2527 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2528 } 2529 } 2530 2531 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2532 // default. If there's more than one, just leave everything alone. 2533 if (browserPkg == null) { 2534 calculateDefaultBrowserLPw(userId); 2535 } 2536 } 2537 2538 private void calculateDefaultBrowserLPw(int userId) { 2539 List<String> allBrowsers = resolveAllBrowserApps(userId); 2540 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2541 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2542 } 2543 2544 private List<String> resolveAllBrowserApps(int userId) { 2545 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2546 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2547 PackageManager.MATCH_ALL, userId); 2548 2549 final int count = list.size(); 2550 List<String> result = new ArrayList<String>(count); 2551 for (int i=0; i<count; i++) { 2552 ResolveInfo info = list.get(i); 2553 if (info.activityInfo == null 2554 || !info.handleAllWebDataURI 2555 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2556 || result.contains(info.activityInfo.packageName)) { 2557 continue; 2558 } 2559 result.add(info.activityInfo.packageName); 2560 } 2561 2562 return result; 2563 } 2564 2565 private boolean packageIsBrowser(String packageName, int userId) { 2566 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2567 PackageManager.MATCH_ALL, userId); 2568 final int N = list.size(); 2569 for (int i = 0; i < N; i++) { 2570 ResolveInfo info = list.get(i); 2571 if (packageName.equals(info.activityInfo.packageName)) { 2572 return true; 2573 } 2574 } 2575 return false; 2576 } 2577 2578 private void checkDefaultBrowser() { 2579 final int myUserId = UserHandle.myUserId(); 2580 final String packageName = getDefaultBrowserPackageName(myUserId); 2581 if (packageName != null) { 2582 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2583 if (info == null) { 2584 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2585 synchronized (mPackages) { 2586 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2587 } 2588 } 2589 } 2590 } 2591 2592 @Override 2593 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2594 throws RemoteException { 2595 try { 2596 return super.onTransact(code, data, reply, flags); 2597 } catch (RuntimeException e) { 2598 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2599 Slog.wtf(TAG, "Package Manager Crash", e); 2600 } 2601 throw e; 2602 } 2603 } 2604 2605 void cleanupInstallFailedPackage(PackageSetting ps) { 2606 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2607 2608 removeDataDirsLI(ps.volumeUuid, ps.name); 2609 if (ps.codePath != null) { 2610 if (ps.codePath.isDirectory()) { 2611 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2612 } else { 2613 ps.codePath.delete(); 2614 } 2615 } 2616 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2617 if (ps.resourcePath.isDirectory()) { 2618 FileUtils.deleteContents(ps.resourcePath); 2619 } 2620 ps.resourcePath.delete(); 2621 } 2622 mSettings.removePackageLPw(ps.name); 2623 } 2624 2625 static int[] appendInts(int[] cur, int[] add) { 2626 if (add == null) return cur; 2627 if (cur == null) return add; 2628 final int N = add.length; 2629 for (int i=0; i<N; i++) { 2630 cur = appendInt(cur, add[i]); 2631 } 2632 return cur; 2633 } 2634 2635 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2636 if (!sUserManager.exists(userId)) return null; 2637 final PackageSetting ps = (PackageSetting) p.mExtras; 2638 if (ps == null) { 2639 return null; 2640 } 2641 2642 final PermissionsState permissionsState = ps.getPermissionsState(); 2643 2644 final int[] gids = permissionsState.computeGids(userId); 2645 final Set<String> permissions = permissionsState.getPermissions(userId); 2646 final PackageUserState state = ps.readUserState(userId); 2647 2648 return PackageParser.generatePackageInfo(p, gids, flags, 2649 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2650 } 2651 2652 @Override 2653 public boolean isPackageFrozen(String packageName) { 2654 synchronized (mPackages) { 2655 final PackageSetting ps = mSettings.mPackages.get(packageName); 2656 if (ps != null) { 2657 return ps.frozen; 2658 } 2659 } 2660 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2661 return true; 2662 } 2663 2664 @Override 2665 public boolean isPackageAvailable(String packageName, int userId) { 2666 if (!sUserManager.exists(userId)) return false; 2667 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2668 synchronized (mPackages) { 2669 PackageParser.Package p = mPackages.get(packageName); 2670 if (p != null) { 2671 final PackageSetting ps = (PackageSetting) p.mExtras; 2672 if (ps != null) { 2673 final PackageUserState state = ps.readUserState(userId); 2674 if (state != null) { 2675 return PackageParser.isAvailable(state); 2676 } 2677 } 2678 } 2679 } 2680 return false; 2681 } 2682 2683 @Override 2684 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2685 if (!sUserManager.exists(userId)) return null; 2686 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2687 // reader 2688 synchronized (mPackages) { 2689 PackageParser.Package p = mPackages.get(packageName); 2690 if (DEBUG_PACKAGE_INFO) 2691 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2692 if (p != null) { 2693 return generatePackageInfo(p, flags, userId); 2694 } 2695 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2696 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2697 } 2698 } 2699 return null; 2700 } 2701 2702 @Override 2703 public String[] currentToCanonicalPackageNames(String[] names) { 2704 String[] out = new String[names.length]; 2705 // reader 2706 synchronized (mPackages) { 2707 for (int i=names.length-1; i>=0; i--) { 2708 PackageSetting ps = mSettings.mPackages.get(names[i]); 2709 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2710 } 2711 } 2712 return out; 2713 } 2714 2715 @Override 2716 public String[] canonicalToCurrentPackageNames(String[] names) { 2717 String[] out = new String[names.length]; 2718 // reader 2719 synchronized (mPackages) { 2720 for (int i=names.length-1; i>=0; i--) { 2721 String cur = mSettings.mRenamedPackages.get(names[i]); 2722 out[i] = cur != null ? cur : names[i]; 2723 } 2724 } 2725 return out; 2726 } 2727 2728 @Override 2729 public int getPackageUid(String packageName, int userId) { 2730 if (!sUserManager.exists(userId)) return -1; 2731 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2732 2733 // reader 2734 synchronized (mPackages) { 2735 PackageParser.Package p = mPackages.get(packageName); 2736 if(p != null) { 2737 return UserHandle.getUid(userId, p.applicationInfo.uid); 2738 } 2739 PackageSetting ps = mSettings.mPackages.get(packageName); 2740 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2741 return -1; 2742 } 2743 p = ps.pkg; 2744 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2745 } 2746 } 2747 2748 @Override 2749 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2750 if (!sUserManager.exists(userId)) { 2751 return null; 2752 } 2753 2754 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2755 "getPackageGids"); 2756 2757 // reader 2758 synchronized (mPackages) { 2759 PackageParser.Package p = mPackages.get(packageName); 2760 if (DEBUG_PACKAGE_INFO) { 2761 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2762 } 2763 if (p != null) { 2764 PackageSetting ps = (PackageSetting) p.mExtras; 2765 return ps.getPermissionsState().computeGids(userId); 2766 } 2767 } 2768 2769 return null; 2770 } 2771 2772 static PermissionInfo generatePermissionInfo( 2773 BasePermission bp, int flags) { 2774 if (bp.perm != null) { 2775 return PackageParser.generatePermissionInfo(bp.perm, flags); 2776 } 2777 PermissionInfo pi = new PermissionInfo(); 2778 pi.name = bp.name; 2779 pi.packageName = bp.sourcePackage; 2780 pi.nonLocalizedLabel = bp.name; 2781 pi.protectionLevel = bp.protectionLevel; 2782 return pi; 2783 } 2784 2785 @Override 2786 public PermissionInfo getPermissionInfo(String name, int flags) { 2787 // reader 2788 synchronized (mPackages) { 2789 final BasePermission p = mSettings.mPermissions.get(name); 2790 if (p != null) { 2791 return generatePermissionInfo(p, flags); 2792 } 2793 return null; 2794 } 2795 } 2796 2797 @Override 2798 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2799 // reader 2800 synchronized (mPackages) { 2801 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2802 for (BasePermission p : mSettings.mPermissions.values()) { 2803 if (group == null) { 2804 if (p.perm == null || p.perm.info.group == null) { 2805 out.add(generatePermissionInfo(p, flags)); 2806 } 2807 } else { 2808 if (p.perm != null && group.equals(p.perm.info.group)) { 2809 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2810 } 2811 } 2812 } 2813 2814 if (out.size() > 0) { 2815 return out; 2816 } 2817 return mPermissionGroups.containsKey(group) ? out : null; 2818 } 2819 } 2820 2821 @Override 2822 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2823 // reader 2824 synchronized (mPackages) { 2825 return PackageParser.generatePermissionGroupInfo( 2826 mPermissionGroups.get(name), flags); 2827 } 2828 } 2829 2830 @Override 2831 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2832 // reader 2833 synchronized (mPackages) { 2834 final int N = mPermissionGroups.size(); 2835 ArrayList<PermissionGroupInfo> out 2836 = new ArrayList<PermissionGroupInfo>(N); 2837 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2838 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2839 } 2840 return out; 2841 } 2842 } 2843 2844 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2845 int userId) { 2846 if (!sUserManager.exists(userId)) return null; 2847 PackageSetting ps = mSettings.mPackages.get(packageName); 2848 if (ps != null) { 2849 if (ps.pkg == null) { 2850 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2851 flags, userId); 2852 if (pInfo != null) { 2853 return pInfo.applicationInfo; 2854 } 2855 return null; 2856 } 2857 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2858 ps.readUserState(userId), userId); 2859 } 2860 return null; 2861 } 2862 2863 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2864 int userId) { 2865 if (!sUserManager.exists(userId)) return null; 2866 PackageSetting ps = mSettings.mPackages.get(packageName); 2867 if (ps != null) { 2868 PackageParser.Package pkg = ps.pkg; 2869 if (pkg == null) { 2870 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2871 return null; 2872 } 2873 // Only data remains, so we aren't worried about code paths 2874 pkg = new PackageParser.Package(packageName); 2875 pkg.applicationInfo.packageName = packageName; 2876 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2877 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2878 pkg.applicationInfo.dataDir = Environment 2879 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2880 .getAbsolutePath(); 2881 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2882 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2883 } 2884 return generatePackageInfo(pkg, flags, userId); 2885 } 2886 return null; 2887 } 2888 2889 @Override 2890 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2891 if (!sUserManager.exists(userId)) return null; 2892 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2893 // writer 2894 synchronized (mPackages) { 2895 PackageParser.Package p = mPackages.get(packageName); 2896 if (DEBUG_PACKAGE_INFO) Log.v( 2897 TAG, "getApplicationInfo " + packageName 2898 + ": " + p); 2899 if (p != null) { 2900 PackageSetting ps = mSettings.mPackages.get(packageName); 2901 if (ps == null) return null; 2902 // Note: isEnabledLP() does not apply here - always return info 2903 return PackageParser.generateApplicationInfo( 2904 p, flags, ps.readUserState(userId), userId); 2905 } 2906 if ("android".equals(packageName)||"system".equals(packageName)) { 2907 return mAndroidApplication; 2908 } 2909 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2910 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2911 } 2912 } 2913 return null; 2914 } 2915 2916 @Override 2917 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2918 final IPackageDataObserver observer) { 2919 mContext.enforceCallingOrSelfPermission( 2920 android.Manifest.permission.CLEAR_APP_CACHE, null); 2921 // Queue up an async operation since clearing cache may take a little while. 2922 mHandler.post(new Runnable() { 2923 public void run() { 2924 mHandler.removeCallbacks(this); 2925 int retCode = -1; 2926 synchronized (mInstallLock) { 2927 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2928 if (retCode < 0) { 2929 Slog.w(TAG, "Couldn't clear application caches"); 2930 } 2931 } 2932 if (observer != null) { 2933 try { 2934 observer.onRemoveCompleted(null, (retCode >= 0)); 2935 } catch (RemoteException e) { 2936 Slog.w(TAG, "RemoveException when invoking call back"); 2937 } 2938 } 2939 } 2940 }); 2941 } 2942 2943 @Override 2944 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2945 final IntentSender pi) { 2946 mContext.enforceCallingOrSelfPermission( 2947 android.Manifest.permission.CLEAR_APP_CACHE, null); 2948 // Queue up an async operation since clearing cache may take a little while. 2949 mHandler.post(new Runnable() { 2950 public void run() { 2951 mHandler.removeCallbacks(this); 2952 int retCode = -1; 2953 synchronized (mInstallLock) { 2954 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2955 if (retCode < 0) { 2956 Slog.w(TAG, "Couldn't clear application caches"); 2957 } 2958 } 2959 if(pi != null) { 2960 try { 2961 // Callback via pending intent 2962 int code = (retCode >= 0) ? 1 : 0; 2963 pi.sendIntent(null, code, null, 2964 null, null); 2965 } catch (SendIntentException e1) { 2966 Slog.i(TAG, "Failed to send pending intent"); 2967 } 2968 } 2969 } 2970 }); 2971 } 2972 2973 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2974 synchronized (mInstallLock) { 2975 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2976 throw new IOException("Failed to free enough space"); 2977 } 2978 } 2979 } 2980 2981 @Override 2982 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2983 if (!sUserManager.exists(userId)) return null; 2984 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2985 synchronized (mPackages) { 2986 PackageParser.Activity a = mActivities.mActivities.get(component); 2987 2988 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2989 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2990 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2991 if (ps == null) return null; 2992 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2993 userId); 2994 } 2995 if (mResolveComponentName.equals(component)) { 2996 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2997 new PackageUserState(), userId); 2998 } 2999 } 3000 return null; 3001 } 3002 3003 @Override 3004 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3005 String resolvedType) { 3006 synchronized (mPackages) { 3007 if (component.equals(mResolveComponentName)) { 3008 // The resolver supports EVERYTHING! 3009 return true; 3010 } 3011 PackageParser.Activity a = mActivities.mActivities.get(component); 3012 if (a == null) { 3013 return false; 3014 } 3015 for (int i=0; i<a.intents.size(); i++) { 3016 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3017 intent.getData(), intent.getCategories(), TAG) >= 0) { 3018 return true; 3019 } 3020 } 3021 return false; 3022 } 3023 } 3024 3025 @Override 3026 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3027 if (!sUserManager.exists(userId)) return null; 3028 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3029 synchronized (mPackages) { 3030 PackageParser.Activity a = mReceivers.mActivities.get(component); 3031 if (DEBUG_PACKAGE_INFO) Log.v( 3032 TAG, "getReceiverInfo " + component + ": " + a); 3033 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3034 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3035 if (ps == null) return null; 3036 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3037 userId); 3038 } 3039 } 3040 return null; 3041 } 3042 3043 @Override 3044 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3045 if (!sUserManager.exists(userId)) return null; 3046 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3047 synchronized (mPackages) { 3048 PackageParser.Service s = mServices.mServices.get(component); 3049 if (DEBUG_PACKAGE_INFO) Log.v( 3050 TAG, "getServiceInfo " + component + ": " + s); 3051 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3052 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3053 if (ps == null) return null; 3054 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3055 userId); 3056 } 3057 } 3058 return null; 3059 } 3060 3061 @Override 3062 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3063 if (!sUserManager.exists(userId)) return null; 3064 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3065 synchronized (mPackages) { 3066 PackageParser.Provider p = mProviders.mProviders.get(component); 3067 if (DEBUG_PACKAGE_INFO) Log.v( 3068 TAG, "getProviderInfo " + component + ": " + p); 3069 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3070 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3071 if (ps == null) return null; 3072 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3073 userId); 3074 } 3075 } 3076 return null; 3077 } 3078 3079 @Override 3080 public String[] getSystemSharedLibraryNames() { 3081 Set<String> libSet; 3082 synchronized (mPackages) { 3083 libSet = mSharedLibraries.keySet(); 3084 int size = libSet.size(); 3085 if (size > 0) { 3086 String[] libs = new String[size]; 3087 libSet.toArray(libs); 3088 return libs; 3089 } 3090 } 3091 return null; 3092 } 3093 3094 /** 3095 * @hide 3096 */ 3097 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3098 synchronized (mPackages) { 3099 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3100 if (lib != null && lib.apk != null) { 3101 return mPackages.get(lib.apk); 3102 } 3103 } 3104 return null; 3105 } 3106 3107 @Override 3108 public FeatureInfo[] getSystemAvailableFeatures() { 3109 Collection<FeatureInfo> featSet; 3110 synchronized (mPackages) { 3111 featSet = mAvailableFeatures.values(); 3112 int size = featSet.size(); 3113 if (size > 0) { 3114 FeatureInfo[] features = new FeatureInfo[size+1]; 3115 featSet.toArray(features); 3116 FeatureInfo fi = new FeatureInfo(); 3117 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3118 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3119 features[size] = fi; 3120 return features; 3121 } 3122 } 3123 return null; 3124 } 3125 3126 @Override 3127 public boolean hasSystemFeature(String name) { 3128 synchronized (mPackages) { 3129 return mAvailableFeatures.containsKey(name); 3130 } 3131 } 3132 3133 private void checkValidCaller(int uid, int userId) { 3134 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3135 return; 3136 3137 throw new SecurityException("Caller uid=" + uid 3138 + " is not privileged to communicate with user=" + userId); 3139 } 3140 3141 @Override 3142 public int checkPermission(String permName, String pkgName, int userId) { 3143 if (!sUserManager.exists(userId)) { 3144 return PackageManager.PERMISSION_DENIED; 3145 } 3146 3147 synchronized (mPackages) { 3148 final PackageParser.Package p = mPackages.get(pkgName); 3149 if (p != null && p.mExtras != null) { 3150 final PackageSetting ps = (PackageSetting) p.mExtras; 3151 final PermissionsState permissionsState = ps.getPermissionsState(); 3152 if (permissionsState.hasPermission(permName, userId)) { 3153 return PackageManager.PERMISSION_GRANTED; 3154 } 3155 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3156 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3157 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3158 return PackageManager.PERMISSION_GRANTED; 3159 } 3160 } 3161 } 3162 3163 return PackageManager.PERMISSION_DENIED; 3164 } 3165 3166 @Override 3167 public int checkUidPermission(String permName, int uid) { 3168 final int userId = UserHandle.getUserId(uid); 3169 3170 if (!sUserManager.exists(userId)) { 3171 return PackageManager.PERMISSION_DENIED; 3172 } 3173 3174 synchronized (mPackages) { 3175 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3176 if (obj != null) { 3177 final SettingBase ps = (SettingBase) obj; 3178 final PermissionsState permissionsState = ps.getPermissionsState(); 3179 if (permissionsState.hasPermission(permName, userId)) { 3180 return PackageManager.PERMISSION_GRANTED; 3181 } 3182 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3183 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3184 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3185 return PackageManager.PERMISSION_GRANTED; 3186 } 3187 } else { 3188 ArraySet<String> perms = mSystemPermissions.get(uid); 3189 if (perms != null) { 3190 if (perms.contains(permName)) { 3191 return PackageManager.PERMISSION_GRANTED; 3192 } 3193 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3194 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3195 return PackageManager.PERMISSION_GRANTED; 3196 } 3197 } 3198 } 3199 } 3200 3201 return PackageManager.PERMISSION_DENIED; 3202 } 3203 3204 @Override 3205 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3206 if (UserHandle.getCallingUserId() != userId) { 3207 mContext.enforceCallingPermission( 3208 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3209 "isPermissionRevokedByPolicy for user " + userId); 3210 } 3211 3212 if (checkPermission(permission, packageName, userId) 3213 == PackageManager.PERMISSION_GRANTED) { 3214 return false; 3215 } 3216 3217 final long identity = Binder.clearCallingIdentity(); 3218 try { 3219 final int flags = getPermissionFlags(permission, packageName, userId); 3220 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3221 } finally { 3222 Binder.restoreCallingIdentity(identity); 3223 } 3224 } 3225 3226 @Override 3227 public String getPermissionControllerPackageName() { 3228 synchronized (mPackages) { 3229 return mRequiredInstallerPackage; 3230 } 3231 } 3232 3233 /** 3234 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3235 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3236 * @param checkShell TODO(yamasani): 3237 * @param message the message to log on security exception 3238 */ 3239 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3240 boolean checkShell, String message) { 3241 if (userId < 0) { 3242 throw new IllegalArgumentException("Invalid userId " + userId); 3243 } 3244 if (checkShell) { 3245 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3246 } 3247 if (userId == UserHandle.getUserId(callingUid)) return; 3248 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3249 if (requireFullPermission) { 3250 mContext.enforceCallingOrSelfPermission( 3251 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3252 } else { 3253 try { 3254 mContext.enforceCallingOrSelfPermission( 3255 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3256 } catch (SecurityException se) { 3257 mContext.enforceCallingOrSelfPermission( 3258 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3259 } 3260 } 3261 } 3262 } 3263 3264 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3265 if (callingUid == Process.SHELL_UID) { 3266 if (userHandle >= 0 3267 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3268 throw new SecurityException("Shell does not have permission to access user " 3269 + userHandle); 3270 } else if (userHandle < 0) { 3271 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3272 + Debug.getCallers(3)); 3273 } 3274 } 3275 } 3276 3277 private BasePermission findPermissionTreeLP(String permName) { 3278 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3279 if (permName.startsWith(bp.name) && 3280 permName.length() > bp.name.length() && 3281 permName.charAt(bp.name.length()) == '.') { 3282 return bp; 3283 } 3284 } 3285 return null; 3286 } 3287 3288 private BasePermission checkPermissionTreeLP(String permName) { 3289 if (permName != null) { 3290 BasePermission bp = findPermissionTreeLP(permName); 3291 if (bp != null) { 3292 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3293 return bp; 3294 } 3295 throw new SecurityException("Calling uid " 3296 + Binder.getCallingUid() 3297 + " is not allowed to add to permission tree " 3298 + bp.name + " owned by uid " + bp.uid); 3299 } 3300 } 3301 throw new SecurityException("No permission tree found for " + permName); 3302 } 3303 3304 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3305 if (s1 == null) { 3306 return s2 == null; 3307 } 3308 if (s2 == null) { 3309 return false; 3310 } 3311 if (s1.getClass() != s2.getClass()) { 3312 return false; 3313 } 3314 return s1.equals(s2); 3315 } 3316 3317 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3318 if (pi1.icon != pi2.icon) return false; 3319 if (pi1.logo != pi2.logo) return false; 3320 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3321 if (!compareStrings(pi1.name, pi2.name)) return false; 3322 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3323 // We'll take care of setting this one. 3324 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3325 // These are not currently stored in settings. 3326 //if (!compareStrings(pi1.group, pi2.group)) return false; 3327 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3328 //if (pi1.labelRes != pi2.labelRes) return false; 3329 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3330 return true; 3331 } 3332 3333 int permissionInfoFootprint(PermissionInfo info) { 3334 int size = info.name.length(); 3335 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3336 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3337 return size; 3338 } 3339 3340 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3341 int size = 0; 3342 for (BasePermission perm : mSettings.mPermissions.values()) { 3343 if (perm.uid == tree.uid) { 3344 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3345 } 3346 } 3347 return size; 3348 } 3349 3350 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3351 // We calculate the max size of permissions defined by this uid and throw 3352 // if that plus the size of 'info' would exceed our stated maximum. 3353 if (tree.uid != Process.SYSTEM_UID) { 3354 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3355 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3356 throw new SecurityException("Permission tree size cap exceeded"); 3357 } 3358 } 3359 } 3360 3361 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3362 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3363 throw new SecurityException("Label must be specified in permission"); 3364 } 3365 BasePermission tree = checkPermissionTreeLP(info.name); 3366 BasePermission bp = mSettings.mPermissions.get(info.name); 3367 boolean added = bp == null; 3368 boolean changed = true; 3369 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3370 if (added) { 3371 enforcePermissionCapLocked(info, tree); 3372 bp = new BasePermission(info.name, tree.sourcePackage, 3373 BasePermission.TYPE_DYNAMIC); 3374 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3375 throw new SecurityException( 3376 "Not allowed to modify non-dynamic permission " 3377 + info.name); 3378 } else { 3379 if (bp.protectionLevel == fixedLevel 3380 && bp.perm.owner.equals(tree.perm.owner) 3381 && bp.uid == tree.uid 3382 && comparePermissionInfos(bp.perm.info, info)) { 3383 changed = false; 3384 } 3385 } 3386 bp.protectionLevel = fixedLevel; 3387 info = new PermissionInfo(info); 3388 info.protectionLevel = fixedLevel; 3389 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3390 bp.perm.info.packageName = tree.perm.info.packageName; 3391 bp.uid = tree.uid; 3392 if (added) { 3393 mSettings.mPermissions.put(info.name, bp); 3394 } 3395 if (changed) { 3396 if (!async) { 3397 mSettings.writeLPr(); 3398 } else { 3399 scheduleWriteSettingsLocked(); 3400 } 3401 } 3402 return added; 3403 } 3404 3405 @Override 3406 public boolean addPermission(PermissionInfo info) { 3407 synchronized (mPackages) { 3408 return addPermissionLocked(info, false); 3409 } 3410 } 3411 3412 @Override 3413 public boolean addPermissionAsync(PermissionInfo info) { 3414 synchronized (mPackages) { 3415 return addPermissionLocked(info, true); 3416 } 3417 } 3418 3419 @Override 3420 public void removePermission(String name) { 3421 synchronized (mPackages) { 3422 checkPermissionTreeLP(name); 3423 BasePermission bp = mSettings.mPermissions.get(name); 3424 if (bp != null) { 3425 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3426 throw new SecurityException( 3427 "Not allowed to modify non-dynamic permission " 3428 + name); 3429 } 3430 mSettings.mPermissions.remove(name); 3431 mSettings.writeLPr(); 3432 } 3433 } 3434 } 3435 3436 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3437 BasePermission bp) { 3438 int index = pkg.requestedPermissions.indexOf(bp.name); 3439 if (index == -1) { 3440 throw new SecurityException("Package " + pkg.packageName 3441 + " has not requested permission " + bp.name); 3442 } 3443 if (!bp.isRuntime() && !bp.isDevelopment()) { 3444 throw new SecurityException("Permission " + bp.name 3445 + " is not a changeable permission type"); 3446 } 3447 } 3448 3449 @Override 3450 public void grantRuntimePermission(String packageName, String name, final int userId) { 3451 if (!sUserManager.exists(userId)) { 3452 Log.e(TAG, "No such user:" + userId); 3453 return; 3454 } 3455 3456 mContext.enforceCallingOrSelfPermission( 3457 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3458 "grantRuntimePermission"); 3459 3460 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3461 "grantRuntimePermission"); 3462 3463 final int uid; 3464 final SettingBase sb; 3465 3466 synchronized (mPackages) { 3467 final PackageParser.Package pkg = mPackages.get(packageName); 3468 if (pkg == null) { 3469 throw new IllegalArgumentException("Unknown package: " + packageName); 3470 } 3471 3472 final BasePermission bp = mSettings.mPermissions.get(name); 3473 if (bp == null) { 3474 throw new IllegalArgumentException("Unknown permission: " + name); 3475 } 3476 3477 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3478 3479 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3480 sb = (SettingBase) pkg.mExtras; 3481 if (sb == null) { 3482 throw new IllegalArgumentException("Unknown package: " + packageName); 3483 } 3484 3485 final PermissionsState permissionsState = sb.getPermissionsState(); 3486 3487 final int flags = permissionsState.getPermissionFlags(name, userId); 3488 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3489 throw new SecurityException("Cannot grant system fixed permission: " 3490 + name + " for package: " + packageName); 3491 } 3492 3493 if (bp.isDevelopment()) { 3494 // Development permissions must be handled specially, since they are not 3495 // normal runtime permissions. For now they apply to all users. 3496 if (permissionsState.grantInstallPermission(bp) != 3497 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3498 scheduleWriteSettingsLocked(); 3499 } 3500 return; 3501 } 3502 3503 final int result = permissionsState.grantRuntimePermission(bp, userId); 3504 switch (result) { 3505 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3506 return; 3507 } 3508 3509 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3510 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3511 mHandler.post(new Runnable() { 3512 @Override 3513 public void run() { 3514 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3515 } 3516 }); 3517 } break; 3518 } 3519 3520 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3521 3522 // Not critical if that is lost - app has to request again. 3523 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3524 } 3525 3526 // Only need to do this if user is initialized. Otherwise it's a new user 3527 // and there are no processes running as the user yet and there's no need 3528 // to make an expensive call to remount processes for the changed permissions. 3529 if (READ_EXTERNAL_STORAGE.equals(name) 3530 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3531 final long token = Binder.clearCallingIdentity(); 3532 try { 3533 if (sUserManager.isInitialized(userId)) { 3534 MountServiceInternal mountServiceInternal = LocalServices.getService( 3535 MountServiceInternal.class); 3536 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3537 } 3538 } finally { 3539 Binder.restoreCallingIdentity(token); 3540 } 3541 } 3542 } 3543 3544 @Override 3545 public void revokeRuntimePermission(String packageName, String name, int userId) { 3546 if (!sUserManager.exists(userId)) { 3547 Log.e(TAG, "No such user:" + userId); 3548 return; 3549 } 3550 3551 mContext.enforceCallingOrSelfPermission( 3552 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3553 "revokeRuntimePermission"); 3554 3555 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3556 "revokeRuntimePermission"); 3557 3558 final int appId; 3559 3560 synchronized (mPackages) { 3561 final PackageParser.Package pkg = mPackages.get(packageName); 3562 if (pkg == null) { 3563 throw new IllegalArgumentException("Unknown package: " + packageName); 3564 } 3565 3566 final BasePermission bp = mSettings.mPermissions.get(name); 3567 if (bp == null) { 3568 throw new IllegalArgumentException("Unknown permission: " + name); 3569 } 3570 3571 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3572 3573 SettingBase sb = (SettingBase) pkg.mExtras; 3574 if (sb == null) { 3575 throw new IllegalArgumentException("Unknown package: " + packageName); 3576 } 3577 3578 final PermissionsState permissionsState = sb.getPermissionsState(); 3579 3580 final int flags = permissionsState.getPermissionFlags(name, userId); 3581 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3582 throw new SecurityException("Cannot revoke system fixed permission: " 3583 + name + " for package: " + packageName); 3584 } 3585 3586 if (bp.isDevelopment()) { 3587 // Development permissions must be handled specially, since they are not 3588 // normal runtime permissions. For now they apply to all users. 3589 if (permissionsState.revokeInstallPermission(bp) != 3590 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3591 scheduleWriteSettingsLocked(); 3592 } 3593 return; 3594 } 3595 3596 if (permissionsState.revokeRuntimePermission(bp, userId) == 3597 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3598 return; 3599 } 3600 3601 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3602 3603 // Critical, after this call app should never have the permission. 3604 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3605 3606 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3607 } 3608 3609 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3610 } 3611 3612 @Override 3613 public void resetRuntimePermissions() { 3614 mContext.enforceCallingOrSelfPermission( 3615 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3616 "revokeRuntimePermission"); 3617 3618 int callingUid = Binder.getCallingUid(); 3619 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3620 mContext.enforceCallingOrSelfPermission( 3621 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3622 "resetRuntimePermissions"); 3623 } 3624 3625 synchronized (mPackages) { 3626 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3627 for (int userId : UserManagerService.getInstance().getUserIds()) { 3628 final int packageCount = mPackages.size(); 3629 for (int i = 0; i < packageCount; i++) { 3630 PackageParser.Package pkg = mPackages.valueAt(i); 3631 if (!(pkg.mExtras instanceof PackageSetting)) { 3632 continue; 3633 } 3634 PackageSetting ps = (PackageSetting) pkg.mExtras; 3635 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3636 } 3637 } 3638 } 3639 } 3640 3641 @Override 3642 public int getPermissionFlags(String name, String packageName, int userId) { 3643 if (!sUserManager.exists(userId)) { 3644 return 0; 3645 } 3646 3647 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3648 3649 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3650 "getPermissionFlags"); 3651 3652 synchronized (mPackages) { 3653 final PackageParser.Package pkg = mPackages.get(packageName); 3654 if (pkg == null) { 3655 throw new IllegalArgumentException("Unknown package: " + packageName); 3656 } 3657 3658 final BasePermission bp = mSettings.mPermissions.get(name); 3659 if (bp == null) { 3660 throw new IllegalArgumentException("Unknown permission: " + name); 3661 } 3662 3663 SettingBase sb = (SettingBase) pkg.mExtras; 3664 if (sb == null) { 3665 throw new IllegalArgumentException("Unknown package: " + packageName); 3666 } 3667 3668 PermissionsState permissionsState = sb.getPermissionsState(); 3669 return permissionsState.getPermissionFlags(name, userId); 3670 } 3671 } 3672 3673 @Override 3674 public void updatePermissionFlags(String name, String packageName, int flagMask, 3675 int flagValues, int userId) { 3676 if (!sUserManager.exists(userId)) { 3677 return; 3678 } 3679 3680 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3681 3682 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3683 "updatePermissionFlags"); 3684 3685 // Only the system can change these flags and nothing else. 3686 if (getCallingUid() != Process.SYSTEM_UID) { 3687 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3688 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3689 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3690 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3691 } 3692 3693 synchronized (mPackages) { 3694 final PackageParser.Package pkg = mPackages.get(packageName); 3695 if (pkg == null) { 3696 throw new IllegalArgumentException("Unknown package: " + packageName); 3697 } 3698 3699 final BasePermission bp = mSettings.mPermissions.get(name); 3700 if (bp == null) { 3701 throw new IllegalArgumentException("Unknown permission: " + name); 3702 } 3703 3704 SettingBase sb = (SettingBase) pkg.mExtras; 3705 if (sb == null) { 3706 throw new IllegalArgumentException("Unknown package: " + packageName); 3707 } 3708 3709 PermissionsState permissionsState = sb.getPermissionsState(); 3710 3711 // Only the package manager can change flags for system component permissions. 3712 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3713 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3714 return; 3715 } 3716 3717 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3718 3719 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3720 // Install and runtime permissions are stored in different places, 3721 // so figure out what permission changed and persist the change. 3722 if (permissionsState.getInstallPermissionState(name) != null) { 3723 scheduleWriteSettingsLocked(); 3724 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3725 || hadState) { 3726 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3727 } 3728 } 3729 } 3730 } 3731 3732 /** 3733 * Update the permission flags for all packages and runtime permissions of a user in order 3734 * to allow device or profile owner to remove POLICY_FIXED. 3735 */ 3736 @Override 3737 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3738 if (!sUserManager.exists(userId)) { 3739 return; 3740 } 3741 3742 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3743 3744 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3745 "updatePermissionFlagsForAllApps"); 3746 3747 // Only the system can change system fixed flags. 3748 if (getCallingUid() != Process.SYSTEM_UID) { 3749 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3750 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3751 } 3752 3753 synchronized (mPackages) { 3754 boolean changed = false; 3755 final int packageCount = mPackages.size(); 3756 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3757 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3758 SettingBase sb = (SettingBase) pkg.mExtras; 3759 if (sb == null) { 3760 continue; 3761 } 3762 PermissionsState permissionsState = sb.getPermissionsState(); 3763 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3764 userId, flagMask, flagValues); 3765 } 3766 if (changed) { 3767 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3768 } 3769 } 3770 } 3771 3772 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3773 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3774 != PackageManager.PERMISSION_GRANTED 3775 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3776 != PackageManager.PERMISSION_GRANTED) { 3777 throw new SecurityException(message + " requires " 3778 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3779 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3780 } 3781 } 3782 3783 @Override 3784 public boolean shouldShowRequestPermissionRationale(String permissionName, 3785 String packageName, int userId) { 3786 if (UserHandle.getCallingUserId() != userId) { 3787 mContext.enforceCallingPermission( 3788 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3789 "canShowRequestPermissionRationale for user " + userId); 3790 } 3791 3792 final int uid = getPackageUid(packageName, userId); 3793 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3794 return false; 3795 } 3796 3797 if (checkPermission(permissionName, packageName, userId) 3798 == PackageManager.PERMISSION_GRANTED) { 3799 return false; 3800 } 3801 3802 final int flags; 3803 3804 final long identity = Binder.clearCallingIdentity(); 3805 try { 3806 flags = getPermissionFlags(permissionName, 3807 packageName, userId); 3808 } finally { 3809 Binder.restoreCallingIdentity(identity); 3810 } 3811 3812 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3813 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3814 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3815 3816 if ((flags & fixedFlags) != 0) { 3817 return false; 3818 } 3819 3820 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3821 } 3822 3823 @Override 3824 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3825 mContext.enforceCallingOrSelfPermission( 3826 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3827 "addOnPermissionsChangeListener"); 3828 3829 synchronized (mPackages) { 3830 mOnPermissionChangeListeners.addListenerLocked(listener); 3831 } 3832 } 3833 3834 @Override 3835 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3836 synchronized (mPackages) { 3837 mOnPermissionChangeListeners.removeListenerLocked(listener); 3838 } 3839 } 3840 3841 @Override 3842 public boolean isProtectedBroadcast(String actionName) { 3843 synchronized (mPackages) { 3844 return mProtectedBroadcasts.contains(actionName); 3845 } 3846 } 3847 3848 @Override 3849 public int checkSignatures(String pkg1, String pkg2) { 3850 synchronized (mPackages) { 3851 final PackageParser.Package p1 = mPackages.get(pkg1); 3852 final PackageParser.Package p2 = mPackages.get(pkg2); 3853 if (p1 == null || p1.mExtras == null 3854 || p2 == null || p2.mExtras == null) { 3855 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3856 } 3857 return compareSignatures(p1.mSignatures, p2.mSignatures); 3858 } 3859 } 3860 3861 @Override 3862 public int checkUidSignatures(int uid1, int uid2) { 3863 // Map to base uids. 3864 uid1 = UserHandle.getAppId(uid1); 3865 uid2 = UserHandle.getAppId(uid2); 3866 // reader 3867 synchronized (mPackages) { 3868 Signature[] s1; 3869 Signature[] s2; 3870 Object obj = mSettings.getUserIdLPr(uid1); 3871 if (obj != null) { 3872 if (obj instanceof SharedUserSetting) { 3873 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3874 } else if (obj instanceof PackageSetting) { 3875 s1 = ((PackageSetting)obj).signatures.mSignatures; 3876 } else { 3877 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3878 } 3879 } else { 3880 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3881 } 3882 obj = mSettings.getUserIdLPr(uid2); 3883 if (obj != null) { 3884 if (obj instanceof SharedUserSetting) { 3885 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3886 } else if (obj instanceof PackageSetting) { 3887 s2 = ((PackageSetting)obj).signatures.mSignatures; 3888 } else { 3889 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3890 } 3891 } else { 3892 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3893 } 3894 return compareSignatures(s1, s2); 3895 } 3896 } 3897 3898 private void killUid(int appId, int userId, String reason) { 3899 final long identity = Binder.clearCallingIdentity(); 3900 try { 3901 IActivityManager am = ActivityManagerNative.getDefault(); 3902 if (am != null) { 3903 try { 3904 am.killUid(appId, userId, reason); 3905 } catch (RemoteException e) { 3906 /* ignore - same process */ 3907 } 3908 } 3909 } finally { 3910 Binder.restoreCallingIdentity(identity); 3911 } 3912 } 3913 3914 /** 3915 * Compares two sets of signatures. Returns: 3916 * <br /> 3917 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3918 * <br /> 3919 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3920 * <br /> 3921 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3922 * <br /> 3923 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3924 * <br /> 3925 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3926 */ 3927 static int compareSignatures(Signature[] s1, Signature[] s2) { 3928 if (s1 == null) { 3929 return s2 == null 3930 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3931 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3932 } 3933 3934 if (s2 == null) { 3935 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3936 } 3937 3938 if (s1.length != s2.length) { 3939 return PackageManager.SIGNATURE_NO_MATCH; 3940 } 3941 3942 // Since both signature sets are of size 1, we can compare without HashSets. 3943 if (s1.length == 1) { 3944 return s1[0].equals(s2[0]) ? 3945 PackageManager.SIGNATURE_MATCH : 3946 PackageManager.SIGNATURE_NO_MATCH; 3947 } 3948 3949 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3950 for (Signature sig : s1) { 3951 set1.add(sig); 3952 } 3953 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3954 for (Signature sig : s2) { 3955 set2.add(sig); 3956 } 3957 // Make sure s2 contains all signatures in s1. 3958 if (set1.equals(set2)) { 3959 return PackageManager.SIGNATURE_MATCH; 3960 } 3961 return PackageManager.SIGNATURE_NO_MATCH; 3962 } 3963 3964 /** 3965 * If the database version for this type of package (internal storage or 3966 * external storage) is less than the version where package signatures 3967 * were updated, return true. 3968 */ 3969 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3970 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3971 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3972 } 3973 3974 /** 3975 * Used for backward compatibility to make sure any packages with 3976 * certificate chains get upgraded to the new style. {@code existingSigs} 3977 * will be in the old format (since they were stored on disk from before the 3978 * system upgrade) and {@code scannedSigs} will be in the newer format. 3979 */ 3980 private int compareSignaturesCompat(PackageSignatures existingSigs, 3981 PackageParser.Package scannedPkg) { 3982 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3983 return PackageManager.SIGNATURE_NO_MATCH; 3984 } 3985 3986 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3987 for (Signature sig : existingSigs.mSignatures) { 3988 existingSet.add(sig); 3989 } 3990 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3991 for (Signature sig : scannedPkg.mSignatures) { 3992 try { 3993 Signature[] chainSignatures = sig.getChainSignatures(); 3994 for (Signature chainSig : chainSignatures) { 3995 scannedCompatSet.add(chainSig); 3996 } 3997 } catch (CertificateEncodingException e) { 3998 scannedCompatSet.add(sig); 3999 } 4000 } 4001 /* 4002 * Make sure the expanded scanned set contains all signatures in the 4003 * existing one. 4004 */ 4005 if (scannedCompatSet.equals(existingSet)) { 4006 // Migrate the old signatures to the new scheme. 4007 existingSigs.assignSignatures(scannedPkg.mSignatures); 4008 // The new KeySets will be re-added later in the scanning process. 4009 synchronized (mPackages) { 4010 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4011 } 4012 return PackageManager.SIGNATURE_MATCH; 4013 } 4014 return PackageManager.SIGNATURE_NO_MATCH; 4015 } 4016 4017 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4018 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4019 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4020 } 4021 4022 private int compareSignaturesRecover(PackageSignatures existingSigs, 4023 PackageParser.Package scannedPkg) { 4024 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4025 return PackageManager.SIGNATURE_NO_MATCH; 4026 } 4027 4028 String msg = null; 4029 try { 4030 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4031 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4032 + scannedPkg.packageName); 4033 return PackageManager.SIGNATURE_MATCH; 4034 } 4035 } catch (CertificateException e) { 4036 msg = e.getMessage(); 4037 } 4038 4039 logCriticalInfo(Log.INFO, 4040 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4041 return PackageManager.SIGNATURE_NO_MATCH; 4042 } 4043 4044 @Override 4045 public String[] getPackagesForUid(int uid) { 4046 uid = UserHandle.getAppId(uid); 4047 // reader 4048 synchronized (mPackages) { 4049 Object obj = mSettings.getUserIdLPr(uid); 4050 if (obj instanceof SharedUserSetting) { 4051 final SharedUserSetting sus = (SharedUserSetting) obj; 4052 final int N = sus.packages.size(); 4053 final String[] res = new String[N]; 4054 final Iterator<PackageSetting> it = sus.packages.iterator(); 4055 int i = 0; 4056 while (it.hasNext()) { 4057 res[i++] = it.next().name; 4058 } 4059 return res; 4060 } else if (obj instanceof PackageSetting) { 4061 final PackageSetting ps = (PackageSetting) obj; 4062 return new String[] { ps.name }; 4063 } 4064 } 4065 return null; 4066 } 4067 4068 @Override 4069 public String getNameForUid(int uid) { 4070 // reader 4071 synchronized (mPackages) { 4072 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4073 if (obj instanceof SharedUserSetting) { 4074 final SharedUserSetting sus = (SharedUserSetting) obj; 4075 return sus.name + ":" + sus.userId; 4076 } else if (obj instanceof PackageSetting) { 4077 final PackageSetting ps = (PackageSetting) obj; 4078 return ps.name; 4079 } 4080 } 4081 return null; 4082 } 4083 4084 @Override 4085 public int getUidForSharedUser(String sharedUserName) { 4086 if(sharedUserName == null) { 4087 return -1; 4088 } 4089 // reader 4090 synchronized (mPackages) { 4091 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4092 if (suid == null) { 4093 return -1; 4094 } 4095 return suid.userId; 4096 } 4097 } 4098 4099 @Override 4100 public int getFlagsForUid(int uid) { 4101 synchronized (mPackages) { 4102 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4103 if (obj instanceof SharedUserSetting) { 4104 final SharedUserSetting sus = (SharedUserSetting) obj; 4105 return sus.pkgFlags; 4106 } else if (obj instanceof PackageSetting) { 4107 final PackageSetting ps = (PackageSetting) obj; 4108 return ps.pkgFlags; 4109 } 4110 } 4111 return 0; 4112 } 4113 4114 @Override 4115 public int getPrivateFlagsForUid(int uid) { 4116 synchronized (mPackages) { 4117 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4118 if (obj instanceof SharedUserSetting) { 4119 final SharedUserSetting sus = (SharedUserSetting) obj; 4120 return sus.pkgPrivateFlags; 4121 } else if (obj instanceof PackageSetting) { 4122 final PackageSetting ps = (PackageSetting) obj; 4123 return ps.pkgPrivateFlags; 4124 } 4125 } 4126 return 0; 4127 } 4128 4129 @Override 4130 public boolean isUidPrivileged(int uid) { 4131 uid = UserHandle.getAppId(uid); 4132 // reader 4133 synchronized (mPackages) { 4134 Object obj = mSettings.getUserIdLPr(uid); 4135 if (obj instanceof SharedUserSetting) { 4136 final SharedUserSetting sus = (SharedUserSetting) obj; 4137 final Iterator<PackageSetting> it = sus.packages.iterator(); 4138 while (it.hasNext()) { 4139 if (it.next().isPrivileged()) { 4140 return true; 4141 } 4142 } 4143 } else if (obj instanceof PackageSetting) { 4144 final PackageSetting ps = (PackageSetting) obj; 4145 return ps.isPrivileged(); 4146 } 4147 } 4148 return false; 4149 } 4150 4151 @Override 4152 public String[] getAppOpPermissionPackages(String permissionName) { 4153 synchronized (mPackages) { 4154 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4155 if (pkgs == null) { 4156 return null; 4157 } 4158 return pkgs.toArray(new String[pkgs.size()]); 4159 } 4160 } 4161 4162 @Override 4163 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4164 int flags, int userId) { 4165 if (!sUserManager.exists(userId)) return null; 4166 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4167 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4168 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4169 } 4170 4171 @Override 4172 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4173 IntentFilter filter, int match, ComponentName activity) { 4174 final int userId = UserHandle.getCallingUserId(); 4175 if (DEBUG_PREFERRED) { 4176 Log.v(TAG, "setLastChosenActivity intent=" + intent 4177 + " resolvedType=" + resolvedType 4178 + " flags=" + flags 4179 + " filter=" + filter 4180 + " match=" + match 4181 + " activity=" + activity); 4182 filter.dump(new PrintStreamPrinter(System.out), " "); 4183 } 4184 intent.setComponent(null); 4185 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4186 // Find any earlier preferred or last chosen entries and nuke them 4187 findPreferredActivity(intent, resolvedType, 4188 flags, query, 0, false, true, false, userId); 4189 // Add the new activity as the last chosen for this filter 4190 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4191 "Setting last chosen"); 4192 } 4193 4194 @Override 4195 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4196 final int userId = UserHandle.getCallingUserId(); 4197 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4198 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4199 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4200 false, false, false, userId); 4201 } 4202 4203 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4204 int flags, List<ResolveInfo> query, int userId) { 4205 if (query != null) { 4206 final int N = query.size(); 4207 if (N == 1) { 4208 return query.get(0); 4209 } else if (N > 1) { 4210 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4211 // If there is more than one activity with the same priority, 4212 // then let the user decide between them. 4213 ResolveInfo r0 = query.get(0); 4214 ResolveInfo r1 = query.get(1); 4215 if (DEBUG_INTENT_MATCHING || debug) { 4216 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4217 + r1.activityInfo.name + "=" + r1.priority); 4218 } 4219 // If the first activity has a higher priority, or a different 4220 // default, then it is always desireable to pick it. 4221 if (r0.priority != r1.priority 4222 || r0.preferredOrder != r1.preferredOrder 4223 || r0.isDefault != r1.isDefault) { 4224 return query.get(0); 4225 } 4226 // If we have saved a preference for a preferred activity for 4227 // this Intent, use that. 4228 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4229 flags, query, r0.priority, true, false, debug, userId); 4230 if (ri != null) { 4231 return ri; 4232 } 4233 ri = new ResolveInfo(mResolveInfo); 4234 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4235 ri.activityInfo.applicationInfo = new ApplicationInfo( 4236 ri.activityInfo.applicationInfo); 4237 if (userId != 0) { 4238 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4239 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4240 } 4241 // Make sure that the resolver is displayable in car mode 4242 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4243 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4244 return ri; 4245 } 4246 } 4247 return null; 4248 } 4249 4250 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4251 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4252 final int N = query.size(); 4253 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4254 .get(userId); 4255 // Get the list of persistent preferred activities that handle the intent 4256 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4257 List<PersistentPreferredActivity> pprefs = ppir != null 4258 ? ppir.queryIntent(intent, resolvedType, 4259 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4260 : null; 4261 if (pprefs != null && pprefs.size() > 0) { 4262 final int M = pprefs.size(); 4263 for (int i=0; i<M; i++) { 4264 final PersistentPreferredActivity ppa = pprefs.get(i); 4265 if (DEBUG_PREFERRED || debug) { 4266 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4267 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4268 + "\n component=" + ppa.mComponent); 4269 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4270 } 4271 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4272 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4273 if (DEBUG_PREFERRED || debug) { 4274 Slog.v(TAG, "Found persistent preferred activity:"); 4275 if (ai != null) { 4276 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4277 } else { 4278 Slog.v(TAG, " null"); 4279 } 4280 } 4281 if (ai == null) { 4282 // This previously registered persistent preferred activity 4283 // component is no longer known. Ignore it and do NOT remove it. 4284 continue; 4285 } 4286 for (int j=0; j<N; j++) { 4287 final ResolveInfo ri = query.get(j); 4288 if (!ri.activityInfo.applicationInfo.packageName 4289 .equals(ai.applicationInfo.packageName)) { 4290 continue; 4291 } 4292 if (!ri.activityInfo.name.equals(ai.name)) { 4293 continue; 4294 } 4295 // Found a persistent preference that can handle the intent. 4296 if (DEBUG_PREFERRED || debug) { 4297 Slog.v(TAG, "Returning persistent preferred activity: " + 4298 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4299 } 4300 return ri; 4301 } 4302 } 4303 } 4304 return null; 4305 } 4306 4307 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4308 List<ResolveInfo> query, int priority, boolean always, 4309 boolean removeMatches, boolean debug, int userId) { 4310 if (!sUserManager.exists(userId)) return null; 4311 // writer 4312 synchronized (mPackages) { 4313 if (intent.getSelector() != null) { 4314 intent = intent.getSelector(); 4315 } 4316 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4317 4318 // Try to find a matching persistent preferred activity. 4319 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4320 debug, userId); 4321 4322 // If a persistent preferred activity matched, use it. 4323 if (pri != null) { 4324 return pri; 4325 } 4326 4327 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4328 // Get the list of preferred activities that handle the intent 4329 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4330 List<PreferredActivity> prefs = pir != null 4331 ? pir.queryIntent(intent, resolvedType, 4332 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4333 : null; 4334 if (prefs != null && prefs.size() > 0) { 4335 boolean changed = false; 4336 try { 4337 // First figure out how good the original match set is. 4338 // We will only allow preferred activities that came 4339 // from the same match quality. 4340 int match = 0; 4341 4342 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4343 4344 final int N = query.size(); 4345 for (int j=0; j<N; j++) { 4346 final ResolveInfo ri = query.get(j); 4347 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4348 + ": 0x" + Integer.toHexString(match)); 4349 if (ri.match > match) { 4350 match = ri.match; 4351 } 4352 } 4353 4354 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4355 + Integer.toHexString(match)); 4356 4357 match &= IntentFilter.MATCH_CATEGORY_MASK; 4358 final int M = prefs.size(); 4359 for (int i=0; i<M; i++) { 4360 final PreferredActivity pa = prefs.get(i); 4361 if (DEBUG_PREFERRED || debug) { 4362 Slog.v(TAG, "Checking PreferredActivity ds=" 4363 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4364 + "\n component=" + pa.mPref.mComponent); 4365 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4366 } 4367 if (pa.mPref.mMatch != match) { 4368 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4369 + Integer.toHexString(pa.mPref.mMatch)); 4370 continue; 4371 } 4372 // If it's not an "always" type preferred activity and that's what we're 4373 // looking for, skip it. 4374 if (always && !pa.mPref.mAlways) { 4375 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4376 continue; 4377 } 4378 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4379 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4380 if (DEBUG_PREFERRED || debug) { 4381 Slog.v(TAG, "Found preferred activity:"); 4382 if (ai != null) { 4383 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4384 } else { 4385 Slog.v(TAG, " null"); 4386 } 4387 } 4388 if (ai == null) { 4389 // This previously registered preferred activity 4390 // component is no longer known. Most likely an update 4391 // to the app was installed and in the new version this 4392 // component no longer exists. Clean it up by removing 4393 // it from the preferred activities list, and skip it. 4394 Slog.w(TAG, "Removing dangling preferred activity: " 4395 + pa.mPref.mComponent); 4396 pir.removeFilter(pa); 4397 changed = true; 4398 continue; 4399 } 4400 for (int j=0; j<N; j++) { 4401 final ResolveInfo ri = query.get(j); 4402 if (!ri.activityInfo.applicationInfo.packageName 4403 .equals(ai.applicationInfo.packageName)) { 4404 continue; 4405 } 4406 if (!ri.activityInfo.name.equals(ai.name)) { 4407 continue; 4408 } 4409 4410 if (removeMatches) { 4411 pir.removeFilter(pa); 4412 changed = true; 4413 if (DEBUG_PREFERRED) { 4414 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4415 } 4416 break; 4417 } 4418 4419 // Okay we found a previously set preferred or last chosen app. 4420 // If the result set is different from when this 4421 // was created, we need to clear it and re-ask the 4422 // user their preference, if we're looking for an "always" type entry. 4423 if (always && !pa.mPref.sameSet(query)) { 4424 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4425 + intent + " type " + resolvedType); 4426 if (DEBUG_PREFERRED) { 4427 Slog.v(TAG, "Removing preferred activity since set changed " 4428 + pa.mPref.mComponent); 4429 } 4430 pir.removeFilter(pa); 4431 // Re-add the filter as a "last chosen" entry (!always) 4432 PreferredActivity lastChosen = new PreferredActivity( 4433 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4434 pir.addFilter(lastChosen); 4435 changed = true; 4436 return null; 4437 } 4438 4439 // Yay! Either the set matched or we're looking for the last chosen 4440 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4441 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4442 return ri; 4443 } 4444 } 4445 } finally { 4446 if (changed) { 4447 if (DEBUG_PREFERRED) { 4448 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4449 } 4450 scheduleWritePackageRestrictionsLocked(userId); 4451 } 4452 } 4453 } 4454 } 4455 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4456 return null; 4457 } 4458 4459 /* 4460 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4461 */ 4462 @Override 4463 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4464 int targetUserId) { 4465 mContext.enforceCallingOrSelfPermission( 4466 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4467 List<CrossProfileIntentFilter> matches = 4468 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4469 if (matches != null) { 4470 int size = matches.size(); 4471 for (int i = 0; i < size; i++) { 4472 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4473 } 4474 } 4475 if (hasWebURI(intent)) { 4476 // cross-profile app linking works only towards the parent. 4477 final UserInfo parent = getProfileParent(sourceUserId); 4478 synchronized(mPackages) { 4479 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4480 intent, resolvedType, 0, sourceUserId, parent.id); 4481 return xpDomainInfo != null; 4482 } 4483 } 4484 return false; 4485 } 4486 4487 private UserInfo getProfileParent(int userId) { 4488 final long identity = Binder.clearCallingIdentity(); 4489 try { 4490 return sUserManager.getProfileParent(userId); 4491 } finally { 4492 Binder.restoreCallingIdentity(identity); 4493 } 4494 } 4495 4496 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4497 String resolvedType, int userId) { 4498 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4499 if (resolver != null) { 4500 return resolver.queryIntent(intent, resolvedType, false, userId); 4501 } 4502 return null; 4503 } 4504 4505 @Override 4506 public List<ResolveInfo> queryIntentActivities(Intent intent, 4507 String resolvedType, int flags, int userId) { 4508 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4509 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4510 ComponentName comp = intent.getComponent(); 4511 if (comp == null) { 4512 if (intent.getSelector() != null) { 4513 intent = intent.getSelector(); 4514 comp = intent.getComponent(); 4515 } 4516 } 4517 4518 if (comp != null) { 4519 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4520 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4521 if (ai != null) { 4522 final ResolveInfo ri = new ResolveInfo(); 4523 ri.activityInfo = ai; 4524 list.add(ri); 4525 } 4526 return list; 4527 } 4528 4529 // reader 4530 synchronized (mPackages) { 4531 final String pkgName = intent.getPackage(); 4532 if (pkgName == null) { 4533 List<CrossProfileIntentFilter> matchingFilters = 4534 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4535 // Check for results that need to skip the current profile. 4536 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4537 resolvedType, flags, userId); 4538 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4539 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4540 result.add(xpResolveInfo); 4541 return filterIfNotPrimaryUser(result, userId); 4542 } 4543 4544 // Check for results in the current profile. 4545 List<ResolveInfo> result = mActivities.queryIntent( 4546 intent, resolvedType, flags, userId); 4547 4548 // Check for cross profile results. 4549 xpResolveInfo = queryCrossProfileIntents( 4550 matchingFilters, intent, resolvedType, flags, userId); 4551 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4552 result.add(xpResolveInfo); 4553 Collections.sort(result, mResolvePrioritySorter); 4554 } 4555 result = filterIfNotPrimaryUser(result, userId); 4556 if (hasWebURI(intent)) { 4557 CrossProfileDomainInfo xpDomainInfo = null; 4558 final UserInfo parent = getProfileParent(userId); 4559 if (parent != null) { 4560 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4561 flags, userId, parent.id); 4562 } 4563 if (xpDomainInfo != null) { 4564 if (xpResolveInfo != null) { 4565 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4566 // in the result. 4567 result.remove(xpResolveInfo); 4568 } 4569 if (result.size() == 0) { 4570 result.add(xpDomainInfo.resolveInfo); 4571 return result; 4572 } 4573 } else if (result.size() <= 1) { 4574 return result; 4575 } 4576 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4577 xpDomainInfo, userId); 4578 Collections.sort(result, mResolvePrioritySorter); 4579 } 4580 return result; 4581 } 4582 final PackageParser.Package pkg = mPackages.get(pkgName); 4583 if (pkg != null) { 4584 return filterIfNotPrimaryUser( 4585 mActivities.queryIntentForPackage( 4586 intent, resolvedType, flags, pkg.activities, userId), 4587 userId); 4588 } 4589 return new ArrayList<ResolveInfo>(); 4590 } 4591 } 4592 4593 private static class CrossProfileDomainInfo { 4594 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4595 ResolveInfo resolveInfo; 4596 /* Best domain verification status of the activities found in the other profile */ 4597 int bestDomainVerificationStatus; 4598 } 4599 4600 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4601 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4602 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4603 sourceUserId)) { 4604 return null; 4605 } 4606 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4607 resolvedType, flags, parentUserId); 4608 4609 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4610 return null; 4611 } 4612 CrossProfileDomainInfo result = null; 4613 int size = resultTargetUser.size(); 4614 for (int i = 0; i < size; i++) { 4615 ResolveInfo riTargetUser = resultTargetUser.get(i); 4616 // Intent filter verification is only for filters that specify a host. So don't return 4617 // those that handle all web uris. 4618 if (riTargetUser.handleAllWebDataURI) { 4619 continue; 4620 } 4621 String packageName = riTargetUser.activityInfo.packageName; 4622 PackageSetting ps = mSettings.mPackages.get(packageName); 4623 if (ps == null) { 4624 continue; 4625 } 4626 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4627 int status = (int)(verificationState >> 32); 4628 if (result == null) { 4629 result = new CrossProfileDomainInfo(); 4630 result.resolveInfo = 4631 createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId); 4632 result.bestDomainVerificationStatus = status; 4633 } else { 4634 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4635 result.bestDomainVerificationStatus); 4636 } 4637 } 4638 // Don't consider matches with status NEVER across profiles. 4639 if (result != null && result.bestDomainVerificationStatus 4640 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4641 return null; 4642 } 4643 return result; 4644 } 4645 4646 /** 4647 * Verification statuses are ordered from the worse to the best, except for 4648 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4649 */ 4650 private int bestDomainVerificationStatus(int status1, int status2) { 4651 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4652 return status2; 4653 } 4654 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4655 return status1; 4656 } 4657 return (int) MathUtils.max(status1, status2); 4658 } 4659 4660 private boolean isUserEnabled(int userId) { 4661 long callingId = Binder.clearCallingIdentity(); 4662 try { 4663 UserInfo userInfo = sUserManager.getUserInfo(userId); 4664 return userInfo != null && userInfo.isEnabled(); 4665 } finally { 4666 Binder.restoreCallingIdentity(callingId); 4667 } 4668 } 4669 4670 /** 4671 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4672 * 4673 * @return filtered list 4674 */ 4675 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4676 if (userId == UserHandle.USER_OWNER) { 4677 return resolveInfos; 4678 } 4679 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4680 ResolveInfo info = resolveInfos.get(i); 4681 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4682 resolveInfos.remove(i); 4683 } 4684 } 4685 return resolveInfos; 4686 } 4687 4688 private static boolean hasWebURI(Intent intent) { 4689 if (intent.getData() == null) { 4690 return false; 4691 } 4692 final String scheme = intent.getScheme(); 4693 if (TextUtils.isEmpty(scheme)) { 4694 return false; 4695 } 4696 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4697 } 4698 4699 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4700 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4701 int userId) { 4702 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4703 4704 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4705 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4706 candidates.size()); 4707 } 4708 4709 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4710 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4711 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4712 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4713 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4714 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4715 4716 synchronized (mPackages) { 4717 final int count = candidates.size(); 4718 // First, try to use linked apps. Partition the candidates into four lists: 4719 // one for the final results, one for the "do not use ever", one for "undefined status" 4720 // and finally one for "browser app type". 4721 for (int n=0; n<count; n++) { 4722 ResolveInfo info = candidates.get(n); 4723 String packageName = info.activityInfo.packageName; 4724 PackageSetting ps = mSettings.mPackages.get(packageName); 4725 if (ps != null) { 4726 // Add to the special match all list (Browser use case) 4727 if (info.handleAllWebDataURI) { 4728 matchAllList.add(info); 4729 continue; 4730 } 4731 // Try to get the status from User settings first 4732 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4733 int status = (int)(packedStatus >> 32); 4734 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4735 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4736 if (DEBUG_DOMAIN_VERIFICATION) { 4737 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4738 + " : linkgen=" + linkGeneration); 4739 } 4740 // Use link-enabled generation as preferredOrder, i.e. 4741 // prefer newly-enabled over earlier-enabled. 4742 info.preferredOrder = linkGeneration; 4743 alwaysList.add(info); 4744 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4745 if (DEBUG_DOMAIN_VERIFICATION) { 4746 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4747 } 4748 neverList.add(info); 4749 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4750 if (DEBUG_DOMAIN_VERIFICATION) { 4751 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4752 } 4753 alwaysAskList.add(info); 4754 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4755 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4756 if (DEBUG_DOMAIN_VERIFICATION) { 4757 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4758 } 4759 undefinedList.add(info); 4760 } 4761 } 4762 } 4763 4764 // We'll want to include browser possibilities in a few cases 4765 boolean includeBrowser = false; 4766 4767 // First try to add the "always" resolution(s) for the current user, if any 4768 if (alwaysList.size() > 0) { 4769 result.addAll(alwaysList); 4770 // if there is an "always" for the parent user, add it. 4771 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4772 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4773 result.add(xpDomainInfo.resolveInfo); 4774 } else { 4775 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4776 result.addAll(undefinedList); 4777 if (xpDomainInfo != null && ( 4778 xpDomainInfo.bestDomainVerificationStatus 4779 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4780 || xpDomainInfo.bestDomainVerificationStatus 4781 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4782 result.add(xpDomainInfo.resolveInfo); 4783 } 4784 includeBrowser = true; 4785 } 4786 4787 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4788 // If there were 'always' entries their preferred order has been set, so we also 4789 // back that off to make the alternatives equivalent 4790 if (alwaysAskList.size() > 0) { 4791 for (ResolveInfo i : result) { 4792 i.preferredOrder = 0; 4793 } 4794 result.addAll(alwaysAskList); 4795 includeBrowser = true; 4796 } 4797 4798 if (includeBrowser) { 4799 // Also add browsers (all of them or only the default one) 4800 if (DEBUG_DOMAIN_VERIFICATION) { 4801 Slog.v(TAG, " ...including browsers in candidate set"); 4802 } 4803 if ((matchFlags & MATCH_ALL) != 0) { 4804 result.addAll(matchAllList); 4805 } else { 4806 // Browser/generic handling case. If there's a default browser, go straight 4807 // to that (but only if there is no other higher-priority match). 4808 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4809 int maxMatchPrio = 0; 4810 ResolveInfo defaultBrowserMatch = null; 4811 final int numCandidates = matchAllList.size(); 4812 for (int n = 0; n < numCandidates; n++) { 4813 ResolveInfo info = matchAllList.get(n); 4814 // track the highest overall match priority... 4815 if (info.priority > maxMatchPrio) { 4816 maxMatchPrio = info.priority; 4817 } 4818 // ...and the highest-priority default browser match 4819 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4820 if (defaultBrowserMatch == null 4821 || (defaultBrowserMatch.priority < info.priority)) { 4822 if (debug) { 4823 Slog.v(TAG, "Considering default browser match " + info); 4824 } 4825 defaultBrowserMatch = info; 4826 } 4827 } 4828 } 4829 if (defaultBrowserMatch != null 4830 && defaultBrowserMatch.priority >= maxMatchPrio 4831 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4832 { 4833 if (debug) { 4834 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4835 } 4836 result.add(defaultBrowserMatch); 4837 } else { 4838 result.addAll(matchAllList); 4839 } 4840 } 4841 4842 // If there is nothing selected, add all candidates and remove the ones that the user 4843 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4844 if (result.size() == 0) { 4845 result.addAll(candidates); 4846 result.removeAll(neverList); 4847 } 4848 } 4849 } 4850 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4851 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4852 result.size()); 4853 for (ResolveInfo info : result) { 4854 Slog.v(TAG, " + " + info.activityInfo); 4855 } 4856 } 4857 return result; 4858 } 4859 4860 // Returns a packed value as a long: 4861 // 4862 // high 'int'-sized word: link status: undefined/ask/never/always. 4863 // low 'int'-sized word: relative priority among 'always' results. 4864 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4865 long result = ps.getDomainVerificationStatusForUser(userId); 4866 // if none available, get the master status 4867 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4868 if (ps.getIntentFilterVerificationInfo() != null) { 4869 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4870 } 4871 } 4872 return result; 4873 } 4874 4875 private ResolveInfo querySkipCurrentProfileIntents( 4876 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4877 int flags, int sourceUserId) { 4878 if (matchingFilters != null) { 4879 int size = matchingFilters.size(); 4880 for (int i = 0; i < size; i ++) { 4881 CrossProfileIntentFilter filter = matchingFilters.get(i); 4882 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4883 // Checking if there are activities in the target user that can handle the 4884 // intent. 4885 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4886 flags, sourceUserId); 4887 if (resolveInfo != null) { 4888 return resolveInfo; 4889 } 4890 } 4891 } 4892 } 4893 return null; 4894 } 4895 4896 // Return matching ResolveInfo if any for skip current profile intent filters. 4897 private ResolveInfo queryCrossProfileIntents( 4898 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4899 int flags, int sourceUserId) { 4900 if (matchingFilters != null) { 4901 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4902 // match the same intent. For performance reasons, it is better not to 4903 // run queryIntent twice for the same userId 4904 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4905 int size = matchingFilters.size(); 4906 for (int i = 0; i < size; i++) { 4907 CrossProfileIntentFilter filter = matchingFilters.get(i); 4908 int targetUserId = filter.getTargetUserId(); 4909 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4910 && !alreadyTriedUserIds.get(targetUserId)) { 4911 // Checking if there are activities in the target user that can handle the 4912 // intent. 4913 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4914 flags, sourceUserId); 4915 if (resolveInfo != null) return resolveInfo; 4916 alreadyTriedUserIds.put(targetUserId, true); 4917 } 4918 } 4919 } 4920 return null; 4921 } 4922 4923 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4924 String resolvedType, int flags, int sourceUserId) { 4925 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4926 resolvedType, flags, filter.getTargetUserId()); 4927 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4928 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4929 } 4930 return null; 4931 } 4932 4933 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4934 int sourceUserId, int targetUserId) { 4935 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4936 String className; 4937 if (targetUserId == UserHandle.USER_OWNER) { 4938 className = FORWARD_INTENT_TO_USER_OWNER; 4939 } else { 4940 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4941 } 4942 ComponentName forwardingActivityComponentName = new ComponentName( 4943 mAndroidApplication.packageName, className); 4944 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4945 sourceUserId); 4946 if (targetUserId == UserHandle.USER_OWNER) { 4947 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4948 forwardingResolveInfo.noResourceId = true; 4949 } 4950 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4951 forwardingResolveInfo.priority = 0; 4952 forwardingResolveInfo.preferredOrder = 0; 4953 forwardingResolveInfo.match = 0; 4954 forwardingResolveInfo.isDefault = true; 4955 forwardingResolveInfo.filter = filter; 4956 forwardingResolveInfo.targetUserId = targetUserId; 4957 return forwardingResolveInfo; 4958 } 4959 4960 @Override 4961 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4962 Intent[] specifics, String[] specificTypes, Intent intent, 4963 String resolvedType, int flags, int userId) { 4964 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4965 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4966 false, "query intent activity options"); 4967 final String resultsAction = intent.getAction(); 4968 4969 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4970 | PackageManager.GET_RESOLVED_FILTER, userId); 4971 4972 if (DEBUG_INTENT_MATCHING) { 4973 Log.v(TAG, "Query " + intent + ": " + results); 4974 } 4975 4976 int specificsPos = 0; 4977 int N; 4978 4979 // todo: note that the algorithm used here is O(N^2). This 4980 // isn't a problem in our current environment, but if we start running 4981 // into situations where we have more than 5 or 10 matches then this 4982 // should probably be changed to something smarter... 4983 4984 // First we go through and resolve each of the specific items 4985 // that were supplied, taking care of removing any corresponding 4986 // duplicate items in the generic resolve list. 4987 if (specifics != null) { 4988 for (int i=0; i<specifics.length; i++) { 4989 final Intent sintent = specifics[i]; 4990 if (sintent == null) { 4991 continue; 4992 } 4993 4994 if (DEBUG_INTENT_MATCHING) { 4995 Log.v(TAG, "Specific #" + i + ": " + sintent); 4996 } 4997 4998 String action = sintent.getAction(); 4999 if (resultsAction != null && resultsAction.equals(action)) { 5000 // If this action was explicitly requested, then don't 5001 // remove things that have it. 5002 action = null; 5003 } 5004 5005 ResolveInfo ri = null; 5006 ActivityInfo ai = null; 5007 5008 ComponentName comp = sintent.getComponent(); 5009 if (comp == null) { 5010 ri = resolveIntent( 5011 sintent, 5012 specificTypes != null ? specificTypes[i] : null, 5013 flags, userId); 5014 if (ri == null) { 5015 continue; 5016 } 5017 if (ri == mResolveInfo) { 5018 // ACK! Must do something better with this. 5019 } 5020 ai = ri.activityInfo; 5021 comp = new ComponentName(ai.applicationInfo.packageName, 5022 ai.name); 5023 } else { 5024 ai = getActivityInfo(comp, flags, userId); 5025 if (ai == null) { 5026 continue; 5027 } 5028 } 5029 5030 // Look for any generic query activities that are duplicates 5031 // of this specific one, and remove them from the results. 5032 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5033 N = results.size(); 5034 int j; 5035 for (j=specificsPos; j<N; j++) { 5036 ResolveInfo sri = results.get(j); 5037 if ((sri.activityInfo.name.equals(comp.getClassName()) 5038 && sri.activityInfo.applicationInfo.packageName.equals( 5039 comp.getPackageName())) 5040 || (action != null && sri.filter.matchAction(action))) { 5041 results.remove(j); 5042 if (DEBUG_INTENT_MATCHING) Log.v( 5043 TAG, "Removing duplicate item from " + j 5044 + " due to specific " + specificsPos); 5045 if (ri == null) { 5046 ri = sri; 5047 } 5048 j--; 5049 N--; 5050 } 5051 } 5052 5053 // Add this specific item to its proper place. 5054 if (ri == null) { 5055 ri = new ResolveInfo(); 5056 ri.activityInfo = ai; 5057 } 5058 results.add(specificsPos, ri); 5059 ri.specificIndex = i; 5060 specificsPos++; 5061 } 5062 } 5063 5064 // Now we go through the remaining generic results and remove any 5065 // duplicate actions that are found here. 5066 N = results.size(); 5067 for (int i=specificsPos; i<N-1; i++) { 5068 final ResolveInfo rii = results.get(i); 5069 if (rii.filter == null) { 5070 continue; 5071 } 5072 5073 // Iterate over all of the actions of this result's intent 5074 // filter... typically this should be just one. 5075 final Iterator<String> it = rii.filter.actionsIterator(); 5076 if (it == null) { 5077 continue; 5078 } 5079 while (it.hasNext()) { 5080 final String action = it.next(); 5081 if (resultsAction != null && resultsAction.equals(action)) { 5082 // If this action was explicitly requested, then don't 5083 // remove things that have it. 5084 continue; 5085 } 5086 for (int j=i+1; j<N; j++) { 5087 final ResolveInfo rij = results.get(j); 5088 if (rij.filter != null && rij.filter.hasAction(action)) { 5089 results.remove(j); 5090 if (DEBUG_INTENT_MATCHING) Log.v( 5091 TAG, "Removing duplicate item from " + j 5092 + " due to action " + action + " at " + i); 5093 j--; 5094 N--; 5095 } 5096 } 5097 } 5098 5099 // If the caller didn't request filter information, drop it now 5100 // so we don't have to marshall/unmarshall it. 5101 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5102 rii.filter = null; 5103 } 5104 } 5105 5106 // Filter out the caller activity if so requested. 5107 if (caller != null) { 5108 N = results.size(); 5109 for (int i=0; i<N; i++) { 5110 ActivityInfo ainfo = results.get(i).activityInfo; 5111 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5112 && caller.getClassName().equals(ainfo.name)) { 5113 results.remove(i); 5114 break; 5115 } 5116 } 5117 } 5118 5119 // If the caller didn't request filter information, 5120 // drop them now so we don't have to 5121 // marshall/unmarshall it. 5122 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5123 N = results.size(); 5124 for (int i=0; i<N; i++) { 5125 results.get(i).filter = null; 5126 } 5127 } 5128 5129 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5130 return results; 5131 } 5132 5133 @Override 5134 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5135 int userId) { 5136 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5137 ComponentName comp = intent.getComponent(); 5138 if (comp == null) { 5139 if (intent.getSelector() != null) { 5140 intent = intent.getSelector(); 5141 comp = intent.getComponent(); 5142 } 5143 } 5144 if (comp != null) { 5145 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5146 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5147 if (ai != null) { 5148 ResolveInfo ri = new ResolveInfo(); 5149 ri.activityInfo = ai; 5150 list.add(ri); 5151 } 5152 return list; 5153 } 5154 5155 // reader 5156 synchronized (mPackages) { 5157 String pkgName = intent.getPackage(); 5158 if (pkgName == null) { 5159 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5160 } 5161 final PackageParser.Package pkg = mPackages.get(pkgName); 5162 if (pkg != null) { 5163 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5164 userId); 5165 } 5166 return null; 5167 } 5168 } 5169 5170 @Override 5171 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5172 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5173 if (!sUserManager.exists(userId)) return null; 5174 if (query != null) { 5175 if (query.size() >= 1) { 5176 // If there is more than one service with the same priority, 5177 // just arbitrarily pick the first one. 5178 return query.get(0); 5179 } 5180 } 5181 return null; 5182 } 5183 5184 @Override 5185 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5186 int userId) { 5187 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5188 ComponentName comp = intent.getComponent(); 5189 if (comp == null) { 5190 if (intent.getSelector() != null) { 5191 intent = intent.getSelector(); 5192 comp = intent.getComponent(); 5193 } 5194 } 5195 if (comp != null) { 5196 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5197 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5198 if (si != null) { 5199 final ResolveInfo ri = new ResolveInfo(); 5200 ri.serviceInfo = si; 5201 list.add(ri); 5202 } 5203 return list; 5204 } 5205 5206 // reader 5207 synchronized (mPackages) { 5208 String pkgName = intent.getPackage(); 5209 if (pkgName == null) { 5210 return mServices.queryIntent(intent, resolvedType, flags, userId); 5211 } 5212 final PackageParser.Package pkg = mPackages.get(pkgName); 5213 if (pkg != null) { 5214 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5215 userId); 5216 } 5217 return null; 5218 } 5219 } 5220 5221 @Override 5222 public List<ResolveInfo> queryIntentContentProviders( 5223 Intent intent, String resolvedType, int flags, int userId) { 5224 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5225 ComponentName comp = intent.getComponent(); 5226 if (comp == null) { 5227 if (intent.getSelector() != null) { 5228 intent = intent.getSelector(); 5229 comp = intent.getComponent(); 5230 } 5231 } 5232 if (comp != null) { 5233 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5234 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5235 if (pi != null) { 5236 final ResolveInfo ri = new ResolveInfo(); 5237 ri.providerInfo = pi; 5238 list.add(ri); 5239 } 5240 return list; 5241 } 5242 5243 // reader 5244 synchronized (mPackages) { 5245 String pkgName = intent.getPackage(); 5246 if (pkgName == null) { 5247 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5248 } 5249 final PackageParser.Package pkg = mPackages.get(pkgName); 5250 if (pkg != null) { 5251 return mProviders.queryIntentForPackage( 5252 intent, resolvedType, flags, pkg.providers, userId); 5253 } 5254 return null; 5255 } 5256 } 5257 5258 @Override 5259 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5260 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5261 5262 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5263 5264 // writer 5265 synchronized (mPackages) { 5266 ArrayList<PackageInfo> list; 5267 if (listUninstalled) { 5268 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5269 for (PackageSetting ps : mSettings.mPackages.values()) { 5270 PackageInfo pi; 5271 if (ps.pkg != null) { 5272 pi = generatePackageInfo(ps.pkg, flags, userId); 5273 } else { 5274 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5275 } 5276 if (pi != null) { 5277 list.add(pi); 5278 } 5279 } 5280 } else { 5281 list = new ArrayList<PackageInfo>(mPackages.size()); 5282 for (PackageParser.Package p : mPackages.values()) { 5283 PackageInfo pi = generatePackageInfo(p, flags, userId); 5284 if (pi != null) { 5285 list.add(pi); 5286 } 5287 } 5288 } 5289 5290 return new ParceledListSlice<PackageInfo>(list); 5291 } 5292 } 5293 5294 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5295 String[] permissions, boolean[] tmp, int flags, int userId) { 5296 int numMatch = 0; 5297 final PermissionsState permissionsState = ps.getPermissionsState(); 5298 for (int i=0; i<permissions.length; i++) { 5299 final String permission = permissions[i]; 5300 if (permissionsState.hasPermission(permission, userId)) { 5301 tmp[i] = true; 5302 numMatch++; 5303 } else { 5304 tmp[i] = false; 5305 } 5306 } 5307 if (numMatch == 0) { 5308 return; 5309 } 5310 PackageInfo pi; 5311 if (ps.pkg != null) { 5312 pi = generatePackageInfo(ps.pkg, flags, userId); 5313 } else { 5314 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5315 } 5316 // The above might return null in cases of uninstalled apps or install-state 5317 // skew across users/profiles. 5318 if (pi != null) { 5319 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5320 if (numMatch == permissions.length) { 5321 pi.requestedPermissions = permissions; 5322 } else { 5323 pi.requestedPermissions = new String[numMatch]; 5324 numMatch = 0; 5325 for (int i=0; i<permissions.length; i++) { 5326 if (tmp[i]) { 5327 pi.requestedPermissions[numMatch] = permissions[i]; 5328 numMatch++; 5329 } 5330 } 5331 } 5332 } 5333 list.add(pi); 5334 } 5335 } 5336 5337 @Override 5338 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5339 String[] permissions, int flags, int userId) { 5340 if (!sUserManager.exists(userId)) return null; 5341 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5342 5343 // writer 5344 synchronized (mPackages) { 5345 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5346 boolean[] tmpBools = new boolean[permissions.length]; 5347 if (listUninstalled) { 5348 for (PackageSetting ps : mSettings.mPackages.values()) { 5349 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5350 } 5351 } else { 5352 for (PackageParser.Package pkg : mPackages.values()) { 5353 PackageSetting ps = (PackageSetting)pkg.mExtras; 5354 if (ps != null) { 5355 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5356 userId); 5357 } 5358 } 5359 } 5360 5361 return new ParceledListSlice<PackageInfo>(list); 5362 } 5363 } 5364 5365 @Override 5366 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5367 if (!sUserManager.exists(userId)) return null; 5368 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5369 5370 // writer 5371 synchronized (mPackages) { 5372 ArrayList<ApplicationInfo> list; 5373 if (listUninstalled) { 5374 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5375 for (PackageSetting ps : mSettings.mPackages.values()) { 5376 ApplicationInfo ai; 5377 if (ps.pkg != null) { 5378 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5379 ps.readUserState(userId), userId); 5380 } else { 5381 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5382 } 5383 if (ai != null) { 5384 list.add(ai); 5385 } 5386 } 5387 } else { 5388 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5389 for (PackageParser.Package p : mPackages.values()) { 5390 if (p.mExtras != null) { 5391 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5392 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5393 if (ai != null) { 5394 list.add(ai); 5395 } 5396 } 5397 } 5398 } 5399 5400 return new ParceledListSlice<ApplicationInfo>(list); 5401 } 5402 } 5403 5404 public List<ApplicationInfo> getPersistentApplications(int flags) { 5405 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5406 5407 // reader 5408 synchronized (mPackages) { 5409 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5410 final int userId = UserHandle.getCallingUserId(); 5411 while (i.hasNext()) { 5412 final PackageParser.Package p = i.next(); 5413 if (p.applicationInfo != null 5414 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5415 && (!mSafeMode || isSystemApp(p))) { 5416 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5417 if (ps != null) { 5418 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5419 ps.readUserState(userId), userId); 5420 if (ai != null) { 5421 finalList.add(ai); 5422 } 5423 } 5424 } 5425 } 5426 } 5427 5428 return finalList; 5429 } 5430 5431 @Override 5432 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5433 if (!sUserManager.exists(userId)) return null; 5434 // reader 5435 synchronized (mPackages) { 5436 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5437 PackageSetting ps = provider != null 5438 ? mSettings.mPackages.get(provider.owner.packageName) 5439 : null; 5440 return ps != null 5441 && mSettings.isEnabledLPr(provider.info, flags, userId) 5442 && (!mSafeMode || (provider.info.applicationInfo.flags 5443 &ApplicationInfo.FLAG_SYSTEM) != 0) 5444 ? PackageParser.generateProviderInfo(provider, flags, 5445 ps.readUserState(userId), userId) 5446 : null; 5447 } 5448 } 5449 5450 /** 5451 * @deprecated 5452 */ 5453 @Deprecated 5454 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5455 // reader 5456 synchronized (mPackages) { 5457 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5458 .entrySet().iterator(); 5459 final int userId = UserHandle.getCallingUserId(); 5460 while (i.hasNext()) { 5461 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5462 PackageParser.Provider p = entry.getValue(); 5463 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5464 5465 if (ps != null && p.syncable 5466 && (!mSafeMode || (p.info.applicationInfo.flags 5467 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5468 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5469 ps.readUserState(userId), userId); 5470 if (info != null) { 5471 outNames.add(entry.getKey()); 5472 outInfo.add(info); 5473 } 5474 } 5475 } 5476 } 5477 } 5478 5479 @Override 5480 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5481 int uid, int flags) { 5482 ArrayList<ProviderInfo> finalList = null; 5483 // reader 5484 synchronized (mPackages) { 5485 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5486 final int userId = processName != null ? 5487 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5488 while (i.hasNext()) { 5489 final PackageParser.Provider p = i.next(); 5490 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5491 if (ps != null && p.info.authority != null 5492 && (processName == null 5493 || (p.info.processName.equals(processName) 5494 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5495 && mSettings.isEnabledLPr(p.info, flags, userId) 5496 && (!mSafeMode 5497 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5498 if (finalList == null) { 5499 finalList = new ArrayList<ProviderInfo>(3); 5500 } 5501 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5502 ps.readUserState(userId), userId); 5503 if (info != null) { 5504 finalList.add(info); 5505 } 5506 } 5507 } 5508 } 5509 5510 if (finalList != null) { 5511 Collections.sort(finalList, mProviderInitOrderSorter); 5512 return new ParceledListSlice<ProviderInfo>(finalList); 5513 } 5514 5515 return null; 5516 } 5517 5518 @Override 5519 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5520 int flags) { 5521 // reader 5522 synchronized (mPackages) { 5523 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5524 return PackageParser.generateInstrumentationInfo(i, flags); 5525 } 5526 } 5527 5528 @Override 5529 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5530 int flags) { 5531 ArrayList<InstrumentationInfo> finalList = 5532 new ArrayList<InstrumentationInfo>(); 5533 5534 // reader 5535 synchronized (mPackages) { 5536 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5537 while (i.hasNext()) { 5538 final PackageParser.Instrumentation p = i.next(); 5539 if (targetPackage == null 5540 || targetPackage.equals(p.info.targetPackage)) { 5541 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5542 flags); 5543 if (ii != null) { 5544 finalList.add(ii); 5545 } 5546 } 5547 } 5548 } 5549 5550 return finalList; 5551 } 5552 5553 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5554 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5555 if (overlays == null) { 5556 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5557 return; 5558 } 5559 for (PackageParser.Package opkg : overlays.values()) { 5560 // Not much to do if idmap fails: we already logged the error 5561 // and we certainly don't want to abort installation of pkg simply 5562 // because an overlay didn't fit properly. For these reasons, 5563 // ignore the return value of createIdmapForPackagePairLI. 5564 createIdmapForPackagePairLI(pkg, opkg); 5565 } 5566 } 5567 5568 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5569 PackageParser.Package opkg) { 5570 if (!opkg.mTrustedOverlay) { 5571 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5572 opkg.baseCodePath + ": overlay not trusted"); 5573 return false; 5574 } 5575 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5576 if (overlaySet == null) { 5577 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5578 opkg.baseCodePath + " but target package has no known overlays"); 5579 return false; 5580 } 5581 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5582 // TODO: generate idmap for split APKs 5583 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5584 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5585 + opkg.baseCodePath); 5586 return false; 5587 } 5588 PackageParser.Package[] overlayArray = 5589 overlaySet.values().toArray(new PackageParser.Package[0]); 5590 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5591 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5592 return p1.mOverlayPriority - p2.mOverlayPriority; 5593 } 5594 }; 5595 Arrays.sort(overlayArray, cmp); 5596 5597 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5598 int i = 0; 5599 for (PackageParser.Package p : overlayArray) { 5600 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5601 } 5602 return true; 5603 } 5604 5605 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5606 final File[] files = dir.listFiles(); 5607 if (ArrayUtils.isEmpty(files)) { 5608 Log.d(TAG, "No files in app dir " + dir); 5609 return; 5610 } 5611 5612 if (DEBUG_PACKAGE_SCANNING) { 5613 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5614 + " flags=0x" + Integer.toHexString(parseFlags)); 5615 } 5616 5617 for (File file : files) { 5618 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5619 && !PackageInstallerService.isStageName(file.getName()); 5620 if (!isPackage) { 5621 // Ignore entries which are not packages 5622 continue; 5623 } 5624 try { 5625 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5626 scanFlags, currentTime, null); 5627 } catch (PackageManagerException e) { 5628 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5629 5630 // Delete invalid userdata apps 5631 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5632 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5633 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5634 if (file.isDirectory()) { 5635 mInstaller.rmPackageDir(file.getAbsolutePath()); 5636 } else { 5637 file.delete(); 5638 } 5639 } 5640 } 5641 } 5642 } 5643 5644 private static File getSettingsProblemFile() { 5645 File dataDir = Environment.getDataDirectory(); 5646 File systemDir = new File(dataDir, "system"); 5647 File fname = new File(systemDir, "uiderrors.txt"); 5648 return fname; 5649 } 5650 5651 static void reportSettingsProblem(int priority, String msg) { 5652 logCriticalInfo(priority, msg); 5653 } 5654 5655 static void logCriticalInfo(int priority, String msg) { 5656 Slog.println(priority, TAG, msg); 5657 EventLogTags.writePmCriticalInfo(msg); 5658 try { 5659 File fname = getSettingsProblemFile(); 5660 FileOutputStream out = new FileOutputStream(fname, true); 5661 PrintWriter pw = new FastPrintWriter(out); 5662 SimpleDateFormat formatter = new SimpleDateFormat(); 5663 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5664 pw.println(dateString + ": " + msg); 5665 pw.close(); 5666 FileUtils.setPermissions( 5667 fname.toString(), 5668 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5669 -1, -1); 5670 } catch (java.io.IOException e) { 5671 } 5672 } 5673 5674 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5675 PackageParser.Package pkg, File srcFile, int parseFlags) 5676 throws PackageManagerException { 5677 if (ps != null 5678 && ps.codePath.equals(srcFile) 5679 && ps.timeStamp == srcFile.lastModified() 5680 && !isCompatSignatureUpdateNeeded(pkg) 5681 && !isRecoverSignatureUpdateNeeded(pkg)) { 5682 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5683 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5684 ArraySet<PublicKey> signingKs; 5685 synchronized (mPackages) { 5686 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5687 } 5688 if (ps.signatures.mSignatures != null 5689 && ps.signatures.mSignatures.length != 0 5690 && signingKs != null) { 5691 // Optimization: reuse the existing cached certificates 5692 // if the package appears to be unchanged. 5693 pkg.mSignatures = ps.signatures.mSignatures; 5694 pkg.mSigningKeys = signingKs; 5695 return; 5696 } 5697 5698 Slog.w(TAG, "PackageSetting for " + ps.name 5699 + " is missing signatures. Collecting certs again to recover them."); 5700 } else { 5701 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5702 } 5703 5704 try { 5705 pp.collectCertificates(pkg, parseFlags); 5706 pp.collectManifestDigest(pkg); 5707 } catch (PackageParserException e) { 5708 throw PackageManagerException.from(e); 5709 } 5710 } 5711 5712 /* 5713 * Scan a package and return the newly parsed package. 5714 * Returns null in case of errors and the error code is stored in mLastScanError 5715 */ 5716 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5717 long currentTime, UserHandle user) throws PackageManagerException { 5718 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5719 parseFlags |= mDefParseFlags; 5720 PackageParser pp = new PackageParser(); 5721 pp.setSeparateProcesses(mSeparateProcesses); 5722 pp.setOnlyCoreApps(mOnlyCore); 5723 pp.setDisplayMetrics(mMetrics); 5724 5725 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5726 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5727 } 5728 5729 final PackageParser.Package pkg; 5730 try { 5731 pkg = pp.parsePackage(scanFile, parseFlags); 5732 } catch (PackageParserException e) { 5733 throw PackageManagerException.from(e); 5734 } 5735 5736 PackageSetting ps = null; 5737 PackageSetting updatedPkg; 5738 // reader 5739 synchronized (mPackages) { 5740 // Look to see if we already know about this package. 5741 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5742 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5743 // This package has been renamed to its original name. Let's 5744 // use that. 5745 ps = mSettings.peekPackageLPr(oldName); 5746 } 5747 // If there was no original package, see one for the real package name. 5748 if (ps == null) { 5749 ps = mSettings.peekPackageLPr(pkg.packageName); 5750 } 5751 // Check to see if this package could be hiding/updating a system 5752 // package. Must look for it either under the original or real 5753 // package name depending on our state. 5754 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5755 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5756 } 5757 boolean updatedPkgBetter = false; 5758 // First check if this is a system package that may involve an update 5759 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5760 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5761 // it needs to drop FLAG_PRIVILEGED. 5762 if (locationIsPrivileged(scanFile)) { 5763 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5764 } else { 5765 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5766 } 5767 5768 if (ps != null && !ps.codePath.equals(scanFile)) { 5769 // The path has changed from what was last scanned... check the 5770 // version of the new path against what we have stored to determine 5771 // what to do. 5772 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5773 if (pkg.mVersionCode <= ps.versionCode) { 5774 // The system package has been updated and the code path does not match 5775 // Ignore entry. Skip it. 5776 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5777 + " ignored: updated version " + ps.versionCode 5778 + " better than this " + pkg.mVersionCode); 5779 if (!updatedPkg.codePath.equals(scanFile)) { 5780 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5781 + ps.name + " changing from " + updatedPkg.codePathString 5782 + " to " + scanFile); 5783 updatedPkg.codePath = scanFile; 5784 updatedPkg.codePathString = scanFile.toString(); 5785 updatedPkg.resourcePath = scanFile; 5786 updatedPkg.resourcePathString = scanFile.toString(); 5787 } 5788 updatedPkg.pkg = pkg; 5789 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5790 "Package " + ps.name + " at " + scanFile 5791 + " ignored: updated version " + ps.versionCode 5792 + " better than this " + pkg.mVersionCode); 5793 } else { 5794 // The current app on the system partition is better than 5795 // what we have updated to on the data partition; switch 5796 // back to the system partition version. 5797 // At this point, its safely assumed that package installation for 5798 // apps in system partition will go through. If not there won't be a working 5799 // version of the app 5800 // writer 5801 synchronized (mPackages) { 5802 // Just remove the loaded entries from package lists. 5803 mPackages.remove(ps.name); 5804 } 5805 5806 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5807 + " reverting from " + ps.codePathString 5808 + ": new version " + pkg.mVersionCode 5809 + " better than installed " + ps.versionCode); 5810 5811 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5812 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5813 synchronized (mInstallLock) { 5814 args.cleanUpResourcesLI(); 5815 } 5816 synchronized (mPackages) { 5817 mSettings.enableSystemPackageLPw(ps.name); 5818 } 5819 updatedPkgBetter = true; 5820 } 5821 } 5822 } 5823 5824 if (updatedPkg != null) { 5825 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5826 // initially 5827 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5828 5829 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5830 // flag set initially 5831 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5832 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5833 } 5834 } 5835 5836 // Verify certificates against what was last scanned 5837 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5838 5839 /* 5840 * A new system app appeared, but we already had a non-system one of the 5841 * same name installed earlier. 5842 */ 5843 boolean shouldHideSystemApp = false; 5844 if (updatedPkg == null && ps != null 5845 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5846 /* 5847 * Check to make sure the signatures match first. If they don't, 5848 * wipe the installed application and its data. 5849 */ 5850 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5851 != PackageManager.SIGNATURE_MATCH) { 5852 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5853 + " signatures don't match existing userdata copy; removing"); 5854 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5855 ps = null; 5856 } else { 5857 /* 5858 * If the newly-added system app is an older version than the 5859 * already installed version, hide it. It will be scanned later 5860 * and re-added like an update. 5861 */ 5862 if (pkg.mVersionCode <= ps.versionCode) { 5863 shouldHideSystemApp = true; 5864 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5865 + " but new version " + pkg.mVersionCode + " better than installed " 5866 + ps.versionCode + "; hiding system"); 5867 } else { 5868 /* 5869 * The newly found system app is a newer version that the 5870 * one previously installed. Simply remove the 5871 * already-installed application and replace it with our own 5872 * while keeping the application data. 5873 */ 5874 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5875 + " reverting from " + ps.codePathString + ": new version " 5876 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5877 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5878 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5879 synchronized (mInstallLock) { 5880 args.cleanUpResourcesLI(); 5881 } 5882 } 5883 } 5884 } 5885 5886 // The apk is forward locked (not public) if its code and resources 5887 // are kept in different files. (except for app in either system or 5888 // vendor path). 5889 // TODO grab this value from PackageSettings 5890 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5891 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5892 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5893 } 5894 } 5895 5896 // TODO: extend to support forward-locked splits 5897 String resourcePath = null; 5898 String baseResourcePath = null; 5899 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5900 if (ps != null && ps.resourcePathString != null) { 5901 resourcePath = ps.resourcePathString; 5902 baseResourcePath = ps.resourcePathString; 5903 } else { 5904 // Should not happen at all. Just log an error. 5905 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5906 } 5907 } else { 5908 resourcePath = pkg.codePath; 5909 baseResourcePath = pkg.baseCodePath; 5910 } 5911 5912 // Set application objects path explicitly. 5913 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5914 pkg.applicationInfo.setCodePath(pkg.codePath); 5915 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5916 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5917 pkg.applicationInfo.setResourcePath(resourcePath); 5918 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5919 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5920 5921 // Note that we invoke the following method only if we are about to unpack an application 5922 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5923 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5924 5925 /* 5926 * If the system app should be overridden by a previously installed 5927 * data, hide the system app now and let the /data/app scan pick it up 5928 * again. 5929 */ 5930 if (shouldHideSystemApp) { 5931 synchronized (mPackages) { 5932 /* 5933 * We have to grant systems permissions before we hide, because 5934 * grantPermissions will assume the package update is trying to 5935 * expand its permissions. 5936 */ 5937 grantPermissionsLPw(pkg, true, pkg.packageName); 5938 mSettings.disableSystemPackageLPw(pkg.packageName); 5939 } 5940 } 5941 5942 return scannedPkg; 5943 } 5944 5945 private static String fixProcessName(String defProcessName, 5946 String processName, int uid) { 5947 if (processName == null) { 5948 return defProcessName; 5949 } 5950 return processName; 5951 } 5952 5953 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5954 throws PackageManagerException { 5955 if (pkgSetting.signatures.mSignatures != null) { 5956 // Already existing package. Make sure signatures match 5957 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5958 == PackageManager.SIGNATURE_MATCH; 5959 if (!match) { 5960 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5961 == PackageManager.SIGNATURE_MATCH; 5962 } 5963 if (!match) { 5964 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5965 == PackageManager.SIGNATURE_MATCH; 5966 } 5967 if (!match) { 5968 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5969 + pkg.packageName + " signatures do not match the " 5970 + "previously installed version; ignoring!"); 5971 } 5972 } 5973 5974 // Check for shared user signatures 5975 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5976 // Already existing package. Make sure signatures match 5977 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5978 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5979 if (!match) { 5980 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5981 == PackageManager.SIGNATURE_MATCH; 5982 } 5983 if (!match) { 5984 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5985 == PackageManager.SIGNATURE_MATCH; 5986 } 5987 if (!match) { 5988 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5989 "Package " + pkg.packageName 5990 + " has no signatures that match those in shared user " 5991 + pkgSetting.sharedUser.name + "; ignoring!"); 5992 } 5993 } 5994 } 5995 5996 /** 5997 * Enforces that only the system UID or root's UID can call a method exposed 5998 * via Binder. 5999 * 6000 * @param message used as message if SecurityException is thrown 6001 * @throws SecurityException if the caller is not system or root 6002 */ 6003 private static final void enforceSystemOrRoot(String message) { 6004 final int uid = Binder.getCallingUid(); 6005 if (uid != Process.SYSTEM_UID && uid != 0) { 6006 throw new SecurityException(message); 6007 } 6008 } 6009 6010 @Override 6011 public void performBootDexOpt() { 6012 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6013 6014 // Before everything else, see whether we need to fstrim. 6015 try { 6016 IMountService ms = PackageHelper.getMountService(); 6017 if (ms != null) { 6018 final boolean isUpgrade = isUpgrade(); 6019 boolean doTrim = isUpgrade; 6020 if (doTrim) { 6021 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6022 } else { 6023 final long interval = android.provider.Settings.Global.getLong( 6024 mContext.getContentResolver(), 6025 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6026 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6027 if (interval > 0) { 6028 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6029 if (timeSinceLast > interval) { 6030 doTrim = true; 6031 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6032 + "; running immediately"); 6033 } 6034 } 6035 } 6036 if (doTrim) { 6037 if (!isFirstBoot()) { 6038 try { 6039 ActivityManagerNative.getDefault().showBootMessage( 6040 mContext.getResources().getString( 6041 R.string.android_upgrading_fstrim), true); 6042 } catch (RemoteException e) { 6043 } 6044 } 6045 ms.runMaintenance(); 6046 } 6047 } else { 6048 Slog.e(TAG, "Mount service unavailable!"); 6049 } 6050 } catch (RemoteException e) { 6051 // Can't happen; MountService is local 6052 } 6053 6054 final ArraySet<PackageParser.Package> pkgs; 6055 synchronized (mPackages) { 6056 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6057 } 6058 6059 if (pkgs != null) { 6060 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6061 // in case the device runs out of space. 6062 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6063 // Give priority to core apps. 6064 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6065 PackageParser.Package pkg = it.next(); 6066 if (pkg.coreApp) { 6067 if (DEBUG_DEXOPT) { 6068 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6069 } 6070 sortedPkgs.add(pkg); 6071 it.remove(); 6072 } 6073 } 6074 // Give priority to system apps that listen for pre boot complete. 6075 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6076 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6077 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6078 PackageParser.Package pkg = it.next(); 6079 if (pkgNames.contains(pkg.packageName)) { 6080 if (DEBUG_DEXOPT) { 6081 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6082 } 6083 sortedPkgs.add(pkg); 6084 it.remove(); 6085 } 6086 } 6087 // Give priority to system apps. 6088 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6089 PackageParser.Package pkg = it.next(); 6090 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6091 if (DEBUG_DEXOPT) { 6092 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6093 } 6094 sortedPkgs.add(pkg); 6095 it.remove(); 6096 } 6097 } 6098 // Give priority to updated system apps. 6099 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6100 PackageParser.Package pkg = it.next(); 6101 if (pkg.isUpdatedSystemApp()) { 6102 if (DEBUG_DEXOPT) { 6103 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6104 } 6105 sortedPkgs.add(pkg); 6106 it.remove(); 6107 } 6108 } 6109 // Give priority to apps that listen for boot complete. 6110 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6111 pkgNames = getPackageNamesForIntent(intent); 6112 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6113 PackageParser.Package pkg = it.next(); 6114 if (pkgNames.contains(pkg.packageName)) { 6115 if (DEBUG_DEXOPT) { 6116 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6117 } 6118 sortedPkgs.add(pkg); 6119 it.remove(); 6120 } 6121 } 6122 // Filter out packages that aren't recently used. 6123 filterRecentlyUsedApps(pkgs); 6124 // Add all remaining apps. 6125 for (PackageParser.Package pkg : pkgs) { 6126 if (DEBUG_DEXOPT) { 6127 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6128 } 6129 sortedPkgs.add(pkg); 6130 } 6131 6132 // If we want to be lazy, filter everything that wasn't recently used. 6133 if (mLazyDexOpt) { 6134 filterRecentlyUsedApps(sortedPkgs); 6135 } 6136 6137 int i = 0; 6138 int total = sortedPkgs.size(); 6139 File dataDir = Environment.getDataDirectory(); 6140 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6141 if (lowThreshold == 0) { 6142 throw new IllegalStateException("Invalid low memory threshold"); 6143 } 6144 for (PackageParser.Package pkg : sortedPkgs) { 6145 long usableSpace = dataDir.getUsableSpace(); 6146 if (usableSpace < lowThreshold) { 6147 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6148 break; 6149 } 6150 performBootDexOpt(pkg, ++i, total); 6151 } 6152 } 6153 } 6154 6155 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6156 // Filter out packages that aren't recently used. 6157 // 6158 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6159 // should do a full dexopt. 6160 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6161 int total = pkgs.size(); 6162 int skipped = 0; 6163 long now = System.currentTimeMillis(); 6164 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6165 PackageParser.Package pkg = i.next(); 6166 long then = pkg.mLastPackageUsageTimeInMills; 6167 if (then + mDexOptLRUThresholdInMills < now) { 6168 if (DEBUG_DEXOPT) { 6169 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6170 ((then == 0) ? "never" : new Date(then))); 6171 } 6172 i.remove(); 6173 skipped++; 6174 } 6175 } 6176 if (DEBUG_DEXOPT) { 6177 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6178 } 6179 } 6180 } 6181 6182 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6183 List<ResolveInfo> ris = null; 6184 try { 6185 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6186 intent, null, 0, UserHandle.USER_OWNER); 6187 } catch (RemoteException e) { 6188 } 6189 ArraySet<String> pkgNames = new ArraySet<String>(); 6190 if (ris != null) { 6191 for (ResolveInfo ri : ris) { 6192 pkgNames.add(ri.activityInfo.packageName); 6193 } 6194 } 6195 return pkgNames; 6196 } 6197 6198 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6199 if (DEBUG_DEXOPT) { 6200 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6201 } 6202 if (!isFirstBoot()) { 6203 try { 6204 ActivityManagerNative.getDefault().showBootMessage( 6205 mContext.getResources().getString(R.string.android_upgrading_apk, 6206 curr, total), true); 6207 } catch (RemoteException e) { 6208 } 6209 } 6210 PackageParser.Package p = pkg; 6211 synchronized (mInstallLock) { 6212 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6213 false /* force dex */, false /* defer */, true /* include dependencies */); 6214 } 6215 } 6216 6217 @Override 6218 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6219 return performDexOpt(packageName, instructionSet, false); 6220 } 6221 6222 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6223 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6224 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6225 if (!dexopt && !updateUsage) { 6226 // We aren't going to dexopt or update usage, so bail early. 6227 return false; 6228 } 6229 PackageParser.Package p; 6230 final String targetInstructionSet; 6231 synchronized (mPackages) { 6232 p = mPackages.get(packageName); 6233 if (p == null) { 6234 return false; 6235 } 6236 if (updateUsage) { 6237 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6238 } 6239 mPackageUsage.write(false); 6240 if (!dexopt) { 6241 // We aren't going to dexopt, so bail early. 6242 return false; 6243 } 6244 6245 targetInstructionSet = instructionSet != null ? instructionSet : 6246 getPrimaryInstructionSet(p.applicationInfo); 6247 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6248 return false; 6249 } 6250 } 6251 long callingId = Binder.clearCallingIdentity(); 6252 try { 6253 synchronized (mInstallLock) { 6254 final String[] instructionSets = new String[] { targetInstructionSet }; 6255 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6256 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6257 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6258 } 6259 } finally { 6260 Binder.restoreCallingIdentity(callingId); 6261 } 6262 } 6263 6264 public ArraySet<String> getPackagesThatNeedDexOpt() { 6265 ArraySet<String> pkgs = null; 6266 synchronized (mPackages) { 6267 for (PackageParser.Package p : mPackages.values()) { 6268 if (DEBUG_DEXOPT) { 6269 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6270 } 6271 if (!p.mDexOptPerformed.isEmpty()) { 6272 continue; 6273 } 6274 if (pkgs == null) { 6275 pkgs = new ArraySet<String>(); 6276 } 6277 pkgs.add(p.packageName); 6278 } 6279 } 6280 return pkgs; 6281 } 6282 6283 public void shutdown() { 6284 mPackageUsage.write(true); 6285 } 6286 6287 @Override 6288 public void forceDexOpt(String packageName) { 6289 enforceSystemOrRoot("forceDexOpt"); 6290 6291 PackageParser.Package pkg; 6292 synchronized (mPackages) { 6293 pkg = mPackages.get(packageName); 6294 if (pkg == null) { 6295 throw new IllegalArgumentException("Missing package: " + packageName); 6296 } 6297 } 6298 6299 synchronized (mInstallLock) { 6300 final String[] instructionSets = new String[] { 6301 getPrimaryInstructionSet(pkg.applicationInfo) }; 6302 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6303 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6304 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6305 throw new IllegalStateException("Failed to dexopt: " + res); 6306 } 6307 } 6308 } 6309 6310 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6311 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6312 Slog.w(TAG, "Unable to update from " + oldPkg.name 6313 + " to " + newPkg.packageName 6314 + ": old package not in system partition"); 6315 return false; 6316 } else if (mPackages.get(oldPkg.name) != null) { 6317 Slog.w(TAG, "Unable to update from " + oldPkg.name 6318 + " to " + newPkg.packageName 6319 + ": old package still exists"); 6320 return false; 6321 } 6322 return true; 6323 } 6324 6325 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6326 int[] users = sUserManager.getUserIds(); 6327 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6328 if (res < 0) { 6329 return res; 6330 } 6331 for (int user : users) { 6332 if (user != 0) { 6333 res = mInstaller.createUserData(volumeUuid, packageName, 6334 UserHandle.getUid(user, uid), user, seinfo); 6335 if (res < 0) { 6336 return res; 6337 } 6338 } 6339 } 6340 return res; 6341 } 6342 6343 private int removeDataDirsLI(String volumeUuid, String packageName) { 6344 int[] users = sUserManager.getUserIds(); 6345 int res = 0; 6346 for (int user : users) { 6347 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6348 if (resInner < 0) { 6349 res = resInner; 6350 } 6351 } 6352 6353 return res; 6354 } 6355 6356 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6357 int[] users = sUserManager.getUserIds(); 6358 int res = 0; 6359 for (int user : users) { 6360 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6361 if (resInner < 0) { 6362 res = resInner; 6363 } 6364 } 6365 return res; 6366 } 6367 6368 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6369 PackageParser.Package changingLib) { 6370 if (file.path != null) { 6371 usesLibraryFiles.add(file.path); 6372 return; 6373 } 6374 PackageParser.Package p = mPackages.get(file.apk); 6375 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6376 // If we are doing this while in the middle of updating a library apk, 6377 // then we need to make sure to use that new apk for determining the 6378 // dependencies here. (We haven't yet finished committing the new apk 6379 // to the package manager state.) 6380 if (p == null || p.packageName.equals(changingLib.packageName)) { 6381 p = changingLib; 6382 } 6383 } 6384 if (p != null) { 6385 usesLibraryFiles.addAll(p.getAllCodePaths()); 6386 } 6387 } 6388 6389 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6390 PackageParser.Package changingLib) throws PackageManagerException { 6391 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6392 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6393 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6394 for (int i=0; i<N; i++) { 6395 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6396 if (file == null) { 6397 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6398 "Package " + pkg.packageName + " requires unavailable shared library " 6399 + pkg.usesLibraries.get(i) + "; failing!"); 6400 } 6401 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6402 } 6403 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6404 for (int i=0; i<N; i++) { 6405 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6406 if (file == null) { 6407 Slog.w(TAG, "Package " + pkg.packageName 6408 + " desires unavailable shared library " 6409 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6410 } else { 6411 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6412 } 6413 } 6414 N = usesLibraryFiles.size(); 6415 if (N > 0) { 6416 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6417 } else { 6418 pkg.usesLibraryFiles = null; 6419 } 6420 } 6421 } 6422 6423 private static boolean hasString(List<String> list, List<String> which) { 6424 if (list == null) { 6425 return false; 6426 } 6427 for (int i=list.size()-1; i>=0; i--) { 6428 for (int j=which.size()-1; j>=0; j--) { 6429 if (which.get(j).equals(list.get(i))) { 6430 return true; 6431 } 6432 } 6433 } 6434 return false; 6435 } 6436 6437 private void updateAllSharedLibrariesLPw() { 6438 for (PackageParser.Package pkg : mPackages.values()) { 6439 try { 6440 updateSharedLibrariesLPw(pkg, null); 6441 } catch (PackageManagerException e) { 6442 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6443 } 6444 } 6445 } 6446 6447 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6448 PackageParser.Package changingPkg) { 6449 ArrayList<PackageParser.Package> res = null; 6450 for (PackageParser.Package pkg : mPackages.values()) { 6451 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6452 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6453 if (res == null) { 6454 res = new ArrayList<PackageParser.Package>(); 6455 } 6456 res.add(pkg); 6457 try { 6458 updateSharedLibrariesLPw(pkg, changingPkg); 6459 } catch (PackageManagerException e) { 6460 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6461 } 6462 } 6463 } 6464 return res; 6465 } 6466 6467 /** 6468 * Derive the value of the {@code cpuAbiOverride} based on the provided 6469 * value and an optional stored value from the package settings. 6470 */ 6471 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6472 String cpuAbiOverride = null; 6473 6474 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6475 cpuAbiOverride = null; 6476 } else if (abiOverride != null) { 6477 cpuAbiOverride = abiOverride; 6478 } else if (settings != null) { 6479 cpuAbiOverride = settings.cpuAbiOverrideString; 6480 } 6481 6482 return cpuAbiOverride; 6483 } 6484 6485 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6486 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6487 boolean success = false; 6488 try { 6489 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6490 currentTime, user); 6491 success = true; 6492 return res; 6493 } finally { 6494 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6495 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6496 } 6497 } 6498 } 6499 6500 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6501 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6502 final File scanFile = new File(pkg.codePath); 6503 if (pkg.applicationInfo.getCodePath() == null || 6504 pkg.applicationInfo.getResourcePath() == null) { 6505 // Bail out. The resource and code paths haven't been set. 6506 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6507 "Code and resource paths haven't been set correctly"); 6508 } 6509 6510 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6511 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6512 } else { 6513 // Only allow system apps to be flagged as core apps. 6514 pkg.coreApp = false; 6515 } 6516 6517 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6518 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6519 } 6520 6521 if (mCustomResolverComponentName != null && 6522 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6523 setUpCustomResolverActivity(pkg); 6524 } 6525 6526 if (pkg.packageName.equals("android")) { 6527 synchronized (mPackages) { 6528 if (mAndroidApplication != null) { 6529 Slog.w(TAG, "*************************************************"); 6530 Slog.w(TAG, "Core android package being redefined. Skipping."); 6531 Slog.w(TAG, " file=" + scanFile); 6532 Slog.w(TAG, "*************************************************"); 6533 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6534 "Core android package being redefined. Skipping."); 6535 } 6536 6537 // Set up information for our fall-back user intent resolution activity. 6538 mPlatformPackage = pkg; 6539 pkg.mVersionCode = mSdkVersion; 6540 mAndroidApplication = pkg.applicationInfo; 6541 6542 if (!mResolverReplaced) { 6543 mResolveActivity.applicationInfo = mAndroidApplication; 6544 mResolveActivity.name = ResolverActivity.class.getName(); 6545 mResolveActivity.packageName = mAndroidApplication.packageName; 6546 mResolveActivity.processName = "system:ui"; 6547 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6548 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6549 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6550 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6551 mResolveActivity.exported = true; 6552 mResolveActivity.enabled = true; 6553 mResolveInfo.activityInfo = mResolveActivity; 6554 mResolveInfo.priority = 0; 6555 mResolveInfo.preferredOrder = 0; 6556 mResolveInfo.match = 0; 6557 mResolveComponentName = new ComponentName( 6558 mAndroidApplication.packageName, mResolveActivity.name); 6559 } 6560 } 6561 } 6562 6563 if (DEBUG_PACKAGE_SCANNING) { 6564 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6565 Log.d(TAG, "Scanning package " + pkg.packageName); 6566 } 6567 6568 if (mPackages.containsKey(pkg.packageName) 6569 || mSharedLibraries.containsKey(pkg.packageName)) { 6570 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6571 "Application package " + pkg.packageName 6572 + " already installed. Skipping duplicate."); 6573 } 6574 6575 // If we're only installing presumed-existing packages, require that the 6576 // scanned APK is both already known and at the path previously established 6577 // for it. Previously unknown packages we pick up normally, but if we have an 6578 // a priori expectation about this package's install presence, enforce it. 6579 // With a singular exception for new system packages. When an OTA contains 6580 // a new system package, we allow the codepath to change from a system location 6581 // to the user-installed location. If we don't allow this change, any newer, 6582 // user-installed version of the application will be ignored. 6583 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6584 if (mExpectingBetter.containsKey(pkg.packageName)) { 6585 logCriticalInfo(Log.WARN, 6586 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6587 } else { 6588 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6589 if (known != null) { 6590 if (DEBUG_PACKAGE_SCANNING) { 6591 Log.d(TAG, "Examining " + pkg.codePath 6592 + " and requiring known paths " + known.codePathString 6593 + " & " + known.resourcePathString); 6594 } 6595 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6596 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6597 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6598 "Application package " + pkg.packageName 6599 + " found at " + pkg.applicationInfo.getCodePath() 6600 + " but expected at " + known.codePathString + "; ignoring."); 6601 } 6602 } 6603 } 6604 } 6605 6606 // Initialize package source and resource directories 6607 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6608 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6609 6610 SharedUserSetting suid = null; 6611 PackageSetting pkgSetting = null; 6612 6613 if (!isSystemApp(pkg)) { 6614 // Only system apps can use these features. 6615 pkg.mOriginalPackages = null; 6616 pkg.mRealPackage = null; 6617 pkg.mAdoptPermissions = null; 6618 } 6619 6620 // writer 6621 synchronized (mPackages) { 6622 if (pkg.mSharedUserId != null) { 6623 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6624 if (suid == null) { 6625 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6626 "Creating application package " + pkg.packageName 6627 + " for shared user failed"); 6628 } 6629 if (DEBUG_PACKAGE_SCANNING) { 6630 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6631 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6632 + "): packages=" + suid.packages); 6633 } 6634 } 6635 6636 // Check if we are renaming from an original package name. 6637 PackageSetting origPackage = null; 6638 String realName = null; 6639 if (pkg.mOriginalPackages != null) { 6640 // This package may need to be renamed to a previously 6641 // installed name. Let's check on that... 6642 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6643 if (pkg.mOriginalPackages.contains(renamed)) { 6644 // This package had originally been installed as the 6645 // original name, and we have already taken care of 6646 // transitioning to the new one. Just update the new 6647 // one to continue using the old name. 6648 realName = pkg.mRealPackage; 6649 if (!pkg.packageName.equals(renamed)) { 6650 // Callers into this function may have already taken 6651 // care of renaming the package; only do it here if 6652 // it is not already done. 6653 pkg.setPackageName(renamed); 6654 } 6655 6656 } else { 6657 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6658 if ((origPackage = mSettings.peekPackageLPr( 6659 pkg.mOriginalPackages.get(i))) != null) { 6660 // We do have the package already installed under its 6661 // original name... should we use it? 6662 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6663 // New package is not compatible with original. 6664 origPackage = null; 6665 continue; 6666 } else if (origPackage.sharedUser != null) { 6667 // Make sure uid is compatible between packages. 6668 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6669 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6670 + " to " + pkg.packageName + ": old uid " 6671 + origPackage.sharedUser.name 6672 + " differs from " + pkg.mSharedUserId); 6673 origPackage = null; 6674 continue; 6675 } 6676 } else { 6677 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6678 + pkg.packageName + " to old name " + origPackage.name); 6679 } 6680 break; 6681 } 6682 } 6683 } 6684 } 6685 6686 if (mTransferedPackages.contains(pkg.packageName)) { 6687 Slog.w(TAG, "Package " + pkg.packageName 6688 + " was transferred to another, but its .apk remains"); 6689 } 6690 6691 // Just create the setting, don't add it yet. For already existing packages 6692 // the PkgSetting exists already and doesn't have to be created. 6693 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6694 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6695 pkg.applicationInfo.primaryCpuAbi, 6696 pkg.applicationInfo.secondaryCpuAbi, 6697 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6698 user, false); 6699 if (pkgSetting == null) { 6700 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6701 "Creating application package " + pkg.packageName + " failed"); 6702 } 6703 6704 if (pkgSetting.origPackage != null) { 6705 // If we are first transitioning from an original package, 6706 // fix up the new package's name now. We need to do this after 6707 // looking up the package under its new name, so getPackageLP 6708 // can take care of fiddling things correctly. 6709 pkg.setPackageName(origPackage.name); 6710 6711 // File a report about this. 6712 String msg = "New package " + pkgSetting.realName 6713 + " renamed to replace old package " + pkgSetting.name; 6714 reportSettingsProblem(Log.WARN, msg); 6715 6716 // Make a note of it. 6717 mTransferedPackages.add(origPackage.name); 6718 6719 // No longer need to retain this. 6720 pkgSetting.origPackage = null; 6721 } 6722 6723 if (realName != null) { 6724 // Make a note of it. 6725 mTransferedPackages.add(pkg.packageName); 6726 } 6727 6728 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6729 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6730 } 6731 6732 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6733 // Check all shared libraries and map to their actual file path. 6734 // We only do this here for apps not on a system dir, because those 6735 // are the only ones that can fail an install due to this. We 6736 // will take care of the system apps by updating all of their 6737 // library paths after the scan is done. 6738 updateSharedLibrariesLPw(pkg, null); 6739 } 6740 6741 if (mFoundPolicyFile) { 6742 SELinuxMMAC.assignSeinfoValue(pkg); 6743 } 6744 6745 pkg.applicationInfo.uid = pkgSetting.appId; 6746 pkg.mExtras = pkgSetting; 6747 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6748 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6749 // We just determined the app is signed correctly, so bring 6750 // over the latest parsed certs. 6751 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6752 } else { 6753 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6754 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6755 "Package " + pkg.packageName + " upgrade keys do not match the " 6756 + "previously installed version"); 6757 } else { 6758 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6759 String msg = "System package " + pkg.packageName 6760 + " signature changed; retaining data."; 6761 reportSettingsProblem(Log.WARN, msg); 6762 } 6763 } 6764 } else { 6765 try { 6766 verifySignaturesLP(pkgSetting, pkg); 6767 // We just determined the app is signed correctly, so bring 6768 // over the latest parsed certs. 6769 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6770 } catch (PackageManagerException e) { 6771 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6772 throw e; 6773 } 6774 // The signature has changed, but this package is in the system 6775 // image... let's recover! 6776 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6777 // However... if this package is part of a shared user, but it 6778 // doesn't match the signature of the shared user, let's fail. 6779 // What this means is that you can't change the signatures 6780 // associated with an overall shared user, which doesn't seem all 6781 // that unreasonable. 6782 if (pkgSetting.sharedUser != null) { 6783 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6784 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6785 throw new PackageManagerException( 6786 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6787 "Signature mismatch for shared user : " 6788 + pkgSetting.sharedUser); 6789 } 6790 } 6791 // File a report about this. 6792 String msg = "System package " + pkg.packageName 6793 + " signature changed; retaining data."; 6794 reportSettingsProblem(Log.WARN, msg); 6795 } 6796 } 6797 // Verify that this new package doesn't have any content providers 6798 // that conflict with existing packages. Only do this if the 6799 // package isn't already installed, since we don't want to break 6800 // things that are installed. 6801 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6802 final int N = pkg.providers.size(); 6803 int i; 6804 for (i=0; i<N; i++) { 6805 PackageParser.Provider p = pkg.providers.get(i); 6806 if (p.info.authority != null) { 6807 String names[] = p.info.authority.split(";"); 6808 for (int j = 0; j < names.length; j++) { 6809 if (mProvidersByAuthority.containsKey(names[j])) { 6810 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6811 final String otherPackageName = 6812 ((other != null && other.getComponentName() != null) ? 6813 other.getComponentName().getPackageName() : "?"); 6814 throw new PackageManagerException( 6815 INSTALL_FAILED_CONFLICTING_PROVIDER, 6816 "Can't install because provider name " + names[j] 6817 + " (in package " + pkg.applicationInfo.packageName 6818 + ") is already used by " + otherPackageName); 6819 } 6820 } 6821 } 6822 } 6823 } 6824 6825 if (pkg.mAdoptPermissions != null) { 6826 // This package wants to adopt ownership of permissions from 6827 // another package. 6828 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6829 final String origName = pkg.mAdoptPermissions.get(i); 6830 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6831 if (orig != null) { 6832 if (verifyPackageUpdateLPr(orig, pkg)) { 6833 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6834 + pkg.packageName); 6835 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6836 } 6837 } 6838 } 6839 } 6840 } 6841 6842 final String pkgName = pkg.packageName; 6843 6844 final long scanFileTime = scanFile.lastModified(); 6845 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6846 pkg.applicationInfo.processName = fixProcessName( 6847 pkg.applicationInfo.packageName, 6848 pkg.applicationInfo.processName, 6849 pkg.applicationInfo.uid); 6850 6851 File dataPath; 6852 if (mPlatformPackage == pkg) { 6853 // The system package is special. 6854 dataPath = new File(Environment.getDataDirectory(), "system"); 6855 6856 pkg.applicationInfo.dataDir = dataPath.getPath(); 6857 6858 } else { 6859 // This is a normal package, need to make its data directory. 6860 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6861 UserHandle.USER_OWNER, pkg.packageName); 6862 6863 boolean uidError = false; 6864 if (dataPath.exists()) { 6865 int currentUid = 0; 6866 try { 6867 StructStat stat = Os.stat(dataPath.getPath()); 6868 currentUid = stat.st_uid; 6869 } catch (ErrnoException e) { 6870 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6871 } 6872 6873 // If we have mismatched owners for the data path, we have a problem. 6874 if (currentUid != pkg.applicationInfo.uid) { 6875 boolean recovered = false; 6876 if (currentUid == 0) { 6877 // The directory somehow became owned by root. Wow. 6878 // This is probably because the system was stopped while 6879 // installd was in the middle of messing with its libs 6880 // directory. Ask installd to fix that. 6881 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6882 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6883 if (ret >= 0) { 6884 recovered = true; 6885 String msg = "Package " + pkg.packageName 6886 + " unexpectedly changed to uid 0; recovered to " + 6887 + pkg.applicationInfo.uid; 6888 reportSettingsProblem(Log.WARN, msg); 6889 } 6890 } 6891 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6892 || (scanFlags&SCAN_BOOTING) != 0)) { 6893 // If this is a system app, we can at least delete its 6894 // current data so the application will still work. 6895 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6896 if (ret >= 0) { 6897 // TODO: Kill the processes first 6898 // Old data gone! 6899 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6900 ? "System package " : "Third party package "; 6901 String msg = prefix + pkg.packageName 6902 + " has changed from uid: " 6903 + currentUid + " to " 6904 + pkg.applicationInfo.uid + "; old data erased"; 6905 reportSettingsProblem(Log.WARN, msg); 6906 recovered = true; 6907 6908 // And now re-install the app. 6909 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6910 pkg.applicationInfo.seinfo); 6911 if (ret == -1) { 6912 // Ack should not happen! 6913 msg = prefix + pkg.packageName 6914 + " could not have data directory re-created after delete."; 6915 reportSettingsProblem(Log.WARN, msg); 6916 throw new PackageManagerException( 6917 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6918 } 6919 } 6920 if (!recovered) { 6921 mHasSystemUidErrors = true; 6922 } 6923 } else if (!recovered) { 6924 // If we allow this install to proceed, we will be broken. 6925 // Abort, abort! 6926 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6927 "scanPackageLI"); 6928 } 6929 if (!recovered) { 6930 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6931 + pkg.applicationInfo.uid + "/fs_" 6932 + currentUid; 6933 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6934 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6935 String msg = "Package " + pkg.packageName 6936 + " has mismatched uid: " 6937 + currentUid + " on disk, " 6938 + pkg.applicationInfo.uid + " in settings"; 6939 // writer 6940 synchronized (mPackages) { 6941 mSettings.mReadMessages.append(msg); 6942 mSettings.mReadMessages.append('\n'); 6943 uidError = true; 6944 if (!pkgSetting.uidError) { 6945 reportSettingsProblem(Log.ERROR, msg); 6946 } 6947 } 6948 } 6949 } 6950 pkg.applicationInfo.dataDir = dataPath.getPath(); 6951 if (mShouldRestoreconData) { 6952 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6953 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6954 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6955 } 6956 } else { 6957 if (DEBUG_PACKAGE_SCANNING) { 6958 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6959 Log.v(TAG, "Want this data dir: " + dataPath); 6960 } 6961 //invoke installer to do the actual installation 6962 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6963 pkg.applicationInfo.seinfo); 6964 if (ret < 0) { 6965 // Error from installer 6966 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6967 "Unable to create data dirs [errorCode=" + ret + "]"); 6968 } 6969 6970 if (dataPath.exists()) { 6971 pkg.applicationInfo.dataDir = dataPath.getPath(); 6972 } else { 6973 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6974 pkg.applicationInfo.dataDir = null; 6975 } 6976 } 6977 6978 pkgSetting.uidError = uidError; 6979 } 6980 6981 final String path = scanFile.getPath(); 6982 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6983 6984 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6985 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6986 6987 // Some system apps still use directory structure for native libraries 6988 // in which case we might end up not detecting abi solely based on apk 6989 // structure. Try to detect abi based on directory structure. 6990 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6991 pkg.applicationInfo.primaryCpuAbi == null) { 6992 setBundledAppAbisAndRoots(pkg, pkgSetting); 6993 setNativeLibraryPaths(pkg); 6994 } 6995 6996 } else { 6997 if ((scanFlags & SCAN_MOVE) != 0) { 6998 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6999 // but we already have this packages package info in the PackageSetting. We just 7000 // use that and derive the native library path based on the new codepath. 7001 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7002 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7003 } 7004 7005 // Set native library paths again. For moves, the path will be updated based on the 7006 // ABIs we've determined above. For non-moves, the path will be updated based on the 7007 // ABIs we determined during compilation, but the path will depend on the final 7008 // package path (after the rename away from the stage path). 7009 setNativeLibraryPaths(pkg); 7010 } 7011 7012 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7013 final int[] userIds = sUserManager.getUserIds(); 7014 synchronized (mInstallLock) { 7015 // Make sure all user data directories are ready to roll; we're okay 7016 // if they already exist 7017 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7018 for (int userId : userIds) { 7019 if (userId != 0) { 7020 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7021 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7022 pkg.applicationInfo.seinfo); 7023 } 7024 } 7025 } 7026 7027 // Create a native library symlink only if we have native libraries 7028 // and if the native libraries are 32 bit libraries. We do not provide 7029 // this symlink for 64 bit libraries. 7030 if (pkg.applicationInfo.primaryCpuAbi != null && 7031 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7032 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7033 for (int userId : userIds) { 7034 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7035 nativeLibPath, userId) < 0) { 7036 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7037 "Failed linking native library dir (user=" + userId + ")"); 7038 } 7039 } 7040 } 7041 } 7042 7043 // This is a special case for the "system" package, where the ABI is 7044 // dictated by the zygote configuration (and init.rc). We should keep track 7045 // of this ABI so that we can deal with "normal" applications that run under 7046 // the same UID correctly. 7047 if (mPlatformPackage == pkg) { 7048 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7049 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7050 } 7051 7052 // If there's a mismatch between the abi-override in the package setting 7053 // and the abiOverride specified for the install. Warn about this because we 7054 // would've already compiled the app without taking the package setting into 7055 // account. 7056 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7057 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7058 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7059 " for package: " + pkg.packageName); 7060 } 7061 } 7062 7063 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7064 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7065 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7066 7067 // Copy the derived override back to the parsed package, so that we can 7068 // update the package settings accordingly. 7069 pkg.cpuAbiOverride = cpuAbiOverride; 7070 7071 if (DEBUG_ABI_SELECTION) { 7072 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7073 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7074 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7075 } 7076 7077 // Push the derived path down into PackageSettings so we know what to 7078 // clean up at uninstall time. 7079 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7080 7081 if (DEBUG_ABI_SELECTION) { 7082 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7083 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7084 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7085 } 7086 7087 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7088 // We don't do this here during boot because we can do it all 7089 // at once after scanning all existing packages. 7090 // 7091 // We also do this *before* we perform dexopt on this package, so that 7092 // we can avoid redundant dexopts, and also to make sure we've got the 7093 // code and package path correct. 7094 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7095 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7096 } 7097 7098 if ((scanFlags & SCAN_NO_DEX) == 0) { 7099 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7100 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7101 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7102 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7103 } 7104 } 7105 if (mFactoryTest && pkg.requestedPermissions.contains( 7106 android.Manifest.permission.FACTORY_TEST)) { 7107 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7108 } 7109 7110 ArrayList<PackageParser.Package> clientLibPkgs = null; 7111 7112 // writer 7113 synchronized (mPackages) { 7114 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7115 // Only system apps can add new shared libraries. 7116 if (pkg.libraryNames != null) { 7117 for (int i=0; i<pkg.libraryNames.size(); i++) { 7118 String name = pkg.libraryNames.get(i); 7119 boolean allowed = false; 7120 if (pkg.isUpdatedSystemApp()) { 7121 // New library entries can only be added through the 7122 // system image. This is important to get rid of a lot 7123 // of nasty edge cases: for example if we allowed a non- 7124 // system update of the app to add a library, then uninstalling 7125 // the update would make the library go away, and assumptions 7126 // we made such as through app install filtering would now 7127 // have allowed apps on the device which aren't compatible 7128 // with it. Better to just have the restriction here, be 7129 // conservative, and create many fewer cases that can negatively 7130 // impact the user experience. 7131 final PackageSetting sysPs = mSettings 7132 .getDisabledSystemPkgLPr(pkg.packageName); 7133 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7134 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7135 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7136 allowed = true; 7137 allowed = true; 7138 break; 7139 } 7140 } 7141 } 7142 } else { 7143 allowed = true; 7144 } 7145 if (allowed) { 7146 if (!mSharedLibraries.containsKey(name)) { 7147 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7148 } else if (!name.equals(pkg.packageName)) { 7149 Slog.w(TAG, "Package " + pkg.packageName + " library " 7150 + name + " already exists; skipping"); 7151 } 7152 } else { 7153 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7154 + name + " that is not declared on system image; skipping"); 7155 } 7156 } 7157 if ((scanFlags&SCAN_BOOTING) == 0) { 7158 // If we are not booting, we need to update any applications 7159 // that are clients of our shared library. If we are booting, 7160 // this will all be done once the scan is complete. 7161 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7162 } 7163 } 7164 } 7165 } 7166 7167 // We also need to dexopt any apps that are dependent on this library. Note that 7168 // if these fail, we should abort the install since installing the library will 7169 // result in some apps being broken. 7170 if (clientLibPkgs != null) { 7171 if ((scanFlags & SCAN_NO_DEX) == 0) { 7172 for (int i = 0; i < clientLibPkgs.size(); i++) { 7173 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7174 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7175 null /* instruction sets */, forceDex, 7176 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7177 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7178 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7179 "scanPackageLI failed to dexopt clientLibPkgs"); 7180 } 7181 } 7182 } 7183 } 7184 7185 // Request the ActivityManager to kill the process(only for existing packages) 7186 // so that we do not end up in a confused state while the user is still using the older 7187 // version of the application while the new one gets installed. 7188 if ((scanFlags & SCAN_REPLACING) != 0) { 7189 killApplication(pkg.applicationInfo.packageName, 7190 pkg.applicationInfo.uid, "replace pkg"); 7191 } 7192 7193 // Also need to kill any apps that are dependent on the library. 7194 if (clientLibPkgs != null) { 7195 for (int i=0; i<clientLibPkgs.size(); i++) { 7196 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7197 killApplication(clientPkg.applicationInfo.packageName, 7198 clientPkg.applicationInfo.uid, "update lib"); 7199 } 7200 } 7201 7202 // Make sure we're not adding any bogus keyset info 7203 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7204 ksms.assertScannedPackageValid(pkg); 7205 7206 // writer 7207 synchronized (mPackages) { 7208 // We don't expect installation to fail beyond this point 7209 7210 // Add the new setting to mSettings 7211 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7212 // Add the new setting to mPackages 7213 mPackages.put(pkg.applicationInfo.packageName, pkg); 7214 // Make sure we don't accidentally delete its data. 7215 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7216 while (iter.hasNext()) { 7217 PackageCleanItem item = iter.next(); 7218 if (pkgName.equals(item.packageName)) { 7219 iter.remove(); 7220 } 7221 } 7222 7223 // Take care of first install / last update times. 7224 if (currentTime != 0) { 7225 if (pkgSetting.firstInstallTime == 0) { 7226 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7227 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7228 pkgSetting.lastUpdateTime = currentTime; 7229 } 7230 } else if (pkgSetting.firstInstallTime == 0) { 7231 // We need *something*. Take time time stamp of the file. 7232 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7233 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7234 if (scanFileTime != pkgSetting.timeStamp) { 7235 // A package on the system image has changed; consider this 7236 // to be an update. 7237 pkgSetting.lastUpdateTime = scanFileTime; 7238 } 7239 } 7240 7241 // Add the package's KeySets to the global KeySetManagerService 7242 ksms.addScannedPackageLPw(pkg); 7243 7244 int N = pkg.providers.size(); 7245 StringBuilder r = null; 7246 int i; 7247 for (i=0; i<N; i++) { 7248 PackageParser.Provider p = pkg.providers.get(i); 7249 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7250 p.info.processName, pkg.applicationInfo.uid); 7251 mProviders.addProvider(p); 7252 p.syncable = p.info.isSyncable; 7253 if (p.info.authority != null) { 7254 String names[] = p.info.authority.split(";"); 7255 p.info.authority = null; 7256 for (int j = 0; j < names.length; j++) { 7257 if (j == 1 && p.syncable) { 7258 // We only want the first authority for a provider to possibly be 7259 // syncable, so if we already added this provider using a different 7260 // authority clear the syncable flag. We copy the provider before 7261 // changing it because the mProviders object contains a reference 7262 // to a provider that we don't want to change. 7263 // Only do this for the second authority since the resulting provider 7264 // object can be the same for all future authorities for this provider. 7265 p = new PackageParser.Provider(p); 7266 p.syncable = false; 7267 } 7268 if (!mProvidersByAuthority.containsKey(names[j])) { 7269 mProvidersByAuthority.put(names[j], p); 7270 if (p.info.authority == null) { 7271 p.info.authority = names[j]; 7272 } else { 7273 p.info.authority = p.info.authority + ";" + names[j]; 7274 } 7275 if (DEBUG_PACKAGE_SCANNING) { 7276 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7277 Log.d(TAG, "Registered content provider: " + names[j] 7278 + ", className = " + p.info.name + ", isSyncable = " 7279 + p.info.isSyncable); 7280 } 7281 } else { 7282 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7283 Slog.w(TAG, "Skipping provider name " + names[j] + 7284 " (in package " + pkg.applicationInfo.packageName + 7285 "): name already used by " 7286 + ((other != null && other.getComponentName() != null) 7287 ? other.getComponentName().getPackageName() : "?")); 7288 } 7289 } 7290 } 7291 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7292 if (r == null) { 7293 r = new StringBuilder(256); 7294 } else { 7295 r.append(' '); 7296 } 7297 r.append(p.info.name); 7298 } 7299 } 7300 if (r != null) { 7301 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7302 } 7303 7304 N = pkg.services.size(); 7305 r = null; 7306 for (i=0; i<N; i++) { 7307 PackageParser.Service s = pkg.services.get(i); 7308 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7309 s.info.processName, pkg.applicationInfo.uid); 7310 mServices.addService(s); 7311 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7312 if (r == null) { 7313 r = new StringBuilder(256); 7314 } else { 7315 r.append(' '); 7316 } 7317 r.append(s.info.name); 7318 } 7319 } 7320 if (r != null) { 7321 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7322 } 7323 7324 N = pkg.receivers.size(); 7325 r = null; 7326 for (i=0; i<N; i++) { 7327 PackageParser.Activity a = pkg.receivers.get(i); 7328 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7329 a.info.processName, pkg.applicationInfo.uid); 7330 mReceivers.addActivity(a, "receiver"); 7331 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7332 if (r == null) { 7333 r = new StringBuilder(256); 7334 } else { 7335 r.append(' '); 7336 } 7337 r.append(a.info.name); 7338 } 7339 } 7340 if (r != null) { 7341 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7342 } 7343 7344 N = pkg.activities.size(); 7345 r = null; 7346 for (i=0; i<N; i++) { 7347 PackageParser.Activity a = pkg.activities.get(i); 7348 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7349 a.info.processName, pkg.applicationInfo.uid); 7350 mActivities.addActivity(a, "activity"); 7351 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7352 if (r == null) { 7353 r = new StringBuilder(256); 7354 } else { 7355 r.append(' '); 7356 } 7357 r.append(a.info.name); 7358 } 7359 } 7360 if (r != null) { 7361 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7362 } 7363 7364 N = pkg.permissionGroups.size(); 7365 r = null; 7366 for (i=0; i<N; i++) { 7367 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7368 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7369 if (cur == null) { 7370 mPermissionGroups.put(pg.info.name, pg); 7371 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7372 if (r == null) { 7373 r = new StringBuilder(256); 7374 } else { 7375 r.append(' '); 7376 } 7377 r.append(pg.info.name); 7378 } 7379 } else { 7380 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7381 + pg.info.packageName + " ignored: original from " 7382 + cur.info.packageName); 7383 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7384 if (r == null) { 7385 r = new StringBuilder(256); 7386 } else { 7387 r.append(' '); 7388 } 7389 r.append("DUP:"); 7390 r.append(pg.info.name); 7391 } 7392 } 7393 } 7394 if (r != null) { 7395 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7396 } 7397 7398 N = pkg.permissions.size(); 7399 r = null; 7400 for (i=0; i<N; i++) { 7401 PackageParser.Permission p = pkg.permissions.get(i); 7402 7403 // Assume by default that we did not install this permission into the system. 7404 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7405 7406 // Now that permission groups have a special meaning, we ignore permission 7407 // groups for legacy apps to prevent unexpected behavior. In particular, 7408 // permissions for one app being granted to someone just becuase they happen 7409 // to be in a group defined by another app (before this had no implications). 7410 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7411 p.group = mPermissionGroups.get(p.info.group); 7412 // Warn for a permission in an unknown group. 7413 if (p.info.group != null && p.group == null) { 7414 Slog.w(TAG, "Permission " + p.info.name + " from package " 7415 + p.info.packageName + " in an unknown group " + p.info.group); 7416 } 7417 } 7418 7419 ArrayMap<String, BasePermission> permissionMap = 7420 p.tree ? mSettings.mPermissionTrees 7421 : mSettings.mPermissions; 7422 BasePermission bp = permissionMap.get(p.info.name); 7423 7424 // Allow system apps to redefine non-system permissions 7425 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7426 final boolean currentOwnerIsSystem = (bp.perm != null 7427 && isSystemApp(bp.perm.owner)); 7428 if (isSystemApp(p.owner)) { 7429 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7430 // It's a built-in permission and no owner, take ownership now 7431 bp.packageSetting = pkgSetting; 7432 bp.perm = p; 7433 bp.uid = pkg.applicationInfo.uid; 7434 bp.sourcePackage = p.info.packageName; 7435 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7436 } else if (!currentOwnerIsSystem) { 7437 String msg = "New decl " + p.owner + " of permission " 7438 + p.info.name + " is system; overriding " + bp.sourcePackage; 7439 reportSettingsProblem(Log.WARN, msg); 7440 bp = null; 7441 } 7442 } 7443 } 7444 7445 if (bp == null) { 7446 bp = new BasePermission(p.info.name, p.info.packageName, 7447 BasePermission.TYPE_NORMAL); 7448 permissionMap.put(p.info.name, bp); 7449 } 7450 7451 if (bp.perm == null) { 7452 if (bp.sourcePackage == null 7453 || bp.sourcePackage.equals(p.info.packageName)) { 7454 BasePermission tree = findPermissionTreeLP(p.info.name); 7455 if (tree == null 7456 || tree.sourcePackage.equals(p.info.packageName)) { 7457 bp.packageSetting = pkgSetting; 7458 bp.perm = p; 7459 bp.uid = pkg.applicationInfo.uid; 7460 bp.sourcePackage = p.info.packageName; 7461 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7462 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7463 if (r == null) { 7464 r = new StringBuilder(256); 7465 } else { 7466 r.append(' '); 7467 } 7468 r.append(p.info.name); 7469 } 7470 } else { 7471 Slog.w(TAG, "Permission " + p.info.name + " from package " 7472 + p.info.packageName + " ignored: base tree " 7473 + tree.name + " is from package " 7474 + tree.sourcePackage); 7475 } 7476 } else { 7477 Slog.w(TAG, "Permission " + p.info.name + " from package " 7478 + p.info.packageName + " ignored: original from " 7479 + bp.sourcePackage); 7480 } 7481 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7482 if (r == null) { 7483 r = new StringBuilder(256); 7484 } else { 7485 r.append(' '); 7486 } 7487 r.append("DUP:"); 7488 r.append(p.info.name); 7489 } 7490 if (bp.perm == p) { 7491 bp.protectionLevel = p.info.protectionLevel; 7492 } 7493 } 7494 7495 if (r != null) { 7496 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7497 } 7498 7499 N = pkg.instrumentation.size(); 7500 r = null; 7501 for (i=0; i<N; i++) { 7502 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7503 a.info.packageName = pkg.applicationInfo.packageName; 7504 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7505 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7506 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7507 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7508 a.info.dataDir = pkg.applicationInfo.dataDir; 7509 7510 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7511 // need other information about the application, like the ABI and what not ? 7512 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7513 mInstrumentation.put(a.getComponentName(), a); 7514 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7515 if (r == null) { 7516 r = new StringBuilder(256); 7517 } else { 7518 r.append(' '); 7519 } 7520 r.append(a.info.name); 7521 } 7522 } 7523 if (r != null) { 7524 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7525 } 7526 7527 if (pkg.protectedBroadcasts != null) { 7528 N = pkg.protectedBroadcasts.size(); 7529 for (i=0; i<N; i++) { 7530 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7531 } 7532 } 7533 7534 pkgSetting.setTimeStamp(scanFileTime); 7535 7536 // Create idmap files for pairs of (packages, overlay packages). 7537 // Note: "android", ie framework-res.apk, is handled by native layers. 7538 if (pkg.mOverlayTarget != null) { 7539 // This is an overlay package. 7540 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7541 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7542 mOverlays.put(pkg.mOverlayTarget, 7543 new ArrayMap<String, PackageParser.Package>()); 7544 } 7545 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7546 map.put(pkg.packageName, pkg); 7547 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7548 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7549 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7550 "scanPackageLI failed to createIdmap"); 7551 } 7552 } 7553 } else if (mOverlays.containsKey(pkg.packageName) && 7554 !pkg.packageName.equals("android")) { 7555 // This is a regular package, with one or more known overlay packages. 7556 createIdmapsForPackageLI(pkg); 7557 } 7558 } 7559 7560 return pkg; 7561 } 7562 7563 /** 7564 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7565 * is derived purely on the basis of the contents of {@code scanFile} and 7566 * {@code cpuAbiOverride}. 7567 * 7568 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7569 */ 7570 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7571 String cpuAbiOverride, boolean extractLibs) 7572 throws PackageManagerException { 7573 // TODO: We can probably be smarter about this stuff. For installed apps, 7574 // we can calculate this information at install time once and for all. For 7575 // system apps, we can probably assume that this information doesn't change 7576 // after the first boot scan. As things stand, we do lots of unnecessary work. 7577 7578 // Give ourselves some initial paths; we'll come back for another 7579 // pass once we've determined ABI below. 7580 setNativeLibraryPaths(pkg); 7581 7582 // We would never need to extract libs for forward-locked and external packages, 7583 // since the container service will do it for us. We shouldn't attempt to 7584 // extract libs from system app when it was not updated. 7585 if (pkg.isForwardLocked() || isExternal(pkg) || 7586 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7587 extractLibs = false; 7588 } 7589 7590 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7591 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7592 7593 NativeLibraryHelper.Handle handle = null; 7594 try { 7595 handle = NativeLibraryHelper.Handle.create(scanFile); 7596 // TODO(multiArch): This can be null for apps that didn't go through the 7597 // usual installation process. We can calculate it again, like we 7598 // do during install time. 7599 // 7600 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7601 // unnecessary. 7602 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7603 7604 // Null out the abis so that they can be recalculated. 7605 pkg.applicationInfo.primaryCpuAbi = null; 7606 pkg.applicationInfo.secondaryCpuAbi = null; 7607 if (isMultiArch(pkg.applicationInfo)) { 7608 // Warn if we've set an abiOverride for multi-lib packages.. 7609 // By definition, we need to copy both 32 and 64 bit libraries for 7610 // such packages. 7611 if (pkg.cpuAbiOverride != null 7612 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7613 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7614 } 7615 7616 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7617 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7618 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7619 if (extractLibs) { 7620 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7621 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7622 useIsaSpecificSubdirs); 7623 } else { 7624 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7625 } 7626 } 7627 7628 maybeThrowExceptionForMultiArchCopy( 7629 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7630 7631 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7632 if (extractLibs) { 7633 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7634 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7635 useIsaSpecificSubdirs); 7636 } else { 7637 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7638 } 7639 } 7640 7641 maybeThrowExceptionForMultiArchCopy( 7642 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7643 7644 if (abi64 >= 0) { 7645 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7646 } 7647 7648 if (abi32 >= 0) { 7649 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7650 if (abi64 >= 0) { 7651 pkg.applicationInfo.secondaryCpuAbi = abi; 7652 } else { 7653 pkg.applicationInfo.primaryCpuAbi = abi; 7654 } 7655 } 7656 } else { 7657 String[] abiList = (cpuAbiOverride != null) ? 7658 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7659 7660 // Enable gross and lame hacks for apps that are built with old 7661 // SDK tools. We must scan their APKs for renderscript bitcode and 7662 // not launch them if it's present. Don't bother checking on devices 7663 // that don't have 64 bit support. 7664 boolean needsRenderScriptOverride = false; 7665 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7666 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7667 abiList = Build.SUPPORTED_32_BIT_ABIS; 7668 needsRenderScriptOverride = true; 7669 } 7670 7671 final int copyRet; 7672 if (extractLibs) { 7673 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7674 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7675 } else { 7676 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7677 } 7678 7679 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7680 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7681 "Error unpackaging native libs for app, errorCode=" + copyRet); 7682 } 7683 7684 if (copyRet >= 0) { 7685 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7686 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7687 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7688 } else if (needsRenderScriptOverride) { 7689 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7690 } 7691 } 7692 } catch (IOException ioe) { 7693 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7694 } finally { 7695 IoUtils.closeQuietly(handle); 7696 } 7697 7698 // Now that we've calculated the ABIs and determined if it's an internal app, 7699 // we will go ahead and populate the nativeLibraryPath. 7700 setNativeLibraryPaths(pkg); 7701 } 7702 7703 /** 7704 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7705 * i.e, so that all packages can be run inside a single process if required. 7706 * 7707 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7708 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7709 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7710 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7711 * updating a package that belongs to a shared user. 7712 * 7713 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7714 * adds unnecessary complexity. 7715 */ 7716 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7717 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7718 String requiredInstructionSet = null; 7719 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7720 requiredInstructionSet = VMRuntime.getInstructionSet( 7721 scannedPackage.applicationInfo.primaryCpuAbi); 7722 } 7723 7724 PackageSetting requirer = null; 7725 for (PackageSetting ps : packagesForUser) { 7726 // If packagesForUser contains scannedPackage, we skip it. This will happen 7727 // when scannedPackage is an update of an existing package. Without this check, 7728 // we will never be able to change the ABI of any package belonging to a shared 7729 // user, even if it's compatible with other packages. 7730 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7731 if (ps.primaryCpuAbiString == null) { 7732 continue; 7733 } 7734 7735 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7736 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7737 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7738 // this but there's not much we can do. 7739 String errorMessage = "Instruction set mismatch, " 7740 + ((requirer == null) ? "[caller]" : requirer) 7741 + " requires " + requiredInstructionSet + " whereas " + ps 7742 + " requires " + instructionSet; 7743 Slog.w(TAG, errorMessage); 7744 } 7745 7746 if (requiredInstructionSet == null) { 7747 requiredInstructionSet = instructionSet; 7748 requirer = ps; 7749 } 7750 } 7751 } 7752 7753 if (requiredInstructionSet != null) { 7754 String adjustedAbi; 7755 if (requirer != null) { 7756 // requirer != null implies that either scannedPackage was null or that scannedPackage 7757 // did not require an ABI, in which case we have to adjust scannedPackage to match 7758 // the ABI of the set (which is the same as requirer's ABI) 7759 adjustedAbi = requirer.primaryCpuAbiString; 7760 if (scannedPackage != null) { 7761 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7762 } 7763 } else { 7764 // requirer == null implies that we're updating all ABIs in the set to 7765 // match scannedPackage. 7766 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7767 } 7768 7769 for (PackageSetting ps : packagesForUser) { 7770 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7771 if (ps.primaryCpuAbiString != null) { 7772 continue; 7773 } 7774 7775 ps.primaryCpuAbiString = adjustedAbi; 7776 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7777 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7778 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7779 7780 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7781 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7782 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7783 ps.primaryCpuAbiString = null; 7784 ps.pkg.applicationInfo.primaryCpuAbi = null; 7785 return; 7786 } else { 7787 mInstaller.rmdex(ps.codePathString, 7788 getDexCodeInstructionSet(getPreferredInstructionSet())); 7789 } 7790 } 7791 } 7792 } 7793 } 7794 } 7795 7796 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7797 synchronized (mPackages) { 7798 mResolverReplaced = true; 7799 // Set up information for custom user intent resolution activity. 7800 mResolveActivity.applicationInfo = pkg.applicationInfo; 7801 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7802 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7803 mResolveActivity.processName = pkg.applicationInfo.packageName; 7804 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7805 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7806 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7807 mResolveActivity.theme = 0; 7808 mResolveActivity.exported = true; 7809 mResolveActivity.enabled = true; 7810 mResolveInfo.activityInfo = mResolveActivity; 7811 mResolveInfo.priority = 0; 7812 mResolveInfo.preferredOrder = 0; 7813 mResolveInfo.match = 0; 7814 mResolveComponentName = mCustomResolverComponentName; 7815 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7816 mResolveComponentName); 7817 } 7818 } 7819 7820 private static String calculateBundledApkRoot(final String codePathString) { 7821 final File codePath = new File(codePathString); 7822 final File codeRoot; 7823 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7824 codeRoot = Environment.getRootDirectory(); 7825 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7826 codeRoot = Environment.getOemDirectory(); 7827 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7828 codeRoot = Environment.getVendorDirectory(); 7829 } else { 7830 // Unrecognized code path; take its top real segment as the apk root: 7831 // e.g. /something/app/blah.apk => /something 7832 try { 7833 File f = codePath.getCanonicalFile(); 7834 File parent = f.getParentFile(); // non-null because codePath is a file 7835 File tmp; 7836 while ((tmp = parent.getParentFile()) != null) { 7837 f = parent; 7838 parent = tmp; 7839 } 7840 codeRoot = f; 7841 Slog.w(TAG, "Unrecognized code path " 7842 + codePath + " - using " + codeRoot); 7843 } catch (IOException e) { 7844 // Can't canonicalize the code path -- shenanigans? 7845 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7846 return Environment.getRootDirectory().getPath(); 7847 } 7848 } 7849 return codeRoot.getPath(); 7850 } 7851 7852 /** 7853 * Derive and set the location of native libraries for the given package, 7854 * which varies depending on where and how the package was installed. 7855 */ 7856 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7857 final ApplicationInfo info = pkg.applicationInfo; 7858 final String codePath = pkg.codePath; 7859 final File codeFile = new File(codePath); 7860 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7861 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7862 7863 info.nativeLibraryRootDir = null; 7864 info.nativeLibraryRootRequiresIsa = false; 7865 info.nativeLibraryDir = null; 7866 info.secondaryNativeLibraryDir = null; 7867 7868 if (isApkFile(codeFile)) { 7869 // Monolithic install 7870 if (bundledApp) { 7871 // If "/system/lib64/apkname" exists, assume that is the per-package 7872 // native library directory to use; otherwise use "/system/lib/apkname". 7873 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7874 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7875 getPrimaryInstructionSet(info)); 7876 7877 // This is a bundled system app so choose the path based on the ABI. 7878 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7879 // is just the default path. 7880 final String apkName = deriveCodePathName(codePath); 7881 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7882 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7883 apkName).getAbsolutePath(); 7884 7885 if (info.secondaryCpuAbi != null) { 7886 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7887 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7888 secondaryLibDir, apkName).getAbsolutePath(); 7889 } 7890 } else if (asecApp) { 7891 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7892 .getAbsolutePath(); 7893 } else { 7894 final String apkName = deriveCodePathName(codePath); 7895 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7896 .getAbsolutePath(); 7897 } 7898 7899 info.nativeLibraryRootRequiresIsa = false; 7900 info.nativeLibraryDir = info.nativeLibraryRootDir; 7901 } else { 7902 // Cluster install 7903 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7904 info.nativeLibraryRootRequiresIsa = true; 7905 7906 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7907 getPrimaryInstructionSet(info)).getAbsolutePath(); 7908 7909 if (info.secondaryCpuAbi != null) { 7910 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7911 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7912 } 7913 } 7914 } 7915 7916 /** 7917 * Calculate the abis and roots for a bundled app. These can uniquely 7918 * be determined from the contents of the system partition, i.e whether 7919 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7920 * of this information, and instead assume that the system was built 7921 * sensibly. 7922 */ 7923 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7924 PackageSetting pkgSetting) { 7925 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7926 7927 // If "/system/lib64/apkname" exists, assume that is the per-package 7928 // native library directory to use; otherwise use "/system/lib/apkname". 7929 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7930 setBundledAppAbi(pkg, apkRoot, apkName); 7931 // pkgSetting might be null during rescan following uninstall of updates 7932 // to a bundled app, so accommodate that possibility. The settings in 7933 // that case will be established later from the parsed package. 7934 // 7935 // If the settings aren't null, sync them up with what we've just derived. 7936 // note that apkRoot isn't stored in the package settings. 7937 if (pkgSetting != null) { 7938 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7939 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7940 } 7941 } 7942 7943 /** 7944 * Deduces the ABI of a bundled app and sets the relevant fields on the 7945 * parsed pkg object. 7946 * 7947 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7948 * under which system libraries are installed. 7949 * @param apkName the name of the installed package. 7950 */ 7951 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7952 final File codeFile = new File(pkg.codePath); 7953 7954 final boolean has64BitLibs; 7955 final boolean has32BitLibs; 7956 if (isApkFile(codeFile)) { 7957 // Monolithic install 7958 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7959 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7960 } else { 7961 // Cluster install 7962 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7963 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7964 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7965 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7966 has64BitLibs = (new File(rootDir, isa)).exists(); 7967 } else { 7968 has64BitLibs = false; 7969 } 7970 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7971 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7972 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7973 has32BitLibs = (new File(rootDir, isa)).exists(); 7974 } else { 7975 has32BitLibs = false; 7976 } 7977 } 7978 7979 if (has64BitLibs && !has32BitLibs) { 7980 // The package has 64 bit libs, but not 32 bit libs. Its primary 7981 // ABI should be 64 bit. We can safely assume here that the bundled 7982 // native libraries correspond to the most preferred ABI in the list. 7983 7984 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7985 pkg.applicationInfo.secondaryCpuAbi = null; 7986 } else if (has32BitLibs && !has64BitLibs) { 7987 // The package has 32 bit libs but not 64 bit libs. Its primary 7988 // ABI should be 32 bit. 7989 7990 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7991 pkg.applicationInfo.secondaryCpuAbi = null; 7992 } else if (has32BitLibs && has64BitLibs) { 7993 // The application has both 64 and 32 bit bundled libraries. We check 7994 // here that the app declares multiArch support, and warn if it doesn't. 7995 // 7996 // We will be lenient here and record both ABIs. The primary will be the 7997 // ABI that's higher on the list, i.e, a device that's configured to prefer 7998 // 64 bit apps will see a 64 bit primary ABI, 7999 8000 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8001 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8002 } 8003 8004 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8005 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8006 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8007 } else { 8008 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8009 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8010 } 8011 } else { 8012 pkg.applicationInfo.primaryCpuAbi = null; 8013 pkg.applicationInfo.secondaryCpuAbi = null; 8014 } 8015 } 8016 8017 private void killApplication(String pkgName, int appId, String reason) { 8018 // Request the ActivityManager to kill the process(only for existing packages) 8019 // so that we do not end up in a confused state while the user is still using the older 8020 // version of the application while the new one gets installed. 8021 IActivityManager am = ActivityManagerNative.getDefault(); 8022 if (am != null) { 8023 try { 8024 am.killApplicationWithAppId(pkgName, appId, reason); 8025 } catch (RemoteException e) { 8026 } 8027 } 8028 } 8029 8030 void removePackageLI(PackageSetting ps, boolean chatty) { 8031 if (DEBUG_INSTALL) { 8032 if (chatty) 8033 Log.d(TAG, "Removing package " + ps.name); 8034 } 8035 8036 // writer 8037 synchronized (mPackages) { 8038 mPackages.remove(ps.name); 8039 final PackageParser.Package pkg = ps.pkg; 8040 if (pkg != null) { 8041 cleanPackageDataStructuresLILPw(pkg, chatty); 8042 } 8043 } 8044 } 8045 8046 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8047 if (DEBUG_INSTALL) { 8048 if (chatty) 8049 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8050 } 8051 8052 // writer 8053 synchronized (mPackages) { 8054 mPackages.remove(pkg.applicationInfo.packageName); 8055 cleanPackageDataStructuresLILPw(pkg, chatty); 8056 } 8057 } 8058 8059 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8060 int N = pkg.providers.size(); 8061 StringBuilder r = null; 8062 int i; 8063 for (i=0; i<N; i++) { 8064 PackageParser.Provider p = pkg.providers.get(i); 8065 mProviders.removeProvider(p); 8066 if (p.info.authority == null) { 8067 8068 /* There was another ContentProvider with this authority when 8069 * this app was installed so this authority is null, 8070 * Ignore it as we don't have to unregister the provider. 8071 */ 8072 continue; 8073 } 8074 String names[] = p.info.authority.split(";"); 8075 for (int j = 0; j < names.length; j++) { 8076 if (mProvidersByAuthority.get(names[j]) == p) { 8077 mProvidersByAuthority.remove(names[j]); 8078 if (DEBUG_REMOVE) { 8079 if (chatty) 8080 Log.d(TAG, "Unregistered content provider: " + names[j] 8081 + ", className = " + p.info.name + ", isSyncable = " 8082 + p.info.isSyncable); 8083 } 8084 } 8085 } 8086 if (DEBUG_REMOVE && chatty) { 8087 if (r == null) { 8088 r = new StringBuilder(256); 8089 } else { 8090 r.append(' '); 8091 } 8092 r.append(p.info.name); 8093 } 8094 } 8095 if (r != null) { 8096 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8097 } 8098 8099 N = pkg.services.size(); 8100 r = null; 8101 for (i=0; i<N; i++) { 8102 PackageParser.Service s = pkg.services.get(i); 8103 mServices.removeService(s); 8104 if (chatty) { 8105 if (r == null) { 8106 r = new StringBuilder(256); 8107 } else { 8108 r.append(' '); 8109 } 8110 r.append(s.info.name); 8111 } 8112 } 8113 if (r != null) { 8114 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8115 } 8116 8117 N = pkg.receivers.size(); 8118 r = null; 8119 for (i=0; i<N; i++) { 8120 PackageParser.Activity a = pkg.receivers.get(i); 8121 mReceivers.removeActivity(a, "receiver"); 8122 if (DEBUG_REMOVE && chatty) { 8123 if (r == null) { 8124 r = new StringBuilder(256); 8125 } else { 8126 r.append(' '); 8127 } 8128 r.append(a.info.name); 8129 } 8130 } 8131 if (r != null) { 8132 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8133 } 8134 8135 N = pkg.activities.size(); 8136 r = null; 8137 for (i=0; i<N; i++) { 8138 PackageParser.Activity a = pkg.activities.get(i); 8139 mActivities.removeActivity(a, "activity"); 8140 if (DEBUG_REMOVE && chatty) { 8141 if (r == null) { 8142 r = new StringBuilder(256); 8143 } else { 8144 r.append(' '); 8145 } 8146 r.append(a.info.name); 8147 } 8148 } 8149 if (r != null) { 8150 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8151 } 8152 8153 N = pkg.permissions.size(); 8154 r = null; 8155 for (i=0; i<N; i++) { 8156 PackageParser.Permission p = pkg.permissions.get(i); 8157 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8158 if (bp == null) { 8159 bp = mSettings.mPermissionTrees.get(p.info.name); 8160 } 8161 if (bp != null && bp.perm == p) { 8162 bp.perm = null; 8163 if (DEBUG_REMOVE && chatty) { 8164 if (r == null) { 8165 r = new StringBuilder(256); 8166 } else { 8167 r.append(' '); 8168 } 8169 r.append(p.info.name); 8170 } 8171 } 8172 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8173 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8174 if (appOpPerms != null) { 8175 appOpPerms.remove(pkg.packageName); 8176 } 8177 } 8178 } 8179 if (r != null) { 8180 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8181 } 8182 8183 N = pkg.requestedPermissions.size(); 8184 r = null; 8185 for (i=0; i<N; i++) { 8186 String perm = pkg.requestedPermissions.get(i); 8187 BasePermission bp = mSettings.mPermissions.get(perm); 8188 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8189 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8190 if (appOpPerms != null) { 8191 appOpPerms.remove(pkg.packageName); 8192 if (appOpPerms.isEmpty()) { 8193 mAppOpPermissionPackages.remove(perm); 8194 } 8195 } 8196 } 8197 } 8198 if (r != null) { 8199 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8200 } 8201 8202 N = pkg.instrumentation.size(); 8203 r = null; 8204 for (i=0; i<N; i++) { 8205 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8206 mInstrumentation.remove(a.getComponentName()); 8207 if (DEBUG_REMOVE && chatty) { 8208 if (r == null) { 8209 r = new StringBuilder(256); 8210 } else { 8211 r.append(' '); 8212 } 8213 r.append(a.info.name); 8214 } 8215 } 8216 if (r != null) { 8217 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8218 } 8219 8220 r = null; 8221 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8222 // Only system apps can hold shared libraries. 8223 if (pkg.libraryNames != null) { 8224 for (i=0; i<pkg.libraryNames.size(); i++) { 8225 String name = pkg.libraryNames.get(i); 8226 SharedLibraryEntry cur = mSharedLibraries.get(name); 8227 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8228 mSharedLibraries.remove(name); 8229 if (DEBUG_REMOVE && chatty) { 8230 if (r == null) { 8231 r = new StringBuilder(256); 8232 } else { 8233 r.append(' '); 8234 } 8235 r.append(name); 8236 } 8237 } 8238 } 8239 } 8240 } 8241 if (r != null) { 8242 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8243 } 8244 } 8245 8246 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8247 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8248 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8249 return true; 8250 } 8251 } 8252 return false; 8253 } 8254 8255 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8256 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8257 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8258 8259 private void updatePermissionsLPw(String changingPkg, 8260 PackageParser.Package pkgInfo, int flags) { 8261 // Make sure there are no dangling permission trees. 8262 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8263 while (it.hasNext()) { 8264 final BasePermission bp = it.next(); 8265 if (bp.packageSetting == null) { 8266 // We may not yet have parsed the package, so just see if 8267 // we still know about its settings. 8268 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8269 } 8270 if (bp.packageSetting == null) { 8271 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8272 + " from package " + bp.sourcePackage); 8273 it.remove(); 8274 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8275 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8276 Slog.i(TAG, "Removing old permission tree: " + bp.name 8277 + " from package " + bp.sourcePackage); 8278 flags |= UPDATE_PERMISSIONS_ALL; 8279 it.remove(); 8280 } 8281 } 8282 } 8283 8284 // Make sure all dynamic permissions have been assigned to a package, 8285 // and make sure there are no dangling permissions. 8286 it = mSettings.mPermissions.values().iterator(); 8287 while (it.hasNext()) { 8288 final BasePermission bp = it.next(); 8289 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8290 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8291 + bp.name + " pkg=" + bp.sourcePackage 8292 + " info=" + bp.pendingInfo); 8293 if (bp.packageSetting == null && bp.pendingInfo != null) { 8294 final BasePermission tree = findPermissionTreeLP(bp.name); 8295 if (tree != null && tree.perm != null) { 8296 bp.packageSetting = tree.packageSetting; 8297 bp.perm = new PackageParser.Permission(tree.perm.owner, 8298 new PermissionInfo(bp.pendingInfo)); 8299 bp.perm.info.packageName = tree.perm.info.packageName; 8300 bp.perm.info.name = bp.name; 8301 bp.uid = tree.uid; 8302 } 8303 } 8304 } 8305 if (bp.packageSetting == null) { 8306 // We may not yet have parsed the package, so just see if 8307 // we still know about its settings. 8308 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8309 } 8310 if (bp.packageSetting == null) { 8311 Slog.w(TAG, "Removing dangling permission: " + bp.name 8312 + " from package " + bp.sourcePackage); 8313 it.remove(); 8314 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8315 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8316 Slog.i(TAG, "Removing old permission: " + bp.name 8317 + " from package " + bp.sourcePackage); 8318 flags |= UPDATE_PERMISSIONS_ALL; 8319 it.remove(); 8320 } 8321 } 8322 } 8323 8324 // Now update the permissions for all packages, in particular 8325 // replace the granted permissions of the system packages. 8326 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8327 for (PackageParser.Package pkg : mPackages.values()) { 8328 if (pkg != pkgInfo) { 8329 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8330 changingPkg); 8331 } 8332 } 8333 } 8334 8335 if (pkgInfo != null) { 8336 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8337 } 8338 } 8339 8340 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8341 String packageOfInterest) { 8342 // IMPORTANT: There are two types of permissions: install and runtime. 8343 // Install time permissions are granted when the app is installed to 8344 // all device users and users added in the future. Runtime permissions 8345 // are granted at runtime explicitly to specific users. Normal and signature 8346 // protected permissions are install time permissions. Dangerous permissions 8347 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8348 // otherwise they are runtime permissions. This function does not manage 8349 // runtime permissions except for the case an app targeting Lollipop MR1 8350 // being upgraded to target a newer SDK, in which case dangerous permissions 8351 // are transformed from install time to runtime ones. 8352 8353 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8354 if (ps == null) { 8355 return; 8356 } 8357 8358 PermissionsState permissionsState = ps.getPermissionsState(); 8359 PermissionsState origPermissions = permissionsState; 8360 8361 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8362 8363 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8364 8365 boolean changedInstallPermission = false; 8366 8367 if (replace) { 8368 ps.installPermissionsFixed = false; 8369 if (!ps.isSharedUser()) { 8370 origPermissions = new PermissionsState(permissionsState); 8371 permissionsState.reset(); 8372 } 8373 } 8374 8375 permissionsState.setGlobalGids(mGlobalGids); 8376 8377 final int N = pkg.requestedPermissions.size(); 8378 for (int i=0; i<N; i++) { 8379 final String name = pkg.requestedPermissions.get(i); 8380 final BasePermission bp = mSettings.mPermissions.get(name); 8381 8382 if (DEBUG_INSTALL) { 8383 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8384 } 8385 8386 if (bp == null || bp.packageSetting == null) { 8387 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8388 Slog.w(TAG, "Unknown permission " + name 8389 + " in package " + pkg.packageName); 8390 } 8391 continue; 8392 } 8393 8394 final String perm = bp.name; 8395 boolean allowedSig = false; 8396 int grant = GRANT_DENIED; 8397 8398 // Keep track of app op permissions. 8399 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8400 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8401 if (pkgs == null) { 8402 pkgs = new ArraySet<>(); 8403 mAppOpPermissionPackages.put(bp.name, pkgs); 8404 } 8405 pkgs.add(pkg.packageName); 8406 } 8407 8408 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8409 switch (level) { 8410 case PermissionInfo.PROTECTION_NORMAL: { 8411 // For all apps normal permissions are install time ones. 8412 grant = GRANT_INSTALL; 8413 } break; 8414 8415 case PermissionInfo.PROTECTION_DANGEROUS: { 8416 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8417 // For legacy apps dangerous permissions are install time ones. 8418 grant = GRANT_INSTALL_LEGACY; 8419 } else if (origPermissions.hasInstallPermission(bp.name)) { 8420 // For legacy apps that became modern, install becomes runtime. 8421 grant = GRANT_UPGRADE; 8422 } else if (mPromoteSystemApps 8423 && isSystemApp(ps) 8424 && mExistingSystemPackages.contains(ps.name)) { 8425 // For legacy system apps, install becomes runtime. 8426 // We cannot check hasInstallPermission() for system apps since those 8427 // permissions were granted implicitly and not persisted pre-M. 8428 grant = GRANT_UPGRADE; 8429 } else { 8430 // For modern apps keep runtime permissions unchanged. 8431 grant = GRANT_RUNTIME; 8432 } 8433 } break; 8434 8435 case PermissionInfo.PROTECTION_SIGNATURE: { 8436 // For all apps signature permissions are install time ones. 8437 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8438 if (allowedSig) { 8439 grant = GRANT_INSTALL; 8440 } 8441 } break; 8442 } 8443 8444 if (DEBUG_INSTALL) { 8445 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8446 } 8447 8448 if (grant != GRANT_DENIED) { 8449 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8450 // If this is an existing, non-system package, then 8451 // we can't add any new permissions to it. 8452 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8453 // Except... if this is a permission that was added 8454 // to the platform (note: need to only do this when 8455 // updating the platform). 8456 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8457 grant = GRANT_DENIED; 8458 } 8459 } 8460 } 8461 8462 switch (grant) { 8463 case GRANT_INSTALL: { 8464 // Revoke this as runtime permission to handle the case of 8465 // a runtime permission being downgraded to an install one. 8466 for (int userId : UserManagerService.getInstance().getUserIds()) { 8467 if (origPermissions.getRuntimePermissionState( 8468 bp.name, userId) != null) { 8469 // Revoke the runtime permission and clear the flags. 8470 origPermissions.revokeRuntimePermission(bp, userId); 8471 origPermissions.updatePermissionFlags(bp, userId, 8472 PackageManager.MASK_PERMISSION_FLAGS, 0); 8473 // If we revoked a permission permission, we have to write. 8474 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8475 changedRuntimePermissionUserIds, userId); 8476 } 8477 } 8478 // Grant an install permission. 8479 if (permissionsState.grantInstallPermission(bp) != 8480 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8481 changedInstallPermission = true; 8482 } 8483 } break; 8484 8485 case GRANT_INSTALL_LEGACY: { 8486 // Grant an install permission. 8487 if (permissionsState.grantInstallPermission(bp) != 8488 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8489 changedInstallPermission = true; 8490 } 8491 } break; 8492 8493 case GRANT_RUNTIME: { 8494 // Grant previously granted runtime permissions. 8495 for (int userId : UserManagerService.getInstance().getUserIds()) { 8496 PermissionState permissionState = origPermissions 8497 .getRuntimePermissionState(bp.name, userId); 8498 final int flags = permissionState != null 8499 ? permissionState.getFlags() : 0; 8500 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8501 if (permissionsState.grantRuntimePermission(bp, userId) == 8502 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8503 // If we cannot put the permission as it was, we have to write. 8504 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8505 changedRuntimePermissionUserIds, userId); 8506 } 8507 } 8508 // Propagate the permission flags. 8509 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8510 } 8511 } break; 8512 8513 case GRANT_UPGRADE: { 8514 // Grant runtime permissions for a previously held install permission. 8515 PermissionState permissionState = origPermissions 8516 .getInstallPermissionState(bp.name); 8517 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8518 8519 if (origPermissions.revokeInstallPermission(bp) 8520 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8521 // We will be transferring the permission flags, so clear them. 8522 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8523 PackageManager.MASK_PERMISSION_FLAGS, 0); 8524 changedInstallPermission = true; 8525 } 8526 8527 // If the permission is not to be promoted to runtime we ignore it and 8528 // also its other flags as they are not applicable to install permissions. 8529 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8530 for (int userId : currentUserIds) { 8531 if (permissionsState.grantRuntimePermission(bp, userId) != 8532 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8533 // Transfer the permission flags. 8534 permissionsState.updatePermissionFlags(bp, userId, 8535 flags, flags); 8536 // If we granted the permission, we have to write. 8537 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8538 changedRuntimePermissionUserIds, userId); 8539 } 8540 } 8541 } 8542 } break; 8543 8544 default: { 8545 if (packageOfInterest == null 8546 || packageOfInterest.equals(pkg.packageName)) { 8547 Slog.w(TAG, "Not granting permission " + perm 8548 + " to package " + pkg.packageName 8549 + " because it was previously installed without"); 8550 } 8551 } break; 8552 } 8553 } else { 8554 if (permissionsState.revokeInstallPermission(bp) != 8555 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8556 // Also drop the permission flags. 8557 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8558 PackageManager.MASK_PERMISSION_FLAGS, 0); 8559 changedInstallPermission = true; 8560 Slog.i(TAG, "Un-granting permission " + perm 8561 + " from package " + pkg.packageName 8562 + " (protectionLevel=" + bp.protectionLevel 8563 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8564 + ")"); 8565 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8566 // Don't print warning for app op permissions, since it is fine for them 8567 // not to be granted, there is a UI for the user to decide. 8568 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8569 Slog.w(TAG, "Not granting permission " + perm 8570 + " to package " + pkg.packageName 8571 + " (protectionLevel=" + bp.protectionLevel 8572 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8573 + ")"); 8574 } 8575 } 8576 } 8577 } 8578 8579 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8580 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8581 // This is the first that we have heard about this package, so the 8582 // permissions we have now selected are fixed until explicitly 8583 // changed. 8584 ps.installPermissionsFixed = true; 8585 } 8586 8587 // Persist the runtime permissions state for users with changes. 8588 for (int userId : changedRuntimePermissionUserIds) { 8589 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8590 } 8591 } 8592 8593 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8594 boolean allowed = false; 8595 final int NP = PackageParser.NEW_PERMISSIONS.length; 8596 for (int ip=0; ip<NP; ip++) { 8597 final PackageParser.NewPermissionInfo npi 8598 = PackageParser.NEW_PERMISSIONS[ip]; 8599 if (npi.name.equals(perm) 8600 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8601 allowed = true; 8602 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8603 + pkg.packageName); 8604 break; 8605 } 8606 } 8607 return allowed; 8608 } 8609 8610 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8611 BasePermission bp, PermissionsState origPermissions) { 8612 boolean allowed; 8613 allowed = (compareSignatures( 8614 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8615 == PackageManager.SIGNATURE_MATCH) 8616 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8617 == PackageManager.SIGNATURE_MATCH); 8618 if (!allowed && (bp.protectionLevel 8619 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8620 if (isSystemApp(pkg)) { 8621 // For updated system applications, a system permission 8622 // is granted only if it had been defined by the original application. 8623 if (pkg.isUpdatedSystemApp()) { 8624 final PackageSetting sysPs = mSettings 8625 .getDisabledSystemPkgLPr(pkg.packageName); 8626 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8627 // If the original was granted this permission, we take 8628 // that grant decision as read and propagate it to the 8629 // update. 8630 if (sysPs.isPrivileged()) { 8631 allowed = true; 8632 } 8633 } else { 8634 // The system apk may have been updated with an older 8635 // version of the one on the data partition, but which 8636 // granted a new system permission that it didn't have 8637 // before. In this case we do want to allow the app to 8638 // now get the new permission if the ancestral apk is 8639 // privileged to get it. 8640 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8641 for (int j=0; 8642 j<sysPs.pkg.requestedPermissions.size(); j++) { 8643 if (perm.equals( 8644 sysPs.pkg.requestedPermissions.get(j))) { 8645 allowed = true; 8646 break; 8647 } 8648 } 8649 } 8650 } 8651 } else { 8652 allowed = isPrivilegedApp(pkg); 8653 } 8654 } 8655 } 8656 if (!allowed) { 8657 if (!allowed && (bp.protectionLevel 8658 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8659 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8660 // If this was a previously normal/dangerous permission that got moved 8661 // to a system permission as part of the runtime permission redesign, then 8662 // we still want to blindly grant it to old apps. 8663 allowed = true; 8664 } 8665 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8666 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8667 // If this permission is to be granted to the system installer and 8668 // this app is an installer, then it gets the permission. 8669 allowed = true; 8670 } 8671 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8672 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8673 // If this permission is to be granted to the system verifier and 8674 // this app is a verifier, then it gets the permission. 8675 allowed = true; 8676 } 8677 if (!allowed && (bp.protectionLevel 8678 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8679 && isSystemApp(pkg)) { 8680 // Any pre-installed system app is allowed to get this permission. 8681 allowed = true; 8682 } 8683 if (!allowed && (bp.protectionLevel 8684 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8685 // For development permissions, a development permission 8686 // is granted only if it was already granted. 8687 allowed = origPermissions.hasInstallPermission(perm); 8688 } 8689 } 8690 return allowed; 8691 } 8692 8693 final class ActivityIntentResolver 8694 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8695 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8696 boolean defaultOnly, int userId) { 8697 if (!sUserManager.exists(userId)) return null; 8698 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8699 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8700 } 8701 8702 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8703 int userId) { 8704 if (!sUserManager.exists(userId)) return null; 8705 mFlags = flags; 8706 return super.queryIntent(intent, resolvedType, 8707 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8708 } 8709 8710 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8711 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8712 if (!sUserManager.exists(userId)) return null; 8713 if (packageActivities == null) { 8714 return null; 8715 } 8716 mFlags = flags; 8717 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8718 final int N = packageActivities.size(); 8719 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8720 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8721 8722 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8723 for (int i = 0; i < N; ++i) { 8724 intentFilters = packageActivities.get(i).intents; 8725 if (intentFilters != null && intentFilters.size() > 0) { 8726 PackageParser.ActivityIntentInfo[] array = 8727 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8728 intentFilters.toArray(array); 8729 listCut.add(array); 8730 } 8731 } 8732 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8733 } 8734 8735 public final void addActivity(PackageParser.Activity a, String type) { 8736 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8737 mActivities.put(a.getComponentName(), a); 8738 if (DEBUG_SHOW_INFO) 8739 Log.v( 8740 TAG, " " + type + " " + 8741 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8742 if (DEBUG_SHOW_INFO) 8743 Log.v(TAG, " Class=" + a.info.name); 8744 final int NI = a.intents.size(); 8745 for (int j=0; j<NI; j++) { 8746 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8747 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8748 intent.setPriority(0); 8749 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8750 + a.className + " with priority > 0, forcing to 0"); 8751 } 8752 if (DEBUG_SHOW_INFO) { 8753 Log.v(TAG, " IntentFilter:"); 8754 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8755 } 8756 if (!intent.debugCheck()) { 8757 Log.w(TAG, "==> For Activity " + a.info.name); 8758 } 8759 addFilter(intent); 8760 } 8761 } 8762 8763 public final void removeActivity(PackageParser.Activity a, String type) { 8764 mActivities.remove(a.getComponentName()); 8765 if (DEBUG_SHOW_INFO) { 8766 Log.v(TAG, " " + type + " " 8767 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8768 : a.info.name) + ":"); 8769 Log.v(TAG, " Class=" + a.info.name); 8770 } 8771 final int NI = a.intents.size(); 8772 for (int j=0; j<NI; j++) { 8773 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8774 if (DEBUG_SHOW_INFO) { 8775 Log.v(TAG, " IntentFilter:"); 8776 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8777 } 8778 removeFilter(intent); 8779 } 8780 } 8781 8782 @Override 8783 protected boolean allowFilterResult( 8784 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8785 ActivityInfo filterAi = filter.activity.info; 8786 for (int i=dest.size()-1; i>=0; i--) { 8787 ActivityInfo destAi = dest.get(i).activityInfo; 8788 if (destAi.name == filterAi.name 8789 && destAi.packageName == filterAi.packageName) { 8790 return false; 8791 } 8792 } 8793 return true; 8794 } 8795 8796 @Override 8797 protected ActivityIntentInfo[] newArray(int size) { 8798 return new ActivityIntentInfo[size]; 8799 } 8800 8801 @Override 8802 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8803 if (!sUserManager.exists(userId)) return true; 8804 PackageParser.Package p = filter.activity.owner; 8805 if (p != null) { 8806 PackageSetting ps = (PackageSetting)p.mExtras; 8807 if (ps != null) { 8808 // System apps are never considered stopped for purposes of 8809 // filtering, because there may be no way for the user to 8810 // actually re-launch them. 8811 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8812 && ps.getStopped(userId); 8813 } 8814 } 8815 return false; 8816 } 8817 8818 @Override 8819 protected boolean isPackageForFilter(String packageName, 8820 PackageParser.ActivityIntentInfo info) { 8821 return packageName.equals(info.activity.owner.packageName); 8822 } 8823 8824 @Override 8825 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8826 int match, int userId) { 8827 if (!sUserManager.exists(userId)) return null; 8828 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8829 return null; 8830 } 8831 final PackageParser.Activity activity = info.activity; 8832 if (mSafeMode && (activity.info.applicationInfo.flags 8833 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8834 return null; 8835 } 8836 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8837 if (ps == null) { 8838 return null; 8839 } 8840 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8841 ps.readUserState(userId), userId); 8842 if (ai == null) { 8843 return null; 8844 } 8845 final ResolveInfo res = new ResolveInfo(); 8846 res.activityInfo = ai; 8847 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8848 res.filter = info; 8849 } 8850 if (info != null) { 8851 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8852 } 8853 res.priority = info.getPriority(); 8854 res.preferredOrder = activity.owner.mPreferredOrder; 8855 //System.out.println("Result: " + res.activityInfo.className + 8856 // " = " + res.priority); 8857 res.match = match; 8858 res.isDefault = info.hasDefault; 8859 res.labelRes = info.labelRes; 8860 res.nonLocalizedLabel = info.nonLocalizedLabel; 8861 if (userNeedsBadging(userId)) { 8862 res.noResourceId = true; 8863 } else { 8864 res.icon = info.icon; 8865 } 8866 res.iconResourceId = info.icon; 8867 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8868 return res; 8869 } 8870 8871 @Override 8872 protected void sortResults(List<ResolveInfo> results) { 8873 Collections.sort(results, mResolvePrioritySorter); 8874 } 8875 8876 @Override 8877 protected void dumpFilter(PrintWriter out, String prefix, 8878 PackageParser.ActivityIntentInfo filter) { 8879 out.print(prefix); out.print( 8880 Integer.toHexString(System.identityHashCode(filter.activity))); 8881 out.print(' '); 8882 filter.activity.printComponentShortName(out); 8883 out.print(" filter "); 8884 out.println(Integer.toHexString(System.identityHashCode(filter))); 8885 } 8886 8887 @Override 8888 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8889 return filter.activity; 8890 } 8891 8892 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8893 PackageParser.Activity activity = (PackageParser.Activity)label; 8894 out.print(prefix); out.print( 8895 Integer.toHexString(System.identityHashCode(activity))); 8896 out.print(' '); 8897 activity.printComponentShortName(out); 8898 if (count > 1) { 8899 out.print(" ("); out.print(count); out.print(" filters)"); 8900 } 8901 out.println(); 8902 } 8903 8904// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8905// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8906// final List<ResolveInfo> retList = Lists.newArrayList(); 8907// while (i.hasNext()) { 8908// final ResolveInfo resolveInfo = i.next(); 8909// if (isEnabledLP(resolveInfo.activityInfo)) { 8910// retList.add(resolveInfo); 8911// } 8912// } 8913// return retList; 8914// } 8915 8916 // Keys are String (activity class name), values are Activity. 8917 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8918 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8919 private int mFlags; 8920 } 8921 8922 private final class ServiceIntentResolver 8923 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8924 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8925 boolean defaultOnly, int userId) { 8926 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8927 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8928 } 8929 8930 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8931 int userId) { 8932 if (!sUserManager.exists(userId)) return null; 8933 mFlags = flags; 8934 return super.queryIntent(intent, resolvedType, 8935 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8936 } 8937 8938 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8939 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8940 if (!sUserManager.exists(userId)) return null; 8941 if (packageServices == null) { 8942 return null; 8943 } 8944 mFlags = flags; 8945 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8946 final int N = packageServices.size(); 8947 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8948 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8949 8950 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8951 for (int i = 0; i < N; ++i) { 8952 intentFilters = packageServices.get(i).intents; 8953 if (intentFilters != null && intentFilters.size() > 0) { 8954 PackageParser.ServiceIntentInfo[] array = 8955 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8956 intentFilters.toArray(array); 8957 listCut.add(array); 8958 } 8959 } 8960 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8961 } 8962 8963 public final void addService(PackageParser.Service s) { 8964 mServices.put(s.getComponentName(), s); 8965 if (DEBUG_SHOW_INFO) { 8966 Log.v(TAG, " " 8967 + (s.info.nonLocalizedLabel != null 8968 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8969 Log.v(TAG, " Class=" + s.info.name); 8970 } 8971 final int NI = s.intents.size(); 8972 int j; 8973 for (j=0; j<NI; j++) { 8974 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8975 if (DEBUG_SHOW_INFO) { 8976 Log.v(TAG, " IntentFilter:"); 8977 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8978 } 8979 if (!intent.debugCheck()) { 8980 Log.w(TAG, "==> For Service " + s.info.name); 8981 } 8982 addFilter(intent); 8983 } 8984 } 8985 8986 public final void removeService(PackageParser.Service s) { 8987 mServices.remove(s.getComponentName()); 8988 if (DEBUG_SHOW_INFO) { 8989 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8990 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8991 Log.v(TAG, " Class=" + s.info.name); 8992 } 8993 final int NI = s.intents.size(); 8994 int j; 8995 for (j=0; j<NI; j++) { 8996 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8997 if (DEBUG_SHOW_INFO) { 8998 Log.v(TAG, " IntentFilter:"); 8999 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9000 } 9001 removeFilter(intent); 9002 } 9003 } 9004 9005 @Override 9006 protected boolean allowFilterResult( 9007 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9008 ServiceInfo filterSi = filter.service.info; 9009 for (int i=dest.size()-1; i>=0; i--) { 9010 ServiceInfo destAi = dest.get(i).serviceInfo; 9011 if (destAi.name == filterSi.name 9012 && destAi.packageName == filterSi.packageName) { 9013 return false; 9014 } 9015 } 9016 return true; 9017 } 9018 9019 @Override 9020 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9021 return new PackageParser.ServiceIntentInfo[size]; 9022 } 9023 9024 @Override 9025 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9026 if (!sUserManager.exists(userId)) return true; 9027 PackageParser.Package p = filter.service.owner; 9028 if (p != null) { 9029 PackageSetting ps = (PackageSetting)p.mExtras; 9030 if (ps != null) { 9031 // System apps are never considered stopped for purposes of 9032 // filtering, because there may be no way for the user to 9033 // actually re-launch them. 9034 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9035 && ps.getStopped(userId); 9036 } 9037 } 9038 return false; 9039 } 9040 9041 @Override 9042 protected boolean isPackageForFilter(String packageName, 9043 PackageParser.ServiceIntentInfo info) { 9044 return packageName.equals(info.service.owner.packageName); 9045 } 9046 9047 @Override 9048 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9049 int match, int userId) { 9050 if (!sUserManager.exists(userId)) return null; 9051 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9052 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9053 return null; 9054 } 9055 final PackageParser.Service service = info.service; 9056 if (mSafeMode && (service.info.applicationInfo.flags 9057 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9058 return null; 9059 } 9060 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9061 if (ps == null) { 9062 return null; 9063 } 9064 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9065 ps.readUserState(userId), userId); 9066 if (si == null) { 9067 return null; 9068 } 9069 final ResolveInfo res = new ResolveInfo(); 9070 res.serviceInfo = si; 9071 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9072 res.filter = filter; 9073 } 9074 res.priority = info.getPriority(); 9075 res.preferredOrder = service.owner.mPreferredOrder; 9076 res.match = match; 9077 res.isDefault = info.hasDefault; 9078 res.labelRes = info.labelRes; 9079 res.nonLocalizedLabel = info.nonLocalizedLabel; 9080 res.icon = info.icon; 9081 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9082 return res; 9083 } 9084 9085 @Override 9086 protected void sortResults(List<ResolveInfo> results) { 9087 Collections.sort(results, mResolvePrioritySorter); 9088 } 9089 9090 @Override 9091 protected void dumpFilter(PrintWriter out, String prefix, 9092 PackageParser.ServiceIntentInfo filter) { 9093 out.print(prefix); out.print( 9094 Integer.toHexString(System.identityHashCode(filter.service))); 9095 out.print(' '); 9096 filter.service.printComponentShortName(out); 9097 out.print(" filter "); 9098 out.println(Integer.toHexString(System.identityHashCode(filter))); 9099 } 9100 9101 @Override 9102 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9103 return filter.service; 9104 } 9105 9106 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9107 PackageParser.Service service = (PackageParser.Service)label; 9108 out.print(prefix); out.print( 9109 Integer.toHexString(System.identityHashCode(service))); 9110 out.print(' '); 9111 service.printComponentShortName(out); 9112 if (count > 1) { 9113 out.print(" ("); out.print(count); out.print(" filters)"); 9114 } 9115 out.println(); 9116 } 9117 9118// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9119// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9120// final List<ResolveInfo> retList = Lists.newArrayList(); 9121// while (i.hasNext()) { 9122// final ResolveInfo resolveInfo = (ResolveInfo) i; 9123// if (isEnabledLP(resolveInfo.serviceInfo)) { 9124// retList.add(resolveInfo); 9125// } 9126// } 9127// return retList; 9128// } 9129 9130 // Keys are String (activity class name), values are Activity. 9131 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9132 = new ArrayMap<ComponentName, PackageParser.Service>(); 9133 private int mFlags; 9134 }; 9135 9136 private final class ProviderIntentResolver 9137 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9138 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9139 boolean defaultOnly, int userId) { 9140 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9141 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9142 } 9143 9144 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9145 int userId) { 9146 if (!sUserManager.exists(userId)) 9147 return null; 9148 mFlags = flags; 9149 return super.queryIntent(intent, resolvedType, 9150 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9151 } 9152 9153 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9154 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9155 if (!sUserManager.exists(userId)) 9156 return null; 9157 if (packageProviders == null) { 9158 return null; 9159 } 9160 mFlags = flags; 9161 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9162 final int N = packageProviders.size(); 9163 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9164 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9165 9166 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9167 for (int i = 0; i < N; ++i) { 9168 intentFilters = packageProviders.get(i).intents; 9169 if (intentFilters != null && intentFilters.size() > 0) { 9170 PackageParser.ProviderIntentInfo[] array = 9171 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9172 intentFilters.toArray(array); 9173 listCut.add(array); 9174 } 9175 } 9176 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9177 } 9178 9179 public final void addProvider(PackageParser.Provider p) { 9180 if (mProviders.containsKey(p.getComponentName())) { 9181 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9182 return; 9183 } 9184 9185 mProviders.put(p.getComponentName(), p); 9186 if (DEBUG_SHOW_INFO) { 9187 Log.v(TAG, " " 9188 + (p.info.nonLocalizedLabel != null 9189 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9190 Log.v(TAG, " Class=" + p.info.name); 9191 } 9192 final int NI = p.intents.size(); 9193 int j; 9194 for (j = 0; j < NI; j++) { 9195 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9196 if (DEBUG_SHOW_INFO) { 9197 Log.v(TAG, " IntentFilter:"); 9198 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9199 } 9200 if (!intent.debugCheck()) { 9201 Log.w(TAG, "==> For Provider " + p.info.name); 9202 } 9203 addFilter(intent); 9204 } 9205 } 9206 9207 public final void removeProvider(PackageParser.Provider p) { 9208 mProviders.remove(p.getComponentName()); 9209 if (DEBUG_SHOW_INFO) { 9210 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9211 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9212 Log.v(TAG, " Class=" + p.info.name); 9213 } 9214 final int NI = p.intents.size(); 9215 int j; 9216 for (j = 0; j < NI; j++) { 9217 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9218 if (DEBUG_SHOW_INFO) { 9219 Log.v(TAG, " IntentFilter:"); 9220 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9221 } 9222 removeFilter(intent); 9223 } 9224 } 9225 9226 @Override 9227 protected boolean allowFilterResult( 9228 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9229 ProviderInfo filterPi = filter.provider.info; 9230 for (int i = dest.size() - 1; i >= 0; i--) { 9231 ProviderInfo destPi = dest.get(i).providerInfo; 9232 if (destPi.name == filterPi.name 9233 && destPi.packageName == filterPi.packageName) { 9234 return false; 9235 } 9236 } 9237 return true; 9238 } 9239 9240 @Override 9241 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9242 return new PackageParser.ProviderIntentInfo[size]; 9243 } 9244 9245 @Override 9246 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9247 if (!sUserManager.exists(userId)) 9248 return true; 9249 PackageParser.Package p = filter.provider.owner; 9250 if (p != null) { 9251 PackageSetting ps = (PackageSetting) p.mExtras; 9252 if (ps != null) { 9253 // System apps are never considered stopped for purposes of 9254 // filtering, because there may be no way for the user to 9255 // actually re-launch them. 9256 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9257 && ps.getStopped(userId); 9258 } 9259 } 9260 return false; 9261 } 9262 9263 @Override 9264 protected boolean isPackageForFilter(String packageName, 9265 PackageParser.ProviderIntentInfo info) { 9266 return packageName.equals(info.provider.owner.packageName); 9267 } 9268 9269 @Override 9270 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9271 int match, int userId) { 9272 if (!sUserManager.exists(userId)) 9273 return null; 9274 final PackageParser.ProviderIntentInfo info = filter; 9275 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9276 return null; 9277 } 9278 final PackageParser.Provider provider = info.provider; 9279 if (mSafeMode && (provider.info.applicationInfo.flags 9280 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9281 return null; 9282 } 9283 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9284 if (ps == null) { 9285 return null; 9286 } 9287 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9288 ps.readUserState(userId), userId); 9289 if (pi == null) { 9290 return null; 9291 } 9292 final ResolveInfo res = new ResolveInfo(); 9293 res.providerInfo = pi; 9294 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9295 res.filter = filter; 9296 } 9297 res.priority = info.getPriority(); 9298 res.preferredOrder = provider.owner.mPreferredOrder; 9299 res.match = match; 9300 res.isDefault = info.hasDefault; 9301 res.labelRes = info.labelRes; 9302 res.nonLocalizedLabel = info.nonLocalizedLabel; 9303 res.icon = info.icon; 9304 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9305 return res; 9306 } 9307 9308 @Override 9309 protected void sortResults(List<ResolveInfo> results) { 9310 Collections.sort(results, mResolvePrioritySorter); 9311 } 9312 9313 @Override 9314 protected void dumpFilter(PrintWriter out, String prefix, 9315 PackageParser.ProviderIntentInfo filter) { 9316 out.print(prefix); 9317 out.print( 9318 Integer.toHexString(System.identityHashCode(filter.provider))); 9319 out.print(' '); 9320 filter.provider.printComponentShortName(out); 9321 out.print(" filter "); 9322 out.println(Integer.toHexString(System.identityHashCode(filter))); 9323 } 9324 9325 @Override 9326 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9327 return filter.provider; 9328 } 9329 9330 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9331 PackageParser.Provider provider = (PackageParser.Provider)label; 9332 out.print(prefix); out.print( 9333 Integer.toHexString(System.identityHashCode(provider))); 9334 out.print(' '); 9335 provider.printComponentShortName(out); 9336 if (count > 1) { 9337 out.print(" ("); out.print(count); out.print(" filters)"); 9338 } 9339 out.println(); 9340 } 9341 9342 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9343 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9344 private int mFlags; 9345 }; 9346 9347 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9348 new Comparator<ResolveInfo>() { 9349 public int compare(ResolveInfo r1, ResolveInfo r2) { 9350 int v1 = r1.priority; 9351 int v2 = r2.priority; 9352 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9353 if (v1 != v2) { 9354 return (v1 > v2) ? -1 : 1; 9355 } 9356 v1 = r1.preferredOrder; 9357 v2 = r2.preferredOrder; 9358 if (v1 != v2) { 9359 return (v1 > v2) ? -1 : 1; 9360 } 9361 if (r1.isDefault != r2.isDefault) { 9362 return r1.isDefault ? -1 : 1; 9363 } 9364 v1 = r1.match; 9365 v2 = r2.match; 9366 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9367 if (v1 != v2) { 9368 return (v1 > v2) ? -1 : 1; 9369 } 9370 if (r1.system != r2.system) { 9371 return r1.system ? -1 : 1; 9372 } 9373 return 0; 9374 } 9375 }; 9376 9377 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9378 new Comparator<ProviderInfo>() { 9379 public int compare(ProviderInfo p1, ProviderInfo p2) { 9380 final int v1 = p1.initOrder; 9381 final int v2 = p2.initOrder; 9382 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9383 } 9384 }; 9385 9386 final void sendPackageBroadcast(final String action, final String pkg, 9387 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9388 final int[] userIds) { 9389 mHandler.post(new Runnable() { 9390 @Override 9391 public void run() { 9392 try { 9393 final IActivityManager am = ActivityManagerNative.getDefault(); 9394 if (am == null) return; 9395 final int[] resolvedUserIds; 9396 if (userIds == null) { 9397 resolvedUserIds = am.getRunningUserIds(); 9398 } else { 9399 resolvedUserIds = userIds; 9400 } 9401 for (int id : resolvedUserIds) { 9402 final Intent intent = new Intent(action, 9403 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9404 if (extras != null) { 9405 intent.putExtras(extras); 9406 } 9407 if (targetPkg != null) { 9408 intent.setPackage(targetPkg); 9409 } 9410 // Modify the UID when posting to other users 9411 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9412 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9413 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9414 intent.putExtra(Intent.EXTRA_UID, uid); 9415 } 9416 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9417 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9418 if (DEBUG_BROADCASTS) { 9419 RuntimeException here = new RuntimeException("here"); 9420 here.fillInStackTrace(); 9421 Slog.d(TAG, "Sending to user " + id + ": " 9422 + intent.toShortString(false, true, false, false) 9423 + " " + intent.getExtras(), here); 9424 } 9425 am.broadcastIntent(null, intent, null, finishedReceiver, 9426 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9427 null, finishedReceiver != null, false, id); 9428 } 9429 } catch (RemoteException ex) { 9430 } 9431 } 9432 }); 9433 } 9434 9435 /** 9436 * Check if the external storage media is available. This is true if there 9437 * is a mounted external storage medium or if the external storage is 9438 * emulated. 9439 */ 9440 private boolean isExternalMediaAvailable() { 9441 return mMediaMounted || Environment.isExternalStorageEmulated(); 9442 } 9443 9444 @Override 9445 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9446 // writer 9447 synchronized (mPackages) { 9448 if (!isExternalMediaAvailable()) { 9449 // If the external storage is no longer mounted at this point, 9450 // the caller may not have been able to delete all of this 9451 // packages files and can not delete any more. Bail. 9452 return null; 9453 } 9454 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9455 if (lastPackage != null) { 9456 pkgs.remove(lastPackage); 9457 } 9458 if (pkgs.size() > 0) { 9459 return pkgs.get(0); 9460 } 9461 } 9462 return null; 9463 } 9464 9465 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9466 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9467 userId, andCode ? 1 : 0, packageName); 9468 if (mSystemReady) { 9469 msg.sendToTarget(); 9470 } else { 9471 if (mPostSystemReadyMessages == null) { 9472 mPostSystemReadyMessages = new ArrayList<>(); 9473 } 9474 mPostSystemReadyMessages.add(msg); 9475 } 9476 } 9477 9478 void startCleaningPackages() { 9479 // reader 9480 synchronized (mPackages) { 9481 if (!isExternalMediaAvailable()) { 9482 return; 9483 } 9484 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9485 return; 9486 } 9487 } 9488 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9489 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9490 IActivityManager am = ActivityManagerNative.getDefault(); 9491 if (am != null) { 9492 try { 9493 am.startService(null, intent, null, mContext.getOpPackageName(), 9494 UserHandle.USER_OWNER); 9495 } catch (RemoteException e) { 9496 } 9497 } 9498 } 9499 9500 @Override 9501 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9502 int installFlags, String installerPackageName, VerificationParams verificationParams, 9503 String packageAbiOverride) { 9504 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9505 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9506 } 9507 9508 @Override 9509 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9510 int installFlags, String installerPackageName, VerificationParams verificationParams, 9511 String packageAbiOverride, int userId) { 9512 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9513 9514 final int callingUid = Binder.getCallingUid(); 9515 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9516 9517 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9518 try { 9519 if (observer != null) { 9520 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9521 } 9522 } catch (RemoteException re) { 9523 } 9524 return; 9525 } 9526 9527 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9528 installFlags |= PackageManager.INSTALL_FROM_ADB; 9529 9530 } else { 9531 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9532 // about installerPackageName. 9533 9534 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9535 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9536 } 9537 9538 UserHandle user; 9539 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9540 user = UserHandle.ALL; 9541 } else { 9542 user = new UserHandle(userId); 9543 } 9544 9545 // Only system components can circumvent runtime permissions when installing. 9546 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9547 && mContext.checkCallingOrSelfPermission(Manifest.permission 9548 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9549 throw new SecurityException("You need the " 9550 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9551 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9552 } 9553 9554 verificationParams.setInstallerUid(callingUid); 9555 9556 final File originFile = new File(originPath); 9557 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9558 9559 final Message msg = mHandler.obtainMessage(INIT_COPY); 9560 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9561 null, verificationParams, user, packageAbiOverride, null); 9562 mHandler.sendMessage(msg); 9563 } 9564 9565 void installStage(String packageName, File stagedDir, String stagedCid, 9566 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9567 String installerPackageName, int installerUid, UserHandle user) { 9568 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9569 params.referrerUri, installerUid, null); 9570 verifParams.setInstallerUid(installerUid); 9571 9572 final OriginInfo origin; 9573 if (stagedDir != null) { 9574 origin = OriginInfo.fromStagedFile(stagedDir); 9575 } else { 9576 origin = OriginInfo.fromStagedContainer(stagedCid); 9577 } 9578 9579 final Message msg = mHandler.obtainMessage(INIT_COPY); 9580 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9581 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9582 params.grantedRuntimePermissions); 9583 mHandler.sendMessage(msg); 9584 } 9585 9586 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9587 Bundle extras = new Bundle(1); 9588 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9589 9590 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9591 packageName, extras, null, null, new int[] {userId}); 9592 try { 9593 IActivityManager am = ActivityManagerNative.getDefault(); 9594 final boolean isSystem = 9595 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9596 if (isSystem && am.isUserRunning(userId, false)) { 9597 // The just-installed/enabled app is bundled on the system, so presumed 9598 // to be able to run automatically without needing an explicit launch. 9599 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9600 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9601 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9602 .setPackage(packageName); 9603 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9604 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9605 } 9606 } catch (RemoteException e) { 9607 // shouldn't happen 9608 Slog.w(TAG, "Unable to bootstrap installed package", e); 9609 } 9610 } 9611 9612 @Override 9613 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9614 int userId) { 9615 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9616 PackageSetting pkgSetting; 9617 final int uid = Binder.getCallingUid(); 9618 enforceCrossUserPermission(uid, userId, true, true, 9619 "setApplicationHiddenSetting for user " + userId); 9620 9621 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9622 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9623 return false; 9624 } 9625 9626 long callingId = Binder.clearCallingIdentity(); 9627 try { 9628 boolean sendAdded = false; 9629 boolean sendRemoved = false; 9630 // writer 9631 synchronized (mPackages) { 9632 pkgSetting = mSettings.mPackages.get(packageName); 9633 if (pkgSetting == null) { 9634 return false; 9635 } 9636 if (pkgSetting.getHidden(userId) != hidden) { 9637 pkgSetting.setHidden(hidden, userId); 9638 mSettings.writePackageRestrictionsLPr(userId); 9639 if (hidden) { 9640 sendRemoved = true; 9641 } else { 9642 sendAdded = true; 9643 } 9644 } 9645 } 9646 if (sendAdded) { 9647 sendPackageAddedForUser(packageName, pkgSetting, userId); 9648 return true; 9649 } 9650 if (sendRemoved) { 9651 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9652 "hiding pkg"); 9653 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9654 return true; 9655 } 9656 } finally { 9657 Binder.restoreCallingIdentity(callingId); 9658 } 9659 return false; 9660 } 9661 9662 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9663 int userId) { 9664 final PackageRemovedInfo info = new PackageRemovedInfo(); 9665 info.removedPackage = packageName; 9666 info.removedUsers = new int[] {userId}; 9667 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9668 info.sendBroadcast(false, false, false); 9669 } 9670 9671 /** 9672 * Returns true if application is not found or there was an error. Otherwise it returns 9673 * the hidden state of the package for the given user. 9674 */ 9675 @Override 9676 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9677 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9678 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9679 false, "getApplicationHidden for user " + userId); 9680 PackageSetting pkgSetting; 9681 long callingId = Binder.clearCallingIdentity(); 9682 try { 9683 // writer 9684 synchronized (mPackages) { 9685 pkgSetting = mSettings.mPackages.get(packageName); 9686 if (pkgSetting == null) { 9687 return true; 9688 } 9689 return pkgSetting.getHidden(userId); 9690 } 9691 } finally { 9692 Binder.restoreCallingIdentity(callingId); 9693 } 9694 } 9695 9696 /** 9697 * @hide 9698 */ 9699 @Override 9700 public int installExistingPackageAsUser(String packageName, int userId) { 9701 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9702 null); 9703 PackageSetting pkgSetting; 9704 final int uid = Binder.getCallingUid(); 9705 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9706 + userId); 9707 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9708 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9709 } 9710 9711 long callingId = Binder.clearCallingIdentity(); 9712 try { 9713 boolean sendAdded = false; 9714 9715 // writer 9716 synchronized (mPackages) { 9717 pkgSetting = mSettings.mPackages.get(packageName); 9718 if (pkgSetting == null) { 9719 return PackageManager.INSTALL_FAILED_INVALID_URI; 9720 } 9721 if (!pkgSetting.getInstalled(userId)) { 9722 pkgSetting.setInstalled(true, userId); 9723 pkgSetting.setHidden(false, userId); 9724 mSettings.writePackageRestrictionsLPr(userId); 9725 sendAdded = true; 9726 } 9727 } 9728 9729 if (sendAdded) { 9730 sendPackageAddedForUser(packageName, pkgSetting, userId); 9731 } 9732 } finally { 9733 Binder.restoreCallingIdentity(callingId); 9734 } 9735 9736 return PackageManager.INSTALL_SUCCEEDED; 9737 } 9738 9739 boolean isUserRestricted(int userId, String restrictionKey) { 9740 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9741 if (restrictions.getBoolean(restrictionKey, false)) { 9742 Log.w(TAG, "User is restricted: " + restrictionKey); 9743 return true; 9744 } 9745 return false; 9746 } 9747 9748 @Override 9749 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9750 mContext.enforceCallingOrSelfPermission( 9751 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9752 "Only package verification agents can verify applications"); 9753 9754 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9755 final PackageVerificationResponse response = new PackageVerificationResponse( 9756 verificationCode, Binder.getCallingUid()); 9757 msg.arg1 = id; 9758 msg.obj = response; 9759 mHandler.sendMessage(msg); 9760 } 9761 9762 @Override 9763 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9764 long millisecondsToDelay) { 9765 mContext.enforceCallingOrSelfPermission( 9766 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9767 "Only package verification agents can extend verification timeouts"); 9768 9769 final PackageVerificationState state = mPendingVerification.get(id); 9770 final PackageVerificationResponse response = new PackageVerificationResponse( 9771 verificationCodeAtTimeout, Binder.getCallingUid()); 9772 9773 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9774 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9775 } 9776 if (millisecondsToDelay < 0) { 9777 millisecondsToDelay = 0; 9778 } 9779 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9780 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9781 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9782 } 9783 9784 if ((state != null) && !state.timeoutExtended()) { 9785 state.extendTimeout(); 9786 9787 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9788 msg.arg1 = id; 9789 msg.obj = response; 9790 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9791 } 9792 } 9793 9794 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9795 int verificationCode, UserHandle user) { 9796 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9797 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9798 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9799 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9800 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9801 9802 mContext.sendBroadcastAsUser(intent, user, 9803 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9804 } 9805 9806 private ComponentName matchComponentForVerifier(String packageName, 9807 List<ResolveInfo> receivers) { 9808 ActivityInfo targetReceiver = null; 9809 9810 final int NR = receivers.size(); 9811 for (int i = 0; i < NR; i++) { 9812 final ResolveInfo info = receivers.get(i); 9813 if (info.activityInfo == null) { 9814 continue; 9815 } 9816 9817 if (packageName.equals(info.activityInfo.packageName)) { 9818 targetReceiver = info.activityInfo; 9819 break; 9820 } 9821 } 9822 9823 if (targetReceiver == null) { 9824 return null; 9825 } 9826 9827 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9828 } 9829 9830 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9831 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9832 if (pkgInfo.verifiers.length == 0) { 9833 return null; 9834 } 9835 9836 final int N = pkgInfo.verifiers.length; 9837 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9838 for (int i = 0; i < N; i++) { 9839 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9840 9841 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9842 receivers); 9843 if (comp == null) { 9844 continue; 9845 } 9846 9847 final int verifierUid = getUidForVerifier(verifierInfo); 9848 if (verifierUid == -1) { 9849 continue; 9850 } 9851 9852 if (DEBUG_VERIFY) { 9853 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9854 + " with the correct signature"); 9855 } 9856 sufficientVerifiers.add(comp); 9857 verificationState.addSufficientVerifier(verifierUid); 9858 } 9859 9860 return sufficientVerifiers; 9861 } 9862 9863 private int getUidForVerifier(VerifierInfo verifierInfo) { 9864 synchronized (mPackages) { 9865 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9866 if (pkg == null) { 9867 return -1; 9868 } else if (pkg.mSignatures.length != 1) { 9869 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9870 + " has more than one signature; ignoring"); 9871 return -1; 9872 } 9873 9874 /* 9875 * If the public key of the package's signature does not match 9876 * our expected public key, then this is a different package and 9877 * we should skip. 9878 */ 9879 9880 final byte[] expectedPublicKey; 9881 try { 9882 final Signature verifierSig = pkg.mSignatures[0]; 9883 final PublicKey publicKey = verifierSig.getPublicKey(); 9884 expectedPublicKey = publicKey.getEncoded(); 9885 } catch (CertificateException e) { 9886 return -1; 9887 } 9888 9889 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9890 9891 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9892 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9893 + " does not have the expected public key; ignoring"); 9894 return -1; 9895 } 9896 9897 return pkg.applicationInfo.uid; 9898 } 9899 } 9900 9901 @Override 9902 public void finishPackageInstall(int token) { 9903 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9904 9905 if (DEBUG_INSTALL) { 9906 Slog.v(TAG, "BM finishing package install for " + token); 9907 } 9908 9909 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9910 mHandler.sendMessage(msg); 9911 } 9912 9913 /** 9914 * Get the verification agent timeout. 9915 * 9916 * @return verification timeout in milliseconds 9917 */ 9918 private long getVerificationTimeout() { 9919 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9920 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9921 DEFAULT_VERIFICATION_TIMEOUT); 9922 } 9923 9924 /** 9925 * Get the default verification agent response code. 9926 * 9927 * @return default verification response code 9928 */ 9929 private int getDefaultVerificationResponse() { 9930 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9931 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9932 DEFAULT_VERIFICATION_RESPONSE); 9933 } 9934 9935 /** 9936 * Check whether or not package verification has been enabled. 9937 * 9938 * @return true if verification should be performed 9939 */ 9940 private boolean isVerificationEnabled(int userId, int installFlags) { 9941 if (!DEFAULT_VERIFY_ENABLE) { 9942 return false; 9943 } 9944 9945 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9946 9947 // Check if installing from ADB 9948 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9949 // Do not run verification in a test harness environment 9950 if (ActivityManager.isRunningInTestHarness()) { 9951 return false; 9952 } 9953 if (ensureVerifyAppsEnabled) { 9954 return true; 9955 } 9956 // Check if the developer does not want package verification for ADB installs 9957 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9958 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9959 return false; 9960 } 9961 } 9962 9963 if (ensureVerifyAppsEnabled) { 9964 return true; 9965 } 9966 9967 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9968 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9969 } 9970 9971 @Override 9972 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9973 throws RemoteException { 9974 mContext.enforceCallingOrSelfPermission( 9975 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9976 "Only intentfilter verification agents can verify applications"); 9977 9978 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9979 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9980 Binder.getCallingUid(), verificationCode, failedDomains); 9981 msg.arg1 = id; 9982 msg.obj = response; 9983 mHandler.sendMessage(msg); 9984 } 9985 9986 @Override 9987 public int getIntentVerificationStatus(String packageName, int userId) { 9988 synchronized (mPackages) { 9989 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9990 } 9991 } 9992 9993 @Override 9994 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9995 mContext.enforceCallingOrSelfPermission( 9996 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9997 9998 boolean result = false; 9999 synchronized (mPackages) { 10000 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10001 } 10002 if (result) { 10003 scheduleWritePackageRestrictionsLocked(userId); 10004 } 10005 return result; 10006 } 10007 10008 @Override 10009 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10010 synchronized (mPackages) { 10011 return mSettings.getIntentFilterVerificationsLPr(packageName); 10012 } 10013 } 10014 10015 @Override 10016 public List<IntentFilter> getAllIntentFilters(String packageName) { 10017 if (TextUtils.isEmpty(packageName)) { 10018 return Collections.<IntentFilter>emptyList(); 10019 } 10020 synchronized (mPackages) { 10021 PackageParser.Package pkg = mPackages.get(packageName); 10022 if (pkg == null || pkg.activities == null) { 10023 return Collections.<IntentFilter>emptyList(); 10024 } 10025 final int count = pkg.activities.size(); 10026 ArrayList<IntentFilter> result = new ArrayList<>(); 10027 for (int n=0; n<count; n++) { 10028 PackageParser.Activity activity = pkg.activities.get(n); 10029 if (activity.intents != null || activity.intents.size() > 0) { 10030 result.addAll(activity.intents); 10031 } 10032 } 10033 return result; 10034 } 10035 } 10036 10037 @Override 10038 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10039 mContext.enforceCallingOrSelfPermission( 10040 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10041 10042 synchronized (mPackages) { 10043 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10044 if (packageName != null) { 10045 result |= updateIntentVerificationStatus(packageName, 10046 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10047 userId); 10048 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10049 packageName, userId); 10050 } 10051 return result; 10052 } 10053 } 10054 10055 @Override 10056 public String getDefaultBrowserPackageName(int userId) { 10057 synchronized (mPackages) { 10058 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10059 } 10060 } 10061 10062 /** 10063 * Get the "allow unknown sources" setting. 10064 * 10065 * @return the current "allow unknown sources" setting 10066 */ 10067 private int getUnknownSourcesSettings() { 10068 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10069 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10070 -1); 10071 } 10072 10073 @Override 10074 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10075 final int uid = Binder.getCallingUid(); 10076 // writer 10077 synchronized (mPackages) { 10078 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10079 if (targetPackageSetting == null) { 10080 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10081 } 10082 10083 PackageSetting installerPackageSetting; 10084 if (installerPackageName != null) { 10085 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10086 if (installerPackageSetting == null) { 10087 throw new IllegalArgumentException("Unknown installer package: " 10088 + installerPackageName); 10089 } 10090 } else { 10091 installerPackageSetting = null; 10092 } 10093 10094 Signature[] callerSignature; 10095 Object obj = mSettings.getUserIdLPr(uid); 10096 if (obj != null) { 10097 if (obj instanceof SharedUserSetting) { 10098 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10099 } else if (obj instanceof PackageSetting) { 10100 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10101 } else { 10102 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10103 } 10104 } else { 10105 throw new SecurityException("Unknown calling uid " + uid); 10106 } 10107 10108 // Verify: can't set installerPackageName to a package that is 10109 // not signed with the same cert as the caller. 10110 if (installerPackageSetting != null) { 10111 if (compareSignatures(callerSignature, 10112 installerPackageSetting.signatures.mSignatures) 10113 != PackageManager.SIGNATURE_MATCH) { 10114 throw new SecurityException( 10115 "Caller does not have same cert as new installer package " 10116 + installerPackageName); 10117 } 10118 } 10119 10120 // Verify: if target already has an installer package, it must 10121 // be signed with the same cert as the caller. 10122 if (targetPackageSetting.installerPackageName != null) { 10123 PackageSetting setting = mSettings.mPackages.get( 10124 targetPackageSetting.installerPackageName); 10125 // If the currently set package isn't valid, then it's always 10126 // okay to change it. 10127 if (setting != null) { 10128 if (compareSignatures(callerSignature, 10129 setting.signatures.mSignatures) 10130 != PackageManager.SIGNATURE_MATCH) { 10131 throw new SecurityException( 10132 "Caller does not have same cert as old installer package " 10133 + targetPackageSetting.installerPackageName); 10134 } 10135 } 10136 } 10137 10138 // Okay! 10139 targetPackageSetting.installerPackageName = installerPackageName; 10140 scheduleWriteSettingsLocked(); 10141 } 10142 } 10143 10144 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10145 // Queue up an async operation since the package installation may take a little while. 10146 mHandler.post(new Runnable() { 10147 public void run() { 10148 mHandler.removeCallbacks(this); 10149 // Result object to be returned 10150 PackageInstalledInfo res = new PackageInstalledInfo(); 10151 res.returnCode = currentStatus; 10152 res.uid = -1; 10153 res.pkg = null; 10154 res.removedInfo = new PackageRemovedInfo(); 10155 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10156 args.doPreInstall(res.returnCode); 10157 synchronized (mInstallLock) { 10158 installPackageLI(args, res); 10159 } 10160 args.doPostInstall(res.returnCode, res.uid); 10161 } 10162 10163 // A restore should be performed at this point if (a) the install 10164 // succeeded, (b) the operation is not an update, and (c) the new 10165 // package has not opted out of backup participation. 10166 final boolean update = res.removedInfo.removedPackage != null; 10167 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10168 boolean doRestore = !update 10169 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10170 10171 // Set up the post-install work request bookkeeping. This will be used 10172 // and cleaned up by the post-install event handling regardless of whether 10173 // there's a restore pass performed. Token values are >= 1. 10174 int token; 10175 if (mNextInstallToken < 0) mNextInstallToken = 1; 10176 token = mNextInstallToken++; 10177 10178 PostInstallData data = new PostInstallData(args, res); 10179 mRunningInstalls.put(token, data); 10180 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10181 10182 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10183 // Pass responsibility to the Backup Manager. It will perform a 10184 // restore if appropriate, then pass responsibility back to the 10185 // Package Manager to run the post-install observer callbacks 10186 // and broadcasts. 10187 IBackupManager bm = IBackupManager.Stub.asInterface( 10188 ServiceManager.getService(Context.BACKUP_SERVICE)); 10189 if (bm != null) { 10190 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10191 + " to BM for possible restore"); 10192 try { 10193 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10194 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10195 } else { 10196 doRestore = false; 10197 } 10198 } catch (RemoteException e) { 10199 // can't happen; the backup manager is local 10200 } catch (Exception e) { 10201 Slog.e(TAG, "Exception trying to enqueue restore", e); 10202 doRestore = false; 10203 } 10204 } else { 10205 Slog.e(TAG, "Backup Manager not found!"); 10206 doRestore = false; 10207 } 10208 } 10209 10210 if (!doRestore) { 10211 // No restore possible, or the Backup Manager was mysteriously not 10212 // available -- just fire the post-install work request directly. 10213 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10214 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10215 mHandler.sendMessage(msg); 10216 } 10217 } 10218 }); 10219 } 10220 10221 private abstract class HandlerParams { 10222 private static final int MAX_RETRIES = 4; 10223 10224 /** 10225 * Number of times startCopy() has been attempted and had a non-fatal 10226 * error. 10227 */ 10228 private int mRetries = 0; 10229 10230 /** User handle for the user requesting the information or installation. */ 10231 private final UserHandle mUser; 10232 10233 HandlerParams(UserHandle user) { 10234 mUser = user; 10235 } 10236 10237 UserHandle getUser() { 10238 return mUser; 10239 } 10240 10241 final boolean startCopy() { 10242 boolean res; 10243 try { 10244 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10245 10246 if (++mRetries > MAX_RETRIES) { 10247 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10248 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10249 handleServiceError(); 10250 return false; 10251 } else { 10252 handleStartCopy(); 10253 res = true; 10254 } 10255 } catch (RemoteException e) { 10256 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10257 mHandler.sendEmptyMessage(MCS_RECONNECT); 10258 res = false; 10259 } 10260 handleReturnCode(); 10261 return res; 10262 } 10263 10264 final void serviceError() { 10265 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10266 handleServiceError(); 10267 handleReturnCode(); 10268 } 10269 10270 abstract void handleStartCopy() throws RemoteException; 10271 abstract void handleServiceError(); 10272 abstract void handleReturnCode(); 10273 } 10274 10275 class MeasureParams extends HandlerParams { 10276 private final PackageStats mStats; 10277 private boolean mSuccess; 10278 10279 private final IPackageStatsObserver mObserver; 10280 10281 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10282 super(new UserHandle(stats.userHandle)); 10283 mObserver = observer; 10284 mStats = stats; 10285 } 10286 10287 @Override 10288 public String toString() { 10289 return "MeasureParams{" 10290 + Integer.toHexString(System.identityHashCode(this)) 10291 + " " + mStats.packageName + "}"; 10292 } 10293 10294 @Override 10295 void handleStartCopy() throws RemoteException { 10296 synchronized (mInstallLock) { 10297 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10298 } 10299 10300 if (mSuccess) { 10301 final boolean mounted; 10302 if (Environment.isExternalStorageEmulated()) { 10303 mounted = true; 10304 } else { 10305 final String status = Environment.getExternalStorageState(); 10306 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10307 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10308 } 10309 10310 if (mounted) { 10311 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10312 10313 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10314 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10315 10316 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10317 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10318 10319 // Always subtract cache size, since it's a subdirectory 10320 mStats.externalDataSize -= mStats.externalCacheSize; 10321 10322 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10323 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10324 10325 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10326 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10327 } 10328 } 10329 } 10330 10331 @Override 10332 void handleReturnCode() { 10333 if (mObserver != null) { 10334 try { 10335 mObserver.onGetStatsCompleted(mStats, mSuccess); 10336 } catch (RemoteException e) { 10337 Slog.i(TAG, "Observer no longer exists."); 10338 } 10339 } 10340 } 10341 10342 @Override 10343 void handleServiceError() { 10344 Slog.e(TAG, "Could not measure application " + mStats.packageName 10345 + " external storage"); 10346 } 10347 } 10348 10349 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10350 throws RemoteException { 10351 long result = 0; 10352 for (File path : paths) { 10353 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10354 } 10355 return result; 10356 } 10357 10358 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10359 for (File path : paths) { 10360 try { 10361 mcs.clearDirectory(path.getAbsolutePath()); 10362 } catch (RemoteException e) { 10363 } 10364 } 10365 } 10366 10367 static class OriginInfo { 10368 /** 10369 * Location where install is coming from, before it has been 10370 * copied/renamed into place. This could be a single monolithic APK 10371 * file, or a cluster directory. This location may be untrusted. 10372 */ 10373 final File file; 10374 final String cid; 10375 10376 /** 10377 * Flag indicating that {@link #file} or {@link #cid} has already been 10378 * staged, meaning downstream users don't need to defensively copy the 10379 * contents. 10380 */ 10381 final boolean staged; 10382 10383 /** 10384 * Flag indicating that {@link #file} or {@link #cid} is an already 10385 * installed app that is being moved. 10386 */ 10387 final boolean existing; 10388 10389 final String resolvedPath; 10390 final File resolvedFile; 10391 10392 static OriginInfo fromNothing() { 10393 return new OriginInfo(null, null, false, false); 10394 } 10395 10396 static OriginInfo fromUntrustedFile(File file) { 10397 return new OriginInfo(file, null, false, false); 10398 } 10399 10400 static OriginInfo fromExistingFile(File file) { 10401 return new OriginInfo(file, null, false, true); 10402 } 10403 10404 static OriginInfo fromStagedFile(File file) { 10405 return new OriginInfo(file, null, true, false); 10406 } 10407 10408 static OriginInfo fromStagedContainer(String cid) { 10409 return new OriginInfo(null, cid, true, false); 10410 } 10411 10412 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10413 this.file = file; 10414 this.cid = cid; 10415 this.staged = staged; 10416 this.existing = existing; 10417 10418 if (cid != null) { 10419 resolvedPath = PackageHelper.getSdDir(cid); 10420 resolvedFile = new File(resolvedPath); 10421 } else if (file != null) { 10422 resolvedPath = file.getAbsolutePath(); 10423 resolvedFile = file; 10424 } else { 10425 resolvedPath = null; 10426 resolvedFile = null; 10427 } 10428 } 10429 } 10430 10431 class MoveInfo { 10432 final int moveId; 10433 final String fromUuid; 10434 final String toUuid; 10435 final String packageName; 10436 final String dataAppName; 10437 final int appId; 10438 final String seinfo; 10439 10440 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10441 String dataAppName, int appId, String seinfo) { 10442 this.moveId = moveId; 10443 this.fromUuid = fromUuid; 10444 this.toUuid = toUuid; 10445 this.packageName = packageName; 10446 this.dataAppName = dataAppName; 10447 this.appId = appId; 10448 this.seinfo = seinfo; 10449 } 10450 } 10451 10452 class InstallParams extends HandlerParams { 10453 final OriginInfo origin; 10454 final MoveInfo move; 10455 final IPackageInstallObserver2 observer; 10456 int installFlags; 10457 final String installerPackageName; 10458 final String volumeUuid; 10459 final VerificationParams verificationParams; 10460 private InstallArgs mArgs; 10461 private int mRet; 10462 final String packageAbiOverride; 10463 final String[] grantedRuntimePermissions; 10464 10465 10466 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10467 int installFlags, String installerPackageName, String volumeUuid, 10468 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10469 String[] grantedPermissions) { 10470 super(user); 10471 this.origin = origin; 10472 this.move = move; 10473 this.observer = observer; 10474 this.installFlags = installFlags; 10475 this.installerPackageName = installerPackageName; 10476 this.volumeUuid = volumeUuid; 10477 this.verificationParams = verificationParams; 10478 this.packageAbiOverride = packageAbiOverride; 10479 this.grantedRuntimePermissions = grantedPermissions; 10480 } 10481 10482 @Override 10483 public String toString() { 10484 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10485 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10486 } 10487 10488 public ManifestDigest getManifestDigest() { 10489 if (verificationParams == null) { 10490 return null; 10491 } 10492 return verificationParams.getManifestDigest(); 10493 } 10494 10495 private int installLocationPolicy(PackageInfoLite pkgLite) { 10496 String packageName = pkgLite.packageName; 10497 int installLocation = pkgLite.installLocation; 10498 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10499 // reader 10500 synchronized (mPackages) { 10501 PackageParser.Package pkg = mPackages.get(packageName); 10502 if (pkg != null) { 10503 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10504 // Check for downgrading. 10505 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10506 try { 10507 checkDowngrade(pkg, pkgLite); 10508 } catch (PackageManagerException e) { 10509 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10510 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10511 } 10512 } 10513 // Check for updated system application. 10514 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10515 if (onSd) { 10516 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10517 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10518 } 10519 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10520 } else { 10521 if (onSd) { 10522 // Install flag overrides everything. 10523 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10524 } 10525 // If current upgrade specifies particular preference 10526 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10527 // Application explicitly specified internal. 10528 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10529 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10530 // App explictly prefers external. Let policy decide 10531 } else { 10532 // Prefer previous location 10533 if (isExternal(pkg)) { 10534 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10535 } 10536 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10537 } 10538 } 10539 } else { 10540 // Invalid install. Return error code 10541 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10542 } 10543 } 10544 } 10545 // All the special cases have been taken care of. 10546 // Return result based on recommended install location. 10547 if (onSd) { 10548 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10549 } 10550 return pkgLite.recommendedInstallLocation; 10551 } 10552 10553 /* 10554 * Invoke remote method to get package information and install 10555 * location values. Override install location based on default 10556 * policy if needed and then create install arguments based 10557 * on the install location. 10558 */ 10559 public void handleStartCopy() throws RemoteException { 10560 int ret = PackageManager.INSTALL_SUCCEEDED; 10561 10562 // If we're already staged, we've firmly committed to an install location 10563 if (origin.staged) { 10564 if (origin.file != null) { 10565 installFlags |= PackageManager.INSTALL_INTERNAL; 10566 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10567 } else if (origin.cid != null) { 10568 installFlags |= PackageManager.INSTALL_EXTERNAL; 10569 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10570 } else { 10571 throw new IllegalStateException("Invalid stage location"); 10572 } 10573 } 10574 10575 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10576 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10577 10578 PackageInfoLite pkgLite = null; 10579 10580 if (onInt && onSd) { 10581 // Check if both bits are set. 10582 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10583 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10584 } else { 10585 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10586 packageAbiOverride); 10587 10588 /* 10589 * If we have too little free space, try to free cache 10590 * before giving up. 10591 */ 10592 if (!origin.staged && pkgLite.recommendedInstallLocation 10593 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10594 // TODO: focus freeing disk space on the target device 10595 final StorageManager storage = StorageManager.from(mContext); 10596 final long lowThreshold = storage.getStorageLowBytes( 10597 Environment.getDataDirectory()); 10598 10599 final long sizeBytes = mContainerService.calculateInstalledSize( 10600 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10601 10602 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10603 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10604 installFlags, packageAbiOverride); 10605 } 10606 10607 /* 10608 * The cache free must have deleted the file we 10609 * downloaded to install. 10610 * 10611 * TODO: fix the "freeCache" call to not delete 10612 * the file we care about. 10613 */ 10614 if (pkgLite.recommendedInstallLocation 10615 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10616 pkgLite.recommendedInstallLocation 10617 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10618 } 10619 } 10620 } 10621 10622 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10623 int loc = pkgLite.recommendedInstallLocation; 10624 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10625 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10626 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10627 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10628 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10629 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10630 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10631 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10632 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10633 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10634 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10635 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10636 } else { 10637 // Override with defaults if needed. 10638 loc = installLocationPolicy(pkgLite); 10639 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10640 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10641 } else if (!onSd && !onInt) { 10642 // Override install location with flags 10643 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10644 // Set the flag to install on external media. 10645 installFlags |= PackageManager.INSTALL_EXTERNAL; 10646 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10647 } else { 10648 // Make sure the flag for installing on external 10649 // media is unset 10650 installFlags |= PackageManager.INSTALL_INTERNAL; 10651 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10652 } 10653 } 10654 } 10655 } 10656 10657 final InstallArgs args = createInstallArgs(this); 10658 mArgs = args; 10659 10660 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10661 /* 10662 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10663 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10664 */ 10665 int userIdentifier = getUser().getIdentifier(); 10666 if (userIdentifier == UserHandle.USER_ALL 10667 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10668 userIdentifier = UserHandle.USER_OWNER; 10669 } 10670 10671 /* 10672 * Determine if we have any installed package verifiers. If we 10673 * do, then we'll defer to them to verify the packages. 10674 */ 10675 final int requiredUid = mRequiredVerifierPackage == null ? -1 10676 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10677 if (!origin.existing && requiredUid != -1 10678 && isVerificationEnabled(userIdentifier, installFlags)) { 10679 final Intent verification = new Intent( 10680 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10681 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10682 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10683 PACKAGE_MIME_TYPE); 10684 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10685 10686 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10687 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10688 0 /* TODO: Which userId? */); 10689 10690 if (DEBUG_VERIFY) { 10691 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10692 + verification.toString() + " with " + pkgLite.verifiers.length 10693 + " optional verifiers"); 10694 } 10695 10696 final int verificationId = mPendingVerificationToken++; 10697 10698 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10699 10700 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10701 installerPackageName); 10702 10703 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10704 installFlags); 10705 10706 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10707 pkgLite.packageName); 10708 10709 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10710 pkgLite.versionCode); 10711 10712 if (verificationParams != null) { 10713 if (verificationParams.getVerificationURI() != null) { 10714 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10715 verificationParams.getVerificationURI()); 10716 } 10717 if (verificationParams.getOriginatingURI() != null) { 10718 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10719 verificationParams.getOriginatingURI()); 10720 } 10721 if (verificationParams.getReferrer() != null) { 10722 verification.putExtra(Intent.EXTRA_REFERRER, 10723 verificationParams.getReferrer()); 10724 } 10725 if (verificationParams.getOriginatingUid() >= 0) { 10726 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10727 verificationParams.getOriginatingUid()); 10728 } 10729 if (verificationParams.getInstallerUid() >= 0) { 10730 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10731 verificationParams.getInstallerUid()); 10732 } 10733 } 10734 10735 final PackageVerificationState verificationState = new PackageVerificationState( 10736 requiredUid, args); 10737 10738 mPendingVerification.append(verificationId, verificationState); 10739 10740 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10741 receivers, verificationState); 10742 10743 // Apps installed for "all" users use the device owner to verify the app 10744 UserHandle verifierUser = getUser(); 10745 if (verifierUser == UserHandle.ALL) { 10746 verifierUser = UserHandle.OWNER; 10747 } 10748 10749 /* 10750 * If any sufficient verifiers were listed in the package 10751 * manifest, attempt to ask them. 10752 */ 10753 if (sufficientVerifiers != null) { 10754 final int N = sufficientVerifiers.size(); 10755 if (N == 0) { 10756 Slog.i(TAG, "Additional verifiers required, but none installed."); 10757 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10758 } else { 10759 for (int i = 0; i < N; i++) { 10760 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10761 10762 final Intent sufficientIntent = new Intent(verification); 10763 sufficientIntent.setComponent(verifierComponent); 10764 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10765 } 10766 } 10767 } 10768 10769 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10770 mRequiredVerifierPackage, receivers); 10771 if (ret == PackageManager.INSTALL_SUCCEEDED 10772 && mRequiredVerifierPackage != null) { 10773 /* 10774 * Send the intent to the required verification agent, 10775 * but only start the verification timeout after the 10776 * target BroadcastReceivers have run. 10777 */ 10778 verification.setComponent(requiredVerifierComponent); 10779 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10780 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10781 new BroadcastReceiver() { 10782 @Override 10783 public void onReceive(Context context, Intent intent) { 10784 final Message msg = mHandler 10785 .obtainMessage(CHECK_PENDING_VERIFICATION); 10786 msg.arg1 = verificationId; 10787 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10788 } 10789 }, null, 0, null, null); 10790 10791 /* 10792 * We don't want the copy to proceed until verification 10793 * succeeds, so null out this field. 10794 */ 10795 mArgs = null; 10796 } 10797 } else { 10798 /* 10799 * No package verification is enabled, so immediately start 10800 * the remote call to initiate copy using temporary file. 10801 */ 10802 ret = args.copyApk(mContainerService, true); 10803 } 10804 } 10805 10806 mRet = ret; 10807 } 10808 10809 @Override 10810 void handleReturnCode() { 10811 // If mArgs is null, then MCS couldn't be reached. When it 10812 // reconnects, it will try again to install. At that point, this 10813 // will succeed. 10814 if (mArgs != null) { 10815 processPendingInstall(mArgs, mRet); 10816 } 10817 } 10818 10819 @Override 10820 void handleServiceError() { 10821 mArgs = createInstallArgs(this); 10822 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10823 } 10824 10825 public boolean isForwardLocked() { 10826 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10827 } 10828 } 10829 10830 /** 10831 * Used during creation of InstallArgs 10832 * 10833 * @param installFlags package installation flags 10834 * @return true if should be installed on external storage 10835 */ 10836 private static boolean installOnExternalAsec(int installFlags) { 10837 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10838 return false; 10839 } 10840 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10841 return true; 10842 } 10843 return false; 10844 } 10845 10846 /** 10847 * Used during creation of InstallArgs 10848 * 10849 * @param installFlags package installation flags 10850 * @return true if should be installed as forward locked 10851 */ 10852 private static boolean installForwardLocked(int installFlags) { 10853 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10854 } 10855 10856 private InstallArgs createInstallArgs(InstallParams params) { 10857 if (params.move != null) { 10858 return new MoveInstallArgs(params); 10859 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10860 return new AsecInstallArgs(params); 10861 } else { 10862 return new FileInstallArgs(params); 10863 } 10864 } 10865 10866 /** 10867 * Create args that describe an existing installed package. Typically used 10868 * when cleaning up old installs, or used as a move source. 10869 */ 10870 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10871 String resourcePath, String[] instructionSets) { 10872 final boolean isInAsec; 10873 if (installOnExternalAsec(installFlags)) { 10874 /* Apps on SD card are always in ASEC containers. */ 10875 isInAsec = true; 10876 } else if (installForwardLocked(installFlags) 10877 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10878 /* 10879 * Forward-locked apps are only in ASEC containers if they're the 10880 * new style 10881 */ 10882 isInAsec = true; 10883 } else { 10884 isInAsec = false; 10885 } 10886 10887 if (isInAsec) { 10888 return new AsecInstallArgs(codePath, instructionSets, 10889 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10890 } else { 10891 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10892 } 10893 } 10894 10895 static abstract class InstallArgs { 10896 /** @see InstallParams#origin */ 10897 final OriginInfo origin; 10898 /** @see InstallParams#move */ 10899 final MoveInfo move; 10900 10901 final IPackageInstallObserver2 observer; 10902 // Always refers to PackageManager flags only 10903 final int installFlags; 10904 final String installerPackageName; 10905 final String volumeUuid; 10906 final ManifestDigest manifestDigest; 10907 final UserHandle user; 10908 final String abiOverride; 10909 final String[] installGrantPermissions; 10910 10911 // The list of instruction sets supported by this app. This is currently 10912 // only used during the rmdex() phase to clean up resources. We can get rid of this 10913 // if we move dex files under the common app path. 10914 /* nullable */ String[] instructionSets; 10915 10916 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10917 int installFlags, String installerPackageName, String volumeUuid, 10918 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10919 String abiOverride, String[] installGrantPermissions) { 10920 this.origin = origin; 10921 this.move = move; 10922 this.installFlags = installFlags; 10923 this.observer = observer; 10924 this.installerPackageName = installerPackageName; 10925 this.volumeUuid = volumeUuid; 10926 this.manifestDigest = manifestDigest; 10927 this.user = user; 10928 this.instructionSets = instructionSets; 10929 this.abiOverride = abiOverride; 10930 this.installGrantPermissions = installGrantPermissions; 10931 } 10932 10933 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10934 abstract int doPreInstall(int status); 10935 10936 /** 10937 * Rename package into final resting place. All paths on the given 10938 * scanned package should be updated to reflect the rename. 10939 */ 10940 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10941 abstract int doPostInstall(int status, int uid); 10942 10943 /** @see PackageSettingBase#codePathString */ 10944 abstract String getCodePath(); 10945 /** @see PackageSettingBase#resourcePathString */ 10946 abstract String getResourcePath(); 10947 10948 // Need installer lock especially for dex file removal. 10949 abstract void cleanUpResourcesLI(); 10950 abstract boolean doPostDeleteLI(boolean delete); 10951 10952 /** 10953 * Called before the source arguments are copied. This is used mostly 10954 * for MoveParams when it needs to read the source file to put it in the 10955 * destination. 10956 */ 10957 int doPreCopy() { 10958 return PackageManager.INSTALL_SUCCEEDED; 10959 } 10960 10961 /** 10962 * Called after the source arguments are copied. This is used mostly for 10963 * MoveParams when it needs to read the source file to put it in the 10964 * destination. 10965 * 10966 * @return 10967 */ 10968 int doPostCopy(int uid) { 10969 return PackageManager.INSTALL_SUCCEEDED; 10970 } 10971 10972 protected boolean isFwdLocked() { 10973 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10974 } 10975 10976 protected boolean isExternalAsec() { 10977 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10978 } 10979 10980 UserHandle getUser() { 10981 return user; 10982 } 10983 } 10984 10985 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10986 if (!allCodePaths.isEmpty()) { 10987 if (instructionSets == null) { 10988 throw new IllegalStateException("instructionSet == null"); 10989 } 10990 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10991 for (String codePath : allCodePaths) { 10992 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10993 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10994 if (retCode < 0) { 10995 Slog.w(TAG, "Couldn't remove dex file for package: " 10996 + " at location " + codePath + ", retcode=" + retCode); 10997 // we don't consider this to be a failure of the core package deletion 10998 } 10999 } 11000 } 11001 } 11002 } 11003 11004 /** 11005 * Logic to handle installation of non-ASEC applications, including copying 11006 * and renaming logic. 11007 */ 11008 class FileInstallArgs extends InstallArgs { 11009 private File codeFile; 11010 private File resourceFile; 11011 11012 // Example topology: 11013 // /data/app/com.example/base.apk 11014 // /data/app/com.example/split_foo.apk 11015 // /data/app/com.example/lib/arm/libfoo.so 11016 // /data/app/com.example/lib/arm64/libfoo.so 11017 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11018 11019 /** New install */ 11020 FileInstallArgs(InstallParams params) { 11021 super(params.origin, params.move, params.observer, params.installFlags, 11022 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11023 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11024 params.grantedRuntimePermissions); 11025 if (isFwdLocked()) { 11026 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11027 } 11028 } 11029 11030 /** Existing install */ 11031 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11032 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11033 null, null); 11034 this.codeFile = (codePath != null) ? new File(codePath) : null; 11035 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11036 } 11037 11038 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11039 if (origin.staged) { 11040 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11041 codeFile = origin.file; 11042 resourceFile = origin.file; 11043 return PackageManager.INSTALL_SUCCEEDED; 11044 } 11045 11046 try { 11047 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11048 codeFile = tempDir; 11049 resourceFile = tempDir; 11050 } catch (IOException e) { 11051 Slog.w(TAG, "Failed to create copy file: " + e); 11052 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11053 } 11054 11055 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11056 @Override 11057 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11058 if (!FileUtils.isValidExtFilename(name)) { 11059 throw new IllegalArgumentException("Invalid filename: " + name); 11060 } 11061 try { 11062 final File file = new File(codeFile, name); 11063 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11064 O_RDWR | O_CREAT, 0644); 11065 Os.chmod(file.getAbsolutePath(), 0644); 11066 return new ParcelFileDescriptor(fd); 11067 } catch (ErrnoException e) { 11068 throw new RemoteException("Failed to open: " + e.getMessage()); 11069 } 11070 } 11071 }; 11072 11073 int ret = PackageManager.INSTALL_SUCCEEDED; 11074 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11075 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11076 Slog.e(TAG, "Failed to copy package"); 11077 return ret; 11078 } 11079 11080 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11081 NativeLibraryHelper.Handle handle = null; 11082 try { 11083 handle = NativeLibraryHelper.Handle.create(codeFile); 11084 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11085 abiOverride); 11086 } catch (IOException e) { 11087 Slog.e(TAG, "Copying native libraries failed", e); 11088 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11089 } finally { 11090 IoUtils.closeQuietly(handle); 11091 } 11092 11093 return ret; 11094 } 11095 11096 int doPreInstall(int status) { 11097 if (status != PackageManager.INSTALL_SUCCEEDED) { 11098 cleanUp(); 11099 } 11100 return status; 11101 } 11102 11103 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11104 if (status != PackageManager.INSTALL_SUCCEEDED) { 11105 cleanUp(); 11106 return false; 11107 } 11108 11109 final File targetDir = codeFile.getParentFile(); 11110 final File beforeCodeFile = codeFile; 11111 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11112 11113 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11114 try { 11115 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11116 } catch (ErrnoException e) { 11117 Slog.w(TAG, "Failed to rename", e); 11118 return false; 11119 } 11120 11121 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11122 Slog.w(TAG, "Failed to restorecon"); 11123 return false; 11124 } 11125 11126 // Reflect the rename internally 11127 codeFile = afterCodeFile; 11128 resourceFile = afterCodeFile; 11129 11130 // Reflect the rename in scanned details 11131 pkg.codePath = afterCodeFile.getAbsolutePath(); 11132 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11133 pkg.baseCodePath); 11134 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11135 pkg.splitCodePaths); 11136 11137 // Reflect the rename in app info 11138 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11139 pkg.applicationInfo.setCodePath(pkg.codePath); 11140 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11141 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11142 pkg.applicationInfo.setResourcePath(pkg.codePath); 11143 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11144 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11145 11146 return true; 11147 } 11148 11149 int doPostInstall(int status, int uid) { 11150 if (status != PackageManager.INSTALL_SUCCEEDED) { 11151 cleanUp(); 11152 } 11153 return status; 11154 } 11155 11156 @Override 11157 String getCodePath() { 11158 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11159 } 11160 11161 @Override 11162 String getResourcePath() { 11163 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11164 } 11165 11166 private boolean cleanUp() { 11167 if (codeFile == null || !codeFile.exists()) { 11168 return false; 11169 } 11170 11171 if (codeFile.isDirectory()) { 11172 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11173 } else { 11174 codeFile.delete(); 11175 } 11176 11177 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11178 resourceFile.delete(); 11179 } 11180 11181 return true; 11182 } 11183 11184 void cleanUpResourcesLI() { 11185 // Try enumerating all code paths before deleting 11186 List<String> allCodePaths = Collections.EMPTY_LIST; 11187 if (codeFile != null && codeFile.exists()) { 11188 try { 11189 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11190 allCodePaths = pkg.getAllCodePaths(); 11191 } catch (PackageParserException e) { 11192 // Ignored; we tried our best 11193 } 11194 } 11195 11196 cleanUp(); 11197 removeDexFiles(allCodePaths, instructionSets); 11198 } 11199 11200 boolean doPostDeleteLI(boolean delete) { 11201 // XXX err, shouldn't we respect the delete flag? 11202 cleanUpResourcesLI(); 11203 return true; 11204 } 11205 } 11206 11207 private boolean isAsecExternal(String cid) { 11208 final String asecPath = PackageHelper.getSdFilesystem(cid); 11209 return !asecPath.startsWith(mAsecInternalPath); 11210 } 11211 11212 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11213 PackageManagerException { 11214 if (copyRet < 0) { 11215 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11216 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11217 throw new PackageManagerException(copyRet, message); 11218 } 11219 } 11220 } 11221 11222 /** 11223 * Extract the MountService "container ID" from the full code path of an 11224 * .apk. 11225 */ 11226 static String cidFromCodePath(String fullCodePath) { 11227 int eidx = fullCodePath.lastIndexOf("/"); 11228 String subStr1 = fullCodePath.substring(0, eidx); 11229 int sidx = subStr1.lastIndexOf("/"); 11230 return subStr1.substring(sidx+1, eidx); 11231 } 11232 11233 /** 11234 * Logic to handle installation of ASEC applications, including copying and 11235 * renaming logic. 11236 */ 11237 class AsecInstallArgs extends InstallArgs { 11238 static final String RES_FILE_NAME = "pkg.apk"; 11239 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11240 11241 String cid; 11242 String packagePath; 11243 String resourcePath; 11244 11245 /** New install */ 11246 AsecInstallArgs(InstallParams params) { 11247 super(params.origin, params.move, params.observer, params.installFlags, 11248 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11249 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11250 params.grantedRuntimePermissions); 11251 } 11252 11253 /** Existing install */ 11254 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11255 boolean isExternal, boolean isForwardLocked) { 11256 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11257 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11258 instructionSets, null, null); 11259 // Hackily pretend we're still looking at a full code path 11260 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11261 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11262 } 11263 11264 // Extract cid from fullCodePath 11265 int eidx = fullCodePath.lastIndexOf("/"); 11266 String subStr1 = fullCodePath.substring(0, eidx); 11267 int sidx = subStr1.lastIndexOf("/"); 11268 cid = subStr1.substring(sidx+1, eidx); 11269 setMountPath(subStr1); 11270 } 11271 11272 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11273 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11274 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11275 instructionSets, null, null); 11276 this.cid = cid; 11277 setMountPath(PackageHelper.getSdDir(cid)); 11278 } 11279 11280 void createCopyFile() { 11281 cid = mInstallerService.allocateExternalStageCidLegacy(); 11282 } 11283 11284 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11285 if (origin.staged) { 11286 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11287 cid = origin.cid; 11288 setMountPath(PackageHelper.getSdDir(cid)); 11289 return PackageManager.INSTALL_SUCCEEDED; 11290 } 11291 11292 if (temp) { 11293 createCopyFile(); 11294 } else { 11295 /* 11296 * Pre-emptively destroy the container since it's destroyed if 11297 * copying fails due to it existing anyway. 11298 */ 11299 PackageHelper.destroySdDir(cid); 11300 } 11301 11302 final String newMountPath = imcs.copyPackageToContainer( 11303 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11304 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11305 11306 if (newMountPath != null) { 11307 setMountPath(newMountPath); 11308 return PackageManager.INSTALL_SUCCEEDED; 11309 } else { 11310 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11311 } 11312 } 11313 11314 @Override 11315 String getCodePath() { 11316 return packagePath; 11317 } 11318 11319 @Override 11320 String getResourcePath() { 11321 return resourcePath; 11322 } 11323 11324 int doPreInstall(int status) { 11325 if (status != PackageManager.INSTALL_SUCCEEDED) { 11326 // Destroy container 11327 PackageHelper.destroySdDir(cid); 11328 } else { 11329 boolean mounted = PackageHelper.isContainerMounted(cid); 11330 if (!mounted) { 11331 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11332 Process.SYSTEM_UID); 11333 if (newMountPath != null) { 11334 setMountPath(newMountPath); 11335 } else { 11336 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11337 } 11338 } 11339 } 11340 return status; 11341 } 11342 11343 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11344 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11345 String newMountPath = null; 11346 if (PackageHelper.isContainerMounted(cid)) { 11347 // Unmount the container 11348 if (!PackageHelper.unMountSdDir(cid)) { 11349 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11350 return false; 11351 } 11352 } 11353 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11354 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11355 " which might be stale. Will try to clean up."); 11356 // Clean up the stale container and proceed to recreate. 11357 if (!PackageHelper.destroySdDir(newCacheId)) { 11358 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11359 return false; 11360 } 11361 // Successfully cleaned up stale container. Try to rename again. 11362 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11363 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11364 + " inspite of cleaning it up."); 11365 return false; 11366 } 11367 } 11368 if (!PackageHelper.isContainerMounted(newCacheId)) { 11369 Slog.w(TAG, "Mounting container " + newCacheId); 11370 newMountPath = PackageHelper.mountSdDir(newCacheId, 11371 getEncryptKey(), Process.SYSTEM_UID); 11372 } else { 11373 newMountPath = PackageHelper.getSdDir(newCacheId); 11374 } 11375 if (newMountPath == null) { 11376 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11377 return false; 11378 } 11379 Log.i(TAG, "Succesfully renamed " + cid + 11380 " to " + newCacheId + 11381 " at new path: " + newMountPath); 11382 cid = newCacheId; 11383 11384 final File beforeCodeFile = new File(packagePath); 11385 setMountPath(newMountPath); 11386 final File afterCodeFile = new File(packagePath); 11387 11388 // Reflect the rename in scanned details 11389 pkg.codePath = afterCodeFile.getAbsolutePath(); 11390 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11391 pkg.baseCodePath); 11392 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11393 pkg.splitCodePaths); 11394 11395 // Reflect the rename in app info 11396 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11397 pkg.applicationInfo.setCodePath(pkg.codePath); 11398 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11399 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11400 pkg.applicationInfo.setResourcePath(pkg.codePath); 11401 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11402 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11403 11404 return true; 11405 } 11406 11407 private void setMountPath(String mountPath) { 11408 final File mountFile = new File(mountPath); 11409 11410 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11411 if (monolithicFile.exists()) { 11412 packagePath = monolithicFile.getAbsolutePath(); 11413 if (isFwdLocked()) { 11414 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11415 } else { 11416 resourcePath = packagePath; 11417 } 11418 } else { 11419 packagePath = mountFile.getAbsolutePath(); 11420 resourcePath = packagePath; 11421 } 11422 } 11423 11424 int doPostInstall(int status, int uid) { 11425 if (status != PackageManager.INSTALL_SUCCEEDED) { 11426 cleanUp(); 11427 } else { 11428 final int groupOwner; 11429 final String protectedFile; 11430 if (isFwdLocked()) { 11431 groupOwner = UserHandle.getSharedAppGid(uid); 11432 protectedFile = RES_FILE_NAME; 11433 } else { 11434 groupOwner = -1; 11435 protectedFile = null; 11436 } 11437 11438 if (uid < Process.FIRST_APPLICATION_UID 11439 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11440 Slog.e(TAG, "Failed to finalize " + cid); 11441 PackageHelper.destroySdDir(cid); 11442 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11443 } 11444 11445 boolean mounted = PackageHelper.isContainerMounted(cid); 11446 if (!mounted) { 11447 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11448 } 11449 } 11450 return status; 11451 } 11452 11453 private void cleanUp() { 11454 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11455 11456 // Destroy secure container 11457 PackageHelper.destroySdDir(cid); 11458 } 11459 11460 private List<String> getAllCodePaths() { 11461 final File codeFile = new File(getCodePath()); 11462 if (codeFile != null && codeFile.exists()) { 11463 try { 11464 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11465 return pkg.getAllCodePaths(); 11466 } catch (PackageParserException e) { 11467 // Ignored; we tried our best 11468 } 11469 } 11470 return Collections.EMPTY_LIST; 11471 } 11472 11473 void cleanUpResourcesLI() { 11474 // Enumerate all code paths before deleting 11475 cleanUpResourcesLI(getAllCodePaths()); 11476 } 11477 11478 private void cleanUpResourcesLI(List<String> allCodePaths) { 11479 cleanUp(); 11480 removeDexFiles(allCodePaths, instructionSets); 11481 } 11482 11483 String getPackageName() { 11484 return getAsecPackageName(cid); 11485 } 11486 11487 boolean doPostDeleteLI(boolean delete) { 11488 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11489 final List<String> allCodePaths = getAllCodePaths(); 11490 boolean mounted = PackageHelper.isContainerMounted(cid); 11491 if (mounted) { 11492 // Unmount first 11493 if (PackageHelper.unMountSdDir(cid)) { 11494 mounted = false; 11495 } 11496 } 11497 if (!mounted && delete) { 11498 cleanUpResourcesLI(allCodePaths); 11499 } 11500 return !mounted; 11501 } 11502 11503 @Override 11504 int doPreCopy() { 11505 if (isFwdLocked()) { 11506 if (!PackageHelper.fixSdPermissions(cid, 11507 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11508 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11509 } 11510 } 11511 11512 return PackageManager.INSTALL_SUCCEEDED; 11513 } 11514 11515 @Override 11516 int doPostCopy(int uid) { 11517 if (isFwdLocked()) { 11518 if (uid < Process.FIRST_APPLICATION_UID 11519 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11520 RES_FILE_NAME)) { 11521 Slog.e(TAG, "Failed to finalize " + cid); 11522 PackageHelper.destroySdDir(cid); 11523 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11524 } 11525 } 11526 11527 return PackageManager.INSTALL_SUCCEEDED; 11528 } 11529 } 11530 11531 /** 11532 * Logic to handle movement of existing installed applications. 11533 */ 11534 class MoveInstallArgs extends InstallArgs { 11535 private File codeFile; 11536 private File resourceFile; 11537 11538 /** New install */ 11539 MoveInstallArgs(InstallParams params) { 11540 super(params.origin, params.move, params.observer, params.installFlags, 11541 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11542 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11543 params.grantedRuntimePermissions); 11544 } 11545 11546 int copyApk(IMediaContainerService imcs, boolean temp) { 11547 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11548 + move.fromUuid + " to " + move.toUuid); 11549 synchronized (mInstaller) { 11550 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11551 move.dataAppName, move.appId, move.seinfo) != 0) { 11552 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11553 } 11554 } 11555 11556 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11557 resourceFile = codeFile; 11558 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11559 11560 return PackageManager.INSTALL_SUCCEEDED; 11561 } 11562 11563 int doPreInstall(int status) { 11564 if (status != PackageManager.INSTALL_SUCCEEDED) { 11565 cleanUp(move.toUuid); 11566 } 11567 return status; 11568 } 11569 11570 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11571 if (status != PackageManager.INSTALL_SUCCEEDED) { 11572 cleanUp(move.toUuid); 11573 return false; 11574 } 11575 11576 // Reflect the move in app info 11577 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11578 pkg.applicationInfo.setCodePath(pkg.codePath); 11579 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11580 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11581 pkg.applicationInfo.setResourcePath(pkg.codePath); 11582 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11583 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11584 11585 return true; 11586 } 11587 11588 int doPostInstall(int status, int uid) { 11589 if (status == PackageManager.INSTALL_SUCCEEDED) { 11590 cleanUp(move.fromUuid); 11591 } else { 11592 cleanUp(move.toUuid); 11593 } 11594 return status; 11595 } 11596 11597 @Override 11598 String getCodePath() { 11599 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11600 } 11601 11602 @Override 11603 String getResourcePath() { 11604 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11605 } 11606 11607 private boolean cleanUp(String volumeUuid) { 11608 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11609 move.dataAppName); 11610 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11611 synchronized (mInstallLock) { 11612 // Clean up both app data and code 11613 removeDataDirsLI(volumeUuid, move.packageName); 11614 if (codeFile.isDirectory()) { 11615 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11616 } else { 11617 codeFile.delete(); 11618 } 11619 } 11620 return true; 11621 } 11622 11623 void cleanUpResourcesLI() { 11624 throw new UnsupportedOperationException(); 11625 } 11626 11627 boolean doPostDeleteLI(boolean delete) { 11628 throw new UnsupportedOperationException(); 11629 } 11630 } 11631 11632 static String getAsecPackageName(String packageCid) { 11633 int idx = packageCid.lastIndexOf("-"); 11634 if (idx == -1) { 11635 return packageCid; 11636 } 11637 return packageCid.substring(0, idx); 11638 } 11639 11640 // Utility method used to create code paths based on package name and available index. 11641 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11642 String idxStr = ""; 11643 int idx = 1; 11644 // Fall back to default value of idx=1 if prefix is not 11645 // part of oldCodePath 11646 if (oldCodePath != null) { 11647 String subStr = oldCodePath; 11648 // Drop the suffix right away 11649 if (suffix != null && subStr.endsWith(suffix)) { 11650 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11651 } 11652 // If oldCodePath already contains prefix find out the 11653 // ending index to either increment or decrement. 11654 int sidx = subStr.lastIndexOf(prefix); 11655 if (sidx != -1) { 11656 subStr = subStr.substring(sidx + prefix.length()); 11657 if (subStr != null) { 11658 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11659 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11660 } 11661 try { 11662 idx = Integer.parseInt(subStr); 11663 if (idx <= 1) { 11664 idx++; 11665 } else { 11666 idx--; 11667 } 11668 } catch(NumberFormatException e) { 11669 } 11670 } 11671 } 11672 } 11673 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11674 return prefix + idxStr; 11675 } 11676 11677 private File getNextCodePath(File targetDir, String packageName) { 11678 int suffix = 1; 11679 File result; 11680 do { 11681 result = new File(targetDir, packageName + "-" + suffix); 11682 suffix++; 11683 } while (result.exists()); 11684 return result; 11685 } 11686 11687 // Utility method that returns the relative package path with respect 11688 // to the installation directory. Like say for /data/data/com.test-1.apk 11689 // string com.test-1 is returned. 11690 static String deriveCodePathName(String codePath) { 11691 if (codePath == null) { 11692 return null; 11693 } 11694 final File codeFile = new File(codePath); 11695 final String name = codeFile.getName(); 11696 if (codeFile.isDirectory()) { 11697 return name; 11698 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11699 final int lastDot = name.lastIndexOf('.'); 11700 return name.substring(0, lastDot); 11701 } else { 11702 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11703 return null; 11704 } 11705 } 11706 11707 class PackageInstalledInfo { 11708 String name; 11709 int uid; 11710 // The set of users that originally had this package installed. 11711 int[] origUsers; 11712 // The set of users that now have this package installed. 11713 int[] newUsers; 11714 PackageParser.Package pkg; 11715 int returnCode; 11716 String returnMsg; 11717 PackageRemovedInfo removedInfo; 11718 11719 public void setError(int code, String msg) { 11720 returnCode = code; 11721 returnMsg = msg; 11722 Slog.w(TAG, msg); 11723 } 11724 11725 public void setError(String msg, PackageParserException e) { 11726 returnCode = e.error; 11727 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11728 Slog.w(TAG, msg, e); 11729 } 11730 11731 public void setError(String msg, PackageManagerException e) { 11732 returnCode = e.error; 11733 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11734 Slog.w(TAG, msg, e); 11735 } 11736 11737 // In some error cases we want to convey more info back to the observer 11738 String origPackage; 11739 String origPermission; 11740 } 11741 11742 /* 11743 * Install a non-existing package. 11744 */ 11745 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11746 UserHandle user, String installerPackageName, String volumeUuid, 11747 PackageInstalledInfo res) { 11748 // Remember this for later, in case we need to rollback this install 11749 String pkgName = pkg.packageName; 11750 11751 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11752 final boolean dataDirExists = Environment 11753 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11754 synchronized(mPackages) { 11755 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11756 // A package with the same name is already installed, though 11757 // it has been renamed to an older name. The package we 11758 // are trying to install should be installed as an update to 11759 // the existing one, but that has not been requested, so bail. 11760 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11761 + " without first uninstalling package running as " 11762 + mSettings.mRenamedPackages.get(pkgName)); 11763 return; 11764 } 11765 if (mPackages.containsKey(pkgName)) { 11766 // Don't allow installation over an existing package with the same name. 11767 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11768 + " without first uninstalling."); 11769 return; 11770 } 11771 } 11772 11773 try { 11774 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11775 System.currentTimeMillis(), user); 11776 11777 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11778 // delete the partially installed application. the data directory will have to be 11779 // restored if it was already existing 11780 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11781 // remove package from internal structures. Note that we want deletePackageX to 11782 // delete the package data and cache directories that it created in 11783 // scanPackageLocked, unless those directories existed before we even tried to 11784 // install. 11785 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11786 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11787 res.removedInfo, true); 11788 } 11789 11790 } catch (PackageManagerException e) { 11791 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11792 } 11793 } 11794 11795 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11796 // Can't rotate keys during boot or if sharedUser. 11797 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11798 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11799 return false; 11800 } 11801 // app is using upgradeKeySets; make sure all are valid 11802 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11803 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11804 for (int i = 0; i < upgradeKeySets.length; i++) { 11805 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11806 Slog.wtf(TAG, "Package " 11807 + (oldPs.name != null ? oldPs.name : "<null>") 11808 + " contains upgrade-key-set reference to unknown key-set: " 11809 + upgradeKeySets[i] 11810 + " reverting to signatures check."); 11811 return false; 11812 } 11813 } 11814 return true; 11815 } 11816 11817 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11818 // Upgrade keysets are being used. Determine if new package has a superset of the 11819 // required keys. 11820 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11821 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11822 for (int i = 0; i < upgradeKeySets.length; i++) { 11823 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11824 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11825 return true; 11826 } 11827 } 11828 return false; 11829 } 11830 11831 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11832 UserHandle user, String installerPackageName, String volumeUuid, 11833 PackageInstalledInfo res) { 11834 final PackageParser.Package oldPackage; 11835 final String pkgName = pkg.packageName; 11836 final int[] allUsers; 11837 final boolean[] perUserInstalled; 11838 11839 // First find the old package info and check signatures 11840 synchronized(mPackages) { 11841 oldPackage = mPackages.get(pkgName); 11842 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11843 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11844 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11845 if(!checkUpgradeKeySetLP(ps, pkg)) { 11846 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11847 "New package not signed by keys specified by upgrade-keysets: " 11848 + pkgName); 11849 return; 11850 } 11851 } else { 11852 // default to original signature matching 11853 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11854 != PackageManager.SIGNATURE_MATCH) { 11855 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11856 "New package has a different signature: " + pkgName); 11857 return; 11858 } 11859 } 11860 11861 // In case of rollback, remember per-user/profile install state 11862 allUsers = sUserManager.getUserIds(); 11863 perUserInstalled = new boolean[allUsers.length]; 11864 for (int i = 0; i < allUsers.length; i++) { 11865 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11866 } 11867 } 11868 11869 boolean sysPkg = (isSystemApp(oldPackage)); 11870 if (sysPkg) { 11871 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11872 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11873 } else { 11874 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11875 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11876 } 11877 } 11878 11879 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11880 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11881 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11882 String volumeUuid, PackageInstalledInfo res) { 11883 String pkgName = deletedPackage.packageName; 11884 boolean deletedPkg = true; 11885 boolean updatedSettings = false; 11886 11887 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11888 + deletedPackage); 11889 long origUpdateTime; 11890 if (pkg.mExtras != null) { 11891 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11892 } else { 11893 origUpdateTime = 0; 11894 } 11895 11896 // First delete the existing package while retaining the data directory 11897 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11898 res.removedInfo, true)) { 11899 // If the existing package wasn't successfully deleted 11900 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11901 deletedPkg = false; 11902 } else { 11903 // Successfully deleted the old package; proceed with replace. 11904 11905 // If deleted package lived in a container, give users a chance to 11906 // relinquish resources before killing. 11907 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11908 if (DEBUG_INSTALL) { 11909 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11910 } 11911 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11912 final ArrayList<String> pkgList = new ArrayList<String>(1); 11913 pkgList.add(deletedPackage.applicationInfo.packageName); 11914 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11915 } 11916 11917 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11918 try { 11919 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11920 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11921 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11922 perUserInstalled, res, user); 11923 updatedSettings = true; 11924 } catch (PackageManagerException e) { 11925 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11926 } 11927 } 11928 11929 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11930 // remove package from internal structures. Note that we want deletePackageX to 11931 // delete the package data and cache directories that it created in 11932 // scanPackageLocked, unless those directories existed before we even tried to 11933 // install. 11934 if(updatedSettings) { 11935 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11936 deletePackageLI( 11937 pkgName, null, true, allUsers, perUserInstalled, 11938 PackageManager.DELETE_KEEP_DATA, 11939 res.removedInfo, true); 11940 } 11941 // Since we failed to install the new package we need to restore the old 11942 // package that we deleted. 11943 if (deletedPkg) { 11944 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11945 File restoreFile = new File(deletedPackage.codePath); 11946 // Parse old package 11947 boolean oldExternal = isExternal(deletedPackage); 11948 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11949 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11950 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11951 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11952 try { 11953 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11954 } catch (PackageManagerException e) { 11955 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11956 + e.getMessage()); 11957 return; 11958 } 11959 // Restore of old package succeeded. Update permissions. 11960 // writer 11961 synchronized (mPackages) { 11962 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11963 UPDATE_PERMISSIONS_ALL); 11964 // can downgrade to reader 11965 mSettings.writeLPr(); 11966 } 11967 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11968 } 11969 } 11970 } 11971 11972 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11973 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11974 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11975 String volumeUuid, PackageInstalledInfo res) { 11976 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11977 + ", old=" + deletedPackage); 11978 boolean disabledSystem = false; 11979 boolean updatedSettings = false; 11980 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11981 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11982 != 0) { 11983 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11984 } 11985 String packageName = deletedPackage.packageName; 11986 if (packageName == null) { 11987 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11988 "Attempt to delete null packageName."); 11989 return; 11990 } 11991 PackageParser.Package oldPkg; 11992 PackageSetting oldPkgSetting; 11993 // reader 11994 synchronized (mPackages) { 11995 oldPkg = mPackages.get(packageName); 11996 oldPkgSetting = mSettings.mPackages.get(packageName); 11997 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11998 (oldPkgSetting == null)) { 11999 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12000 "Couldn't find package:" + packageName + " information"); 12001 return; 12002 } 12003 } 12004 12005 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12006 12007 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12008 res.removedInfo.removedPackage = packageName; 12009 // Remove existing system package 12010 removePackageLI(oldPkgSetting, true); 12011 // writer 12012 synchronized (mPackages) { 12013 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12014 if (!disabledSystem && deletedPackage != null) { 12015 // We didn't need to disable the .apk as a current system package, 12016 // which means we are replacing another update that is already 12017 // installed. We need to make sure to delete the older one's .apk. 12018 res.removedInfo.args = createInstallArgsForExisting(0, 12019 deletedPackage.applicationInfo.getCodePath(), 12020 deletedPackage.applicationInfo.getResourcePath(), 12021 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12022 } else { 12023 res.removedInfo.args = null; 12024 } 12025 } 12026 12027 // Successfully disabled the old package. Now proceed with re-installation 12028 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12029 12030 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12031 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12032 12033 PackageParser.Package newPackage = null; 12034 try { 12035 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 12036 if (newPackage.mExtras != null) { 12037 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12038 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12039 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12040 12041 // is the update attempting to change shared user? that isn't going to work... 12042 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12043 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12044 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12045 + " to " + newPkgSetting.sharedUser); 12046 updatedSettings = true; 12047 } 12048 } 12049 12050 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12051 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12052 perUserInstalled, res, user); 12053 updatedSettings = true; 12054 } 12055 12056 } catch (PackageManagerException e) { 12057 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12058 } 12059 12060 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12061 // Re installation failed. Restore old information 12062 // Remove new pkg information 12063 if (newPackage != null) { 12064 removeInstalledPackageLI(newPackage, true); 12065 } 12066 // Add back the old system package 12067 try { 12068 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12069 } catch (PackageManagerException e) { 12070 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12071 } 12072 // Restore the old system information in Settings 12073 synchronized (mPackages) { 12074 if (disabledSystem) { 12075 mSettings.enableSystemPackageLPw(packageName); 12076 } 12077 if (updatedSettings) { 12078 mSettings.setInstallerPackageName(packageName, 12079 oldPkgSetting.installerPackageName); 12080 } 12081 mSettings.writeLPr(); 12082 } 12083 } 12084 } 12085 12086 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12087 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12088 UserHandle user) { 12089 String pkgName = newPackage.packageName; 12090 synchronized (mPackages) { 12091 //write settings. the installStatus will be incomplete at this stage. 12092 //note that the new package setting would have already been 12093 //added to mPackages. It hasn't been persisted yet. 12094 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12095 mSettings.writeLPr(); 12096 } 12097 12098 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12099 12100 synchronized (mPackages) { 12101 updatePermissionsLPw(newPackage.packageName, newPackage, 12102 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12103 ? UPDATE_PERMISSIONS_ALL : 0)); 12104 // For system-bundled packages, we assume that installing an upgraded version 12105 // of the package implies that the user actually wants to run that new code, 12106 // so we enable the package. 12107 PackageSetting ps = mSettings.mPackages.get(pkgName); 12108 if (ps != null) { 12109 if (isSystemApp(newPackage)) { 12110 // NB: implicit assumption that system package upgrades apply to all users 12111 if (DEBUG_INSTALL) { 12112 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12113 } 12114 if (res.origUsers != null) { 12115 for (int userHandle : res.origUsers) { 12116 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12117 userHandle, installerPackageName); 12118 } 12119 } 12120 // Also convey the prior install/uninstall state 12121 if (allUsers != null && perUserInstalled != null) { 12122 for (int i = 0; i < allUsers.length; i++) { 12123 if (DEBUG_INSTALL) { 12124 Slog.d(TAG, " user " + allUsers[i] 12125 + " => " + perUserInstalled[i]); 12126 } 12127 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12128 } 12129 // these install state changes will be persisted in the 12130 // upcoming call to mSettings.writeLPr(). 12131 } 12132 } 12133 // It's implied that when a user requests installation, they want the app to be 12134 // installed and enabled. 12135 int userId = user.getIdentifier(); 12136 if (userId != UserHandle.USER_ALL) { 12137 ps.setInstalled(true, userId); 12138 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12139 } 12140 } 12141 res.name = pkgName; 12142 res.uid = newPackage.applicationInfo.uid; 12143 res.pkg = newPackage; 12144 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12145 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12146 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12147 //to update install status 12148 mSettings.writeLPr(); 12149 } 12150 } 12151 12152 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12153 final int installFlags = args.installFlags; 12154 final String installerPackageName = args.installerPackageName; 12155 final String volumeUuid = args.volumeUuid; 12156 final File tmpPackageFile = new File(args.getCodePath()); 12157 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12158 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12159 || (args.volumeUuid != null)); 12160 boolean replace = false; 12161 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12162 if (args.move != null) { 12163 // moving a complete application; perfom an initial scan on the new install location 12164 scanFlags |= SCAN_INITIAL; 12165 } 12166 // Result object to be returned 12167 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12168 12169 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12170 // Retrieve PackageSettings and parse package 12171 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12172 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12173 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12174 PackageParser pp = new PackageParser(); 12175 pp.setSeparateProcesses(mSeparateProcesses); 12176 pp.setDisplayMetrics(mMetrics); 12177 12178 final PackageParser.Package pkg; 12179 try { 12180 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12181 } catch (PackageParserException e) { 12182 res.setError("Failed parse during installPackageLI", e); 12183 return; 12184 } 12185 12186 // Mark that we have an install time CPU ABI override. 12187 pkg.cpuAbiOverride = args.abiOverride; 12188 12189 String pkgName = res.name = pkg.packageName; 12190 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12191 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12192 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12193 return; 12194 } 12195 } 12196 12197 try { 12198 pp.collectCertificates(pkg, parseFlags); 12199 pp.collectManifestDigest(pkg); 12200 } catch (PackageParserException e) { 12201 res.setError("Failed collect during installPackageLI", e); 12202 return; 12203 } 12204 12205 /* If the installer passed in a manifest digest, compare it now. */ 12206 if (args.manifestDigest != null) { 12207 if (DEBUG_INSTALL) { 12208 final String parsedManifest = pkg.manifestDigest == null ? "null" 12209 : pkg.manifestDigest.toString(); 12210 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12211 + parsedManifest); 12212 } 12213 12214 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12215 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12216 return; 12217 } 12218 } else if (DEBUG_INSTALL) { 12219 final String parsedManifest = pkg.manifestDigest == null 12220 ? "null" : pkg.manifestDigest.toString(); 12221 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12222 } 12223 12224 // Get rid of all references to package scan path via parser. 12225 pp = null; 12226 String oldCodePath = null; 12227 boolean systemApp = false; 12228 synchronized (mPackages) { 12229 // Check if installing already existing package 12230 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12231 String oldName = mSettings.mRenamedPackages.get(pkgName); 12232 if (pkg.mOriginalPackages != null 12233 && pkg.mOriginalPackages.contains(oldName) 12234 && mPackages.containsKey(oldName)) { 12235 // This package is derived from an original package, 12236 // and this device has been updating from that original 12237 // name. We must continue using the original name, so 12238 // rename the new package here. 12239 pkg.setPackageName(oldName); 12240 pkgName = pkg.packageName; 12241 replace = true; 12242 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12243 + oldName + " pkgName=" + pkgName); 12244 } else if (mPackages.containsKey(pkgName)) { 12245 // This package, under its official name, already exists 12246 // on the device; we should replace it. 12247 replace = true; 12248 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12249 } 12250 12251 // Prevent apps opting out from runtime permissions 12252 if (replace) { 12253 PackageParser.Package oldPackage = mPackages.get(pkgName); 12254 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12255 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12256 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12257 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12258 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12259 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12260 + " doesn't support runtime permissions but the old" 12261 + " target SDK " + oldTargetSdk + " does."); 12262 return; 12263 } 12264 } 12265 } 12266 12267 PackageSetting ps = mSettings.mPackages.get(pkgName); 12268 if (ps != null) { 12269 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12270 12271 // Quick sanity check that we're signed correctly if updating; 12272 // we'll check this again later when scanning, but we want to 12273 // bail early here before tripping over redefined permissions. 12274 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12275 if (!checkUpgradeKeySetLP(ps, pkg)) { 12276 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12277 + pkg.packageName + " upgrade keys do not match the " 12278 + "previously installed version"); 12279 return; 12280 } 12281 } else { 12282 try { 12283 verifySignaturesLP(ps, pkg); 12284 } catch (PackageManagerException e) { 12285 res.setError(e.error, e.getMessage()); 12286 return; 12287 } 12288 } 12289 12290 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12291 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12292 systemApp = (ps.pkg.applicationInfo.flags & 12293 ApplicationInfo.FLAG_SYSTEM) != 0; 12294 } 12295 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12296 } 12297 12298 // Check whether the newly-scanned package wants to define an already-defined perm 12299 int N = pkg.permissions.size(); 12300 for (int i = N-1; i >= 0; i--) { 12301 PackageParser.Permission perm = pkg.permissions.get(i); 12302 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12303 if (bp != null) { 12304 // If the defining package is signed with our cert, it's okay. This 12305 // also includes the "updating the same package" case, of course. 12306 // "updating same package" could also involve key-rotation. 12307 final boolean sigsOk; 12308 if (bp.sourcePackage.equals(pkg.packageName) 12309 && (bp.packageSetting instanceof PackageSetting) 12310 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12311 scanFlags))) { 12312 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12313 } else { 12314 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12315 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12316 } 12317 if (!sigsOk) { 12318 // If the owning package is the system itself, we log but allow 12319 // install to proceed; we fail the install on all other permission 12320 // redefinitions. 12321 if (!bp.sourcePackage.equals("android")) { 12322 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12323 + pkg.packageName + " attempting to redeclare permission " 12324 + perm.info.name + " already owned by " + bp.sourcePackage); 12325 res.origPermission = perm.info.name; 12326 res.origPackage = bp.sourcePackage; 12327 return; 12328 } else { 12329 Slog.w(TAG, "Package " + pkg.packageName 12330 + " attempting to redeclare system permission " 12331 + perm.info.name + "; ignoring new declaration"); 12332 pkg.permissions.remove(i); 12333 } 12334 } 12335 } 12336 } 12337 12338 } 12339 12340 if (systemApp && onExternal) { 12341 // Disable updates to system apps on sdcard 12342 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12343 "Cannot install updates to system apps on sdcard"); 12344 return; 12345 } 12346 12347 if (args.move != null) { 12348 // We did an in-place move, so dex is ready to roll 12349 scanFlags |= SCAN_NO_DEX; 12350 scanFlags |= SCAN_MOVE; 12351 12352 synchronized (mPackages) { 12353 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12354 if (ps == null) { 12355 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12356 "Missing settings for moved package " + pkgName); 12357 } 12358 12359 // We moved the entire application as-is, so bring over the 12360 // previously derived ABI information. 12361 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12362 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12363 } 12364 12365 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12366 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12367 scanFlags |= SCAN_NO_DEX; 12368 12369 try { 12370 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12371 true /* extract libs */); 12372 } catch (PackageManagerException pme) { 12373 Slog.e(TAG, "Error deriving application ABI", pme); 12374 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12375 return; 12376 } 12377 12378 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12379 int result = mPackageDexOptimizer 12380 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12381 false /* defer */, false /* inclDependencies */); 12382 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12383 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12384 return; 12385 } 12386 } 12387 12388 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12389 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12390 return; 12391 } 12392 12393 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12394 12395 if (replace) { 12396 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12397 installerPackageName, volumeUuid, res); 12398 } else { 12399 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12400 args.user, installerPackageName, volumeUuid, res); 12401 } 12402 synchronized (mPackages) { 12403 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12404 if (ps != null) { 12405 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12406 } 12407 } 12408 } 12409 12410 private void startIntentFilterVerifications(int userId, boolean replacing, 12411 PackageParser.Package pkg) { 12412 if (mIntentFilterVerifierComponent == null) { 12413 Slog.w(TAG, "No IntentFilter verification will not be done as " 12414 + "there is no IntentFilterVerifier available!"); 12415 return; 12416 } 12417 12418 final int verifierUid = getPackageUid( 12419 mIntentFilterVerifierComponent.getPackageName(), 12420 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12421 12422 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12423 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12424 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12425 mHandler.sendMessage(msg); 12426 } 12427 12428 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12429 PackageParser.Package pkg) { 12430 int size = pkg.activities.size(); 12431 if (size == 0) { 12432 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12433 "No activity, so no need to verify any IntentFilter!"); 12434 return; 12435 } 12436 12437 final boolean hasDomainURLs = hasDomainURLs(pkg); 12438 if (!hasDomainURLs) { 12439 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12440 "No domain URLs, so no need to verify any IntentFilter!"); 12441 return; 12442 } 12443 12444 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12445 + " if any IntentFilter from the " + size 12446 + " Activities needs verification ..."); 12447 12448 int count = 0; 12449 final String packageName = pkg.packageName; 12450 12451 synchronized (mPackages) { 12452 // If this is a new install and we see that we've already run verification for this 12453 // package, we have nothing to do: it means the state was restored from backup. 12454 if (!replacing) { 12455 IntentFilterVerificationInfo ivi = 12456 mSettings.getIntentFilterVerificationLPr(packageName); 12457 if (ivi != null) { 12458 if (DEBUG_DOMAIN_VERIFICATION) { 12459 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12460 + ivi.getStatusString()); 12461 } 12462 return; 12463 } 12464 } 12465 12466 // If any filters need to be verified, then all need to be. 12467 boolean needToVerify = false; 12468 for (PackageParser.Activity a : pkg.activities) { 12469 for (ActivityIntentInfo filter : a.intents) { 12470 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12471 if (DEBUG_DOMAIN_VERIFICATION) { 12472 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12473 } 12474 needToVerify = true; 12475 break; 12476 } 12477 } 12478 } 12479 12480 if (needToVerify) { 12481 final int verificationId = mIntentFilterVerificationToken++; 12482 for (PackageParser.Activity a : pkg.activities) { 12483 for (ActivityIntentInfo filter : a.intents) { 12484 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12485 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12486 "Verification needed for IntentFilter:" + filter.toString()); 12487 mIntentFilterVerifier.addOneIntentFilterVerification( 12488 verifierUid, userId, verificationId, filter, packageName); 12489 count++; 12490 } 12491 } 12492 } 12493 } 12494 } 12495 12496 if (count > 0) { 12497 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12498 + " IntentFilter verification" + (count > 1 ? "s" : "") 12499 + " for userId:" + userId); 12500 mIntentFilterVerifier.startVerifications(userId); 12501 } else { 12502 if (DEBUG_DOMAIN_VERIFICATION) { 12503 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12504 } 12505 } 12506 } 12507 12508 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12509 final ComponentName cn = filter.activity.getComponentName(); 12510 final String packageName = cn.getPackageName(); 12511 12512 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12513 packageName); 12514 if (ivi == null) { 12515 return true; 12516 } 12517 int status = ivi.getStatus(); 12518 switch (status) { 12519 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12520 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12521 return true; 12522 12523 default: 12524 // Nothing to do 12525 return false; 12526 } 12527 } 12528 12529 private static boolean isMultiArch(PackageSetting ps) { 12530 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12531 } 12532 12533 private static boolean isMultiArch(ApplicationInfo info) { 12534 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12535 } 12536 12537 private static boolean isExternal(PackageParser.Package pkg) { 12538 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12539 } 12540 12541 private static boolean isExternal(PackageSetting ps) { 12542 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12543 } 12544 12545 private static boolean isExternal(ApplicationInfo info) { 12546 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12547 } 12548 12549 private static boolean isSystemApp(PackageParser.Package pkg) { 12550 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12551 } 12552 12553 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12554 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12555 } 12556 12557 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12558 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12559 } 12560 12561 private static boolean isSystemApp(PackageSetting ps) { 12562 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12563 } 12564 12565 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12566 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12567 } 12568 12569 private int packageFlagsToInstallFlags(PackageSetting ps) { 12570 int installFlags = 0; 12571 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12572 // This existing package was an external ASEC install when we have 12573 // the external flag without a UUID 12574 installFlags |= PackageManager.INSTALL_EXTERNAL; 12575 } 12576 if (ps.isForwardLocked()) { 12577 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12578 } 12579 return installFlags; 12580 } 12581 12582 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12583 if (isExternal(pkg)) { 12584 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12585 return mSettings.getExternalVersion(); 12586 } else { 12587 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12588 } 12589 } else { 12590 return mSettings.getInternalVersion(); 12591 } 12592 } 12593 12594 private void deleteTempPackageFiles() { 12595 final FilenameFilter filter = new FilenameFilter() { 12596 public boolean accept(File dir, String name) { 12597 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12598 } 12599 }; 12600 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12601 file.delete(); 12602 } 12603 } 12604 12605 @Override 12606 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12607 int flags) { 12608 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12609 flags); 12610 } 12611 12612 @Override 12613 public void deletePackage(final String packageName, 12614 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12615 mContext.enforceCallingOrSelfPermission( 12616 android.Manifest.permission.DELETE_PACKAGES, null); 12617 Preconditions.checkNotNull(packageName); 12618 Preconditions.checkNotNull(observer); 12619 final int uid = Binder.getCallingUid(); 12620 if (UserHandle.getUserId(uid) != userId) { 12621 mContext.enforceCallingPermission( 12622 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12623 "deletePackage for user " + userId); 12624 } 12625 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12626 try { 12627 observer.onPackageDeleted(packageName, 12628 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12629 } catch (RemoteException re) { 12630 } 12631 return; 12632 } 12633 12634 boolean uninstallBlocked = false; 12635 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12636 int[] users = sUserManager.getUserIds(); 12637 for (int i = 0; i < users.length; ++i) { 12638 if (getBlockUninstallForUser(packageName, users[i])) { 12639 uninstallBlocked = true; 12640 break; 12641 } 12642 } 12643 } else { 12644 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12645 } 12646 if (uninstallBlocked) { 12647 try { 12648 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12649 null); 12650 } catch (RemoteException re) { 12651 } 12652 return; 12653 } 12654 12655 if (DEBUG_REMOVE) { 12656 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12657 } 12658 // Queue up an async operation since the package deletion may take a little while. 12659 mHandler.post(new Runnable() { 12660 public void run() { 12661 mHandler.removeCallbacks(this); 12662 final int returnCode = deletePackageX(packageName, userId, flags); 12663 if (observer != null) { 12664 try { 12665 observer.onPackageDeleted(packageName, returnCode, null); 12666 } catch (RemoteException e) { 12667 Log.i(TAG, "Observer no longer exists."); 12668 } //end catch 12669 } //end if 12670 } //end run 12671 }); 12672 } 12673 12674 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12675 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12676 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12677 try { 12678 if (dpm != null) { 12679 if (dpm.isDeviceOwner(packageName)) { 12680 return true; 12681 } 12682 int[] users; 12683 if (userId == UserHandle.USER_ALL) { 12684 users = sUserManager.getUserIds(); 12685 } else { 12686 users = new int[]{userId}; 12687 } 12688 for (int i = 0; i < users.length; ++i) { 12689 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12690 return true; 12691 } 12692 } 12693 } 12694 } catch (RemoteException e) { 12695 } 12696 return false; 12697 } 12698 12699 /** 12700 * This method is an internal method that could be get invoked either 12701 * to delete an installed package or to clean up a failed installation. 12702 * After deleting an installed package, a broadcast is sent to notify any 12703 * listeners that the package has been installed. For cleaning up a failed 12704 * installation, the broadcast is not necessary since the package's 12705 * installation wouldn't have sent the initial broadcast either 12706 * The key steps in deleting a package are 12707 * deleting the package information in internal structures like mPackages, 12708 * deleting the packages base directories through installd 12709 * updating mSettings to reflect current status 12710 * persisting settings for later use 12711 * sending a broadcast if necessary 12712 */ 12713 private int deletePackageX(String packageName, int userId, int flags) { 12714 final PackageRemovedInfo info = new PackageRemovedInfo(); 12715 final boolean res; 12716 12717 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12718 ? UserHandle.ALL : new UserHandle(userId); 12719 12720 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12721 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12722 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12723 } 12724 12725 boolean removedForAllUsers = false; 12726 boolean systemUpdate = false; 12727 12728 // for the uninstall-updates case and restricted profiles, remember the per- 12729 // userhandle installed state 12730 int[] allUsers; 12731 boolean[] perUserInstalled; 12732 synchronized (mPackages) { 12733 PackageSetting ps = mSettings.mPackages.get(packageName); 12734 allUsers = sUserManager.getUserIds(); 12735 perUserInstalled = new boolean[allUsers.length]; 12736 for (int i = 0; i < allUsers.length; i++) { 12737 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12738 } 12739 } 12740 12741 synchronized (mInstallLock) { 12742 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12743 res = deletePackageLI(packageName, removeForUser, 12744 true, allUsers, perUserInstalled, 12745 flags | REMOVE_CHATTY, info, true); 12746 systemUpdate = info.isRemovedPackageSystemUpdate; 12747 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12748 removedForAllUsers = true; 12749 } 12750 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12751 + " removedForAllUsers=" + removedForAllUsers); 12752 } 12753 12754 if (res) { 12755 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12756 12757 // If the removed package was a system update, the old system package 12758 // was re-enabled; we need to broadcast this information 12759 if (systemUpdate) { 12760 Bundle extras = new Bundle(1); 12761 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12762 ? info.removedAppId : info.uid); 12763 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12764 12765 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12766 extras, null, null, null); 12767 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12768 extras, null, null, null); 12769 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12770 null, packageName, null, null); 12771 } 12772 } 12773 // Force a gc here. 12774 Runtime.getRuntime().gc(); 12775 // Delete the resources here after sending the broadcast to let 12776 // other processes clean up before deleting resources. 12777 if (info.args != null) { 12778 synchronized (mInstallLock) { 12779 info.args.doPostDeleteLI(true); 12780 } 12781 } 12782 12783 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12784 } 12785 12786 class PackageRemovedInfo { 12787 String removedPackage; 12788 int uid = -1; 12789 int removedAppId = -1; 12790 int[] removedUsers = null; 12791 boolean isRemovedPackageSystemUpdate = false; 12792 // Clean up resources deleted packages. 12793 InstallArgs args = null; 12794 12795 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12796 Bundle extras = new Bundle(1); 12797 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12798 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12799 if (replacing) { 12800 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12801 } 12802 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12803 if (removedPackage != null) { 12804 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12805 extras, null, null, removedUsers); 12806 if (fullRemove && !replacing) { 12807 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12808 extras, null, null, removedUsers); 12809 } 12810 } 12811 if (removedAppId >= 0) { 12812 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12813 removedUsers); 12814 } 12815 } 12816 } 12817 12818 /* 12819 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12820 * flag is not set, the data directory is removed as well. 12821 * make sure this flag is set for partially installed apps. If not its meaningless to 12822 * delete a partially installed application. 12823 */ 12824 private void removePackageDataLI(PackageSetting ps, 12825 int[] allUserHandles, boolean[] perUserInstalled, 12826 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12827 String packageName = ps.name; 12828 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12829 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12830 // Retrieve object to delete permissions for shared user later on 12831 final PackageSetting deletedPs; 12832 // reader 12833 synchronized (mPackages) { 12834 deletedPs = mSettings.mPackages.get(packageName); 12835 if (outInfo != null) { 12836 outInfo.removedPackage = packageName; 12837 outInfo.removedUsers = deletedPs != null 12838 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12839 : null; 12840 } 12841 } 12842 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12843 removeDataDirsLI(ps.volumeUuid, packageName); 12844 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12845 } 12846 // writer 12847 synchronized (mPackages) { 12848 if (deletedPs != null) { 12849 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12850 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12851 clearDefaultBrowserIfNeeded(packageName); 12852 if (outInfo != null) { 12853 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12854 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12855 } 12856 updatePermissionsLPw(deletedPs.name, null, 0); 12857 if (deletedPs.sharedUser != null) { 12858 // Remove permissions associated with package. Since runtime 12859 // permissions are per user we have to kill the removed package 12860 // or packages running under the shared user of the removed 12861 // package if revoking the permissions requested only by the removed 12862 // package is successful and this causes a change in gids. 12863 for (int userId : UserManagerService.getInstance().getUserIds()) { 12864 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12865 userId); 12866 if (userIdToKill == UserHandle.USER_ALL 12867 || userIdToKill >= UserHandle.USER_OWNER) { 12868 // If gids changed for this user, kill all affected packages. 12869 mHandler.post(new Runnable() { 12870 @Override 12871 public void run() { 12872 // This has to happen with no lock held. 12873 killApplication(deletedPs.name, deletedPs.appId, 12874 KILL_APP_REASON_GIDS_CHANGED); 12875 } 12876 }); 12877 break; 12878 } 12879 } 12880 } 12881 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12882 } 12883 // make sure to preserve per-user disabled state if this removal was just 12884 // a downgrade of a system app to the factory package 12885 if (allUserHandles != null && perUserInstalled != null) { 12886 if (DEBUG_REMOVE) { 12887 Slog.d(TAG, "Propagating install state across downgrade"); 12888 } 12889 for (int i = 0; i < allUserHandles.length; i++) { 12890 if (DEBUG_REMOVE) { 12891 Slog.d(TAG, " user " + allUserHandles[i] 12892 + " => " + perUserInstalled[i]); 12893 } 12894 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12895 } 12896 } 12897 } 12898 // can downgrade to reader 12899 if (writeSettings) { 12900 // Save settings now 12901 mSettings.writeLPr(); 12902 } 12903 } 12904 if (outInfo != null) { 12905 // A user ID was deleted here. Go through all users and remove it 12906 // from KeyStore. 12907 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12908 } 12909 } 12910 12911 static boolean locationIsPrivileged(File path) { 12912 try { 12913 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12914 .getCanonicalPath(); 12915 return path.getCanonicalPath().startsWith(privilegedAppDir); 12916 } catch (IOException e) { 12917 Slog.e(TAG, "Unable to access code path " + path); 12918 } 12919 return false; 12920 } 12921 12922 /* 12923 * Tries to delete system package. 12924 */ 12925 private boolean deleteSystemPackageLI(PackageSetting newPs, 12926 int[] allUserHandles, boolean[] perUserInstalled, 12927 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12928 final boolean applyUserRestrictions 12929 = (allUserHandles != null) && (perUserInstalled != null); 12930 PackageSetting disabledPs = null; 12931 // Confirm if the system package has been updated 12932 // An updated system app can be deleted. This will also have to restore 12933 // the system pkg from system partition 12934 // reader 12935 synchronized (mPackages) { 12936 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12937 } 12938 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12939 + " disabledPs=" + disabledPs); 12940 if (disabledPs == null) { 12941 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12942 return false; 12943 } else if (DEBUG_REMOVE) { 12944 Slog.d(TAG, "Deleting system pkg from data partition"); 12945 } 12946 if (DEBUG_REMOVE) { 12947 if (applyUserRestrictions) { 12948 Slog.d(TAG, "Remembering install states:"); 12949 for (int i = 0; i < allUserHandles.length; i++) { 12950 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12951 } 12952 } 12953 } 12954 // Delete the updated package 12955 outInfo.isRemovedPackageSystemUpdate = true; 12956 if (disabledPs.versionCode < newPs.versionCode) { 12957 // Delete data for downgrades 12958 flags &= ~PackageManager.DELETE_KEEP_DATA; 12959 } else { 12960 // Preserve data by setting flag 12961 flags |= PackageManager.DELETE_KEEP_DATA; 12962 } 12963 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12964 allUserHandles, perUserInstalled, outInfo, writeSettings); 12965 if (!ret) { 12966 return false; 12967 } 12968 // writer 12969 synchronized (mPackages) { 12970 // Reinstate the old system package 12971 mSettings.enableSystemPackageLPw(newPs.name); 12972 // Remove any native libraries from the upgraded package. 12973 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12974 } 12975 // Install the system package 12976 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12977 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12978 if (locationIsPrivileged(disabledPs.codePath)) { 12979 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12980 } 12981 12982 final PackageParser.Package newPkg; 12983 try { 12984 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12985 } catch (PackageManagerException e) { 12986 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12987 return false; 12988 } 12989 12990 // writer 12991 synchronized (mPackages) { 12992 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12993 12994 // Propagate the permissions state as we do not want to drop on the floor 12995 // runtime permissions. The update permissions method below will take 12996 // care of removing obsolete permissions and grant install permissions. 12997 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 12998 updatePermissionsLPw(newPkg.packageName, newPkg, 12999 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13000 13001 if (applyUserRestrictions) { 13002 if (DEBUG_REMOVE) { 13003 Slog.d(TAG, "Propagating install state across reinstall"); 13004 } 13005 for (int i = 0; i < allUserHandles.length; i++) { 13006 if (DEBUG_REMOVE) { 13007 Slog.d(TAG, " user " + allUserHandles[i] 13008 + " => " + perUserInstalled[i]); 13009 } 13010 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13011 13012 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13013 } 13014 // Regardless of writeSettings we need to ensure that this restriction 13015 // state propagation is persisted 13016 mSettings.writeAllUsersPackageRestrictionsLPr(); 13017 } 13018 // can downgrade to reader here 13019 if (writeSettings) { 13020 mSettings.writeLPr(); 13021 } 13022 } 13023 return true; 13024 } 13025 13026 private boolean deleteInstalledPackageLI(PackageSetting ps, 13027 boolean deleteCodeAndResources, int flags, 13028 int[] allUserHandles, boolean[] perUserInstalled, 13029 PackageRemovedInfo outInfo, boolean writeSettings) { 13030 if (outInfo != null) { 13031 outInfo.uid = ps.appId; 13032 } 13033 13034 // Delete package data from internal structures and also remove data if flag is set 13035 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13036 13037 // Delete application code and resources 13038 if (deleteCodeAndResources && (outInfo != null)) { 13039 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13040 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13041 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13042 } 13043 return true; 13044 } 13045 13046 @Override 13047 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13048 int userId) { 13049 mContext.enforceCallingOrSelfPermission( 13050 android.Manifest.permission.DELETE_PACKAGES, null); 13051 synchronized (mPackages) { 13052 PackageSetting ps = mSettings.mPackages.get(packageName); 13053 if (ps == null) { 13054 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13055 return false; 13056 } 13057 if (!ps.getInstalled(userId)) { 13058 // Can't block uninstall for an app that is not installed or enabled. 13059 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13060 return false; 13061 } 13062 ps.setBlockUninstall(blockUninstall, userId); 13063 mSettings.writePackageRestrictionsLPr(userId); 13064 } 13065 return true; 13066 } 13067 13068 @Override 13069 public boolean getBlockUninstallForUser(String packageName, int userId) { 13070 synchronized (mPackages) { 13071 PackageSetting ps = mSettings.mPackages.get(packageName); 13072 if (ps == null) { 13073 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13074 return false; 13075 } 13076 return ps.getBlockUninstall(userId); 13077 } 13078 } 13079 13080 /* 13081 * This method handles package deletion in general 13082 */ 13083 private boolean deletePackageLI(String packageName, UserHandle user, 13084 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13085 int flags, PackageRemovedInfo outInfo, 13086 boolean writeSettings) { 13087 if (packageName == null) { 13088 Slog.w(TAG, "Attempt to delete null packageName."); 13089 return false; 13090 } 13091 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13092 PackageSetting ps; 13093 boolean dataOnly = false; 13094 int removeUser = -1; 13095 int appId = -1; 13096 synchronized (mPackages) { 13097 ps = mSettings.mPackages.get(packageName); 13098 if (ps == null) { 13099 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13100 return false; 13101 } 13102 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13103 && user.getIdentifier() != UserHandle.USER_ALL) { 13104 // The caller is asking that the package only be deleted for a single 13105 // user. To do this, we just mark its uninstalled state and delete 13106 // its data. If this is a system app, we only allow this to happen if 13107 // they have set the special DELETE_SYSTEM_APP which requests different 13108 // semantics than normal for uninstalling system apps. 13109 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13110 final int userId = user.getIdentifier(); 13111 ps.setUserState(userId, 13112 COMPONENT_ENABLED_STATE_DEFAULT, 13113 false, //installed 13114 true, //stopped 13115 true, //notLaunched 13116 false, //hidden 13117 null, null, null, 13118 false, // blockUninstall 13119 ps.readUserState(userId).domainVerificationStatus, 0); 13120 if (!isSystemApp(ps)) { 13121 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13122 // Other user still have this package installed, so all 13123 // we need to do is clear this user's data and save that 13124 // it is uninstalled. 13125 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13126 removeUser = user.getIdentifier(); 13127 appId = ps.appId; 13128 scheduleWritePackageRestrictionsLocked(removeUser); 13129 } else { 13130 // We need to set it back to 'installed' so the uninstall 13131 // broadcasts will be sent correctly. 13132 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13133 ps.setInstalled(true, user.getIdentifier()); 13134 } 13135 } else { 13136 // This is a system app, so we assume that the 13137 // other users still have this package installed, so all 13138 // we need to do is clear this user's data and save that 13139 // it is uninstalled. 13140 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13141 removeUser = user.getIdentifier(); 13142 appId = ps.appId; 13143 scheduleWritePackageRestrictionsLocked(removeUser); 13144 } 13145 } 13146 } 13147 13148 if (removeUser >= 0) { 13149 // From above, we determined that we are deleting this only 13150 // for a single user. Continue the work here. 13151 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13152 if (outInfo != null) { 13153 outInfo.removedPackage = packageName; 13154 outInfo.removedAppId = appId; 13155 outInfo.removedUsers = new int[] {removeUser}; 13156 } 13157 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13158 removeKeystoreDataIfNeeded(removeUser, appId); 13159 schedulePackageCleaning(packageName, removeUser, false); 13160 synchronized (mPackages) { 13161 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13162 scheduleWritePackageRestrictionsLocked(removeUser); 13163 } 13164 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13165 } 13166 return true; 13167 } 13168 13169 if (dataOnly) { 13170 // Delete application data first 13171 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13172 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13173 return true; 13174 } 13175 13176 boolean ret = false; 13177 if (isSystemApp(ps)) { 13178 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13179 // When an updated system application is deleted we delete the existing resources as well and 13180 // fall back to existing code in system partition 13181 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13182 flags, outInfo, writeSettings); 13183 } else { 13184 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13185 // Kill application pre-emptively especially for apps on sd. 13186 killApplication(packageName, ps.appId, "uninstall pkg"); 13187 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13188 allUserHandles, perUserInstalled, 13189 outInfo, writeSettings); 13190 } 13191 13192 return ret; 13193 } 13194 13195 private final class ClearStorageConnection implements ServiceConnection { 13196 IMediaContainerService mContainerService; 13197 13198 @Override 13199 public void onServiceConnected(ComponentName name, IBinder service) { 13200 synchronized (this) { 13201 mContainerService = IMediaContainerService.Stub.asInterface(service); 13202 notifyAll(); 13203 } 13204 } 13205 13206 @Override 13207 public void onServiceDisconnected(ComponentName name) { 13208 } 13209 } 13210 13211 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13212 final boolean mounted; 13213 if (Environment.isExternalStorageEmulated()) { 13214 mounted = true; 13215 } else { 13216 final String status = Environment.getExternalStorageState(); 13217 13218 mounted = status.equals(Environment.MEDIA_MOUNTED) 13219 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13220 } 13221 13222 if (!mounted) { 13223 return; 13224 } 13225 13226 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13227 int[] users; 13228 if (userId == UserHandle.USER_ALL) { 13229 users = sUserManager.getUserIds(); 13230 } else { 13231 users = new int[] { userId }; 13232 } 13233 final ClearStorageConnection conn = new ClearStorageConnection(); 13234 if (mContext.bindServiceAsUser( 13235 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13236 try { 13237 for (int curUser : users) { 13238 long timeout = SystemClock.uptimeMillis() + 5000; 13239 synchronized (conn) { 13240 long now = SystemClock.uptimeMillis(); 13241 while (conn.mContainerService == null && now < timeout) { 13242 try { 13243 conn.wait(timeout - now); 13244 } catch (InterruptedException e) { 13245 } 13246 } 13247 } 13248 if (conn.mContainerService == null) { 13249 return; 13250 } 13251 13252 final UserEnvironment userEnv = new UserEnvironment(curUser); 13253 clearDirectory(conn.mContainerService, 13254 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13255 if (allData) { 13256 clearDirectory(conn.mContainerService, 13257 userEnv.buildExternalStorageAppDataDirs(packageName)); 13258 clearDirectory(conn.mContainerService, 13259 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13260 } 13261 } 13262 } finally { 13263 mContext.unbindService(conn); 13264 } 13265 } 13266 } 13267 13268 @Override 13269 public void clearApplicationUserData(final String packageName, 13270 final IPackageDataObserver observer, final int userId) { 13271 mContext.enforceCallingOrSelfPermission( 13272 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13273 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13274 // Queue up an async operation since the package deletion may take a little while. 13275 mHandler.post(new Runnable() { 13276 public void run() { 13277 mHandler.removeCallbacks(this); 13278 final boolean succeeded; 13279 synchronized (mInstallLock) { 13280 succeeded = clearApplicationUserDataLI(packageName, userId); 13281 } 13282 clearExternalStorageDataSync(packageName, userId, true); 13283 if (succeeded) { 13284 // invoke DeviceStorageMonitor's update method to clear any notifications 13285 DeviceStorageMonitorInternal 13286 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13287 if (dsm != null) { 13288 dsm.checkMemory(); 13289 } 13290 } 13291 if(observer != null) { 13292 try { 13293 observer.onRemoveCompleted(packageName, succeeded); 13294 } catch (RemoteException e) { 13295 Log.i(TAG, "Observer no longer exists."); 13296 } 13297 } //end if observer 13298 } //end run 13299 }); 13300 } 13301 13302 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13303 if (packageName == null) { 13304 Slog.w(TAG, "Attempt to delete null packageName."); 13305 return false; 13306 } 13307 13308 // Try finding details about the requested package 13309 PackageParser.Package pkg; 13310 synchronized (mPackages) { 13311 pkg = mPackages.get(packageName); 13312 if (pkg == null) { 13313 final PackageSetting ps = mSettings.mPackages.get(packageName); 13314 if (ps != null) { 13315 pkg = ps.pkg; 13316 } 13317 } 13318 13319 if (pkg == null) { 13320 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13321 return false; 13322 } 13323 13324 PackageSetting ps = (PackageSetting) pkg.mExtras; 13325 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13326 } 13327 13328 // Always delete data directories for package, even if we found no other 13329 // record of app. This helps users recover from UID mismatches without 13330 // resorting to a full data wipe. 13331 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13332 if (retCode < 0) { 13333 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13334 return false; 13335 } 13336 13337 final int appId = pkg.applicationInfo.uid; 13338 removeKeystoreDataIfNeeded(userId, appId); 13339 13340 // Create a native library symlink only if we have native libraries 13341 // and if the native libraries are 32 bit libraries. We do not provide 13342 // this symlink for 64 bit libraries. 13343 if (pkg.applicationInfo.primaryCpuAbi != null && 13344 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13345 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13346 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13347 nativeLibPath, userId) < 0) { 13348 Slog.w(TAG, "Failed linking native library dir"); 13349 return false; 13350 } 13351 } 13352 13353 return true; 13354 } 13355 13356 /** 13357 * Reverts user permission state changes (permissions and flags) in 13358 * all packages for a given user. 13359 * 13360 * @param userId The device user for which to do a reset. 13361 */ 13362 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13363 final int packageCount = mPackages.size(); 13364 for (int i = 0; i < packageCount; i++) { 13365 PackageParser.Package pkg = mPackages.valueAt(i); 13366 PackageSetting ps = (PackageSetting) pkg.mExtras; 13367 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13368 } 13369 } 13370 13371 /** 13372 * Reverts user permission state changes (permissions and flags). 13373 * 13374 * @param ps The package for which to reset. 13375 * @param userId The device user for which to do a reset. 13376 */ 13377 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13378 final PackageSetting ps, final int userId) { 13379 if (ps.pkg == null) { 13380 return; 13381 } 13382 13383 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13384 | FLAG_PERMISSION_USER_FIXED 13385 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13386 13387 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13388 | FLAG_PERMISSION_POLICY_FIXED; 13389 13390 boolean writeInstallPermissions = false; 13391 boolean writeRuntimePermissions = false; 13392 13393 final int permissionCount = ps.pkg.requestedPermissions.size(); 13394 for (int i = 0; i < permissionCount; i++) { 13395 String permission = ps.pkg.requestedPermissions.get(i); 13396 13397 BasePermission bp = mSettings.mPermissions.get(permission); 13398 if (bp == null) { 13399 continue; 13400 } 13401 13402 // If shared user we just reset the state to which only this app contributed. 13403 if (ps.sharedUser != null) { 13404 boolean used = false; 13405 final int packageCount = ps.sharedUser.packages.size(); 13406 for (int j = 0; j < packageCount; j++) { 13407 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13408 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13409 && pkg.pkg.requestedPermissions.contains(permission)) { 13410 used = true; 13411 break; 13412 } 13413 } 13414 if (used) { 13415 continue; 13416 } 13417 } 13418 13419 PermissionsState permissionsState = ps.getPermissionsState(); 13420 13421 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13422 13423 // Always clear the user settable flags. 13424 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13425 bp.name) != null; 13426 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13427 if (hasInstallState) { 13428 writeInstallPermissions = true; 13429 } else { 13430 writeRuntimePermissions = true; 13431 } 13432 } 13433 13434 // Below is only runtime permission handling. 13435 if (!bp.isRuntime()) { 13436 continue; 13437 } 13438 13439 // Never clobber system or policy. 13440 if ((oldFlags & policyOrSystemFlags) != 0) { 13441 continue; 13442 } 13443 13444 // If this permission was granted by default, make sure it is. 13445 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13446 if (permissionsState.grantRuntimePermission(bp, userId) 13447 != PERMISSION_OPERATION_FAILURE) { 13448 writeRuntimePermissions = true; 13449 } 13450 } else { 13451 // Otherwise, reset the permission. 13452 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13453 switch (revokeResult) { 13454 case PERMISSION_OPERATION_SUCCESS: { 13455 writeRuntimePermissions = true; 13456 } break; 13457 13458 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13459 writeRuntimePermissions = true; 13460 final int appId = ps.appId; 13461 mHandler.post(new Runnable() { 13462 @Override 13463 public void run() { 13464 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13465 } 13466 }); 13467 } break; 13468 } 13469 } 13470 } 13471 13472 // Synchronously write as we are taking permissions away. 13473 if (writeRuntimePermissions) { 13474 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13475 } 13476 13477 // Synchronously write as we are taking permissions away. 13478 if (writeInstallPermissions) { 13479 mSettings.writeLPr(); 13480 } 13481 } 13482 13483 /** 13484 * Remove entries from the keystore daemon. Will only remove it if the 13485 * {@code appId} is valid. 13486 */ 13487 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13488 if (appId < 0) { 13489 return; 13490 } 13491 13492 final KeyStore keyStore = KeyStore.getInstance(); 13493 if (keyStore != null) { 13494 if (userId == UserHandle.USER_ALL) { 13495 for (final int individual : sUserManager.getUserIds()) { 13496 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13497 } 13498 } else { 13499 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13500 } 13501 } else { 13502 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13503 } 13504 } 13505 13506 @Override 13507 public void deleteApplicationCacheFiles(final String packageName, 13508 final IPackageDataObserver observer) { 13509 mContext.enforceCallingOrSelfPermission( 13510 android.Manifest.permission.DELETE_CACHE_FILES, null); 13511 // Queue up an async operation since the package deletion may take a little while. 13512 final int userId = UserHandle.getCallingUserId(); 13513 mHandler.post(new Runnable() { 13514 public void run() { 13515 mHandler.removeCallbacks(this); 13516 final boolean succeded; 13517 synchronized (mInstallLock) { 13518 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13519 } 13520 clearExternalStorageDataSync(packageName, userId, false); 13521 if (observer != null) { 13522 try { 13523 observer.onRemoveCompleted(packageName, succeded); 13524 } catch (RemoteException e) { 13525 Log.i(TAG, "Observer no longer exists."); 13526 } 13527 } //end if observer 13528 } //end run 13529 }); 13530 } 13531 13532 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13533 if (packageName == null) { 13534 Slog.w(TAG, "Attempt to delete null packageName."); 13535 return false; 13536 } 13537 PackageParser.Package p; 13538 synchronized (mPackages) { 13539 p = mPackages.get(packageName); 13540 } 13541 if (p == null) { 13542 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13543 return false; 13544 } 13545 final ApplicationInfo applicationInfo = p.applicationInfo; 13546 if (applicationInfo == null) { 13547 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13548 return false; 13549 } 13550 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13551 if (retCode < 0) { 13552 Slog.w(TAG, "Couldn't remove cache files for package: " 13553 + packageName + " u" + userId); 13554 return false; 13555 } 13556 return true; 13557 } 13558 13559 @Override 13560 public void getPackageSizeInfo(final String packageName, int userHandle, 13561 final IPackageStatsObserver observer) { 13562 mContext.enforceCallingOrSelfPermission( 13563 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13564 if (packageName == null) { 13565 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13566 } 13567 13568 PackageStats stats = new PackageStats(packageName, userHandle); 13569 13570 /* 13571 * Queue up an async operation since the package measurement may take a 13572 * little while. 13573 */ 13574 Message msg = mHandler.obtainMessage(INIT_COPY); 13575 msg.obj = new MeasureParams(stats, observer); 13576 mHandler.sendMessage(msg); 13577 } 13578 13579 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13580 PackageStats pStats) { 13581 if (packageName == null) { 13582 Slog.w(TAG, "Attempt to get size of null packageName."); 13583 return false; 13584 } 13585 PackageParser.Package p; 13586 boolean dataOnly = false; 13587 String libDirRoot = null; 13588 String asecPath = null; 13589 PackageSetting ps = null; 13590 synchronized (mPackages) { 13591 p = mPackages.get(packageName); 13592 ps = mSettings.mPackages.get(packageName); 13593 if(p == null) { 13594 dataOnly = true; 13595 if((ps == null) || (ps.pkg == null)) { 13596 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13597 return false; 13598 } 13599 p = ps.pkg; 13600 } 13601 if (ps != null) { 13602 libDirRoot = ps.legacyNativeLibraryPathString; 13603 } 13604 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13605 final long token = Binder.clearCallingIdentity(); 13606 try { 13607 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13608 if (secureContainerId != null) { 13609 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13610 } 13611 } finally { 13612 Binder.restoreCallingIdentity(token); 13613 } 13614 } 13615 } 13616 String publicSrcDir = null; 13617 if(!dataOnly) { 13618 final ApplicationInfo applicationInfo = p.applicationInfo; 13619 if (applicationInfo == null) { 13620 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13621 return false; 13622 } 13623 if (p.isForwardLocked()) { 13624 publicSrcDir = applicationInfo.getBaseResourcePath(); 13625 } 13626 } 13627 // TODO: extend to measure size of split APKs 13628 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13629 // not just the first level. 13630 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13631 // just the primary. 13632 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13633 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13634 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13635 if (res < 0) { 13636 return false; 13637 } 13638 13639 // Fix-up for forward-locked applications in ASEC containers. 13640 if (!isExternal(p)) { 13641 pStats.codeSize += pStats.externalCodeSize; 13642 pStats.externalCodeSize = 0L; 13643 } 13644 13645 return true; 13646 } 13647 13648 13649 @Override 13650 public void addPackageToPreferred(String packageName) { 13651 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13652 } 13653 13654 @Override 13655 public void removePackageFromPreferred(String packageName) { 13656 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13657 } 13658 13659 @Override 13660 public List<PackageInfo> getPreferredPackages(int flags) { 13661 return new ArrayList<PackageInfo>(); 13662 } 13663 13664 private int getUidTargetSdkVersionLockedLPr(int uid) { 13665 Object obj = mSettings.getUserIdLPr(uid); 13666 if (obj instanceof SharedUserSetting) { 13667 final SharedUserSetting sus = (SharedUserSetting) obj; 13668 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13669 final Iterator<PackageSetting> it = sus.packages.iterator(); 13670 while (it.hasNext()) { 13671 final PackageSetting ps = it.next(); 13672 if (ps.pkg != null) { 13673 int v = ps.pkg.applicationInfo.targetSdkVersion; 13674 if (v < vers) vers = v; 13675 } 13676 } 13677 return vers; 13678 } else if (obj instanceof PackageSetting) { 13679 final PackageSetting ps = (PackageSetting) obj; 13680 if (ps.pkg != null) { 13681 return ps.pkg.applicationInfo.targetSdkVersion; 13682 } 13683 } 13684 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13685 } 13686 13687 @Override 13688 public void addPreferredActivity(IntentFilter filter, int match, 13689 ComponentName[] set, ComponentName activity, int userId) { 13690 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13691 "Adding preferred"); 13692 } 13693 13694 private void addPreferredActivityInternal(IntentFilter filter, int match, 13695 ComponentName[] set, ComponentName activity, boolean always, int userId, 13696 String opname) { 13697 // writer 13698 int callingUid = Binder.getCallingUid(); 13699 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13700 if (filter.countActions() == 0) { 13701 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13702 return; 13703 } 13704 synchronized (mPackages) { 13705 if (mContext.checkCallingOrSelfPermission( 13706 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13707 != PackageManager.PERMISSION_GRANTED) { 13708 if (getUidTargetSdkVersionLockedLPr(callingUid) 13709 < Build.VERSION_CODES.FROYO) { 13710 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13711 + callingUid); 13712 return; 13713 } 13714 mContext.enforceCallingOrSelfPermission( 13715 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13716 } 13717 13718 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13719 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13720 + userId + ":"); 13721 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13722 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13723 scheduleWritePackageRestrictionsLocked(userId); 13724 } 13725 } 13726 13727 @Override 13728 public void replacePreferredActivity(IntentFilter filter, int match, 13729 ComponentName[] set, ComponentName activity, int userId) { 13730 if (filter.countActions() != 1) { 13731 throw new IllegalArgumentException( 13732 "replacePreferredActivity expects filter to have only 1 action."); 13733 } 13734 if (filter.countDataAuthorities() != 0 13735 || filter.countDataPaths() != 0 13736 || filter.countDataSchemes() > 1 13737 || filter.countDataTypes() != 0) { 13738 throw new IllegalArgumentException( 13739 "replacePreferredActivity expects filter to have no data authorities, " + 13740 "paths, or types; and at most one scheme."); 13741 } 13742 13743 final int callingUid = Binder.getCallingUid(); 13744 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13745 synchronized (mPackages) { 13746 if (mContext.checkCallingOrSelfPermission( 13747 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13748 != PackageManager.PERMISSION_GRANTED) { 13749 if (getUidTargetSdkVersionLockedLPr(callingUid) 13750 < Build.VERSION_CODES.FROYO) { 13751 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13752 + Binder.getCallingUid()); 13753 return; 13754 } 13755 mContext.enforceCallingOrSelfPermission( 13756 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13757 } 13758 13759 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13760 if (pir != null) { 13761 // Get all of the existing entries that exactly match this filter. 13762 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13763 if (existing != null && existing.size() == 1) { 13764 PreferredActivity cur = existing.get(0); 13765 if (DEBUG_PREFERRED) { 13766 Slog.i(TAG, "Checking replace of preferred:"); 13767 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13768 if (!cur.mPref.mAlways) { 13769 Slog.i(TAG, " -- CUR; not mAlways!"); 13770 } else { 13771 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13772 Slog.i(TAG, " -- CUR: mSet=" 13773 + Arrays.toString(cur.mPref.mSetComponents)); 13774 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13775 Slog.i(TAG, " -- NEW: mMatch=" 13776 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13777 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13778 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13779 } 13780 } 13781 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13782 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13783 && cur.mPref.sameSet(set)) { 13784 // Setting the preferred activity to what it happens to be already 13785 if (DEBUG_PREFERRED) { 13786 Slog.i(TAG, "Replacing with same preferred activity " 13787 + cur.mPref.mShortComponent + " for user " 13788 + userId + ":"); 13789 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13790 } 13791 return; 13792 } 13793 } 13794 13795 if (existing != null) { 13796 if (DEBUG_PREFERRED) { 13797 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13798 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13799 } 13800 for (int i = 0; i < existing.size(); i++) { 13801 PreferredActivity pa = existing.get(i); 13802 if (DEBUG_PREFERRED) { 13803 Slog.i(TAG, "Removing existing preferred activity " 13804 + pa.mPref.mComponent + ":"); 13805 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13806 } 13807 pir.removeFilter(pa); 13808 } 13809 } 13810 } 13811 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13812 "Replacing preferred"); 13813 } 13814 } 13815 13816 @Override 13817 public void clearPackagePreferredActivities(String packageName) { 13818 final int uid = Binder.getCallingUid(); 13819 // writer 13820 synchronized (mPackages) { 13821 PackageParser.Package pkg = mPackages.get(packageName); 13822 if (pkg == null || pkg.applicationInfo.uid != uid) { 13823 if (mContext.checkCallingOrSelfPermission( 13824 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13825 != PackageManager.PERMISSION_GRANTED) { 13826 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13827 < Build.VERSION_CODES.FROYO) { 13828 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13829 + Binder.getCallingUid()); 13830 return; 13831 } 13832 mContext.enforceCallingOrSelfPermission( 13833 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13834 } 13835 } 13836 13837 int user = UserHandle.getCallingUserId(); 13838 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13839 scheduleWritePackageRestrictionsLocked(user); 13840 } 13841 } 13842 } 13843 13844 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13845 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13846 ArrayList<PreferredActivity> removed = null; 13847 boolean changed = false; 13848 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13849 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13850 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13851 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13852 continue; 13853 } 13854 Iterator<PreferredActivity> it = pir.filterIterator(); 13855 while (it.hasNext()) { 13856 PreferredActivity pa = it.next(); 13857 // Mark entry for removal only if it matches the package name 13858 // and the entry is of type "always". 13859 if (packageName == null || 13860 (pa.mPref.mComponent.getPackageName().equals(packageName) 13861 && pa.mPref.mAlways)) { 13862 if (removed == null) { 13863 removed = new ArrayList<PreferredActivity>(); 13864 } 13865 removed.add(pa); 13866 } 13867 } 13868 if (removed != null) { 13869 for (int j=0; j<removed.size(); j++) { 13870 PreferredActivity pa = removed.get(j); 13871 pir.removeFilter(pa); 13872 } 13873 changed = true; 13874 } 13875 } 13876 return changed; 13877 } 13878 13879 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13880 private void clearIntentFilterVerificationsLPw(int userId) { 13881 final int packageCount = mPackages.size(); 13882 for (int i = 0; i < packageCount; i++) { 13883 PackageParser.Package pkg = mPackages.valueAt(i); 13884 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13885 } 13886 } 13887 13888 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13889 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13890 if (userId == UserHandle.USER_ALL) { 13891 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13892 sUserManager.getUserIds())) { 13893 for (int oneUserId : sUserManager.getUserIds()) { 13894 scheduleWritePackageRestrictionsLocked(oneUserId); 13895 } 13896 } 13897 } else { 13898 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13899 scheduleWritePackageRestrictionsLocked(userId); 13900 } 13901 } 13902 } 13903 13904 void clearDefaultBrowserIfNeeded(String packageName) { 13905 for (int oneUserId : sUserManager.getUserIds()) { 13906 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13907 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13908 if (packageName.equals(defaultBrowserPackageName)) { 13909 setDefaultBrowserPackageName(null, oneUserId); 13910 } 13911 } 13912 } 13913 13914 @Override 13915 public void resetApplicationPreferences(int userId) { 13916 mContext.enforceCallingOrSelfPermission( 13917 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13918 // writer 13919 synchronized (mPackages) { 13920 final long identity = Binder.clearCallingIdentity(); 13921 try { 13922 clearPackagePreferredActivitiesLPw(null, userId); 13923 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13924 // TODO: We have to reset the default SMS and Phone. This requires 13925 // significant refactoring to keep all default apps in the package 13926 // manager (cleaner but more work) or have the services provide 13927 // callbacks to the package manager to request a default app reset. 13928 applyFactoryDefaultBrowserLPw(userId); 13929 clearIntentFilterVerificationsLPw(userId); 13930 primeDomainVerificationsLPw(userId); 13931 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 13932 scheduleWritePackageRestrictionsLocked(userId); 13933 } finally { 13934 Binder.restoreCallingIdentity(identity); 13935 } 13936 } 13937 } 13938 13939 @Override 13940 public int getPreferredActivities(List<IntentFilter> outFilters, 13941 List<ComponentName> outActivities, String packageName) { 13942 13943 int num = 0; 13944 final int userId = UserHandle.getCallingUserId(); 13945 // reader 13946 synchronized (mPackages) { 13947 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13948 if (pir != null) { 13949 final Iterator<PreferredActivity> it = pir.filterIterator(); 13950 while (it.hasNext()) { 13951 final PreferredActivity pa = it.next(); 13952 if (packageName == null 13953 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13954 && pa.mPref.mAlways)) { 13955 if (outFilters != null) { 13956 outFilters.add(new IntentFilter(pa)); 13957 } 13958 if (outActivities != null) { 13959 outActivities.add(pa.mPref.mComponent); 13960 } 13961 } 13962 } 13963 } 13964 } 13965 13966 return num; 13967 } 13968 13969 @Override 13970 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13971 int userId) { 13972 int callingUid = Binder.getCallingUid(); 13973 if (callingUid != Process.SYSTEM_UID) { 13974 throw new SecurityException( 13975 "addPersistentPreferredActivity can only be run by the system"); 13976 } 13977 if (filter.countActions() == 0) { 13978 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13979 return; 13980 } 13981 synchronized (mPackages) { 13982 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13983 " :"); 13984 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13985 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13986 new PersistentPreferredActivity(filter, activity)); 13987 scheduleWritePackageRestrictionsLocked(userId); 13988 } 13989 } 13990 13991 @Override 13992 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13993 int callingUid = Binder.getCallingUid(); 13994 if (callingUid != Process.SYSTEM_UID) { 13995 throw new SecurityException( 13996 "clearPackagePersistentPreferredActivities can only be run by the system"); 13997 } 13998 ArrayList<PersistentPreferredActivity> removed = null; 13999 boolean changed = false; 14000 synchronized (mPackages) { 14001 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14002 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14003 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14004 .valueAt(i); 14005 if (userId != thisUserId) { 14006 continue; 14007 } 14008 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14009 while (it.hasNext()) { 14010 PersistentPreferredActivity ppa = it.next(); 14011 // Mark entry for removal only if it matches the package name. 14012 if (ppa.mComponent.getPackageName().equals(packageName)) { 14013 if (removed == null) { 14014 removed = new ArrayList<PersistentPreferredActivity>(); 14015 } 14016 removed.add(ppa); 14017 } 14018 } 14019 if (removed != null) { 14020 for (int j=0; j<removed.size(); j++) { 14021 PersistentPreferredActivity ppa = removed.get(j); 14022 ppir.removeFilter(ppa); 14023 } 14024 changed = true; 14025 } 14026 } 14027 14028 if (changed) { 14029 scheduleWritePackageRestrictionsLocked(userId); 14030 } 14031 } 14032 } 14033 14034 /** 14035 * Common machinery for picking apart a restored XML blob and passing 14036 * it to a caller-supplied functor to be applied to the running system. 14037 */ 14038 private void restoreFromXml(XmlPullParser parser, int userId, 14039 String expectedStartTag, BlobXmlRestorer functor) 14040 throws IOException, XmlPullParserException { 14041 int type; 14042 while ((type = parser.next()) != XmlPullParser.START_TAG 14043 && type != XmlPullParser.END_DOCUMENT) { 14044 } 14045 if (type != XmlPullParser.START_TAG) { 14046 // oops didn't find a start tag?! 14047 if (DEBUG_BACKUP) { 14048 Slog.e(TAG, "Didn't find start tag during restore"); 14049 } 14050 return; 14051 } 14052 14053 // this is supposed to be TAG_PREFERRED_BACKUP 14054 if (!expectedStartTag.equals(parser.getName())) { 14055 if (DEBUG_BACKUP) { 14056 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14057 } 14058 return; 14059 } 14060 14061 // skip interfering stuff, then we're aligned with the backing implementation 14062 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14063 functor.apply(parser, userId); 14064 } 14065 14066 private interface BlobXmlRestorer { 14067 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14068 } 14069 14070 /** 14071 * Non-Binder method, support for the backup/restore mechanism: write the 14072 * full set of preferred activities in its canonical XML format. Returns the 14073 * XML output as a byte array, or null if there is none. 14074 */ 14075 @Override 14076 public byte[] getPreferredActivityBackup(int userId) { 14077 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14078 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14079 } 14080 14081 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14082 try { 14083 final XmlSerializer serializer = new FastXmlSerializer(); 14084 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14085 serializer.startDocument(null, true); 14086 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14087 14088 synchronized (mPackages) { 14089 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14090 } 14091 14092 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14093 serializer.endDocument(); 14094 serializer.flush(); 14095 } catch (Exception e) { 14096 if (DEBUG_BACKUP) { 14097 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14098 } 14099 return null; 14100 } 14101 14102 return dataStream.toByteArray(); 14103 } 14104 14105 @Override 14106 public void restorePreferredActivities(byte[] backup, int userId) { 14107 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14108 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14109 } 14110 14111 try { 14112 final XmlPullParser parser = Xml.newPullParser(); 14113 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14114 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14115 new BlobXmlRestorer() { 14116 @Override 14117 public void apply(XmlPullParser parser, int userId) 14118 throws XmlPullParserException, IOException { 14119 synchronized (mPackages) { 14120 mSettings.readPreferredActivitiesLPw(parser, userId); 14121 } 14122 } 14123 } ); 14124 } catch (Exception e) { 14125 if (DEBUG_BACKUP) { 14126 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14127 } 14128 } 14129 } 14130 14131 /** 14132 * Non-Binder method, support for the backup/restore mechanism: write the 14133 * default browser (etc) settings in its canonical XML format. Returns the default 14134 * browser XML representation as a byte array, or null if there is none. 14135 */ 14136 @Override 14137 public byte[] getDefaultAppsBackup(int userId) { 14138 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14139 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14140 } 14141 14142 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14143 try { 14144 final XmlSerializer serializer = new FastXmlSerializer(); 14145 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14146 serializer.startDocument(null, true); 14147 serializer.startTag(null, TAG_DEFAULT_APPS); 14148 14149 synchronized (mPackages) { 14150 mSettings.writeDefaultAppsLPr(serializer, userId); 14151 } 14152 14153 serializer.endTag(null, TAG_DEFAULT_APPS); 14154 serializer.endDocument(); 14155 serializer.flush(); 14156 } catch (Exception e) { 14157 if (DEBUG_BACKUP) { 14158 Slog.e(TAG, "Unable to write default apps for backup", e); 14159 } 14160 return null; 14161 } 14162 14163 return dataStream.toByteArray(); 14164 } 14165 14166 @Override 14167 public void restoreDefaultApps(byte[] backup, int userId) { 14168 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14169 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14170 } 14171 14172 try { 14173 final XmlPullParser parser = Xml.newPullParser(); 14174 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14175 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14176 new BlobXmlRestorer() { 14177 @Override 14178 public void apply(XmlPullParser parser, int userId) 14179 throws XmlPullParserException, IOException { 14180 synchronized (mPackages) { 14181 mSettings.readDefaultAppsLPw(parser, userId); 14182 } 14183 } 14184 } ); 14185 } catch (Exception e) { 14186 if (DEBUG_BACKUP) { 14187 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14188 } 14189 } 14190 } 14191 14192 @Override 14193 public byte[] getIntentFilterVerificationBackup(int userId) { 14194 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14195 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14196 } 14197 14198 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14199 try { 14200 final XmlSerializer serializer = new FastXmlSerializer(); 14201 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14202 serializer.startDocument(null, true); 14203 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14204 14205 synchronized (mPackages) { 14206 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14207 } 14208 14209 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14210 serializer.endDocument(); 14211 serializer.flush(); 14212 } catch (Exception e) { 14213 if (DEBUG_BACKUP) { 14214 Slog.e(TAG, "Unable to write default apps for backup", e); 14215 } 14216 return null; 14217 } 14218 14219 return dataStream.toByteArray(); 14220 } 14221 14222 @Override 14223 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14224 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14225 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14226 } 14227 14228 try { 14229 final XmlPullParser parser = Xml.newPullParser(); 14230 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14231 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14232 new BlobXmlRestorer() { 14233 @Override 14234 public void apply(XmlPullParser parser, int userId) 14235 throws XmlPullParserException, IOException { 14236 synchronized (mPackages) { 14237 mSettings.readAllDomainVerificationsLPr(parser, userId); 14238 mSettings.writeLPr(); 14239 } 14240 } 14241 } ); 14242 } catch (Exception e) { 14243 if (DEBUG_BACKUP) { 14244 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14245 } 14246 } 14247 } 14248 14249 @Override 14250 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14251 int sourceUserId, int targetUserId, int flags) { 14252 mContext.enforceCallingOrSelfPermission( 14253 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14254 int callingUid = Binder.getCallingUid(); 14255 enforceOwnerRights(ownerPackage, callingUid); 14256 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14257 if (intentFilter.countActions() == 0) { 14258 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14259 return; 14260 } 14261 synchronized (mPackages) { 14262 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14263 ownerPackage, targetUserId, flags); 14264 CrossProfileIntentResolver resolver = 14265 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14266 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14267 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14268 if (existing != null) { 14269 int size = existing.size(); 14270 for (int i = 0; i < size; i++) { 14271 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14272 return; 14273 } 14274 } 14275 } 14276 resolver.addFilter(newFilter); 14277 scheduleWritePackageRestrictionsLocked(sourceUserId); 14278 } 14279 } 14280 14281 @Override 14282 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14283 mContext.enforceCallingOrSelfPermission( 14284 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14285 int callingUid = Binder.getCallingUid(); 14286 enforceOwnerRights(ownerPackage, callingUid); 14287 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14288 synchronized (mPackages) { 14289 CrossProfileIntentResolver resolver = 14290 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14291 ArraySet<CrossProfileIntentFilter> set = 14292 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14293 for (CrossProfileIntentFilter filter : set) { 14294 if (filter.getOwnerPackage().equals(ownerPackage)) { 14295 resolver.removeFilter(filter); 14296 } 14297 } 14298 scheduleWritePackageRestrictionsLocked(sourceUserId); 14299 } 14300 } 14301 14302 // Enforcing that callingUid is owning pkg on userId 14303 private void enforceOwnerRights(String pkg, int callingUid) { 14304 // The system owns everything. 14305 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14306 return; 14307 } 14308 int callingUserId = UserHandle.getUserId(callingUid); 14309 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14310 if (pi == null) { 14311 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14312 + callingUserId); 14313 } 14314 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14315 throw new SecurityException("Calling uid " + callingUid 14316 + " does not own package " + pkg); 14317 } 14318 } 14319 14320 @Override 14321 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14322 Intent intent = new Intent(Intent.ACTION_MAIN); 14323 intent.addCategory(Intent.CATEGORY_HOME); 14324 14325 final int callingUserId = UserHandle.getCallingUserId(); 14326 List<ResolveInfo> list = queryIntentActivities(intent, null, 14327 PackageManager.GET_META_DATA, callingUserId); 14328 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14329 true, false, false, callingUserId); 14330 14331 allHomeCandidates.clear(); 14332 if (list != null) { 14333 for (ResolveInfo ri : list) { 14334 allHomeCandidates.add(ri); 14335 } 14336 } 14337 return (preferred == null || preferred.activityInfo == null) 14338 ? null 14339 : new ComponentName(preferred.activityInfo.packageName, 14340 preferred.activityInfo.name); 14341 } 14342 14343 @Override 14344 public void setApplicationEnabledSetting(String appPackageName, 14345 int newState, int flags, int userId, String callingPackage) { 14346 if (!sUserManager.exists(userId)) return; 14347 if (callingPackage == null) { 14348 callingPackage = Integer.toString(Binder.getCallingUid()); 14349 } 14350 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14351 } 14352 14353 @Override 14354 public void setComponentEnabledSetting(ComponentName componentName, 14355 int newState, int flags, int userId) { 14356 if (!sUserManager.exists(userId)) return; 14357 setEnabledSetting(componentName.getPackageName(), 14358 componentName.getClassName(), newState, flags, userId, null); 14359 } 14360 14361 private void setEnabledSetting(final String packageName, String className, int newState, 14362 final int flags, int userId, String callingPackage) { 14363 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14364 || newState == COMPONENT_ENABLED_STATE_ENABLED 14365 || newState == COMPONENT_ENABLED_STATE_DISABLED 14366 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14367 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14368 throw new IllegalArgumentException("Invalid new component state: " 14369 + newState); 14370 } 14371 PackageSetting pkgSetting; 14372 final int uid = Binder.getCallingUid(); 14373 final int permission = mContext.checkCallingOrSelfPermission( 14374 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14375 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14376 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14377 boolean sendNow = false; 14378 boolean isApp = (className == null); 14379 String componentName = isApp ? packageName : className; 14380 int packageUid = -1; 14381 ArrayList<String> components; 14382 14383 // writer 14384 synchronized (mPackages) { 14385 pkgSetting = mSettings.mPackages.get(packageName); 14386 if (pkgSetting == null) { 14387 if (className == null) { 14388 throw new IllegalArgumentException( 14389 "Unknown package: " + packageName); 14390 } 14391 throw new IllegalArgumentException( 14392 "Unknown component: " + packageName 14393 + "/" + className); 14394 } 14395 // Allow root and verify that userId is not being specified by a different user 14396 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14397 throw new SecurityException( 14398 "Permission Denial: attempt to change component state from pid=" 14399 + Binder.getCallingPid() 14400 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14401 } 14402 if (className == null) { 14403 // We're dealing with an application/package level state change 14404 if (pkgSetting.getEnabled(userId) == newState) { 14405 // Nothing to do 14406 return; 14407 } 14408 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14409 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14410 // Don't care about who enables an app. 14411 callingPackage = null; 14412 } 14413 pkgSetting.setEnabled(newState, userId, callingPackage); 14414 // pkgSetting.pkg.mSetEnabled = newState; 14415 } else { 14416 // We're dealing with a component level state change 14417 // First, verify that this is a valid class name. 14418 PackageParser.Package pkg = pkgSetting.pkg; 14419 if (pkg == null || !pkg.hasComponentClassName(className)) { 14420 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14421 throw new IllegalArgumentException("Component class " + className 14422 + " does not exist in " + packageName); 14423 } else { 14424 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14425 + className + " does not exist in " + packageName); 14426 } 14427 } 14428 switch (newState) { 14429 case COMPONENT_ENABLED_STATE_ENABLED: 14430 if (!pkgSetting.enableComponentLPw(className, userId)) { 14431 return; 14432 } 14433 break; 14434 case COMPONENT_ENABLED_STATE_DISABLED: 14435 if (!pkgSetting.disableComponentLPw(className, userId)) { 14436 return; 14437 } 14438 break; 14439 case COMPONENT_ENABLED_STATE_DEFAULT: 14440 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14441 return; 14442 } 14443 break; 14444 default: 14445 Slog.e(TAG, "Invalid new component state: " + newState); 14446 return; 14447 } 14448 } 14449 scheduleWritePackageRestrictionsLocked(userId); 14450 components = mPendingBroadcasts.get(userId, packageName); 14451 final boolean newPackage = components == null; 14452 if (newPackage) { 14453 components = new ArrayList<String>(); 14454 } 14455 if (!components.contains(componentName)) { 14456 components.add(componentName); 14457 } 14458 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14459 sendNow = true; 14460 // Purge entry from pending broadcast list if another one exists already 14461 // since we are sending one right away. 14462 mPendingBroadcasts.remove(userId, packageName); 14463 } else { 14464 if (newPackage) { 14465 mPendingBroadcasts.put(userId, packageName, components); 14466 } 14467 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14468 // Schedule a message 14469 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14470 } 14471 } 14472 } 14473 14474 long callingId = Binder.clearCallingIdentity(); 14475 try { 14476 if (sendNow) { 14477 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14478 sendPackageChangedBroadcast(packageName, 14479 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14480 } 14481 } finally { 14482 Binder.restoreCallingIdentity(callingId); 14483 } 14484 } 14485 14486 private void sendPackageChangedBroadcast(String packageName, 14487 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14488 if (DEBUG_INSTALL) 14489 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14490 + componentNames); 14491 Bundle extras = new Bundle(4); 14492 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14493 String nameList[] = new String[componentNames.size()]; 14494 componentNames.toArray(nameList); 14495 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14496 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14497 extras.putInt(Intent.EXTRA_UID, packageUid); 14498 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14499 new int[] {UserHandle.getUserId(packageUid)}); 14500 } 14501 14502 @Override 14503 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14504 if (!sUserManager.exists(userId)) return; 14505 final int uid = Binder.getCallingUid(); 14506 final int permission = mContext.checkCallingOrSelfPermission( 14507 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14508 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14509 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14510 // writer 14511 synchronized (mPackages) { 14512 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14513 allowedByPermission, uid, userId)) { 14514 scheduleWritePackageRestrictionsLocked(userId); 14515 } 14516 } 14517 } 14518 14519 @Override 14520 public String getInstallerPackageName(String packageName) { 14521 // reader 14522 synchronized (mPackages) { 14523 return mSettings.getInstallerPackageNameLPr(packageName); 14524 } 14525 } 14526 14527 @Override 14528 public int getApplicationEnabledSetting(String packageName, int userId) { 14529 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14530 int uid = Binder.getCallingUid(); 14531 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14532 // reader 14533 synchronized (mPackages) { 14534 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14535 } 14536 } 14537 14538 @Override 14539 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14540 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14541 int uid = Binder.getCallingUid(); 14542 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14543 // reader 14544 synchronized (mPackages) { 14545 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14546 } 14547 } 14548 14549 @Override 14550 public void enterSafeMode() { 14551 enforceSystemOrRoot("Only the system can request entering safe mode"); 14552 14553 if (!mSystemReady) { 14554 mSafeMode = true; 14555 } 14556 } 14557 14558 @Override 14559 public void systemReady() { 14560 mSystemReady = true; 14561 14562 // Read the compatibilty setting when the system is ready. 14563 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14564 mContext.getContentResolver(), 14565 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14566 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14567 if (DEBUG_SETTINGS) { 14568 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14569 } 14570 14571 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14572 14573 synchronized (mPackages) { 14574 // Verify that all of the preferred activity components actually 14575 // exist. It is possible for applications to be updated and at 14576 // that point remove a previously declared activity component that 14577 // had been set as a preferred activity. We try to clean this up 14578 // the next time we encounter that preferred activity, but it is 14579 // possible for the user flow to never be able to return to that 14580 // situation so here we do a sanity check to make sure we haven't 14581 // left any junk around. 14582 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14583 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14584 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14585 removed.clear(); 14586 for (PreferredActivity pa : pir.filterSet()) { 14587 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14588 removed.add(pa); 14589 } 14590 } 14591 if (removed.size() > 0) { 14592 for (int r=0; r<removed.size(); r++) { 14593 PreferredActivity pa = removed.get(r); 14594 Slog.w(TAG, "Removing dangling preferred activity: " 14595 + pa.mPref.mComponent); 14596 pir.removeFilter(pa); 14597 } 14598 mSettings.writePackageRestrictionsLPr( 14599 mSettings.mPreferredActivities.keyAt(i)); 14600 } 14601 } 14602 14603 for (int userId : UserManagerService.getInstance().getUserIds()) { 14604 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14605 grantPermissionsUserIds = ArrayUtils.appendInt( 14606 grantPermissionsUserIds, userId); 14607 } 14608 } 14609 } 14610 sUserManager.systemReady(); 14611 14612 // If we upgraded grant all default permissions before kicking off. 14613 for (int userId : grantPermissionsUserIds) { 14614 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14615 } 14616 14617 // Kick off any messages waiting for system ready 14618 if (mPostSystemReadyMessages != null) { 14619 for (Message msg : mPostSystemReadyMessages) { 14620 msg.sendToTarget(); 14621 } 14622 mPostSystemReadyMessages = null; 14623 } 14624 14625 // Watch for external volumes that come and go over time 14626 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14627 storage.registerListener(mStorageListener); 14628 14629 mInstallerService.systemReady(); 14630 mPackageDexOptimizer.systemReady(); 14631 14632 MountServiceInternal mountServiceInternal = LocalServices.getService( 14633 MountServiceInternal.class); 14634 mountServiceInternal.addExternalStoragePolicy( 14635 new MountServiceInternal.ExternalStorageMountPolicy() { 14636 @Override 14637 public int getMountMode(int uid, String packageName) { 14638 if (Process.isIsolated(uid)) { 14639 return Zygote.MOUNT_EXTERNAL_NONE; 14640 } 14641 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14642 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14643 } 14644 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14645 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14646 } 14647 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14648 return Zygote.MOUNT_EXTERNAL_READ; 14649 } 14650 return Zygote.MOUNT_EXTERNAL_WRITE; 14651 } 14652 14653 @Override 14654 public boolean hasExternalStorage(int uid, String packageName) { 14655 return true; 14656 } 14657 }); 14658 } 14659 14660 @Override 14661 public boolean isSafeMode() { 14662 return mSafeMode; 14663 } 14664 14665 @Override 14666 public boolean hasSystemUidErrors() { 14667 return mHasSystemUidErrors; 14668 } 14669 14670 static String arrayToString(int[] array) { 14671 StringBuffer buf = new StringBuffer(128); 14672 buf.append('['); 14673 if (array != null) { 14674 for (int i=0; i<array.length; i++) { 14675 if (i > 0) buf.append(", "); 14676 buf.append(array[i]); 14677 } 14678 } 14679 buf.append(']'); 14680 return buf.toString(); 14681 } 14682 14683 static class DumpState { 14684 public static final int DUMP_LIBS = 1 << 0; 14685 public static final int DUMP_FEATURES = 1 << 1; 14686 public static final int DUMP_RESOLVERS = 1 << 2; 14687 public static final int DUMP_PERMISSIONS = 1 << 3; 14688 public static final int DUMP_PACKAGES = 1 << 4; 14689 public static final int DUMP_SHARED_USERS = 1 << 5; 14690 public static final int DUMP_MESSAGES = 1 << 6; 14691 public static final int DUMP_PROVIDERS = 1 << 7; 14692 public static final int DUMP_VERIFIERS = 1 << 8; 14693 public static final int DUMP_PREFERRED = 1 << 9; 14694 public static final int DUMP_PREFERRED_XML = 1 << 10; 14695 public static final int DUMP_KEYSETS = 1 << 11; 14696 public static final int DUMP_VERSION = 1 << 12; 14697 public static final int DUMP_INSTALLS = 1 << 13; 14698 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14699 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14700 14701 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14702 14703 private int mTypes; 14704 14705 private int mOptions; 14706 14707 private boolean mTitlePrinted; 14708 14709 private SharedUserSetting mSharedUser; 14710 14711 public boolean isDumping(int type) { 14712 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14713 return true; 14714 } 14715 14716 return (mTypes & type) != 0; 14717 } 14718 14719 public void setDump(int type) { 14720 mTypes |= type; 14721 } 14722 14723 public boolean isOptionEnabled(int option) { 14724 return (mOptions & option) != 0; 14725 } 14726 14727 public void setOptionEnabled(int option) { 14728 mOptions |= option; 14729 } 14730 14731 public boolean onTitlePrinted() { 14732 final boolean printed = mTitlePrinted; 14733 mTitlePrinted = true; 14734 return printed; 14735 } 14736 14737 public boolean getTitlePrinted() { 14738 return mTitlePrinted; 14739 } 14740 14741 public void setTitlePrinted(boolean enabled) { 14742 mTitlePrinted = enabled; 14743 } 14744 14745 public SharedUserSetting getSharedUser() { 14746 return mSharedUser; 14747 } 14748 14749 public void setSharedUser(SharedUserSetting user) { 14750 mSharedUser = user; 14751 } 14752 } 14753 14754 @Override 14755 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14756 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14757 != PackageManager.PERMISSION_GRANTED) { 14758 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14759 + Binder.getCallingPid() 14760 + ", uid=" + Binder.getCallingUid() 14761 + " without permission " 14762 + android.Manifest.permission.DUMP); 14763 return; 14764 } 14765 14766 DumpState dumpState = new DumpState(); 14767 boolean fullPreferred = false; 14768 boolean checkin = false; 14769 14770 String packageName = null; 14771 ArraySet<String> permissionNames = null; 14772 14773 int opti = 0; 14774 while (opti < args.length) { 14775 String opt = args[opti]; 14776 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14777 break; 14778 } 14779 opti++; 14780 14781 if ("-a".equals(opt)) { 14782 // Right now we only know how to print all. 14783 } else if ("-h".equals(opt)) { 14784 pw.println("Package manager dump options:"); 14785 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14786 pw.println(" --checkin: dump for a checkin"); 14787 pw.println(" -f: print details of intent filters"); 14788 pw.println(" -h: print this help"); 14789 pw.println(" cmd may be one of:"); 14790 pw.println(" l[ibraries]: list known shared libraries"); 14791 pw.println(" f[ibraries]: list device features"); 14792 pw.println(" k[eysets]: print known keysets"); 14793 pw.println(" r[esolvers]: dump intent resolvers"); 14794 pw.println(" perm[issions]: dump permissions"); 14795 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14796 pw.println(" pref[erred]: print preferred package settings"); 14797 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14798 pw.println(" prov[iders]: dump content providers"); 14799 pw.println(" p[ackages]: dump installed packages"); 14800 pw.println(" s[hared-users]: dump shared user IDs"); 14801 pw.println(" m[essages]: print collected runtime messages"); 14802 pw.println(" v[erifiers]: print package verifier info"); 14803 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14804 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14805 pw.println(" version: print database version info"); 14806 pw.println(" write: write current settings now"); 14807 pw.println(" installs: details about install sessions"); 14808 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 14809 pw.println(" <package.name>: info about given package"); 14810 return; 14811 } else if ("--checkin".equals(opt)) { 14812 checkin = true; 14813 } else if ("-f".equals(opt)) { 14814 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14815 } else { 14816 pw.println("Unknown argument: " + opt + "; use -h for help"); 14817 } 14818 } 14819 14820 // Is the caller requesting to dump a particular piece of data? 14821 if (opti < args.length) { 14822 String cmd = args[opti]; 14823 opti++; 14824 // Is this a package name? 14825 if ("android".equals(cmd) || cmd.contains(".")) { 14826 packageName = cmd; 14827 // When dumping a single package, we always dump all of its 14828 // filter information since the amount of data will be reasonable. 14829 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14830 } else if ("check-permission".equals(cmd)) { 14831 if (opti >= args.length) { 14832 pw.println("Error: check-permission missing permission argument"); 14833 return; 14834 } 14835 String perm = args[opti]; 14836 opti++; 14837 if (opti >= args.length) { 14838 pw.println("Error: check-permission missing package argument"); 14839 return; 14840 } 14841 String pkg = args[opti]; 14842 opti++; 14843 int user = UserHandle.getUserId(Binder.getCallingUid()); 14844 if (opti < args.length) { 14845 try { 14846 user = Integer.parseInt(args[opti]); 14847 } catch (NumberFormatException e) { 14848 pw.println("Error: check-permission user argument is not a number: " 14849 + args[opti]); 14850 return; 14851 } 14852 } 14853 pw.println(checkPermission(perm, pkg, user)); 14854 return; 14855 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14856 dumpState.setDump(DumpState.DUMP_LIBS); 14857 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14858 dumpState.setDump(DumpState.DUMP_FEATURES); 14859 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14860 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14861 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14862 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14863 } else if ("permission".equals(cmd)) { 14864 if (opti >= args.length) { 14865 pw.println("Error: permission requires permission name"); 14866 return; 14867 } 14868 permissionNames = new ArraySet<>(); 14869 while (opti < args.length) { 14870 permissionNames.add(args[opti]); 14871 opti++; 14872 } 14873 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14874 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14875 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14876 dumpState.setDump(DumpState.DUMP_PREFERRED); 14877 } else if ("preferred-xml".equals(cmd)) { 14878 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14879 if (opti < args.length && "--full".equals(args[opti])) { 14880 fullPreferred = true; 14881 opti++; 14882 } 14883 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14884 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14885 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14886 dumpState.setDump(DumpState.DUMP_PACKAGES); 14887 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14888 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14889 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14890 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14891 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14892 dumpState.setDump(DumpState.DUMP_MESSAGES); 14893 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14894 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14895 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14896 || "intent-filter-verifiers".equals(cmd)) { 14897 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14898 } else if ("version".equals(cmd)) { 14899 dumpState.setDump(DumpState.DUMP_VERSION); 14900 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14901 dumpState.setDump(DumpState.DUMP_KEYSETS); 14902 } else if ("installs".equals(cmd)) { 14903 dumpState.setDump(DumpState.DUMP_INSTALLS); 14904 } else if ("write".equals(cmd)) { 14905 synchronized (mPackages) { 14906 mSettings.writeLPr(); 14907 pw.println("Settings written."); 14908 return; 14909 } 14910 } 14911 } 14912 14913 if (checkin) { 14914 pw.println("vers,1"); 14915 } 14916 14917 // reader 14918 synchronized (mPackages) { 14919 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14920 if (!checkin) { 14921 if (dumpState.onTitlePrinted()) 14922 pw.println(); 14923 pw.println("Database versions:"); 14924 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 14925 } 14926 } 14927 14928 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14929 if (!checkin) { 14930 if (dumpState.onTitlePrinted()) 14931 pw.println(); 14932 pw.println("Verifiers:"); 14933 pw.print(" Required: "); 14934 pw.print(mRequiredVerifierPackage); 14935 pw.print(" (uid="); 14936 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14937 pw.println(")"); 14938 } else if (mRequiredVerifierPackage != null) { 14939 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14940 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14941 } 14942 } 14943 14944 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14945 packageName == null) { 14946 if (mIntentFilterVerifierComponent != null) { 14947 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14948 if (!checkin) { 14949 if (dumpState.onTitlePrinted()) 14950 pw.println(); 14951 pw.println("Intent Filter Verifier:"); 14952 pw.print(" Using: "); 14953 pw.print(verifierPackageName); 14954 pw.print(" (uid="); 14955 pw.print(getPackageUid(verifierPackageName, 0)); 14956 pw.println(")"); 14957 } else if (verifierPackageName != null) { 14958 pw.print("ifv,"); pw.print(verifierPackageName); 14959 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14960 } 14961 } else { 14962 pw.println(); 14963 pw.println("No Intent Filter Verifier available!"); 14964 } 14965 } 14966 14967 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14968 boolean printedHeader = false; 14969 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14970 while (it.hasNext()) { 14971 String name = it.next(); 14972 SharedLibraryEntry ent = mSharedLibraries.get(name); 14973 if (!checkin) { 14974 if (!printedHeader) { 14975 if (dumpState.onTitlePrinted()) 14976 pw.println(); 14977 pw.println("Libraries:"); 14978 printedHeader = true; 14979 } 14980 pw.print(" "); 14981 } else { 14982 pw.print("lib,"); 14983 } 14984 pw.print(name); 14985 if (!checkin) { 14986 pw.print(" -> "); 14987 } 14988 if (ent.path != null) { 14989 if (!checkin) { 14990 pw.print("(jar) "); 14991 pw.print(ent.path); 14992 } else { 14993 pw.print(",jar,"); 14994 pw.print(ent.path); 14995 } 14996 } else { 14997 if (!checkin) { 14998 pw.print("(apk) "); 14999 pw.print(ent.apk); 15000 } else { 15001 pw.print(",apk,"); 15002 pw.print(ent.apk); 15003 } 15004 } 15005 pw.println(); 15006 } 15007 } 15008 15009 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15010 if (dumpState.onTitlePrinted()) 15011 pw.println(); 15012 if (!checkin) { 15013 pw.println("Features:"); 15014 } 15015 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15016 while (it.hasNext()) { 15017 String name = it.next(); 15018 if (!checkin) { 15019 pw.print(" "); 15020 } else { 15021 pw.print("feat,"); 15022 } 15023 pw.println(name); 15024 } 15025 } 15026 15027 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15028 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15029 : "Activity Resolver Table:", " ", packageName, 15030 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15031 dumpState.setTitlePrinted(true); 15032 } 15033 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15034 : "Receiver Resolver Table:", " ", packageName, 15035 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15036 dumpState.setTitlePrinted(true); 15037 } 15038 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15039 : "Service Resolver Table:", " ", packageName, 15040 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15041 dumpState.setTitlePrinted(true); 15042 } 15043 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15044 : "Provider Resolver Table:", " ", packageName, 15045 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15046 dumpState.setTitlePrinted(true); 15047 } 15048 } 15049 15050 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15051 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15052 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15053 int user = mSettings.mPreferredActivities.keyAt(i); 15054 if (pir.dump(pw, 15055 dumpState.getTitlePrinted() 15056 ? "\nPreferred Activities User " + user + ":" 15057 : "Preferred Activities User " + user + ":", " ", 15058 packageName, true, false)) { 15059 dumpState.setTitlePrinted(true); 15060 } 15061 } 15062 } 15063 15064 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15065 pw.flush(); 15066 FileOutputStream fout = new FileOutputStream(fd); 15067 BufferedOutputStream str = new BufferedOutputStream(fout); 15068 XmlSerializer serializer = new FastXmlSerializer(); 15069 try { 15070 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15071 serializer.startDocument(null, true); 15072 serializer.setFeature( 15073 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15074 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15075 serializer.endDocument(); 15076 serializer.flush(); 15077 } catch (IllegalArgumentException e) { 15078 pw.println("Failed writing: " + e); 15079 } catch (IllegalStateException e) { 15080 pw.println("Failed writing: " + e); 15081 } catch (IOException e) { 15082 pw.println("Failed writing: " + e); 15083 } 15084 } 15085 15086 if (!checkin 15087 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15088 && packageName == null) { 15089 pw.println(); 15090 int count = mSettings.mPackages.size(); 15091 if (count == 0) { 15092 pw.println("No applications!"); 15093 pw.println(); 15094 } else { 15095 final String prefix = " "; 15096 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15097 if (allPackageSettings.size() == 0) { 15098 pw.println("No domain preferred apps!"); 15099 pw.println(); 15100 } else { 15101 pw.println("App verification status:"); 15102 pw.println(); 15103 count = 0; 15104 for (PackageSetting ps : allPackageSettings) { 15105 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15106 if (ivi == null || ivi.getPackageName() == null) continue; 15107 pw.println(prefix + "Package: " + ivi.getPackageName()); 15108 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15109 pw.println(prefix + "Status: " + ivi.getStatusString()); 15110 pw.println(); 15111 count++; 15112 } 15113 if (count == 0) { 15114 pw.println(prefix + "No app verification established."); 15115 pw.println(); 15116 } 15117 for (int userId : sUserManager.getUserIds()) { 15118 pw.println("App linkages for user " + userId + ":"); 15119 pw.println(); 15120 count = 0; 15121 for (PackageSetting ps : allPackageSettings) { 15122 final long status = ps.getDomainVerificationStatusForUser(userId); 15123 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15124 continue; 15125 } 15126 pw.println(prefix + "Package: " + ps.name); 15127 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15128 String statusStr = IntentFilterVerificationInfo. 15129 getStatusStringFromValue(status); 15130 pw.println(prefix + "Status: " + statusStr); 15131 pw.println(); 15132 count++; 15133 } 15134 if (count == 0) { 15135 pw.println(prefix + "No configured app linkages."); 15136 pw.println(); 15137 } 15138 } 15139 } 15140 } 15141 } 15142 15143 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15144 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15145 if (packageName == null && permissionNames == null) { 15146 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15147 if (iperm == 0) { 15148 if (dumpState.onTitlePrinted()) 15149 pw.println(); 15150 pw.println("AppOp Permissions:"); 15151 } 15152 pw.print(" AppOp Permission "); 15153 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15154 pw.println(":"); 15155 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15156 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15157 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15158 } 15159 } 15160 } 15161 } 15162 15163 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15164 boolean printedSomething = false; 15165 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15166 if (packageName != null && !packageName.equals(p.info.packageName)) { 15167 continue; 15168 } 15169 if (!printedSomething) { 15170 if (dumpState.onTitlePrinted()) 15171 pw.println(); 15172 pw.println("Registered ContentProviders:"); 15173 printedSomething = true; 15174 } 15175 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15176 pw.print(" "); pw.println(p.toString()); 15177 } 15178 printedSomething = false; 15179 for (Map.Entry<String, PackageParser.Provider> entry : 15180 mProvidersByAuthority.entrySet()) { 15181 PackageParser.Provider p = entry.getValue(); 15182 if (packageName != null && !packageName.equals(p.info.packageName)) { 15183 continue; 15184 } 15185 if (!printedSomething) { 15186 if (dumpState.onTitlePrinted()) 15187 pw.println(); 15188 pw.println("ContentProvider Authorities:"); 15189 printedSomething = true; 15190 } 15191 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15192 pw.print(" "); pw.println(p.toString()); 15193 if (p.info != null && p.info.applicationInfo != null) { 15194 final String appInfo = p.info.applicationInfo.toString(); 15195 pw.print(" applicationInfo="); pw.println(appInfo); 15196 } 15197 } 15198 } 15199 15200 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15201 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15202 } 15203 15204 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15205 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15206 } 15207 15208 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15209 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15210 } 15211 15212 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15213 // XXX should handle packageName != null by dumping only install data that 15214 // the given package is involved with. 15215 if (dumpState.onTitlePrinted()) pw.println(); 15216 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15217 } 15218 15219 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15220 if (dumpState.onTitlePrinted()) pw.println(); 15221 mSettings.dumpReadMessagesLPr(pw, dumpState); 15222 15223 pw.println(); 15224 pw.println("Package warning messages:"); 15225 BufferedReader in = null; 15226 String line = null; 15227 try { 15228 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15229 while ((line = in.readLine()) != null) { 15230 if (line.contains("ignored: updated version")) continue; 15231 pw.println(line); 15232 } 15233 } catch (IOException ignored) { 15234 } finally { 15235 IoUtils.closeQuietly(in); 15236 } 15237 } 15238 15239 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15240 BufferedReader in = null; 15241 String line = null; 15242 try { 15243 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15244 while ((line = in.readLine()) != null) { 15245 if (line.contains("ignored: updated version")) continue; 15246 pw.print("msg,"); 15247 pw.println(line); 15248 } 15249 } catch (IOException ignored) { 15250 } finally { 15251 IoUtils.closeQuietly(in); 15252 } 15253 } 15254 } 15255 } 15256 15257 private String dumpDomainString(String packageName) { 15258 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15259 List<IntentFilter> filters = getAllIntentFilters(packageName); 15260 15261 ArraySet<String> result = new ArraySet<>(); 15262 if (iviList.size() > 0) { 15263 for (IntentFilterVerificationInfo ivi : iviList) { 15264 for (String host : ivi.getDomains()) { 15265 result.add(host); 15266 } 15267 } 15268 } 15269 if (filters != null && filters.size() > 0) { 15270 for (IntentFilter filter : filters) { 15271 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15272 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15273 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15274 result.addAll(filter.getHostsList()); 15275 } 15276 } 15277 } 15278 15279 StringBuilder sb = new StringBuilder(result.size() * 16); 15280 for (String domain : result) { 15281 if (sb.length() > 0) sb.append(" "); 15282 sb.append(domain); 15283 } 15284 return sb.toString(); 15285 } 15286 15287 // ------- apps on sdcard specific code ------- 15288 static final boolean DEBUG_SD_INSTALL = false; 15289 15290 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15291 15292 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15293 15294 private boolean mMediaMounted = false; 15295 15296 static String getEncryptKey() { 15297 try { 15298 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15299 SD_ENCRYPTION_KEYSTORE_NAME); 15300 if (sdEncKey == null) { 15301 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15302 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15303 if (sdEncKey == null) { 15304 Slog.e(TAG, "Failed to create encryption keys"); 15305 return null; 15306 } 15307 } 15308 return sdEncKey; 15309 } catch (NoSuchAlgorithmException nsae) { 15310 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15311 return null; 15312 } catch (IOException ioe) { 15313 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15314 return null; 15315 } 15316 } 15317 15318 /* 15319 * Update media status on PackageManager. 15320 */ 15321 @Override 15322 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15323 int callingUid = Binder.getCallingUid(); 15324 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15325 throw new SecurityException("Media status can only be updated by the system"); 15326 } 15327 // reader; this apparently protects mMediaMounted, but should probably 15328 // be a different lock in that case. 15329 synchronized (mPackages) { 15330 Log.i(TAG, "Updating external media status from " 15331 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15332 + (mediaStatus ? "mounted" : "unmounted")); 15333 if (DEBUG_SD_INSTALL) 15334 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15335 + ", mMediaMounted=" + mMediaMounted); 15336 if (mediaStatus == mMediaMounted) { 15337 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15338 : 0, -1); 15339 mHandler.sendMessage(msg); 15340 return; 15341 } 15342 mMediaMounted = mediaStatus; 15343 } 15344 // Queue up an async operation since the package installation may take a 15345 // little while. 15346 mHandler.post(new Runnable() { 15347 public void run() { 15348 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15349 } 15350 }); 15351 } 15352 15353 /** 15354 * Called by MountService when the initial ASECs to scan are available. 15355 * Should block until all the ASEC containers are finished being scanned. 15356 */ 15357 public void scanAvailableAsecs() { 15358 updateExternalMediaStatusInner(true, false, false); 15359 if (mShouldRestoreconData) { 15360 SELinuxMMAC.setRestoreconDone(); 15361 mShouldRestoreconData = false; 15362 } 15363 } 15364 15365 /* 15366 * Collect information of applications on external media, map them against 15367 * existing containers and update information based on current mount status. 15368 * Please note that we always have to report status if reportStatus has been 15369 * set to true especially when unloading packages. 15370 */ 15371 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15372 boolean externalStorage) { 15373 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15374 int[] uidArr = EmptyArray.INT; 15375 15376 final String[] list = PackageHelper.getSecureContainerList(); 15377 if (ArrayUtils.isEmpty(list)) { 15378 Log.i(TAG, "No secure containers found"); 15379 } else { 15380 // Process list of secure containers and categorize them 15381 // as active or stale based on their package internal state. 15382 15383 // reader 15384 synchronized (mPackages) { 15385 for (String cid : list) { 15386 // Leave stages untouched for now; installer service owns them 15387 if (PackageInstallerService.isStageName(cid)) continue; 15388 15389 if (DEBUG_SD_INSTALL) 15390 Log.i(TAG, "Processing container " + cid); 15391 String pkgName = getAsecPackageName(cid); 15392 if (pkgName == null) { 15393 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15394 continue; 15395 } 15396 if (DEBUG_SD_INSTALL) 15397 Log.i(TAG, "Looking for pkg : " + pkgName); 15398 15399 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15400 if (ps == null) { 15401 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15402 continue; 15403 } 15404 15405 /* 15406 * Skip packages that are not external if we're unmounting 15407 * external storage. 15408 */ 15409 if (externalStorage && !isMounted && !isExternal(ps)) { 15410 continue; 15411 } 15412 15413 final AsecInstallArgs args = new AsecInstallArgs(cid, 15414 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15415 // The package status is changed only if the code path 15416 // matches between settings and the container id. 15417 if (ps.codePathString != null 15418 && ps.codePathString.startsWith(args.getCodePath())) { 15419 if (DEBUG_SD_INSTALL) { 15420 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15421 + " at code path: " + ps.codePathString); 15422 } 15423 15424 // We do have a valid package installed on sdcard 15425 processCids.put(args, ps.codePathString); 15426 final int uid = ps.appId; 15427 if (uid != -1) { 15428 uidArr = ArrayUtils.appendInt(uidArr, uid); 15429 } 15430 } else { 15431 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15432 + ps.codePathString); 15433 } 15434 } 15435 } 15436 15437 Arrays.sort(uidArr); 15438 } 15439 15440 // Process packages with valid entries. 15441 if (isMounted) { 15442 if (DEBUG_SD_INSTALL) 15443 Log.i(TAG, "Loading packages"); 15444 loadMediaPackages(processCids, uidArr); 15445 startCleaningPackages(); 15446 mInstallerService.onSecureContainersAvailable(); 15447 } else { 15448 if (DEBUG_SD_INSTALL) 15449 Log.i(TAG, "Unloading packages"); 15450 unloadMediaPackages(processCids, uidArr, reportStatus); 15451 } 15452 } 15453 15454 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15455 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15456 final int size = infos.size(); 15457 final String[] packageNames = new String[size]; 15458 final int[] packageUids = new int[size]; 15459 for (int i = 0; i < size; i++) { 15460 final ApplicationInfo info = infos.get(i); 15461 packageNames[i] = info.packageName; 15462 packageUids[i] = info.uid; 15463 } 15464 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15465 finishedReceiver); 15466 } 15467 15468 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15469 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15470 sendResourcesChangedBroadcast(mediaStatus, replacing, 15471 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15472 } 15473 15474 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15475 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15476 int size = pkgList.length; 15477 if (size > 0) { 15478 // Send broadcasts here 15479 Bundle extras = new Bundle(); 15480 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15481 if (uidArr != null) { 15482 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15483 } 15484 if (replacing) { 15485 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15486 } 15487 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15488 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15489 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15490 } 15491 } 15492 15493 /* 15494 * Look at potentially valid container ids from processCids If package 15495 * information doesn't match the one on record or package scanning fails, 15496 * the cid is added to list of removeCids. We currently don't delete stale 15497 * containers. 15498 */ 15499 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15500 ArrayList<String> pkgList = new ArrayList<String>(); 15501 Set<AsecInstallArgs> keys = processCids.keySet(); 15502 15503 for (AsecInstallArgs args : keys) { 15504 String codePath = processCids.get(args); 15505 if (DEBUG_SD_INSTALL) 15506 Log.i(TAG, "Loading container : " + args.cid); 15507 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15508 try { 15509 // Make sure there are no container errors first. 15510 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15511 Slog.e(TAG, "Failed to mount cid : " + args.cid 15512 + " when installing from sdcard"); 15513 continue; 15514 } 15515 // Check code path here. 15516 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15517 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15518 + " does not match one in settings " + codePath); 15519 continue; 15520 } 15521 // Parse package 15522 int parseFlags = mDefParseFlags; 15523 if (args.isExternalAsec()) { 15524 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15525 } 15526 if (args.isFwdLocked()) { 15527 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15528 } 15529 15530 synchronized (mInstallLock) { 15531 PackageParser.Package pkg = null; 15532 try { 15533 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15534 } catch (PackageManagerException e) { 15535 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15536 } 15537 // Scan the package 15538 if (pkg != null) { 15539 /* 15540 * TODO why is the lock being held? doPostInstall is 15541 * called in other places without the lock. This needs 15542 * to be straightened out. 15543 */ 15544 // writer 15545 synchronized (mPackages) { 15546 retCode = PackageManager.INSTALL_SUCCEEDED; 15547 pkgList.add(pkg.packageName); 15548 // Post process args 15549 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15550 pkg.applicationInfo.uid); 15551 } 15552 } else { 15553 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15554 } 15555 } 15556 15557 } finally { 15558 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15559 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15560 } 15561 } 15562 } 15563 // writer 15564 synchronized (mPackages) { 15565 // If the platform SDK has changed since the last time we booted, 15566 // we need to re-grant app permission to catch any new ones that 15567 // appear. This is really a hack, and means that apps can in some 15568 // cases get permissions that the user didn't initially explicitly 15569 // allow... it would be nice to have some better way to handle 15570 // this situation. 15571 final VersionInfo ver = mSettings.getExternalVersion(); 15572 15573 int updateFlags = UPDATE_PERMISSIONS_ALL; 15574 if (ver.sdkVersion != mSdkVersion) { 15575 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15576 + mSdkVersion + "; regranting permissions for external"); 15577 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15578 } 15579 updatePermissionsLPw(null, null, updateFlags); 15580 15581 // Yay, everything is now upgraded 15582 ver.forceCurrent(); 15583 15584 // can downgrade to reader 15585 // Persist settings 15586 mSettings.writeLPr(); 15587 } 15588 // Send a broadcast to let everyone know we are done processing 15589 if (pkgList.size() > 0) { 15590 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15591 } 15592 } 15593 15594 /* 15595 * Utility method to unload a list of specified containers 15596 */ 15597 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15598 // Just unmount all valid containers. 15599 for (AsecInstallArgs arg : cidArgs) { 15600 synchronized (mInstallLock) { 15601 arg.doPostDeleteLI(false); 15602 } 15603 } 15604 } 15605 15606 /* 15607 * Unload packages mounted on external media. This involves deleting package 15608 * data from internal structures, sending broadcasts about diabled packages, 15609 * gc'ing to free up references, unmounting all secure containers 15610 * corresponding to packages on external media, and posting a 15611 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15612 * that we always have to post this message if status has been requested no 15613 * matter what. 15614 */ 15615 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15616 final boolean reportStatus) { 15617 if (DEBUG_SD_INSTALL) 15618 Log.i(TAG, "unloading media packages"); 15619 ArrayList<String> pkgList = new ArrayList<String>(); 15620 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15621 final Set<AsecInstallArgs> keys = processCids.keySet(); 15622 for (AsecInstallArgs args : keys) { 15623 String pkgName = args.getPackageName(); 15624 if (DEBUG_SD_INSTALL) 15625 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15626 // Delete package internally 15627 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15628 synchronized (mInstallLock) { 15629 boolean res = deletePackageLI(pkgName, null, false, null, null, 15630 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15631 if (res) { 15632 pkgList.add(pkgName); 15633 } else { 15634 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15635 failedList.add(args); 15636 } 15637 } 15638 } 15639 15640 // reader 15641 synchronized (mPackages) { 15642 // We didn't update the settings after removing each package; 15643 // write them now for all packages. 15644 mSettings.writeLPr(); 15645 } 15646 15647 // We have to absolutely send UPDATED_MEDIA_STATUS only 15648 // after confirming that all the receivers processed the ordered 15649 // broadcast when packages get disabled, force a gc to clean things up. 15650 // and unload all the containers. 15651 if (pkgList.size() > 0) { 15652 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15653 new IIntentReceiver.Stub() { 15654 public void performReceive(Intent intent, int resultCode, String data, 15655 Bundle extras, boolean ordered, boolean sticky, 15656 int sendingUser) throws RemoteException { 15657 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15658 reportStatus ? 1 : 0, 1, keys); 15659 mHandler.sendMessage(msg); 15660 } 15661 }); 15662 } else { 15663 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15664 keys); 15665 mHandler.sendMessage(msg); 15666 } 15667 } 15668 15669 private void loadPrivatePackages(VolumeInfo vol) { 15670 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15671 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15672 synchronized (mInstallLock) { 15673 synchronized (mPackages) { 15674 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15675 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15676 for (PackageSetting ps : packages) { 15677 final PackageParser.Package pkg; 15678 try { 15679 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15680 loaded.add(pkg.applicationInfo); 15681 } catch (PackageManagerException e) { 15682 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15683 } 15684 15685 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15686 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15687 } 15688 } 15689 15690 int updateFlags = UPDATE_PERMISSIONS_ALL; 15691 if (ver.sdkVersion != mSdkVersion) { 15692 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15693 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15694 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15695 } 15696 updatePermissionsLPw(null, null, updateFlags); 15697 15698 // Yay, everything is now upgraded 15699 ver.forceCurrent(); 15700 15701 mSettings.writeLPr(); 15702 } 15703 } 15704 15705 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15706 sendResourcesChangedBroadcast(true, false, loaded, null); 15707 } 15708 15709 private void unloadPrivatePackages(VolumeInfo vol) { 15710 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15711 synchronized (mInstallLock) { 15712 synchronized (mPackages) { 15713 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15714 for (PackageSetting ps : packages) { 15715 if (ps.pkg == null) continue; 15716 15717 final ApplicationInfo info = ps.pkg.applicationInfo; 15718 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15719 if (deletePackageLI(ps.name, null, false, null, null, 15720 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15721 unloaded.add(info); 15722 } else { 15723 Slog.w(TAG, "Failed to unload " + ps.codePath); 15724 } 15725 } 15726 15727 mSettings.writeLPr(); 15728 } 15729 } 15730 15731 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15732 sendResourcesChangedBroadcast(false, false, unloaded, null); 15733 } 15734 15735 /** 15736 * Examine all users present on given mounted volume, and destroy data 15737 * belonging to users that are no longer valid, or whose user ID has been 15738 * recycled. 15739 */ 15740 private void reconcileUsers(String volumeUuid) { 15741 final File[] files = FileUtils 15742 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15743 for (File file : files) { 15744 if (!file.isDirectory()) continue; 15745 15746 final int userId; 15747 final UserInfo info; 15748 try { 15749 userId = Integer.parseInt(file.getName()); 15750 info = sUserManager.getUserInfo(userId); 15751 } catch (NumberFormatException e) { 15752 Slog.w(TAG, "Invalid user directory " + file); 15753 continue; 15754 } 15755 15756 boolean destroyUser = false; 15757 if (info == null) { 15758 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15759 + " because no matching user was found"); 15760 destroyUser = true; 15761 } else { 15762 try { 15763 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15764 } catch (IOException e) { 15765 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15766 + " because we failed to enforce serial number: " + e); 15767 destroyUser = true; 15768 } 15769 } 15770 15771 if (destroyUser) { 15772 synchronized (mInstallLock) { 15773 mInstaller.removeUserDataDirs(volumeUuid, userId); 15774 } 15775 } 15776 } 15777 15778 final UserManager um = mContext.getSystemService(UserManager.class); 15779 for (UserInfo user : um.getUsers()) { 15780 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15781 if (userDir.exists()) continue; 15782 15783 try { 15784 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15785 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15786 } catch (IOException e) { 15787 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15788 } 15789 } 15790 } 15791 15792 /** 15793 * Examine all apps present on given mounted volume, and destroy apps that 15794 * aren't expected, either due to uninstallation or reinstallation on 15795 * another volume. 15796 */ 15797 private void reconcileApps(String volumeUuid) { 15798 final File[] files = FileUtils 15799 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15800 for (File file : files) { 15801 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15802 && !PackageInstallerService.isStageName(file.getName()); 15803 if (!isPackage) { 15804 // Ignore entries which are not packages 15805 continue; 15806 } 15807 15808 boolean destroyApp = false; 15809 String packageName = null; 15810 try { 15811 final PackageLite pkg = PackageParser.parsePackageLite(file, 15812 PackageParser.PARSE_MUST_BE_APK); 15813 packageName = pkg.packageName; 15814 15815 synchronized (mPackages) { 15816 final PackageSetting ps = mSettings.mPackages.get(packageName); 15817 if (ps == null) { 15818 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15819 + volumeUuid + " because we found no install record"); 15820 destroyApp = true; 15821 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15822 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15823 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15824 destroyApp = true; 15825 } 15826 } 15827 15828 } catch (PackageParserException e) { 15829 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15830 destroyApp = true; 15831 } 15832 15833 if (destroyApp) { 15834 synchronized (mInstallLock) { 15835 if (packageName != null) { 15836 removeDataDirsLI(volumeUuid, packageName); 15837 } 15838 if (file.isDirectory()) { 15839 mInstaller.rmPackageDir(file.getAbsolutePath()); 15840 } else { 15841 file.delete(); 15842 } 15843 } 15844 } 15845 } 15846 } 15847 15848 private void unfreezePackage(String packageName) { 15849 synchronized (mPackages) { 15850 final PackageSetting ps = mSettings.mPackages.get(packageName); 15851 if (ps != null) { 15852 ps.frozen = false; 15853 } 15854 } 15855 } 15856 15857 @Override 15858 public int movePackage(final String packageName, final String volumeUuid) { 15859 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15860 15861 final int moveId = mNextMoveId.getAndIncrement(); 15862 try { 15863 movePackageInternal(packageName, volumeUuid, moveId); 15864 } catch (PackageManagerException e) { 15865 Slog.w(TAG, "Failed to move " + packageName, e); 15866 mMoveCallbacks.notifyStatusChanged(moveId, 15867 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15868 } 15869 return moveId; 15870 } 15871 15872 private void movePackageInternal(final String packageName, final String volumeUuid, 15873 final int moveId) throws PackageManagerException { 15874 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15875 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15876 final PackageManager pm = mContext.getPackageManager(); 15877 15878 final boolean currentAsec; 15879 final String currentVolumeUuid; 15880 final File codeFile; 15881 final String installerPackageName; 15882 final String packageAbiOverride; 15883 final int appId; 15884 final String seinfo; 15885 final String label; 15886 15887 // reader 15888 synchronized (mPackages) { 15889 final PackageParser.Package pkg = mPackages.get(packageName); 15890 final PackageSetting ps = mSettings.mPackages.get(packageName); 15891 if (pkg == null || ps == null) { 15892 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15893 } 15894 15895 if (pkg.applicationInfo.isSystemApp()) { 15896 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15897 "Cannot move system application"); 15898 } 15899 15900 if (pkg.applicationInfo.isExternalAsec()) { 15901 currentAsec = true; 15902 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 15903 } else if (pkg.applicationInfo.isForwardLocked()) { 15904 currentAsec = true; 15905 currentVolumeUuid = "forward_locked"; 15906 } else { 15907 currentAsec = false; 15908 currentVolumeUuid = ps.volumeUuid; 15909 15910 final File probe = new File(pkg.codePath); 15911 final File probeOat = new File(probe, "oat"); 15912 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15913 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15914 "Move only supported for modern cluster style installs"); 15915 } 15916 } 15917 15918 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 15919 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15920 "Package already moved to " + volumeUuid); 15921 } 15922 15923 if (ps.frozen) { 15924 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15925 "Failed to move already frozen package"); 15926 } 15927 ps.frozen = true; 15928 15929 codeFile = new File(pkg.codePath); 15930 installerPackageName = ps.installerPackageName; 15931 packageAbiOverride = ps.cpuAbiOverrideString; 15932 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15933 seinfo = pkg.applicationInfo.seinfo; 15934 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15935 } 15936 15937 // Now that we're guarded by frozen state, kill app during move 15938 final long token = Binder.clearCallingIdentity(); 15939 try { 15940 killApplication(packageName, appId, "move pkg"); 15941 } finally { 15942 Binder.restoreCallingIdentity(token); 15943 } 15944 15945 final Bundle extras = new Bundle(); 15946 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15947 extras.putString(Intent.EXTRA_TITLE, label); 15948 mMoveCallbacks.notifyCreated(moveId, extras); 15949 15950 int installFlags; 15951 final boolean moveCompleteApp; 15952 final File measurePath; 15953 15954 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15955 installFlags = INSTALL_INTERNAL; 15956 moveCompleteApp = !currentAsec; 15957 measurePath = Environment.getDataAppDirectory(volumeUuid); 15958 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15959 installFlags = INSTALL_EXTERNAL; 15960 moveCompleteApp = false; 15961 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15962 } else { 15963 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15964 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15965 || !volume.isMountedWritable()) { 15966 unfreezePackage(packageName); 15967 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15968 "Move location not mounted private volume"); 15969 } 15970 15971 Preconditions.checkState(!currentAsec); 15972 15973 installFlags = INSTALL_INTERNAL; 15974 moveCompleteApp = true; 15975 measurePath = Environment.getDataAppDirectory(volumeUuid); 15976 } 15977 15978 final PackageStats stats = new PackageStats(null, -1); 15979 synchronized (mInstaller) { 15980 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15981 unfreezePackage(packageName); 15982 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15983 "Failed to measure package size"); 15984 } 15985 } 15986 15987 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15988 + stats.dataSize); 15989 15990 final long startFreeBytes = measurePath.getFreeSpace(); 15991 final long sizeBytes; 15992 if (moveCompleteApp) { 15993 sizeBytes = stats.codeSize + stats.dataSize; 15994 } else { 15995 sizeBytes = stats.codeSize; 15996 } 15997 15998 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15999 unfreezePackage(packageName); 16000 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16001 "Not enough free space to move"); 16002 } 16003 16004 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16005 16006 final CountDownLatch installedLatch = new CountDownLatch(1); 16007 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16008 @Override 16009 public void onUserActionRequired(Intent intent) throws RemoteException { 16010 throw new IllegalStateException(); 16011 } 16012 16013 @Override 16014 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16015 Bundle extras) throws RemoteException { 16016 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16017 + PackageManager.installStatusToString(returnCode, msg)); 16018 16019 installedLatch.countDown(); 16020 16021 // Regardless of success or failure of the move operation, 16022 // always unfreeze the package 16023 unfreezePackage(packageName); 16024 16025 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16026 switch (status) { 16027 case PackageInstaller.STATUS_SUCCESS: 16028 mMoveCallbacks.notifyStatusChanged(moveId, 16029 PackageManager.MOVE_SUCCEEDED); 16030 break; 16031 case PackageInstaller.STATUS_FAILURE_STORAGE: 16032 mMoveCallbacks.notifyStatusChanged(moveId, 16033 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16034 break; 16035 default: 16036 mMoveCallbacks.notifyStatusChanged(moveId, 16037 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16038 break; 16039 } 16040 } 16041 }; 16042 16043 final MoveInfo move; 16044 if (moveCompleteApp) { 16045 // Kick off a thread to report progress estimates 16046 new Thread() { 16047 @Override 16048 public void run() { 16049 while (true) { 16050 try { 16051 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16052 break; 16053 } 16054 } catch (InterruptedException ignored) { 16055 } 16056 16057 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16058 final int progress = 10 + (int) MathUtils.constrain( 16059 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16060 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16061 } 16062 } 16063 }.start(); 16064 16065 final String dataAppName = codeFile.getName(); 16066 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16067 dataAppName, appId, seinfo); 16068 } else { 16069 move = null; 16070 } 16071 16072 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16073 16074 final Message msg = mHandler.obtainMessage(INIT_COPY); 16075 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16076 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 16077 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16078 mHandler.sendMessage(msg); 16079 } 16080 16081 @Override 16082 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16083 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16084 16085 final int realMoveId = mNextMoveId.getAndIncrement(); 16086 final Bundle extras = new Bundle(); 16087 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16088 mMoveCallbacks.notifyCreated(realMoveId, extras); 16089 16090 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16091 @Override 16092 public void onCreated(int moveId, Bundle extras) { 16093 // Ignored 16094 } 16095 16096 @Override 16097 public void onStatusChanged(int moveId, int status, long estMillis) { 16098 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16099 } 16100 }; 16101 16102 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16103 storage.setPrimaryStorageUuid(volumeUuid, callback); 16104 return realMoveId; 16105 } 16106 16107 @Override 16108 public int getMoveStatus(int moveId) { 16109 mContext.enforceCallingOrSelfPermission( 16110 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16111 return mMoveCallbacks.mLastStatus.get(moveId); 16112 } 16113 16114 @Override 16115 public void registerMoveCallback(IPackageMoveObserver callback) { 16116 mContext.enforceCallingOrSelfPermission( 16117 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16118 mMoveCallbacks.register(callback); 16119 } 16120 16121 @Override 16122 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16123 mContext.enforceCallingOrSelfPermission( 16124 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16125 mMoveCallbacks.unregister(callback); 16126 } 16127 16128 @Override 16129 public boolean setInstallLocation(int loc) { 16130 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16131 null); 16132 if (getInstallLocation() == loc) { 16133 return true; 16134 } 16135 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16136 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16137 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16138 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16139 return true; 16140 } 16141 return false; 16142 } 16143 16144 @Override 16145 public int getInstallLocation() { 16146 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16147 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16148 PackageHelper.APP_INSTALL_AUTO); 16149 } 16150 16151 /** Called by UserManagerService */ 16152 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16153 mDirtyUsers.remove(userHandle); 16154 mSettings.removeUserLPw(userHandle); 16155 mPendingBroadcasts.remove(userHandle); 16156 if (mInstaller != null) { 16157 // Technically, we shouldn't be doing this with the package lock 16158 // held. However, this is very rare, and there is already so much 16159 // other disk I/O going on, that we'll let it slide for now. 16160 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16161 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16162 final String volumeUuid = vol.getFsUuid(); 16163 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16164 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16165 } 16166 } 16167 mUserNeedsBadging.delete(userHandle); 16168 removeUnusedPackagesLILPw(userManager, userHandle); 16169 } 16170 16171 /** 16172 * We're removing userHandle and would like to remove any downloaded packages 16173 * that are no longer in use by any other user. 16174 * @param userHandle the user being removed 16175 */ 16176 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16177 final boolean DEBUG_CLEAN_APKS = false; 16178 int [] users = userManager.getUserIdsLPr(); 16179 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16180 while (psit.hasNext()) { 16181 PackageSetting ps = psit.next(); 16182 if (ps.pkg == null) { 16183 continue; 16184 } 16185 final String packageName = ps.pkg.packageName; 16186 // Skip over if system app 16187 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16188 continue; 16189 } 16190 if (DEBUG_CLEAN_APKS) { 16191 Slog.i(TAG, "Checking package " + packageName); 16192 } 16193 boolean keep = false; 16194 for (int i = 0; i < users.length; i++) { 16195 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16196 keep = true; 16197 if (DEBUG_CLEAN_APKS) { 16198 Slog.i(TAG, " Keeping package " + packageName + " for user " 16199 + users[i]); 16200 } 16201 break; 16202 } 16203 } 16204 if (!keep) { 16205 if (DEBUG_CLEAN_APKS) { 16206 Slog.i(TAG, " Removing package " + packageName); 16207 } 16208 mHandler.post(new Runnable() { 16209 public void run() { 16210 deletePackageX(packageName, userHandle, 0); 16211 } //end run 16212 }); 16213 } 16214 } 16215 } 16216 16217 /** Called by UserManagerService */ 16218 void createNewUserLILPw(int userHandle) { 16219 if (mInstaller != null) { 16220 mInstaller.createUserConfig(userHandle); 16221 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16222 applyFactoryDefaultBrowserLPw(userHandle); 16223 primeDomainVerificationsLPw(userHandle); 16224 } 16225 } 16226 16227 void newUserCreated(final int userHandle) { 16228 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16229 } 16230 16231 @Override 16232 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16233 mContext.enforceCallingOrSelfPermission( 16234 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16235 "Only package verification agents can read the verifier device identity"); 16236 16237 synchronized (mPackages) { 16238 return mSettings.getVerifierDeviceIdentityLPw(); 16239 } 16240 } 16241 16242 @Override 16243 public void setPermissionEnforced(String permission, boolean enforced) { 16244 // TODO: Now that we no longer change GID for storage, this should to away. 16245 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16246 "setPermissionEnforced"); 16247 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16248 synchronized (mPackages) { 16249 if (mSettings.mReadExternalStorageEnforced == null 16250 || mSettings.mReadExternalStorageEnforced != enforced) { 16251 mSettings.mReadExternalStorageEnforced = enforced; 16252 mSettings.writeLPr(); 16253 } 16254 } 16255 // kill any non-foreground processes so we restart them and 16256 // grant/revoke the GID. 16257 final IActivityManager am = ActivityManagerNative.getDefault(); 16258 if (am != null) { 16259 final long token = Binder.clearCallingIdentity(); 16260 try { 16261 am.killProcessesBelowForeground("setPermissionEnforcement"); 16262 } catch (RemoteException e) { 16263 } finally { 16264 Binder.restoreCallingIdentity(token); 16265 } 16266 } 16267 } else { 16268 throw new IllegalArgumentException("No selective enforcement for " + permission); 16269 } 16270 } 16271 16272 @Override 16273 @Deprecated 16274 public boolean isPermissionEnforced(String permission) { 16275 return true; 16276 } 16277 16278 @Override 16279 public boolean isStorageLow() { 16280 final long token = Binder.clearCallingIdentity(); 16281 try { 16282 final DeviceStorageMonitorInternal 16283 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16284 if (dsm != null) { 16285 return dsm.isMemoryLow(); 16286 } else { 16287 return false; 16288 } 16289 } finally { 16290 Binder.restoreCallingIdentity(token); 16291 } 16292 } 16293 16294 @Override 16295 public IPackageInstaller getPackageInstaller() { 16296 return mInstallerService; 16297 } 16298 16299 private boolean userNeedsBadging(int userId) { 16300 int index = mUserNeedsBadging.indexOfKey(userId); 16301 if (index < 0) { 16302 final UserInfo userInfo; 16303 final long token = Binder.clearCallingIdentity(); 16304 try { 16305 userInfo = sUserManager.getUserInfo(userId); 16306 } finally { 16307 Binder.restoreCallingIdentity(token); 16308 } 16309 final boolean b; 16310 if (userInfo != null && userInfo.isManagedProfile()) { 16311 b = true; 16312 } else { 16313 b = false; 16314 } 16315 mUserNeedsBadging.put(userId, b); 16316 return b; 16317 } 16318 return mUserNeedsBadging.valueAt(index); 16319 } 16320 16321 @Override 16322 public KeySet getKeySetByAlias(String packageName, String alias) { 16323 if (packageName == null || alias == null) { 16324 return null; 16325 } 16326 synchronized(mPackages) { 16327 final PackageParser.Package pkg = mPackages.get(packageName); 16328 if (pkg == null) { 16329 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16330 throw new IllegalArgumentException("Unknown package: " + packageName); 16331 } 16332 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16333 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16334 } 16335 } 16336 16337 @Override 16338 public KeySet getSigningKeySet(String packageName) { 16339 if (packageName == null) { 16340 return null; 16341 } 16342 synchronized(mPackages) { 16343 final PackageParser.Package pkg = mPackages.get(packageName); 16344 if (pkg == null) { 16345 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16346 throw new IllegalArgumentException("Unknown package: " + packageName); 16347 } 16348 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16349 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16350 throw new SecurityException("May not access signing KeySet of other apps."); 16351 } 16352 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16353 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16354 } 16355 } 16356 16357 @Override 16358 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16359 if (packageName == null || ks == null) { 16360 return false; 16361 } 16362 synchronized(mPackages) { 16363 final PackageParser.Package pkg = mPackages.get(packageName); 16364 if (pkg == null) { 16365 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16366 throw new IllegalArgumentException("Unknown package: " + packageName); 16367 } 16368 IBinder ksh = ks.getToken(); 16369 if (ksh instanceof KeySetHandle) { 16370 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16371 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16372 } 16373 return false; 16374 } 16375 } 16376 16377 @Override 16378 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16379 if (packageName == null || ks == null) { 16380 return false; 16381 } 16382 synchronized(mPackages) { 16383 final PackageParser.Package pkg = mPackages.get(packageName); 16384 if (pkg == null) { 16385 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16386 throw new IllegalArgumentException("Unknown package: " + packageName); 16387 } 16388 IBinder ksh = ks.getToken(); 16389 if (ksh instanceof KeySetHandle) { 16390 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16391 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16392 } 16393 return false; 16394 } 16395 } 16396 16397 public void getUsageStatsIfNoPackageUsageInfo() { 16398 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16399 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16400 if (usm == null) { 16401 throw new IllegalStateException("UsageStatsManager must be initialized"); 16402 } 16403 long now = System.currentTimeMillis(); 16404 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16405 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16406 String packageName = entry.getKey(); 16407 PackageParser.Package pkg = mPackages.get(packageName); 16408 if (pkg == null) { 16409 continue; 16410 } 16411 UsageStats usage = entry.getValue(); 16412 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16413 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16414 } 16415 } 16416 } 16417 16418 /** 16419 * Check and throw if the given before/after packages would be considered a 16420 * downgrade. 16421 */ 16422 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16423 throws PackageManagerException { 16424 if (after.versionCode < before.mVersionCode) { 16425 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16426 "Update version code " + after.versionCode + " is older than current " 16427 + before.mVersionCode); 16428 } else if (after.versionCode == before.mVersionCode) { 16429 if (after.baseRevisionCode < before.baseRevisionCode) { 16430 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16431 "Update base revision code " + after.baseRevisionCode 16432 + " is older than current " + before.baseRevisionCode); 16433 } 16434 16435 if (!ArrayUtils.isEmpty(after.splitNames)) { 16436 for (int i = 0; i < after.splitNames.length; i++) { 16437 final String splitName = after.splitNames[i]; 16438 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16439 if (j != -1) { 16440 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16441 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16442 "Update split " + splitName + " revision code " 16443 + after.splitRevisionCodes[i] + " is older than current " 16444 + before.splitRevisionCodes[j]); 16445 } 16446 } 16447 } 16448 } 16449 } 16450 } 16451 16452 private static class MoveCallbacks extends Handler { 16453 private static final int MSG_CREATED = 1; 16454 private static final int MSG_STATUS_CHANGED = 2; 16455 16456 private final RemoteCallbackList<IPackageMoveObserver> 16457 mCallbacks = new RemoteCallbackList<>(); 16458 16459 private final SparseIntArray mLastStatus = new SparseIntArray(); 16460 16461 public MoveCallbacks(Looper looper) { 16462 super(looper); 16463 } 16464 16465 public void register(IPackageMoveObserver callback) { 16466 mCallbacks.register(callback); 16467 } 16468 16469 public void unregister(IPackageMoveObserver callback) { 16470 mCallbacks.unregister(callback); 16471 } 16472 16473 @Override 16474 public void handleMessage(Message msg) { 16475 final SomeArgs args = (SomeArgs) msg.obj; 16476 final int n = mCallbacks.beginBroadcast(); 16477 for (int i = 0; i < n; i++) { 16478 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16479 try { 16480 invokeCallback(callback, msg.what, args); 16481 } catch (RemoteException ignored) { 16482 } 16483 } 16484 mCallbacks.finishBroadcast(); 16485 args.recycle(); 16486 } 16487 16488 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16489 throws RemoteException { 16490 switch (what) { 16491 case MSG_CREATED: { 16492 callback.onCreated(args.argi1, (Bundle) args.arg2); 16493 break; 16494 } 16495 case MSG_STATUS_CHANGED: { 16496 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16497 break; 16498 } 16499 } 16500 } 16501 16502 private void notifyCreated(int moveId, Bundle extras) { 16503 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16504 16505 final SomeArgs args = SomeArgs.obtain(); 16506 args.argi1 = moveId; 16507 args.arg2 = extras; 16508 obtainMessage(MSG_CREATED, args).sendToTarget(); 16509 } 16510 16511 private void notifyStatusChanged(int moveId, int status) { 16512 notifyStatusChanged(moveId, status, -1); 16513 } 16514 16515 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16516 Slog.v(TAG, "Move " + moveId + " status " + status); 16517 16518 final SomeArgs args = SomeArgs.obtain(); 16519 args.argi1 = moveId; 16520 args.argi2 = status; 16521 args.arg3 = estMillis; 16522 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16523 16524 synchronized (mLastStatus) { 16525 mLastStatus.put(moveId, status); 16526 } 16527 } 16528 } 16529 16530 private final class OnPermissionChangeListeners extends Handler { 16531 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16532 16533 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16534 new RemoteCallbackList<>(); 16535 16536 public OnPermissionChangeListeners(Looper looper) { 16537 super(looper); 16538 } 16539 16540 @Override 16541 public void handleMessage(Message msg) { 16542 switch (msg.what) { 16543 case MSG_ON_PERMISSIONS_CHANGED: { 16544 final int uid = msg.arg1; 16545 handleOnPermissionsChanged(uid); 16546 } break; 16547 } 16548 } 16549 16550 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16551 mPermissionListeners.register(listener); 16552 16553 } 16554 16555 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16556 mPermissionListeners.unregister(listener); 16557 } 16558 16559 public void onPermissionsChanged(int uid) { 16560 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16561 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16562 } 16563 } 16564 16565 private void handleOnPermissionsChanged(int uid) { 16566 final int count = mPermissionListeners.beginBroadcast(); 16567 try { 16568 for (int i = 0; i < count; i++) { 16569 IOnPermissionsChangeListener callback = mPermissionListeners 16570 .getBroadcastItem(i); 16571 try { 16572 callback.onPermissionsChanged(uid); 16573 } catch (RemoteException e) { 16574 Log.e(TAG, "Permission listener is dead", e); 16575 } 16576 } 16577 } finally { 16578 mPermissionListeners.finishBroadcast(); 16579 } 16580 } 16581 } 16582 16583 private class PackageManagerInternalImpl extends PackageManagerInternal { 16584 @Override 16585 public void setLocationPackagesProvider(PackagesProvider provider) { 16586 synchronized (mPackages) { 16587 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16588 } 16589 } 16590 16591 @Override 16592 public void setImePackagesProvider(PackagesProvider provider) { 16593 synchronized (mPackages) { 16594 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16595 } 16596 } 16597 16598 @Override 16599 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16600 synchronized (mPackages) { 16601 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16602 } 16603 } 16604 16605 @Override 16606 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16607 synchronized (mPackages) { 16608 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16609 } 16610 } 16611 16612 @Override 16613 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16614 synchronized (mPackages) { 16615 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16616 } 16617 } 16618 16619 @Override 16620 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16621 synchronized (mPackages) { 16622 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16623 } 16624 } 16625 16626 @Override 16627 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16628 synchronized (mPackages) { 16629 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16630 } 16631 } 16632 16633 @Override 16634 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16635 synchronized (mPackages) { 16636 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16637 packageName, userId); 16638 } 16639 } 16640 16641 @Override 16642 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16643 synchronized (mPackages) { 16644 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16645 packageName, userId); 16646 } 16647 } 16648 @Override 16649 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16650 synchronized (mPackages) { 16651 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16652 packageName, userId); 16653 } 16654 } 16655 } 16656 16657 @Override 16658 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16659 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16660 synchronized (mPackages) { 16661 final long identity = Binder.clearCallingIdentity(); 16662 try { 16663 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16664 packageNames, userId); 16665 } finally { 16666 Binder.restoreCallingIdentity(identity); 16667 } 16668 } 16669 } 16670 16671 private static void enforceSystemOrPhoneCaller(String tag) { 16672 int callingUid = Binder.getCallingUid(); 16673 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16674 throw new SecurityException( 16675 "Cannot call " + tag + " from UID " + callingUid); 16676 } 16677 } 16678} 16679