PackageManagerService.java revision 56f0ff3c48c88b969d9bf5e62eb1ee590e03e461
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 enforceDeclaredAsUsedAndRuntimePermission(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()) { 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 enforceDeclaredAsUsedAndRuntimePermission(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 final int result = permissionsState.grantRuntimePermission(bp, userId); 3494 switch (result) { 3495 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3496 return; 3497 } 3498 3499 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3500 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3501 mHandler.post(new Runnable() { 3502 @Override 3503 public void run() { 3504 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3505 } 3506 }); 3507 } break; 3508 } 3509 3510 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3511 3512 // Not critical if that is lost - app has to request again. 3513 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3514 } 3515 3516 // Only need to do this if user is initialized. Otherwise it's a new user 3517 // and there are no processes running as the user yet and there's no need 3518 // to make an expensive call to remount processes for the changed permissions. 3519 if (READ_EXTERNAL_STORAGE.equals(name) 3520 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3521 final long token = Binder.clearCallingIdentity(); 3522 try { 3523 if (sUserManager.isInitialized(userId)) { 3524 MountServiceInternal mountServiceInternal = LocalServices.getService( 3525 MountServiceInternal.class); 3526 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3527 } 3528 } finally { 3529 Binder.restoreCallingIdentity(token); 3530 } 3531 } 3532 } 3533 3534 @Override 3535 public void revokeRuntimePermission(String packageName, String name, int userId) { 3536 if (!sUserManager.exists(userId)) { 3537 Log.e(TAG, "No such user:" + userId); 3538 return; 3539 } 3540 3541 mContext.enforceCallingOrSelfPermission( 3542 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3543 "revokeRuntimePermission"); 3544 3545 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3546 "revokeRuntimePermission"); 3547 3548 final int appId; 3549 3550 synchronized (mPackages) { 3551 final PackageParser.Package pkg = mPackages.get(packageName); 3552 if (pkg == null) { 3553 throw new IllegalArgumentException("Unknown package: " + packageName); 3554 } 3555 3556 final BasePermission bp = mSettings.mPermissions.get(name); 3557 if (bp == null) { 3558 throw new IllegalArgumentException("Unknown permission: " + name); 3559 } 3560 3561 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3562 3563 SettingBase sb = (SettingBase) pkg.mExtras; 3564 if (sb == null) { 3565 throw new IllegalArgumentException("Unknown package: " + packageName); 3566 } 3567 3568 final PermissionsState permissionsState = sb.getPermissionsState(); 3569 3570 final int flags = permissionsState.getPermissionFlags(name, userId); 3571 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3572 throw new SecurityException("Cannot revoke system fixed permission: " 3573 + name + " for package: " + packageName); 3574 } 3575 3576 if (permissionsState.revokeRuntimePermission(bp, userId) == 3577 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3578 return; 3579 } 3580 3581 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3582 3583 // Critical, after this call app should never have the permission. 3584 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3585 3586 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3587 } 3588 3589 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3590 } 3591 3592 @Override 3593 public void resetRuntimePermissions() { 3594 mContext.enforceCallingOrSelfPermission( 3595 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3596 "revokeRuntimePermission"); 3597 3598 int callingUid = Binder.getCallingUid(); 3599 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3600 mContext.enforceCallingOrSelfPermission( 3601 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3602 "resetRuntimePermissions"); 3603 } 3604 3605 synchronized (mPackages) { 3606 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3607 for (int userId : UserManagerService.getInstance().getUserIds()) { 3608 final int packageCount = mPackages.size(); 3609 for (int i = 0; i < packageCount; i++) { 3610 PackageParser.Package pkg = mPackages.valueAt(i); 3611 if (!(pkg.mExtras instanceof PackageSetting)) { 3612 continue; 3613 } 3614 PackageSetting ps = (PackageSetting) pkg.mExtras; 3615 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3616 } 3617 } 3618 } 3619 } 3620 3621 @Override 3622 public int getPermissionFlags(String name, String packageName, int userId) { 3623 if (!sUserManager.exists(userId)) { 3624 return 0; 3625 } 3626 3627 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3628 3629 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3630 "getPermissionFlags"); 3631 3632 synchronized (mPackages) { 3633 final PackageParser.Package pkg = mPackages.get(packageName); 3634 if (pkg == null) { 3635 throw new IllegalArgumentException("Unknown package: " + packageName); 3636 } 3637 3638 final BasePermission bp = mSettings.mPermissions.get(name); 3639 if (bp == null) { 3640 throw new IllegalArgumentException("Unknown permission: " + name); 3641 } 3642 3643 SettingBase sb = (SettingBase) pkg.mExtras; 3644 if (sb == null) { 3645 throw new IllegalArgumentException("Unknown package: " + packageName); 3646 } 3647 3648 PermissionsState permissionsState = sb.getPermissionsState(); 3649 return permissionsState.getPermissionFlags(name, userId); 3650 } 3651 } 3652 3653 @Override 3654 public void updatePermissionFlags(String name, String packageName, int flagMask, 3655 int flagValues, int userId) { 3656 if (!sUserManager.exists(userId)) { 3657 return; 3658 } 3659 3660 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3661 3662 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3663 "updatePermissionFlags"); 3664 3665 // Only the system can change these flags and nothing else. 3666 if (getCallingUid() != Process.SYSTEM_UID) { 3667 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3668 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3669 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3670 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3671 } 3672 3673 synchronized (mPackages) { 3674 final PackageParser.Package pkg = mPackages.get(packageName); 3675 if (pkg == null) { 3676 throw new IllegalArgumentException("Unknown package: " + packageName); 3677 } 3678 3679 final BasePermission bp = mSettings.mPermissions.get(name); 3680 if (bp == null) { 3681 throw new IllegalArgumentException("Unknown permission: " + name); 3682 } 3683 3684 SettingBase sb = (SettingBase) pkg.mExtras; 3685 if (sb == null) { 3686 throw new IllegalArgumentException("Unknown package: " + packageName); 3687 } 3688 3689 PermissionsState permissionsState = sb.getPermissionsState(); 3690 3691 // Only the package manager can change flags for system component permissions. 3692 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3693 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3694 return; 3695 } 3696 3697 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3698 3699 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3700 // Install and runtime permissions are stored in different places, 3701 // so figure out what permission changed and persist the change. 3702 if (permissionsState.getInstallPermissionState(name) != null) { 3703 scheduleWriteSettingsLocked(); 3704 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3705 || hadState) { 3706 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3707 } 3708 } 3709 } 3710 } 3711 3712 /** 3713 * Update the permission flags for all packages and runtime permissions of a user in order 3714 * to allow device or profile owner to remove POLICY_FIXED. 3715 */ 3716 @Override 3717 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3718 if (!sUserManager.exists(userId)) { 3719 return; 3720 } 3721 3722 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3723 3724 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3725 "updatePermissionFlagsForAllApps"); 3726 3727 // Only the system can change system fixed flags. 3728 if (getCallingUid() != Process.SYSTEM_UID) { 3729 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3730 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3731 } 3732 3733 synchronized (mPackages) { 3734 boolean changed = false; 3735 final int packageCount = mPackages.size(); 3736 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3737 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3738 SettingBase sb = (SettingBase) pkg.mExtras; 3739 if (sb == null) { 3740 continue; 3741 } 3742 PermissionsState permissionsState = sb.getPermissionsState(); 3743 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3744 userId, flagMask, flagValues); 3745 } 3746 if (changed) { 3747 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3748 } 3749 } 3750 } 3751 3752 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3753 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3754 != PackageManager.PERMISSION_GRANTED 3755 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3756 != PackageManager.PERMISSION_GRANTED) { 3757 throw new SecurityException(message + " requires " 3758 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3759 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3760 } 3761 } 3762 3763 @Override 3764 public boolean shouldShowRequestPermissionRationale(String permissionName, 3765 String packageName, int userId) { 3766 if (UserHandle.getCallingUserId() != userId) { 3767 mContext.enforceCallingPermission( 3768 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3769 "canShowRequestPermissionRationale for user " + userId); 3770 } 3771 3772 final int uid = getPackageUid(packageName, userId); 3773 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3774 return false; 3775 } 3776 3777 if (checkPermission(permissionName, packageName, userId) 3778 == PackageManager.PERMISSION_GRANTED) { 3779 return false; 3780 } 3781 3782 final int flags; 3783 3784 final long identity = Binder.clearCallingIdentity(); 3785 try { 3786 flags = getPermissionFlags(permissionName, 3787 packageName, userId); 3788 } finally { 3789 Binder.restoreCallingIdentity(identity); 3790 } 3791 3792 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3793 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3794 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3795 3796 if ((flags & fixedFlags) != 0) { 3797 return false; 3798 } 3799 3800 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3801 } 3802 3803 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3804 BasePermission bp = mSettings.mPermissions.get(permission); 3805 if (bp == null) { 3806 throw new SecurityException("Missing " + permission + " permission"); 3807 } 3808 3809 SettingBase sb = (SettingBase) pkg.mExtras; 3810 PermissionsState permissionsState = sb.getPermissionsState(); 3811 3812 if (permissionsState.grantInstallPermission(bp) != 3813 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3814 scheduleWriteSettingsLocked(); 3815 } 3816 } 3817 3818 @Override 3819 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3820 mContext.enforceCallingOrSelfPermission( 3821 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3822 "addOnPermissionsChangeListener"); 3823 3824 synchronized (mPackages) { 3825 mOnPermissionChangeListeners.addListenerLocked(listener); 3826 } 3827 } 3828 3829 @Override 3830 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3831 synchronized (mPackages) { 3832 mOnPermissionChangeListeners.removeListenerLocked(listener); 3833 } 3834 } 3835 3836 @Override 3837 public boolean isProtectedBroadcast(String actionName) { 3838 synchronized (mPackages) { 3839 return mProtectedBroadcasts.contains(actionName); 3840 } 3841 } 3842 3843 @Override 3844 public int checkSignatures(String pkg1, String pkg2) { 3845 synchronized (mPackages) { 3846 final PackageParser.Package p1 = mPackages.get(pkg1); 3847 final PackageParser.Package p2 = mPackages.get(pkg2); 3848 if (p1 == null || p1.mExtras == null 3849 || p2 == null || p2.mExtras == null) { 3850 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3851 } 3852 return compareSignatures(p1.mSignatures, p2.mSignatures); 3853 } 3854 } 3855 3856 @Override 3857 public int checkUidSignatures(int uid1, int uid2) { 3858 // Map to base uids. 3859 uid1 = UserHandle.getAppId(uid1); 3860 uid2 = UserHandle.getAppId(uid2); 3861 // reader 3862 synchronized (mPackages) { 3863 Signature[] s1; 3864 Signature[] s2; 3865 Object obj = mSettings.getUserIdLPr(uid1); 3866 if (obj != null) { 3867 if (obj instanceof SharedUserSetting) { 3868 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3869 } else if (obj instanceof PackageSetting) { 3870 s1 = ((PackageSetting)obj).signatures.mSignatures; 3871 } else { 3872 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3873 } 3874 } else { 3875 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3876 } 3877 obj = mSettings.getUserIdLPr(uid2); 3878 if (obj != null) { 3879 if (obj instanceof SharedUserSetting) { 3880 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3881 } else if (obj instanceof PackageSetting) { 3882 s2 = ((PackageSetting)obj).signatures.mSignatures; 3883 } else { 3884 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3885 } 3886 } else { 3887 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3888 } 3889 return compareSignatures(s1, s2); 3890 } 3891 } 3892 3893 private void killUid(int appId, int userId, String reason) { 3894 final long identity = Binder.clearCallingIdentity(); 3895 try { 3896 IActivityManager am = ActivityManagerNative.getDefault(); 3897 if (am != null) { 3898 try { 3899 am.killUid(appId, userId, reason); 3900 } catch (RemoteException e) { 3901 /* ignore - same process */ 3902 } 3903 } 3904 } finally { 3905 Binder.restoreCallingIdentity(identity); 3906 } 3907 } 3908 3909 /** 3910 * Compares two sets of signatures. Returns: 3911 * <br /> 3912 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3913 * <br /> 3914 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3915 * <br /> 3916 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3917 * <br /> 3918 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3919 * <br /> 3920 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3921 */ 3922 static int compareSignatures(Signature[] s1, Signature[] s2) { 3923 if (s1 == null) { 3924 return s2 == null 3925 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3926 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3927 } 3928 3929 if (s2 == null) { 3930 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3931 } 3932 3933 if (s1.length != s2.length) { 3934 return PackageManager.SIGNATURE_NO_MATCH; 3935 } 3936 3937 // Since both signature sets are of size 1, we can compare without HashSets. 3938 if (s1.length == 1) { 3939 return s1[0].equals(s2[0]) ? 3940 PackageManager.SIGNATURE_MATCH : 3941 PackageManager.SIGNATURE_NO_MATCH; 3942 } 3943 3944 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3945 for (Signature sig : s1) { 3946 set1.add(sig); 3947 } 3948 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3949 for (Signature sig : s2) { 3950 set2.add(sig); 3951 } 3952 // Make sure s2 contains all signatures in s1. 3953 if (set1.equals(set2)) { 3954 return PackageManager.SIGNATURE_MATCH; 3955 } 3956 return PackageManager.SIGNATURE_NO_MATCH; 3957 } 3958 3959 /** 3960 * If the database version for this type of package (internal storage or 3961 * external storage) is less than the version where package signatures 3962 * were updated, return true. 3963 */ 3964 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3965 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3966 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3967 } 3968 3969 /** 3970 * Used for backward compatibility to make sure any packages with 3971 * certificate chains get upgraded to the new style. {@code existingSigs} 3972 * will be in the old format (since they were stored on disk from before the 3973 * system upgrade) and {@code scannedSigs} will be in the newer format. 3974 */ 3975 private int compareSignaturesCompat(PackageSignatures existingSigs, 3976 PackageParser.Package scannedPkg) { 3977 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3978 return PackageManager.SIGNATURE_NO_MATCH; 3979 } 3980 3981 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3982 for (Signature sig : existingSigs.mSignatures) { 3983 existingSet.add(sig); 3984 } 3985 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3986 for (Signature sig : scannedPkg.mSignatures) { 3987 try { 3988 Signature[] chainSignatures = sig.getChainSignatures(); 3989 for (Signature chainSig : chainSignatures) { 3990 scannedCompatSet.add(chainSig); 3991 } 3992 } catch (CertificateEncodingException e) { 3993 scannedCompatSet.add(sig); 3994 } 3995 } 3996 /* 3997 * Make sure the expanded scanned set contains all signatures in the 3998 * existing one. 3999 */ 4000 if (scannedCompatSet.equals(existingSet)) { 4001 // Migrate the old signatures to the new scheme. 4002 existingSigs.assignSignatures(scannedPkg.mSignatures); 4003 // The new KeySets will be re-added later in the scanning process. 4004 synchronized (mPackages) { 4005 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4006 } 4007 return PackageManager.SIGNATURE_MATCH; 4008 } 4009 return PackageManager.SIGNATURE_NO_MATCH; 4010 } 4011 4012 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4013 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4014 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4015 } 4016 4017 private int compareSignaturesRecover(PackageSignatures existingSigs, 4018 PackageParser.Package scannedPkg) { 4019 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4020 return PackageManager.SIGNATURE_NO_MATCH; 4021 } 4022 4023 String msg = null; 4024 try { 4025 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4026 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4027 + scannedPkg.packageName); 4028 return PackageManager.SIGNATURE_MATCH; 4029 } 4030 } catch (CertificateException e) { 4031 msg = e.getMessage(); 4032 } 4033 4034 logCriticalInfo(Log.INFO, 4035 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4036 return PackageManager.SIGNATURE_NO_MATCH; 4037 } 4038 4039 @Override 4040 public String[] getPackagesForUid(int uid) { 4041 uid = UserHandle.getAppId(uid); 4042 // reader 4043 synchronized (mPackages) { 4044 Object obj = mSettings.getUserIdLPr(uid); 4045 if (obj instanceof SharedUserSetting) { 4046 final SharedUserSetting sus = (SharedUserSetting) obj; 4047 final int N = sus.packages.size(); 4048 final String[] res = new String[N]; 4049 final Iterator<PackageSetting> it = sus.packages.iterator(); 4050 int i = 0; 4051 while (it.hasNext()) { 4052 res[i++] = it.next().name; 4053 } 4054 return res; 4055 } else if (obj instanceof PackageSetting) { 4056 final PackageSetting ps = (PackageSetting) obj; 4057 return new String[] { ps.name }; 4058 } 4059 } 4060 return null; 4061 } 4062 4063 @Override 4064 public String getNameForUid(int uid) { 4065 // reader 4066 synchronized (mPackages) { 4067 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4068 if (obj instanceof SharedUserSetting) { 4069 final SharedUserSetting sus = (SharedUserSetting) obj; 4070 return sus.name + ":" + sus.userId; 4071 } else if (obj instanceof PackageSetting) { 4072 final PackageSetting ps = (PackageSetting) obj; 4073 return ps.name; 4074 } 4075 } 4076 return null; 4077 } 4078 4079 @Override 4080 public int getUidForSharedUser(String sharedUserName) { 4081 if(sharedUserName == null) { 4082 return -1; 4083 } 4084 // reader 4085 synchronized (mPackages) { 4086 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4087 if (suid == null) { 4088 return -1; 4089 } 4090 return suid.userId; 4091 } 4092 } 4093 4094 @Override 4095 public int getFlagsForUid(int uid) { 4096 synchronized (mPackages) { 4097 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4098 if (obj instanceof SharedUserSetting) { 4099 final SharedUserSetting sus = (SharedUserSetting) obj; 4100 return sus.pkgFlags; 4101 } else if (obj instanceof PackageSetting) { 4102 final PackageSetting ps = (PackageSetting) obj; 4103 return ps.pkgFlags; 4104 } 4105 } 4106 return 0; 4107 } 4108 4109 @Override 4110 public int getPrivateFlagsForUid(int uid) { 4111 synchronized (mPackages) { 4112 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4113 if (obj instanceof SharedUserSetting) { 4114 final SharedUserSetting sus = (SharedUserSetting) obj; 4115 return sus.pkgPrivateFlags; 4116 } else if (obj instanceof PackageSetting) { 4117 final PackageSetting ps = (PackageSetting) obj; 4118 return ps.pkgPrivateFlags; 4119 } 4120 } 4121 return 0; 4122 } 4123 4124 @Override 4125 public boolean isUidPrivileged(int uid) { 4126 uid = UserHandle.getAppId(uid); 4127 // reader 4128 synchronized (mPackages) { 4129 Object obj = mSettings.getUserIdLPr(uid); 4130 if (obj instanceof SharedUserSetting) { 4131 final SharedUserSetting sus = (SharedUserSetting) obj; 4132 final Iterator<PackageSetting> it = sus.packages.iterator(); 4133 while (it.hasNext()) { 4134 if (it.next().isPrivileged()) { 4135 return true; 4136 } 4137 } 4138 } else if (obj instanceof PackageSetting) { 4139 final PackageSetting ps = (PackageSetting) obj; 4140 return ps.isPrivileged(); 4141 } 4142 } 4143 return false; 4144 } 4145 4146 @Override 4147 public String[] getAppOpPermissionPackages(String permissionName) { 4148 synchronized (mPackages) { 4149 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4150 if (pkgs == null) { 4151 return null; 4152 } 4153 return pkgs.toArray(new String[pkgs.size()]); 4154 } 4155 } 4156 4157 @Override 4158 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4159 int flags, int userId) { 4160 if (!sUserManager.exists(userId)) return null; 4161 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4162 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4163 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4164 } 4165 4166 @Override 4167 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4168 IntentFilter filter, int match, ComponentName activity) { 4169 final int userId = UserHandle.getCallingUserId(); 4170 if (DEBUG_PREFERRED) { 4171 Log.v(TAG, "setLastChosenActivity intent=" + intent 4172 + " resolvedType=" + resolvedType 4173 + " flags=" + flags 4174 + " filter=" + filter 4175 + " match=" + match 4176 + " activity=" + activity); 4177 filter.dump(new PrintStreamPrinter(System.out), " "); 4178 } 4179 intent.setComponent(null); 4180 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4181 // Find any earlier preferred or last chosen entries and nuke them 4182 findPreferredActivity(intent, resolvedType, 4183 flags, query, 0, false, true, false, userId); 4184 // Add the new activity as the last chosen for this filter 4185 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4186 "Setting last chosen"); 4187 } 4188 4189 @Override 4190 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4191 final int userId = UserHandle.getCallingUserId(); 4192 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4193 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4194 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4195 false, false, false, userId); 4196 } 4197 4198 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4199 int flags, List<ResolveInfo> query, int userId) { 4200 if (query != null) { 4201 final int N = query.size(); 4202 if (N == 1) { 4203 return query.get(0); 4204 } else if (N > 1) { 4205 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4206 // If there is more than one activity with the same priority, 4207 // then let the user decide between them. 4208 ResolveInfo r0 = query.get(0); 4209 ResolveInfo r1 = query.get(1); 4210 if (DEBUG_INTENT_MATCHING || debug) { 4211 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4212 + r1.activityInfo.name + "=" + r1.priority); 4213 } 4214 // If the first activity has a higher priority, or a different 4215 // default, then it is always desireable to pick it. 4216 if (r0.priority != r1.priority 4217 || r0.preferredOrder != r1.preferredOrder 4218 || r0.isDefault != r1.isDefault) { 4219 return query.get(0); 4220 } 4221 // If we have saved a preference for a preferred activity for 4222 // this Intent, use that. 4223 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4224 flags, query, r0.priority, true, false, debug, userId); 4225 if (ri != null) { 4226 return ri; 4227 } 4228 if (userId != 0) { 4229 ri = new ResolveInfo(mResolveInfo); 4230 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4231 ri.activityInfo.applicationInfo = new ApplicationInfo( 4232 ri.activityInfo.applicationInfo); 4233 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4234 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4235 return ri; 4236 } 4237 return mResolveInfo; 4238 } 4239 } 4240 return null; 4241 } 4242 4243 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4244 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4245 final int N = query.size(); 4246 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4247 .get(userId); 4248 // Get the list of persistent preferred activities that handle the intent 4249 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4250 List<PersistentPreferredActivity> pprefs = ppir != null 4251 ? ppir.queryIntent(intent, resolvedType, 4252 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4253 : null; 4254 if (pprefs != null && pprefs.size() > 0) { 4255 final int M = pprefs.size(); 4256 for (int i=0; i<M; i++) { 4257 final PersistentPreferredActivity ppa = pprefs.get(i); 4258 if (DEBUG_PREFERRED || debug) { 4259 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4260 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4261 + "\n component=" + ppa.mComponent); 4262 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4263 } 4264 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4265 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4266 if (DEBUG_PREFERRED || debug) { 4267 Slog.v(TAG, "Found persistent preferred activity:"); 4268 if (ai != null) { 4269 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4270 } else { 4271 Slog.v(TAG, " null"); 4272 } 4273 } 4274 if (ai == null) { 4275 // This previously registered persistent preferred activity 4276 // component is no longer known. Ignore it and do NOT remove it. 4277 continue; 4278 } 4279 for (int j=0; j<N; j++) { 4280 final ResolveInfo ri = query.get(j); 4281 if (!ri.activityInfo.applicationInfo.packageName 4282 .equals(ai.applicationInfo.packageName)) { 4283 continue; 4284 } 4285 if (!ri.activityInfo.name.equals(ai.name)) { 4286 continue; 4287 } 4288 // Found a persistent preference that can handle the intent. 4289 if (DEBUG_PREFERRED || debug) { 4290 Slog.v(TAG, "Returning persistent preferred activity: " + 4291 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4292 } 4293 return ri; 4294 } 4295 } 4296 } 4297 return null; 4298 } 4299 4300 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4301 List<ResolveInfo> query, int priority, boolean always, 4302 boolean removeMatches, boolean debug, int userId) { 4303 if (!sUserManager.exists(userId)) return null; 4304 // writer 4305 synchronized (mPackages) { 4306 if (intent.getSelector() != null) { 4307 intent = intent.getSelector(); 4308 } 4309 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4310 4311 // Try to find a matching persistent preferred activity. 4312 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4313 debug, userId); 4314 4315 // If a persistent preferred activity matched, use it. 4316 if (pri != null) { 4317 return pri; 4318 } 4319 4320 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4321 // Get the list of preferred activities that handle the intent 4322 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4323 List<PreferredActivity> prefs = pir != null 4324 ? pir.queryIntent(intent, resolvedType, 4325 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4326 : null; 4327 if (prefs != null && prefs.size() > 0) { 4328 boolean changed = false; 4329 try { 4330 // First figure out how good the original match set is. 4331 // We will only allow preferred activities that came 4332 // from the same match quality. 4333 int match = 0; 4334 4335 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4336 4337 final int N = query.size(); 4338 for (int j=0; j<N; j++) { 4339 final ResolveInfo ri = query.get(j); 4340 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4341 + ": 0x" + Integer.toHexString(match)); 4342 if (ri.match > match) { 4343 match = ri.match; 4344 } 4345 } 4346 4347 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4348 + Integer.toHexString(match)); 4349 4350 match &= IntentFilter.MATCH_CATEGORY_MASK; 4351 final int M = prefs.size(); 4352 for (int i=0; i<M; i++) { 4353 final PreferredActivity pa = prefs.get(i); 4354 if (DEBUG_PREFERRED || debug) { 4355 Slog.v(TAG, "Checking PreferredActivity ds=" 4356 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4357 + "\n component=" + pa.mPref.mComponent); 4358 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4359 } 4360 if (pa.mPref.mMatch != match) { 4361 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4362 + Integer.toHexString(pa.mPref.mMatch)); 4363 continue; 4364 } 4365 // If it's not an "always" type preferred activity and that's what we're 4366 // looking for, skip it. 4367 if (always && !pa.mPref.mAlways) { 4368 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4369 continue; 4370 } 4371 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4372 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4373 if (DEBUG_PREFERRED || debug) { 4374 Slog.v(TAG, "Found preferred activity:"); 4375 if (ai != null) { 4376 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4377 } else { 4378 Slog.v(TAG, " null"); 4379 } 4380 } 4381 if (ai == null) { 4382 // This previously registered preferred activity 4383 // component is no longer known. Most likely an update 4384 // to the app was installed and in the new version this 4385 // component no longer exists. Clean it up by removing 4386 // it from the preferred activities list, and skip it. 4387 Slog.w(TAG, "Removing dangling preferred activity: " 4388 + pa.mPref.mComponent); 4389 pir.removeFilter(pa); 4390 changed = true; 4391 continue; 4392 } 4393 for (int j=0; j<N; j++) { 4394 final ResolveInfo ri = query.get(j); 4395 if (!ri.activityInfo.applicationInfo.packageName 4396 .equals(ai.applicationInfo.packageName)) { 4397 continue; 4398 } 4399 if (!ri.activityInfo.name.equals(ai.name)) { 4400 continue; 4401 } 4402 4403 if (removeMatches) { 4404 pir.removeFilter(pa); 4405 changed = true; 4406 if (DEBUG_PREFERRED) { 4407 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4408 } 4409 break; 4410 } 4411 4412 // Okay we found a previously set preferred or last chosen app. 4413 // If the result set is different from when this 4414 // was created, we need to clear it and re-ask the 4415 // user their preference, if we're looking for an "always" type entry. 4416 if (always && !pa.mPref.sameSet(query)) { 4417 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4418 + intent + " type " + resolvedType); 4419 if (DEBUG_PREFERRED) { 4420 Slog.v(TAG, "Removing preferred activity since set changed " 4421 + pa.mPref.mComponent); 4422 } 4423 pir.removeFilter(pa); 4424 // Re-add the filter as a "last chosen" entry (!always) 4425 PreferredActivity lastChosen = new PreferredActivity( 4426 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4427 pir.addFilter(lastChosen); 4428 changed = true; 4429 return null; 4430 } 4431 4432 // Yay! Either the set matched or we're looking for the last chosen 4433 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4434 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4435 return ri; 4436 } 4437 } 4438 } finally { 4439 if (changed) { 4440 if (DEBUG_PREFERRED) { 4441 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4442 } 4443 scheduleWritePackageRestrictionsLocked(userId); 4444 } 4445 } 4446 } 4447 } 4448 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4449 return null; 4450 } 4451 4452 /* 4453 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4454 */ 4455 @Override 4456 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4457 int targetUserId) { 4458 mContext.enforceCallingOrSelfPermission( 4459 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4460 List<CrossProfileIntentFilter> matches = 4461 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4462 if (matches != null) { 4463 int size = matches.size(); 4464 for (int i = 0; i < size; i++) { 4465 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4466 } 4467 } 4468 if (hasWebURI(intent)) { 4469 // cross-profile app linking works only towards the parent. 4470 final UserInfo parent = getProfileParent(sourceUserId); 4471 synchronized(mPackages) { 4472 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4473 intent, resolvedType, 0, sourceUserId, parent.id); 4474 return xpDomainInfo != null; 4475 } 4476 } 4477 return false; 4478 } 4479 4480 private UserInfo getProfileParent(int userId) { 4481 final long identity = Binder.clearCallingIdentity(); 4482 try { 4483 return sUserManager.getProfileParent(userId); 4484 } finally { 4485 Binder.restoreCallingIdentity(identity); 4486 } 4487 } 4488 4489 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4490 String resolvedType, int userId) { 4491 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4492 if (resolver != null) { 4493 return resolver.queryIntent(intent, resolvedType, false, userId); 4494 } 4495 return null; 4496 } 4497 4498 @Override 4499 public List<ResolveInfo> queryIntentActivities(Intent intent, 4500 String resolvedType, int flags, int userId) { 4501 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4502 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4503 ComponentName comp = intent.getComponent(); 4504 if (comp == null) { 4505 if (intent.getSelector() != null) { 4506 intent = intent.getSelector(); 4507 comp = intent.getComponent(); 4508 } 4509 } 4510 4511 if (comp != null) { 4512 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4513 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4514 if (ai != null) { 4515 final ResolveInfo ri = new ResolveInfo(); 4516 ri.activityInfo = ai; 4517 list.add(ri); 4518 } 4519 return list; 4520 } 4521 4522 // reader 4523 synchronized (mPackages) { 4524 final String pkgName = intent.getPackage(); 4525 if (pkgName == null) { 4526 List<CrossProfileIntentFilter> matchingFilters = 4527 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4528 // Check for results that need to skip the current profile. 4529 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4530 resolvedType, flags, userId); 4531 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4532 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4533 result.add(xpResolveInfo); 4534 return filterIfNotPrimaryUser(result, userId); 4535 } 4536 4537 // Check for results in the current profile. 4538 List<ResolveInfo> result = mActivities.queryIntent( 4539 intent, resolvedType, flags, userId); 4540 4541 // Check for cross profile results. 4542 xpResolveInfo = queryCrossProfileIntents( 4543 matchingFilters, intent, resolvedType, flags, userId); 4544 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4545 result.add(xpResolveInfo); 4546 Collections.sort(result, mResolvePrioritySorter); 4547 } 4548 result = filterIfNotPrimaryUser(result, userId); 4549 if (hasWebURI(intent)) { 4550 CrossProfileDomainInfo xpDomainInfo = null; 4551 final UserInfo parent = getProfileParent(userId); 4552 if (parent != null) { 4553 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4554 flags, userId, parent.id); 4555 } 4556 if (xpDomainInfo != null) { 4557 if (xpResolveInfo != null) { 4558 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4559 // in the result. 4560 result.remove(xpResolveInfo); 4561 } 4562 if (result.size() == 0) { 4563 result.add(xpDomainInfo.resolveInfo); 4564 return result; 4565 } 4566 } else if (result.size() <= 1) { 4567 return result; 4568 } 4569 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4570 xpDomainInfo, userId); 4571 Collections.sort(result, mResolvePrioritySorter); 4572 } 4573 return result; 4574 } 4575 final PackageParser.Package pkg = mPackages.get(pkgName); 4576 if (pkg != null) { 4577 return filterIfNotPrimaryUser( 4578 mActivities.queryIntentForPackage( 4579 intent, resolvedType, flags, pkg.activities, userId), 4580 userId); 4581 } 4582 return new ArrayList<ResolveInfo>(); 4583 } 4584 } 4585 4586 private static class CrossProfileDomainInfo { 4587 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4588 ResolveInfo resolveInfo; 4589 /* Best domain verification status of the activities found in the other profile */ 4590 int bestDomainVerificationStatus; 4591 } 4592 4593 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4594 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4595 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4596 sourceUserId)) { 4597 return null; 4598 } 4599 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4600 resolvedType, flags, parentUserId); 4601 4602 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4603 return null; 4604 } 4605 CrossProfileDomainInfo result = null; 4606 int size = resultTargetUser.size(); 4607 for (int i = 0; i < size; i++) { 4608 ResolveInfo riTargetUser = resultTargetUser.get(i); 4609 // Intent filter verification is only for filters that specify a host. So don't return 4610 // those that handle all web uris. 4611 if (riTargetUser.handleAllWebDataURI) { 4612 continue; 4613 } 4614 String packageName = riTargetUser.activityInfo.packageName; 4615 PackageSetting ps = mSettings.mPackages.get(packageName); 4616 if (ps == null) { 4617 continue; 4618 } 4619 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4620 int status = (int)(verificationState >> 32); 4621 if (result == null) { 4622 result = new CrossProfileDomainInfo(); 4623 result.resolveInfo = 4624 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4625 result.bestDomainVerificationStatus = status; 4626 } else { 4627 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4628 result.bestDomainVerificationStatus); 4629 } 4630 } 4631 // Don't consider matches with status NEVER across profiles. 4632 if (result != null && result.bestDomainVerificationStatus 4633 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4634 return null; 4635 } 4636 return result; 4637 } 4638 4639 /** 4640 * Verification statuses are ordered from the worse to the best, except for 4641 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4642 */ 4643 private int bestDomainVerificationStatus(int status1, int status2) { 4644 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4645 return status2; 4646 } 4647 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4648 return status1; 4649 } 4650 return (int) MathUtils.max(status1, status2); 4651 } 4652 4653 private boolean isUserEnabled(int userId) { 4654 long callingId = Binder.clearCallingIdentity(); 4655 try { 4656 UserInfo userInfo = sUserManager.getUserInfo(userId); 4657 return userInfo != null && userInfo.isEnabled(); 4658 } finally { 4659 Binder.restoreCallingIdentity(callingId); 4660 } 4661 } 4662 4663 /** 4664 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4665 * 4666 * @return filtered list 4667 */ 4668 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4669 if (userId == UserHandle.USER_OWNER) { 4670 return resolveInfos; 4671 } 4672 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4673 ResolveInfo info = resolveInfos.get(i); 4674 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4675 resolveInfos.remove(i); 4676 } 4677 } 4678 return resolveInfos; 4679 } 4680 4681 private static boolean hasWebURI(Intent intent) { 4682 if (intent.getData() == null) { 4683 return false; 4684 } 4685 final String scheme = intent.getScheme(); 4686 if (TextUtils.isEmpty(scheme)) { 4687 return false; 4688 } 4689 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4690 } 4691 4692 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4693 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4694 int userId) { 4695 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4696 4697 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4698 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4699 candidates.size()); 4700 } 4701 4702 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4703 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4704 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4705 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4706 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4707 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4708 4709 synchronized (mPackages) { 4710 final int count = candidates.size(); 4711 // First, try to use linked apps. Partition the candidates into four lists: 4712 // one for the final results, one for the "do not use ever", one for "undefined status" 4713 // and finally one for "browser app type". 4714 for (int n=0; n<count; n++) { 4715 ResolveInfo info = candidates.get(n); 4716 String packageName = info.activityInfo.packageName; 4717 PackageSetting ps = mSettings.mPackages.get(packageName); 4718 if (ps != null) { 4719 // Add to the special match all list (Browser use case) 4720 if (info.handleAllWebDataURI) { 4721 matchAllList.add(info); 4722 continue; 4723 } 4724 // Try to get the status from User settings first 4725 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4726 int status = (int)(packedStatus >> 32); 4727 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4728 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4729 if (DEBUG_DOMAIN_VERIFICATION) { 4730 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4731 + " : linkgen=" + linkGeneration); 4732 } 4733 // Use link-enabled generation as preferredOrder, i.e. 4734 // prefer newly-enabled over earlier-enabled. 4735 info.preferredOrder = linkGeneration; 4736 alwaysList.add(info); 4737 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4738 if (DEBUG_DOMAIN_VERIFICATION) { 4739 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4740 } 4741 neverList.add(info); 4742 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4743 if (DEBUG_DOMAIN_VERIFICATION) { 4744 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4745 } 4746 alwaysAskList.add(info); 4747 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4748 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4749 if (DEBUG_DOMAIN_VERIFICATION) { 4750 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4751 } 4752 undefinedList.add(info); 4753 } 4754 } 4755 } 4756 4757 // We'll want to include browser possibilities in a few cases 4758 boolean includeBrowser = false; 4759 4760 // First try to add the "always" resolution(s) for the current user, if any 4761 if (alwaysList.size() > 0) { 4762 result.addAll(alwaysList); 4763 // if there is an "always" for the parent user, add it. 4764 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4765 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4766 result.add(xpDomainInfo.resolveInfo); 4767 } else { 4768 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4769 result.addAll(undefinedList); 4770 if (xpDomainInfo != null && ( 4771 xpDomainInfo.bestDomainVerificationStatus 4772 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4773 || xpDomainInfo.bestDomainVerificationStatus 4774 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4775 result.add(xpDomainInfo.resolveInfo); 4776 } 4777 includeBrowser = true; 4778 } 4779 4780 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4781 // If there were 'always' entries their preferred order has been set, so we also 4782 // back that off to make the alternatives equivalent 4783 if (alwaysAskList.size() > 0) { 4784 for (ResolveInfo i : result) { 4785 i.preferredOrder = 0; 4786 } 4787 result.addAll(alwaysAskList); 4788 includeBrowser = true; 4789 } 4790 4791 if (includeBrowser) { 4792 // Also add browsers (all of them or only the default one) 4793 if (DEBUG_DOMAIN_VERIFICATION) { 4794 Slog.v(TAG, " ...including browsers in candidate set"); 4795 } 4796 if ((matchFlags & MATCH_ALL) != 0) { 4797 result.addAll(matchAllList); 4798 } else { 4799 // Browser/generic handling case. If there's a default browser, go straight 4800 // to that (but only if there is no other higher-priority match). 4801 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4802 int maxMatchPrio = 0; 4803 ResolveInfo defaultBrowserMatch = null; 4804 final int numCandidates = matchAllList.size(); 4805 for (int n = 0; n < numCandidates; n++) { 4806 ResolveInfo info = matchAllList.get(n); 4807 // track the highest overall match priority... 4808 if (info.priority > maxMatchPrio) { 4809 maxMatchPrio = info.priority; 4810 } 4811 // ...and the highest-priority default browser match 4812 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4813 if (defaultBrowserMatch == null 4814 || (defaultBrowserMatch.priority < info.priority)) { 4815 if (debug) { 4816 Slog.v(TAG, "Considering default browser match " + info); 4817 } 4818 defaultBrowserMatch = info; 4819 } 4820 } 4821 } 4822 if (defaultBrowserMatch != null 4823 && defaultBrowserMatch.priority >= maxMatchPrio 4824 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4825 { 4826 if (debug) { 4827 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4828 } 4829 result.add(defaultBrowserMatch); 4830 } else { 4831 result.addAll(matchAllList); 4832 } 4833 } 4834 4835 // If there is nothing selected, add all candidates and remove the ones that the user 4836 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4837 if (result.size() == 0) { 4838 result.addAll(candidates); 4839 result.removeAll(neverList); 4840 } 4841 } 4842 } 4843 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4844 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4845 result.size()); 4846 for (ResolveInfo info : result) { 4847 Slog.v(TAG, " + " + info.activityInfo); 4848 } 4849 } 4850 return result; 4851 } 4852 4853 // Returns a packed value as a long: 4854 // 4855 // high 'int'-sized word: link status: undefined/ask/never/always. 4856 // low 'int'-sized word: relative priority among 'always' results. 4857 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4858 long result = ps.getDomainVerificationStatusForUser(userId); 4859 // if none available, get the master status 4860 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4861 if (ps.getIntentFilterVerificationInfo() != null) { 4862 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4863 } 4864 } 4865 return result; 4866 } 4867 4868 private ResolveInfo querySkipCurrentProfileIntents( 4869 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4870 int flags, int sourceUserId) { 4871 if (matchingFilters != null) { 4872 int size = matchingFilters.size(); 4873 for (int i = 0; i < size; i ++) { 4874 CrossProfileIntentFilter filter = matchingFilters.get(i); 4875 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4876 // Checking if there are activities in the target user that can handle the 4877 // intent. 4878 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4879 flags, sourceUserId); 4880 if (resolveInfo != null) { 4881 return resolveInfo; 4882 } 4883 } 4884 } 4885 } 4886 return null; 4887 } 4888 4889 // Return matching ResolveInfo if any for skip current profile intent filters. 4890 private ResolveInfo queryCrossProfileIntents( 4891 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4892 int flags, int sourceUserId) { 4893 if (matchingFilters != null) { 4894 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4895 // match the same intent. For performance reasons, it is better not to 4896 // run queryIntent twice for the same userId 4897 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4898 int size = matchingFilters.size(); 4899 for (int i = 0; i < size; i++) { 4900 CrossProfileIntentFilter filter = matchingFilters.get(i); 4901 int targetUserId = filter.getTargetUserId(); 4902 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4903 && !alreadyTriedUserIds.get(targetUserId)) { 4904 // Checking if there are activities in the target user that can handle the 4905 // intent. 4906 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4907 flags, sourceUserId); 4908 if (resolveInfo != null) return resolveInfo; 4909 alreadyTriedUserIds.put(targetUserId, true); 4910 } 4911 } 4912 } 4913 return null; 4914 } 4915 4916 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4917 String resolvedType, int flags, int sourceUserId) { 4918 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4919 resolvedType, flags, filter.getTargetUserId()); 4920 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4921 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4922 } 4923 return null; 4924 } 4925 4926 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4927 int sourceUserId, int targetUserId) { 4928 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4929 String className; 4930 if (targetUserId == UserHandle.USER_OWNER) { 4931 className = FORWARD_INTENT_TO_USER_OWNER; 4932 } else { 4933 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4934 } 4935 ComponentName forwardingActivityComponentName = new ComponentName( 4936 mAndroidApplication.packageName, className); 4937 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4938 sourceUserId); 4939 if (targetUserId == UserHandle.USER_OWNER) { 4940 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4941 forwardingResolveInfo.noResourceId = true; 4942 } 4943 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4944 forwardingResolveInfo.priority = 0; 4945 forwardingResolveInfo.preferredOrder = 0; 4946 forwardingResolveInfo.match = 0; 4947 forwardingResolveInfo.isDefault = true; 4948 forwardingResolveInfo.filter = filter; 4949 forwardingResolveInfo.targetUserId = targetUserId; 4950 return forwardingResolveInfo; 4951 } 4952 4953 @Override 4954 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4955 Intent[] specifics, String[] specificTypes, Intent intent, 4956 String resolvedType, int flags, int userId) { 4957 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4958 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4959 false, "query intent activity options"); 4960 final String resultsAction = intent.getAction(); 4961 4962 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4963 | PackageManager.GET_RESOLVED_FILTER, userId); 4964 4965 if (DEBUG_INTENT_MATCHING) { 4966 Log.v(TAG, "Query " + intent + ": " + results); 4967 } 4968 4969 int specificsPos = 0; 4970 int N; 4971 4972 // todo: note that the algorithm used here is O(N^2). This 4973 // isn't a problem in our current environment, but if we start running 4974 // into situations where we have more than 5 or 10 matches then this 4975 // should probably be changed to something smarter... 4976 4977 // First we go through and resolve each of the specific items 4978 // that were supplied, taking care of removing any corresponding 4979 // duplicate items in the generic resolve list. 4980 if (specifics != null) { 4981 for (int i=0; i<specifics.length; i++) { 4982 final Intent sintent = specifics[i]; 4983 if (sintent == null) { 4984 continue; 4985 } 4986 4987 if (DEBUG_INTENT_MATCHING) { 4988 Log.v(TAG, "Specific #" + i + ": " + sintent); 4989 } 4990 4991 String action = sintent.getAction(); 4992 if (resultsAction != null && resultsAction.equals(action)) { 4993 // If this action was explicitly requested, then don't 4994 // remove things that have it. 4995 action = null; 4996 } 4997 4998 ResolveInfo ri = null; 4999 ActivityInfo ai = null; 5000 5001 ComponentName comp = sintent.getComponent(); 5002 if (comp == null) { 5003 ri = resolveIntent( 5004 sintent, 5005 specificTypes != null ? specificTypes[i] : null, 5006 flags, userId); 5007 if (ri == null) { 5008 continue; 5009 } 5010 if (ri == mResolveInfo) { 5011 // ACK! Must do something better with this. 5012 } 5013 ai = ri.activityInfo; 5014 comp = new ComponentName(ai.applicationInfo.packageName, 5015 ai.name); 5016 } else { 5017 ai = getActivityInfo(comp, flags, userId); 5018 if (ai == null) { 5019 continue; 5020 } 5021 } 5022 5023 // Look for any generic query activities that are duplicates 5024 // of this specific one, and remove them from the results. 5025 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5026 N = results.size(); 5027 int j; 5028 for (j=specificsPos; j<N; j++) { 5029 ResolveInfo sri = results.get(j); 5030 if ((sri.activityInfo.name.equals(comp.getClassName()) 5031 && sri.activityInfo.applicationInfo.packageName.equals( 5032 comp.getPackageName())) 5033 || (action != null && sri.filter.matchAction(action))) { 5034 results.remove(j); 5035 if (DEBUG_INTENT_MATCHING) Log.v( 5036 TAG, "Removing duplicate item from " + j 5037 + " due to specific " + specificsPos); 5038 if (ri == null) { 5039 ri = sri; 5040 } 5041 j--; 5042 N--; 5043 } 5044 } 5045 5046 // Add this specific item to its proper place. 5047 if (ri == null) { 5048 ri = new ResolveInfo(); 5049 ri.activityInfo = ai; 5050 } 5051 results.add(specificsPos, ri); 5052 ri.specificIndex = i; 5053 specificsPos++; 5054 } 5055 } 5056 5057 // Now we go through the remaining generic results and remove any 5058 // duplicate actions that are found here. 5059 N = results.size(); 5060 for (int i=specificsPos; i<N-1; i++) { 5061 final ResolveInfo rii = results.get(i); 5062 if (rii.filter == null) { 5063 continue; 5064 } 5065 5066 // Iterate over all of the actions of this result's intent 5067 // filter... typically this should be just one. 5068 final Iterator<String> it = rii.filter.actionsIterator(); 5069 if (it == null) { 5070 continue; 5071 } 5072 while (it.hasNext()) { 5073 final String action = it.next(); 5074 if (resultsAction != null && resultsAction.equals(action)) { 5075 // If this action was explicitly requested, then don't 5076 // remove things that have it. 5077 continue; 5078 } 5079 for (int j=i+1; j<N; j++) { 5080 final ResolveInfo rij = results.get(j); 5081 if (rij.filter != null && rij.filter.hasAction(action)) { 5082 results.remove(j); 5083 if (DEBUG_INTENT_MATCHING) Log.v( 5084 TAG, "Removing duplicate item from " + j 5085 + " due to action " + action + " at " + i); 5086 j--; 5087 N--; 5088 } 5089 } 5090 } 5091 5092 // If the caller didn't request filter information, drop it now 5093 // so we don't have to marshall/unmarshall it. 5094 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5095 rii.filter = null; 5096 } 5097 } 5098 5099 // Filter out the caller activity if so requested. 5100 if (caller != null) { 5101 N = results.size(); 5102 for (int i=0; i<N; i++) { 5103 ActivityInfo ainfo = results.get(i).activityInfo; 5104 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5105 && caller.getClassName().equals(ainfo.name)) { 5106 results.remove(i); 5107 break; 5108 } 5109 } 5110 } 5111 5112 // If the caller didn't request filter information, 5113 // drop them now so we don't have to 5114 // marshall/unmarshall it. 5115 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5116 N = results.size(); 5117 for (int i=0; i<N; i++) { 5118 results.get(i).filter = null; 5119 } 5120 } 5121 5122 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5123 return results; 5124 } 5125 5126 @Override 5127 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5128 int userId) { 5129 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5130 ComponentName comp = intent.getComponent(); 5131 if (comp == null) { 5132 if (intent.getSelector() != null) { 5133 intent = intent.getSelector(); 5134 comp = intent.getComponent(); 5135 } 5136 } 5137 if (comp != null) { 5138 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5139 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5140 if (ai != null) { 5141 ResolveInfo ri = new ResolveInfo(); 5142 ri.activityInfo = ai; 5143 list.add(ri); 5144 } 5145 return list; 5146 } 5147 5148 // reader 5149 synchronized (mPackages) { 5150 String pkgName = intent.getPackage(); 5151 if (pkgName == null) { 5152 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5153 } 5154 final PackageParser.Package pkg = mPackages.get(pkgName); 5155 if (pkg != null) { 5156 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5157 userId); 5158 } 5159 return null; 5160 } 5161 } 5162 5163 @Override 5164 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5165 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5166 if (!sUserManager.exists(userId)) return null; 5167 if (query != null) { 5168 if (query.size() >= 1) { 5169 // If there is more than one service with the same priority, 5170 // just arbitrarily pick the first one. 5171 return query.get(0); 5172 } 5173 } 5174 return null; 5175 } 5176 5177 @Override 5178 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5179 int userId) { 5180 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5181 ComponentName comp = intent.getComponent(); 5182 if (comp == null) { 5183 if (intent.getSelector() != null) { 5184 intent = intent.getSelector(); 5185 comp = intent.getComponent(); 5186 } 5187 } 5188 if (comp != null) { 5189 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5190 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5191 if (si != null) { 5192 final ResolveInfo ri = new ResolveInfo(); 5193 ri.serviceInfo = si; 5194 list.add(ri); 5195 } 5196 return list; 5197 } 5198 5199 // reader 5200 synchronized (mPackages) { 5201 String pkgName = intent.getPackage(); 5202 if (pkgName == null) { 5203 return mServices.queryIntent(intent, resolvedType, flags, userId); 5204 } 5205 final PackageParser.Package pkg = mPackages.get(pkgName); 5206 if (pkg != null) { 5207 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5208 userId); 5209 } 5210 return null; 5211 } 5212 } 5213 5214 @Override 5215 public List<ResolveInfo> queryIntentContentProviders( 5216 Intent intent, String resolvedType, int flags, int userId) { 5217 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5218 ComponentName comp = intent.getComponent(); 5219 if (comp == null) { 5220 if (intent.getSelector() != null) { 5221 intent = intent.getSelector(); 5222 comp = intent.getComponent(); 5223 } 5224 } 5225 if (comp != null) { 5226 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5227 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5228 if (pi != null) { 5229 final ResolveInfo ri = new ResolveInfo(); 5230 ri.providerInfo = pi; 5231 list.add(ri); 5232 } 5233 return list; 5234 } 5235 5236 // reader 5237 synchronized (mPackages) { 5238 String pkgName = intent.getPackage(); 5239 if (pkgName == null) { 5240 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5241 } 5242 final PackageParser.Package pkg = mPackages.get(pkgName); 5243 if (pkg != null) { 5244 return mProviders.queryIntentForPackage( 5245 intent, resolvedType, flags, pkg.providers, userId); 5246 } 5247 return null; 5248 } 5249 } 5250 5251 @Override 5252 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5253 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5254 5255 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5256 5257 // writer 5258 synchronized (mPackages) { 5259 ArrayList<PackageInfo> list; 5260 if (listUninstalled) { 5261 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5262 for (PackageSetting ps : mSettings.mPackages.values()) { 5263 PackageInfo pi; 5264 if (ps.pkg != null) { 5265 pi = generatePackageInfo(ps.pkg, flags, userId); 5266 } else { 5267 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5268 } 5269 if (pi != null) { 5270 list.add(pi); 5271 } 5272 } 5273 } else { 5274 list = new ArrayList<PackageInfo>(mPackages.size()); 5275 for (PackageParser.Package p : mPackages.values()) { 5276 PackageInfo pi = generatePackageInfo(p, flags, userId); 5277 if (pi != null) { 5278 list.add(pi); 5279 } 5280 } 5281 } 5282 5283 return new ParceledListSlice<PackageInfo>(list); 5284 } 5285 } 5286 5287 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5288 String[] permissions, boolean[] tmp, int flags, int userId) { 5289 int numMatch = 0; 5290 final PermissionsState permissionsState = ps.getPermissionsState(); 5291 for (int i=0; i<permissions.length; i++) { 5292 final String permission = permissions[i]; 5293 if (permissionsState.hasPermission(permission, userId)) { 5294 tmp[i] = true; 5295 numMatch++; 5296 } else { 5297 tmp[i] = false; 5298 } 5299 } 5300 if (numMatch == 0) { 5301 return; 5302 } 5303 PackageInfo pi; 5304 if (ps.pkg != null) { 5305 pi = generatePackageInfo(ps.pkg, flags, userId); 5306 } else { 5307 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5308 } 5309 // The above might return null in cases of uninstalled apps or install-state 5310 // skew across users/profiles. 5311 if (pi != null) { 5312 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5313 if (numMatch == permissions.length) { 5314 pi.requestedPermissions = permissions; 5315 } else { 5316 pi.requestedPermissions = new String[numMatch]; 5317 numMatch = 0; 5318 for (int i=0; i<permissions.length; i++) { 5319 if (tmp[i]) { 5320 pi.requestedPermissions[numMatch] = permissions[i]; 5321 numMatch++; 5322 } 5323 } 5324 } 5325 } 5326 list.add(pi); 5327 } 5328 } 5329 5330 @Override 5331 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5332 String[] permissions, int flags, int userId) { 5333 if (!sUserManager.exists(userId)) return null; 5334 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5335 5336 // writer 5337 synchronized (mPackages) { 5338 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5339 boolean[] tmpBools = new boolean[permissions.length]; 5340 if (listUninstalled) { 5341 for (PackageSetting ps : mSettings.mPackages.values()) { 5342 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5343 } 5344 } else { 5345 for (PackageParser.Package pkg : mPackages.values()) { 5346 PackageSetting ps = (PackageSetting)pkg.mExtras; 5347 if (ps != null) { 5348 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5349 userId); 5350 } 5351 } 5352 } 5353 5354 return new ParceledListSlice<PackageInfo>(list); 5355 } 5356 } 5357 5358 @Override 5359 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5360 if (!sUserManager.exists(userId)) return null; 5361 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5362 5363 // writer 5364 synchronized (mPackages) { 5365 ArrayList<ApplicationInfo> list; 5366 if (listUninstalled) { 5367 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5368 for (PackageSetting ps : mSettings.mPackages.values()) { 5369 ApplicationInfo ai; 5370 if (ps.pkg != null) { 5371 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5372 ps.readUserState(userId), userId); 5373 } else { 5374 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5375 } 5376 if (ai != null) { 5377 list.add(ai); 5378 } 5379 } 5380 } else { 5381 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5382 for (PackageParser.Package p : mPackages.values()) { 5383 if (p.mExtras != null) { 5384 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5385 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5386 if (ai != null) { 5387 list.add(ai); 5388 } 5389 } 5390 } 5391 } 5392 5393 return new ParceledListSlice<ApplicationInfo>(list); 5394 } 5395 } 5396 5397 public List<ApplicationInfo> getPersistentApplications(int flags) { 5398 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5399 5400 // reader 5401 synchronized (mPackages) { 5402 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5403 final int userId = UserHandle.getCallingUserId(); 5404 while (i.hasNext()) { 5405 final PackageParser.Package p = i.next(); 5406 if (p.applicationInfo != null 5407 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5408 && (!mSafeMode || isSystemApp(p))) { 5409 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5410 if (ps != null) { 5411 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5412 ps.readUserState(userId), userId); 5413 if (ai != null) { 5414 finalList.add(ai); 5415 } 5416 } 5417 } 5418 } 5419 } 5420 5421 return finalList; 5422 } 5423 5424 @Override 5425 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5426 if (!sUserManager.exists(userId)) return null; 5427 // reader 5428 synchronized (mPackages) { 5429 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5430 PackageSetting ps = provider != null 5431 ? mSettings.mPackages.get(provider.owner.packageName) 5432 : null; 5433 return ps != null 5434 && mSettings.isEnabledLPr(provider.info, flags, userId) 5435 && (!mSafeMode || (provider.info.applicationInfo.flags 5436 &ApplicationInfo.FLAG_SYSTEM) != 0) 5437 ? PackageParser.generateProviderInfo(provider, flags, 5438 ps.readUserState(userId), userId) 5439 : null; 5440 } 5441 } 5442 5443 /** 5444 * @deprecated 5445 */ 5446 @Deprecated 5447 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5448 // reader 5449 synchronized (mPackages) { 5450 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5451 .entrySet().iterator(); 5452 final int userId = UserHandle.getCallingUserId(); 5453 while (i.hasNext()) { 5454 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5455 PackageParser.Provider p = entry.getValue(); 5456 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5457 5458 if (ps != null && p.syncable 5459 && (!mSafeMode || (p.info.applicationInfo.flags 5460 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5461 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5462 ps.readUserState(userId), userId); 5463 if (info != null) { 5464 outNames.add(entry.getKey()); 5465 outInfo.add(info); 5466 } 5467 } 5468 } 5469 } 5470 } 5471 5472 @Override 5473 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5474 int uid, int flags) { 5475 ArrayList<ProviderInfo> finalList = null; 5476 // reader 5477 synchronized (mPackages) { 5478 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5479 final int userId = processName != null ? 5480 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5481 while (i.hasNext()) { 5482 final PackageParser.Provider p = i.next(); 5483 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5484 if (ps != null && p.info.authority != null 5485 && (processName == null 5486 || (p.info.processName.equals(processName) 5487 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5488 && mSettings.isEnabledLPr(p.info, flags, userId) 5489 && (!mSafeMode 5490 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5491 if (finalList == null) { 5492 finalList = new ArrayList<ProviderInfo>(3); 5493 } 5494 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5495 ps.readUserState(userId), userId); 5496 if (info != null) { 5497 finalList.add(info); 5498 } 5499 } 5500 } 5501 } 5502 5503 if (finalList != null) { 5504 Collections.sort(finalList, mProviderInitOrderSorter); 5505 return new ParceledListSlice<ProviderInfo>(finalList); 5506 } 5507 5508 return null; 5509 } 5510 5511 @Override 5512 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5513 int flags) { 5514 // reader 5515 synchronized (mPackages) { 5516 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5517 return PackageParser.generateInstrumentationInfo(i, flags); 5518 } 5519 } 5520 5521 @Override 5522 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5523 int flags) { 5524 ArrayList<InstrumentationInfo> finalList = 5525 new ArrayList<InstrumentationInfo>(); 5526 5527 // reader 5528 synchronized (mPackages) { 5529 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5530 while (i.hasNext()) { 5531 final PackageParser.Instrumentation p = i.next(); 5532 if (targetPackage == null 5533 || targetPackage.equals(p.info.targetPackage)) { 5534 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5535 flags); 5536 if (ii != null) { 5537 finalList.add(ii); 5538 } 5539 } 5540 } 5541 } 5542 5543 return finalList; 5544 } 5545 5546 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5547 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5548 if (overlays == null) { 5549 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5550 return; 5551 } 5552 for (PackageParser.Package opkg : overlays.values()) { 5553 // Not much to do if idmap fails: we already logged the error 5554 // and we certainly don't want to abort installation of pkg simply 5555 // because an overlay didn't fit properly. For these reasons, 5556 // ignore the return value of createIdmapForPackagePairLI. 5557 createIdmapForPackagePairLI(pkg, opkg); 5558 } 5559 } 5560 5561 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5562 PackageParser.Package opkg) { 5563 if (!opkg.mTrustedOverlay) { 5564 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5565 opkg.baseCodePath + ": overlay not trusted"); 5566 return false; 5567 } 5568 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5569 if (overlaySet == null) { 5570 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5571 opkg.baseCodePath + " but target package has no known overlays"); 5572 return false; 5573 } 5574 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5575 // TODO: generate idmap for split APKs 5576 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5577 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5578 + opkg.baseCodePath); 5579 return false; 5580 } 5581 PackageParser.Package[] overlayArray = 5582 overlaySet.values().toArray(new PackageParser.Package[0]); 5583 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5584 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5585 return p1.mOverlayPriority - p2.mOverlayPriority; 5586 } 5587 }; 5588 Arrays.sort(overlayArray, cmp); 5589 5590 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5591 int i = 0; 5592 for (PackageParser.Package p : overlayArray) { 5593 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5594 } 5595 return true; 5596 } 5597 5598 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5599 final File[] files = dir.listFiles(); 5600 if (ArrayUtils.isEmpty(files)) { 5601 Log.d(TAG, "No files in app dir " + dir); 5602 return; 5603 } 5604 5605 if (DEBUG_PACKAGE_SCANNING) { 5606 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5607 + " flags=0x" + Integer.toHexString(parseFlags)); 5608 } 5609 5610 for (File file : files) { 5611 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5612 && !PackageInstallerService.isStageName(file.getName()); 5613 if (!isPackage) { 5614 // Ignore entries which are not packages 5615 continue; 5616 } 5617 try { 5618 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5619 scanFlags, currentTime, null); 5620 } catch (PackageManagerException e) { 5621 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5622 5623 // Delete invalid userdata apps 5624 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5625 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5626 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5627 if (file.isDirectory()) { 5628 mInstaller.rmPackageDir(file.getAbsolutePath()); 5629 } else { 5630 file.delete(); 5631 } 5632 } 5633 } 5634 } 5635 } 5636 5637 private static File getSettingsProblemFile() { 5638 File dataDir = Environment.getDataDirectory(); 5639 File systemDir = new File(dataDir, "system"); 5640 File fname = new File(systemDir, "uiderrors.txt"); 5641 return fname; 5642 } 5643 5644 static void reportSettingsProblem(int priority, String msg) { 5645 logCriticalInfo(priority, msg); 5646 } 5647 5648 static void logCriticalInfo(int priority, String msg) { 5649 Slog.println(priority, TAG, msg); 5650 EventLogTags.writePmCriticalInfo(msg); 5651 try { 5652 File fname = getSettingsProblemFile(); 5653 FileOutputStream out = new FileOutputStream(fname, true); 5654 PrintWriter pw = new FastPrintWriter(out); 5655 SimpleDateFormat formatter = new SimpleDateFormat(); 5656 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5657 pw.println(dateString + ": " + msg); 5658 pw.close(); 5659 FileUtils.setPermissions( 5660 fname.toString(), 5661 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5662 -1, -1); 5663 } catch (java.io.IOException e) { 5664 } 5665 } 5666 5667 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5668 PackageParser.Package pkg, File srcFile, int parseFlags) 5669 throws PackageManagerException { 5670 if (ps != null 5671 && ps.codePath.equals(srcFile) 5672 && ps.timeStamp == srcFile.lastModified() 5673 && !isCompatSignatureUpdateNeeded(pkg) 5674 && !isRecoverSignatureUpdateNeeded(pkg)) { 5675 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5676 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5677 ArraySet<PublicKey> signingKs; 5678 synchronized (mPackages) { 5679 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5680 } 5681 if (ps.signatures.mSignatures != null 5682 && ps.signatures.mSignatures.length != 0 5683 && signingKs != null) { 5684 // Optimization: reuse the existing cached certificates 5685 // if the package appears to be unchanged. 5686 pkg.mSignatures = ps.signatures.mSignatures; 5687 pkg.mSigningKeys = signingKs; 5688 return; 5689 } 5690 5691 Slog.w(TAG, "PackageSetting for " + ps.name 5692 + " is missing signatures. Collecting certs again to recover them."); 5693 } else { 5694 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5695 } 5696 5697 try { 5698 pp.collectCertificates(pkg, parseFlags); 5699 pp.collectManifestDigest(pkg); 5700 } catch (PackageParserException e) { 5701 throw PackageManagerException.from(e); 5702 } 5703 } 5704 5705 /* 5706 * Scan a package and return the newly parsed package. 5707 * Returns null in case of errors and the error code is stored in mLastScanError 5708 */ 5709 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5710 long currentTime, UserHandle user) throws PackageManagerException { 5711 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5712 parseFlags |= mDefParseFlags; 5713 PackageParser pp = new PackageParser(); 5714 pp.setSeparateProcesses(mSeparateProcesses); 5715 pp.setOnlyCoreApps(mOnlyCore); 5716 pp.setDisplayMetrics(mMetrics); 5717 5718 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5719 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5720 } 5721 5722 final PackageParser.Package pkg; 5723 try { 5724 pkg = pp.parsePackage(scanFile, parseFlags); 5725 } catch (PackageParserException e) { 5726 throw PackageManagerException.from(e); 5727 } 5728 5729 PackageSetting ps = null; 5730 PackageSetting updatedPkg; 5731 // reader 5732 synchronized (mPackages) { 5733 // Look to see if we already know about this package. 5734 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5735 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5736 // This package has been renamed to its original name. Let's 5737 // use that. 5738 ps = mSettings.peekPackageLPr(oldName); 5739 } 5740 // If there was no original package, see one for the real package name. 5741 if (ps == null) { 5742 ps = mSettings.peekPackageLPr(pkg.packageName); 5743 } 5744 // Check to see if this package could be hiding/updating a system 5745 // package. Must look for it either under the original or real 5746 // package name depending on our state. 5747 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5748 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5749 } 5750 boolean updatedPkgBetter = false; 5751 // First check if this is a system package that may involve an update 5752 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5753 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5754 // it needs to drop FLAG_PRIVILEGED. 5755 if (locationIsPrivileged(scanFile)) { 5756 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5757 } else { 5758 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5759 } 5760 5761 if (ps != null && !ps.codePath.equals(scanFile)) { 5762 // The path has changed from what was last scanned... check the 5763 // version of the new path against what we have stored to determine 5764 // what to do. 5765 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5766 if (pkg.mVersionCode <= ps.versionCode) { 5767 // The system package has been updated and the code path does not match 5768 // Ignore entry. Skip it. 5769 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5770 + " ignored: updated version " + ps.versionCode 5771 + " better than this " + pkg.mVersionCode); 5772 if (!updatedPkg.codePath.equals(scanFile)) { 5773 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5774 + ps.name + " changing from " + updatedPkg.codePathString 5775 + " to " + scanFile); 5776 updatedPkg.codePath = scanFile; 5777 updatedPkg.codePathString = scanFile.toString(); 5778 updatedPkg.resourcePath = scanFile; 5779 updatedPkg.resourcePathString = scanFile.toString(); 5780 } 5781 updatedPkg.pkg = pkg; 5782 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5783 "Package " + ps.name + " at " + scanFile 5784 + " ignored: updated version " + ps.versionCode 5785 + " better than this " + pkg.mVersionCode); 5786 } else { 5787 // The current app on the system partition is better than 5788 // what we have updated to on the data partition; switch 5789 // back to the system partition version. 5790 // At this point, its safely assumed that package installation for 5791 // apps in system partition will go through. If not there won't be a working 5792 // version of the app 5793 // writer 5794 synchronized (mPackages) { 5795 // Just remove the loaded entries from package lists. 5796 mPackages.remove(ps.name); 5797 } 5798 5799 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5800 + " reverting from " + ps.codePathString 5801 + ": new version " + pkg.mVersionCode 5802 + " better than installed " + ps.versionCode); 5803 5804 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5805 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5806 synchronized (mInstallLock) { 5807 args.cleanUpResourcesLI(); 5808 } 5809 synchronized (mPackages) { 5810 mSettings.enableSystemPackageLPw(ps.name); 5811 } 5812 updatedPkgBetter = true; 5813 } 5814 } 5815 } 5816 5817 if (updatedPkg != null) { 5818 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5819 // initially 5820 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5821 5822 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5823 // flag set initially 5824 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5825 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5826 } 5827 } 5828 5829 // Verify certificates against what was last scanned 5830 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5831 5832 /* 5833 * A new system app appeared, but we already had a non-system one of the 5834 * same name installed earlier. 5835 */ 5836 boolean shouldHideSystemApp = false; 5837 if (updatedPkg == null && ps != null 5838 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5839 /* 5840 * Check to make sure the signatures match first. If they don't, 5841 * wipe the installed application and its data. 5842 */ 5843 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5844 != PackageManager.SIGNATURE_MATCH) { 5845 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5846 + " signatures don't match existing userdata copy; removing"); 5847 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5848 ps = null; 5849 } else { 5850 /* 5851 * If the newly-added system app is an older version than the 5852 * already installed version, hide it. It will be scanned later 5853 * and re-added like an update. 5854 */ 5855 if (pkg.mVersionCode <= ps.versionCode) { 5856 shouldHideSystemApp = true; 5857 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5858 + " but new version " + pkg.mVersionCode + " better than installed " 5859 + ps.versionCode + "; hiding system"); 5860 } else { 5861 /* 5862 * The newly found system app is a newer version that the 5863 * one previously installed. Simply remove the 5864 * already-installed application and replace it with our own 5865 * while keeping the application data. 5866 */ 5867 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5868 + " reverting from " + ps.codePathString + ": new version " 5869 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5870 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5871 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5872 synchronized (mInstallLock) { 5873 args.cleanUpResourcesLI(); 5874 } 5875 } 5876 } 5877 } 5878 5879 // The apk is forward locked (not public) if its code and resources 5880 // are kept in different files. (except for app in either system or 5881 // vendor path). 5882 // TODO grab this value from PackageSettings 5883 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5884 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5885 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5886 } 5887 } 5888 5889 // TODO: extend to support forward-locked splits 5890 String resourcePath = null; 5891 String baseResourcePath = null; 5892 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5893 if (ps != null && ps.resourcePathString != null) { 5894 resourcePath = ps.resourcePathString; 5895 baseResourcePath = ps.resourcePathString; 5896 } else { 5897 // Should not happen at all. Just log an error. 5898 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5899 } 5900 } else { 5901 resourcePath = pkg.codePath; 5902 baseResourcePath = pkg.baseCodePath; 5903 } 5904 5905 // Set application objects path explicitly. 5906 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5907 pkg.applicationInfo.setCodePath(pkg.codePath); 5908 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5909 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5910 pkg.applicationInfo.setResourcePath(resourcePath); 5911 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5912 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5913 5914 // Note that we invoke the following method only if we are about to unpack an application 5915 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5916 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5917 5918 /* 5919 * If the system app should be overridden by a previously installed 5920 * data, hide the system app now and let the /data/app scan pick it up 5921 * again. 5922 */ 5923 if (shouldHideSystemApp) { 5924 synchronized (mPackages) { 5925 /* 5926 * We have to grant systems permissions before we hide, because 5927 * grantPermissions will assume the package update is trying to 5928 * expand its permissions. 5929 */ 5930 grantPermissionsLPw(pkg, true, pkg.packageName); 5931 mSettings.disableSystemPackageLPw(pkg.packageName); 5932 } 5933 } 5934 5935 return scannedPkg; 5936 } 5937 5938 private static String fixProcessName(String defProcessName, 5939 String processName, int uid) { 5940 if (processName == null) { 5941 return defProcessName; 5942 } 5943 return processName; 5944 } 5945 5946 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5947 throws PackageManagerException { 5948 if (pkgSetting.signatures.mSignatures != null) { 5949 // Already existing package. Make sure signatures match 5950 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5951 == PackageManager.SIGNATURE_MATCH; 5952 if (!match) { 5953 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5954 == PackageManager.SIGNATURE_MATCH; 5955 } 5956 if (!match) { 5957 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5958 == PackageManager.SIGNATURE_MATCH; 5959 } 5960 if (!match) { 5961 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5962 + pkg.packageName + " signatures do not match the " 5963 + "previously installed version; ignoring!"); 5964 } 5965 } 5966 5967 // Check for shared user signatures 5968 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5969 // Already existing package. Make sure signatures match 5970 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5971 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5972 if (!match) { 5973 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5974 == PackageManager.SIGNATURE_MATCH; 5975 } 5976 if (!match) { 5977 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5978 == PackageManager.SIGNATURE_MATCH; 5979 } 5980 if (!match) { 5981 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5982 "Package " + pkg.packageName 5983 + " has no signatures that match those in shared user " 5984 + pkgSetting.sharedUser.name + "; ignoring!"); 5985 } 5986 } 5987 } 5988 5989 /** 5990 * Enforces that only the system UID or root's UID can call a method exposed 5991 * via Binder. 5992 * 5993 * @param message used as message if SecurityException is thrown 5994 * @throws SecurityException if the caller is not system or root 5995 */ 5996 private static final void enforceSystemOrRoot(String message) { 5997 final int uid = Binder.getCallingUid(); 5998 if (uid != Process.SYSTEM_UID && uid != 0) { 5999 throw new SecurityException(message); 6000 } 6001 } 6002 6003 @Override 6004 public void performBootDexOpt() { 6005 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6006 6007 // Before everything else, see whether we need to fstrim. 6008 try { 6009 IMountService ms = PackageHelper.getMountService(); 6010 if (ms != null) { 6011 final boolean isUpgrade = isUpgrade(); 6012 boolean doTrim = isUpgrade; 6013 if (doTrim) { 6014 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6015 } else { 6016 final long interval = android.provider.Settings.Global.getLong( 6017 mContext.getContentResolver(), 6018 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6019 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6020 if (interval > 0) { 6021 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6022 if (timeSinceLast > interval) { 6023 doTrim = true; 6024 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6025 + "; running immediately"); 6026 } 6027 } 6028 } 6029 if (doTrim) { 6030 if (!isFirstBoot()) { 6031 try { 6032 ActivityManagerNative.getDefault().showBootMessage( 6033 mContext.getResources().getString( 6034 R.string.android_upgrading_fstrim), true); 6035 } catch (RemoteException e) { 6036 } 6037 } 6038 ms.runMaintenance(); 6039 } 6040 } else { 6041 Slog.e(TAG, "Mount service unavailable!"); 6042 } 6043 } catch (RemoteException e) { 6044 // Can't happen; MountService is local 6045 } 6046 6047 final ArraySet<PackageParser.Package> pkgs; 6048 synchronized (mPackages) { 6049 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6050 } 6051 6052 if (pkgs != null) { 6053 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6054 // in case the device runs out of space. 6055 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6056 // Give priority to core apps. 6057 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6058 PackageParser.Package pkg = it.next(); 6059 if (pkg.coreApp) { 6060 if (DEBUG_DEXOPT) { 6061 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6062 } 6063 sortedPkgs.add(pkg); 6064 it.remove(); 6065 } 6066 } 6067 // Give priority to system apps that listen for pre boot complete. 6068 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6069 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6070 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6071 PackageParser.Package pkg = it.next(); 6072 if (pkgNames.contains(pkg.packageName)) { 6073 if (DEBUG_DEXOPT) { 6074 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6075 } 6076 sortedPkgs.add(pkg); 6077 it.remove(); 6078 } 6079 } 6080 // Give priority to system apps. 6081 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6082 PackageParser.Package pkg = it.next(); 6083 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6084 if (DEBUG_DEXOPT) { 6085 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6086 } 6087 sortedPkgs.add(pkg); 6088 it.remove(); 6089 } 6090 } 6091 // Give priority to updated system apps. 6092 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6093 PackageParser.Package pkg = it.next(); 6094 if (pkg.isUpdatedSystemApp()) { 6095 if (DEBUG_DEXOPT) { 6096 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6097 } 6098 sortedPkgs.add(pkg); 6099 it.remove(); 6100 } 6101 } 6102 // Give priority to apps that listen for boot complete. 6103 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6104 pkgNames = getPackageNamesForIntent(intent); 6105 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6106 PackageParser.Package pkg = it.next(); 6107 if (pkgNames.contains(pkg.packageName)) { 6108 if (DEBUG_DEXOPT) { 6109 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6110 } 6111 sortedPkgs.add(pkg); 6112 it.remove(); 6113 } 6114 } 6115 // Filter out packages that aren't recently used. 6116 filterRecentlyUsedApps(pkgs); 6117 // Add all remaining apps. 6118 for (PackageParser.Package pkg : pkgs) { 6119 if (DEBUG_DEXOPT) { 6120 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6121 } 6122 sortedPkgs.add(pkg); 6123 } 6124 6125 // If we want to be lazy, filter everything that wasn't recently used. 6126 if (mLazyDexOpt) { 6127 filterRecentlyUsedApps(sortedPkgs); 6128 } 6129 6130 int i = 0; 6131 int total = sortedPkgs.size(); 6132 File dataDir = Environment.getDataDirectory(); 6133 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6134 if (lowThreshold == 0) { 6135 throw new IllegalStateException("Invalid low memory threshold"); 6136 } 6137 for (PackageParser.Package pkg : sortedPkgs) { 6138 long usableSpace = dataDir.getUsableSpace(); 6139 if (usableSpace < lowThreshold) { 6140 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6141 break; 6142 } 6143 performBootDexOpt(pkg, ++i, total); 6144 } 6145 } 6146 } 6147 6148 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6149 // Filter out packages that aren't recently used. 6150 // 6151 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6152 // should do a full dexopt. 6153 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6154 int total = pkgs.size(); 6155 int skipped = 0; 6156 long now = System.currentTimeMillis(); 6157 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6158 PackageParser.Package pkg = i.next(); 6159 long then = pkg.mLastPackageUsageTimeInMills; 6160 if (then + mDexOptLRUThresholdInMills < now) { 6161 if (DEBUG_DEXOPT) { 6162 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6163 ((then == 0) ? "never" : new Date(then))); 6164 } 6165 i.remove(); 6166 skipped++; 6167 } 6168 } 6169 if (DEBUG_DEXOPT) { 6170 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6171 } 6172 } 6173 } 6174 6175 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6176 List<ResolveInfo> ris = null; 6177 try { 6178 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6179 intent, null, 0, UserHandle.USER_OWNER); 6180 } catch (RemoteException e) { 6181 } 6182 ArraySet<String> pkgNames = new ArraySet<String>(); 6183 if (ris != null) { 6184 for (ResolveInfo ri : ris) { 6185 pkgNames.add(ri.activityInfo.packageName); 6186 } 6187 } 6188 return pkgNames; 6189 } 6190 6191 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6192 if (DEBUG_DEXOPT) { 6193 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6194 } 6195 if (!isFirstBoot()) { 6196 try { 6197 ActivityManagerNative.getDefault().showBootMessage( 6198 mContext.getResources().getString(R.string.android_upgrading_apk, 6199 curr, total), true); 6200 } catch (RemoteException e) { 6201 } 6202 } 6203 PackageParser.Package p = pkg; 6204 synchronized (mInstallLock) { 6205 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6206 false /* force dex */, false /* defer */, true /* include dependencies */); 6207 } 6208 } 6209 6210 @Override 6211 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6212 return performDexOpt(packageName, instructionSet, false); 6213 } 6214 6215 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6216 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6217 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6218 if (!dexopt && !updateUsage) { 6219 // We aren't going to dexopt or update usage, so bail early. 6220 return false; 6221 } 6222 PackageParser.Package p; 6223 final String targetInstructionSet; 6224 synchronized (mPackages) { 6225 p = mPackages.get(packageName); 6226 if (p == null) { 6227 return false; 6228 } 6229 if (updateUsage) { 6230 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6231 } 6232 mPackageUsage.write(false); 6233 if (!dexopt) { 6234 // We aren't going to dexopt, so bail early. 6235 return false; 6236 } 6237 6238 targetInstructionSet = instructionSet != null ? instructionSet : 6239 getPrimaryInstructionSet(p.applicationInfo); 6240 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6241 return false; 6242 } 6243 } 6244 long callingId = Binder.clearCallingIdentity(); 6245 try { 6246 synchronized (mInstallLock) { 6247 final String[] instructionSets = new String[] { targetInstructionSet }; 6248 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6249 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6250 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6251 } 6252 } finally { 6253 Binder.restoreCallingIdentity(callingId); 6254 } 6255 } 6256 6257 public ArraySet<String> getPackagesThatNeedDexOpt() { 6258 ArraySet<String> pkgs = null; 6259 synchronized (mPackages) { 6260 for (PackageParser.Package p : mPackages.values()) { 6261 if (DEBUG_DEXOPT) { 6262 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6263 } 6264 if (!p.mDexOptPerformed.isEmpty()) { 6265 continue; 6266 } 6267 if (pkgs == null) { 6268 pkgs = new ArraySet<String>(); 6269 } 6270 pkgs.add(p.packageName); 6271 } 6272 } 6273 return pkgs; 6274 } 6275 6276 public void shutdown() { 6277 mPackageUsage.write(true); 6278 } 6279 6280 @Override 6281 public void forceDexOpt(String packageName) { 6282 enforceSystemOrRoot("forceDexOpt"); 6283 6284 PackageParser.Package pkg; 6285 synchronized (mPackages) { 6286 pkg = mPackages.get(packageName); 6287 if (pkg == null) { 6288 throw new IllegalArgumentException("Missing package: " + packageName); 6289 } 6290 } 6291 6292 synchronized (mInstallLock) { 6293 final String[] instructionSets = new String[] { 6294 getPrimaryInstructionSet(pkg.applicationInfo) }; 6295 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6296 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6297 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6298 throw new IllegalStateException("Failed to dexopt: " + res); 6299 } 6300 } 6301 } 6302 6303 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6304 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6305 Slog.w(TAG, "Unable to update from " + oldPkg.name 6306 + " to " + newPkg.packageName 6307 + ": old package not in system partition"); 6308 return false; 6309 } else if (mPackages.get(oldPkg.name) != null) { 6310 Slog.w(TAG, "Unable to update from " + oldPkg.name 6311 + " to " + newPkg.packageName 6312 + ": old package still exists"); 6313 return false; 6314 } 6315 return true; 6316 } 6317 6318 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6319 int[] users = sUserManager.getUserIds(); 6320 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6321 if (res < 0) { 6322 return res; 6323 } 6324 for (int user : users) { 6325 if (user != 0) { 6326 res = mInstaller.createUserData(volumeUuid, packageName, 6327 UserHandle.getUid(user, uid), user, seinfo); 6328 if (res < 0) { 6329 return res; 6330 } 6331 } 6332 } 6333 return res; 6334 } 6335 6336 private int removeDataDirsLI(String volumeUuid, String packageName) { 6337 int[] users = sUserManager.getUserIds(); 6338 int res = 0; 6339 for (int user : users) { 6340 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6341 if (resInner < 0) { 6342 res = resInner; 6343 } 6344 } 6345 6346 return res; 6347 } 6348 6349 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6350 int[] users = sUserManager.getUserIds(); 6351 int res = 0; 6352 for (int user : users) { 6353 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6354 if (resInner < 0) { 6355 res = resInner; 6356 } 6357 } 6358 return res; 6359 } 6360 6361 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6362 PackageParser.Package changingLib) { 6363 if (file.path != null) { 6364 usesLibraryFiles.add(file.path); 6365 return; 6366 } 6367 PackageParser.Package p = mPackages.get(file.apk); 6368 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6369 // If we are doing this while in the middle of updating a library apk, 6370 // then we need to make sure to use that new apk for determining the 6371 // dependencies here. (We haven't yet finished committing the new apk 6372 // to the package manager state.) 6373 if (p == null || p.packageName.equals(changingLib.packageName)) { 6374 p = changingLib; 6375 } 6376 } 6377 if (p != null) { 6378 usesLibraryFiles.addAll(p.getAllCodePaths()); 6379 } 6380 } 6381 6382 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6383 PackageParser.Package changingLib) throws PackageManagerException { 6384 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6385 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6386 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6387 for (int i=0; i<N; i++) { 6388 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6389 if (file == null) { 6390 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6391 "Package " + pkg.packageName + " requires unavailable shared library " 6392 + pkg.usesLibraries.get(i) + "; failing!"); 6393 } 6394 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6395 } 6396 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6397 for (int i=0; i<N; i++) { 6398 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6399 if (file == null) { 6400 Slog.w(TAG, "Package " + pkg.packageName 6401 + " desires unavailable shared library " 6402 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6403 } else { 6404 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6405 } 6406 } 6407 N = usesLibraryFiles.size(); 6408 if (N > 0) { 6409 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6410 } else { 6411 pkg.usesLibraryFiles = null; 6412 } 6413 } 6414 } 6415 6416 private static boolean hasString(List<String> list, List<String> which) { 6417 if (list == null) { 6418 return false; 6419 } 6420 for (int i=list.size()-1; i>=0; i--) { 6421 for (int j=which.size()-1; j>=0; j--) { 6422 if (which.get(j).equals(list.get(i))) { 6423 return true; 6424 } 6425 } 6426 } 6427 return false; 6428 } 6429 6430 private void updateAllSharedLibrariesLPw() { 6431 for (PackageParser.Package pkg : mPackages.values()) { 6432 try { 6433 updateSharedLibrariesLPw(pkg, null); 6434 } catch (PackageManagerException e) { 6435 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6436 } 6437 } 6438 } 6439 6440 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6441 PackageParser.Package changingPkg) { 6442 ArrayList<PackageParser.Package> res = null; 6443 for (PackageParser.Package pkg : mPackages.values()) { 6444 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6445 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6446 if (res == null) { 6447 res = new ArrayList<PackageParser.Package>(); 6448 } 6449 res.add(pkg); 6450 try { 6451 updateSharedLibrariesLPw(pkg, changingPkg); 6452 } catch (PackageManagerException e) { 6453 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6454 } 6455 } 6456 } 6457 return res; 6458 } 6459 6460 /** 6461 * Derive the value of the {@code cpuAbiOverride} based on the provided 6462 * value and an optional stored value from the package settings. 6463 */ 6464 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6465 String cpuAbiOverride = null; 6466 6467 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6468 cpuAbiOverride = null; 6469 } else if (abiOverride != null) { 6470 cpuAbiOverride = abiOverride; 6471 } else if (settings != null) { 6472 cpuAbiOverride = settings.cpuAbiOverrideString; 6473 } 6474 6475 return cpuAbiOverride; 6476 } 6477 6478 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6479 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6480 boolean success = false; 6481 try { 6482 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6483 currentTime, user); 6484 success = true; 6485 return res; 6486 } finally { 6487 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6488 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6489 } 6490 } 6491 } 6492 6493 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6494 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6495 final File scanFile = new File(pkg.codePath); 6496 if (pkg.applicationInfo.getCodePath() == null || 6497 pkg.applicationInfo.getResourcePath() == null) { 6498 // Bail out. The resource and code paths haven't been set. 6499 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6500 "Code and resource paths haven't been set correctly"); 6501 } 6502 6503 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6504 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6505 } else { 6506 // Only allow system apps to be flagged as core apps. 6507 pkg.coreApp = false; 6508 } 6509 6510 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6511 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6512 } 6513 6514 if (mCustomResolverComponentName != null && 6515 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6516 setUpCustomResolverActivity(pkg); 6517 } 6518 6519 if (pkg.packageName.equals("android")) { 6520 synchronized (mPackages) { 6521 if (mAndroidApplication != null) { 6522 Slog.w(TAG, "*************************************************"); 6523 Slog.w(TAG, "Core android package being redefined. Skipping."); 6524 Slog.w(TAG, " file=" + scanFile); 6525 Slog.w(TAG, "*************************************************"); 6526 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6527 "Core android package being redefined. Skipping."); 6528 } 6529 6530 // Set up information for our fall-back user intent resolution activity. 6531 mPlatformPackage = pkg; 6532 pkg.mVersionCode = mSdkVersion; 6533 mAndroidApplication = pkg.applicationInfo; 6534 6535 if (!mResolverReplaced) { 6536 mResolveActivity.applicationInfo = mAndroidApplication; 6537 mResolveActivity.name = ResolverActivity.class.getName(); 6538 mResolveActivity.packageName = mAndroidApplication.packageName; 6539 mResolveActivity.processName = "system:ui"; 6540 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6541 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6542 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6543 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6544 mResolveActivity.exported = true; 6545 mResolveActivity.enabled = true; 6546 mResolveInfo.activityInfo = mResolveActivity; 6547 mResolveInfo.priority = 0; 6548 mResolveInfo.preferredOrder = 0; 6549 mResolveInfo.match = 0; 6550 mResolveComponentName = new ComponentName( 6551 mAndroidApplication.packageName, mResolveActivity.name); 6552 } 6553 } 6554 } 6555 6556 if (DEBUG_PACKAGE_SCANNING) { 6557 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6558 Log.d(TAG, "Scanning package " + pkg.packageName); 6559 } 6560 6561 if (mPackages.containsKey(pkg.packageName) 6562 || mSharedLibraries.containsKey(pkg.packageName)) { 6563 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6564 "Application package " + pkg.packageName 6565 + " already installed. Skipping duplicate."); 6566 } 6567 6568 // If we're only installing presumed-existing packages, require that the 6569 // scanned APK is both already known and at the path previously established 6570 // for it. Previously unknown packages we pick up normally, but if we have an 6571 // a priori expectation about this package's install presence, enforce it. 6572 // With a singular exception for new system packages. When an OTA contains 6573 // a new system package, we allow the codepath to change from a system location 6574 // to the user-installed location. If we don't allow this change, any newer, 6575 // user-installed version of the application will be ignored. 6576 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6577 if (mExpectingBetter.containsKey(pkg.packageName)) { 6578 logCriticalInfo(Log.WARN, 6579 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6580 } else { 6581 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6582 if (known != null) { 6583 if (DEBUG_PACKAGE_SCANNING) { 6584 Log.d(TAG, "Examining " + pkg.codePath 6585 + " and requiring known paths " + known.codePathString 6586 + " & " + known.resourcePathString); 6587 } 6588 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6589 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6590 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6591 "Application package " + pkg.packageName 6592 + " found at " + pkg.applicationInfo.getCodePath() 6593 + " but expected at " + known.codePathString + "; ignoring."); 6594 } 6595 } 6596 } 6597 } 6598 6599 // Initialize package source and resource directories 6600 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6601 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6602 6603 SharedUserSetting suid = null; 6604 PackageSetting pkgSetting = null; 6605 6606 if (!isSystemApp(pkg)) { 6607 // Only system apps can use these features. 6608 pkg.mOriginalPackages = null; 6609 pkg.mRealPackage = null; 6610 pkg.mAdoptPermissions = null; 6611 } 6612 6613 // writer 6614 synchronized (mPackages) { 6615 if (pkg.mSharedUserId != null) { 6616 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6617 if (suid == null) { 6618 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6619 "Creating application package " + pkg.packageName 6620 + " for shared user failed"); 6621 } 6622 if (DEBUG_PACKAGE_SCANNING) { 6623 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6624 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6625 + "): packages=" + suid.packages); 6626 } 6627 } 6628 6629 // Check if we are renaming from an original package name. 6630 PackageSetting origPackage = null; 6631 String realName = null; 6632 if (pkg.mOriginalPackages != null) { 6633 // This package may need to be renamed to a previously 6634 // installed name. Let's check on that... 6635 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6636 if (pkg.mOriginalPackages.contains(renamed)) { 6637 // This package had originally been installed as the 6638 // original name, and we have already taken care of 6639 // transitioning to the new one. Just update the new 6640 // one to continue using the old name. 6641 realName = pkg.mRealPackage; 6642 if (!pkg.packageName.equals(renamed)) { 6643 // Callers into this function may have already taken 6644 // care of renaming the package; only do it here if 6645 // it is not already done. 6646 pkg.setPackageName(renamed); 6647 } 6648 6649 } else { 6650 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6651 if ((origPackage = mSettings.peekPackageLPr( 6652 pkg.mOriginalPackages.get(i))) != null) { 6653 // We do have the package already installed under its 6654 // original name... should we use it? 6655 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6656 // New package is not compatible with original. 6657 origPackage = null; 6658 continue; 6659 } else if (origPackage.sharedUser != null) { 6660 // Make sure uid is compatible between packages. 6661 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6662 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6663 + " to " + pkg.packageName + ": old uid " 6664 + origPackage.sharedUser.name 6665 + " differs from " + pkg.mSharedUserId); 6666 origPackage = null; 6667 continue; 6668 } 6669 } else { 6670 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6671 + pkg.packageName + " to old name " + origPackage.name); 6672 } 6673 break; 6674 } 6675 } 6676 } 6677 } 6678 6679 if (mTransferedPackages.contains(pkg.packageName)) { 6680 Slog.w(TAG, "Package " + pkg.packageName 6681 + " was transferred to another, but its .apk remains"); 6682 } 6683 6684 // Just create the setting, don't add it yet. For already existing packages 6685 // the PkgSetting exists already and doesn't have to be created. 6686 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6687 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6688 pkg.applicationInfo.primaryCpuAbi, 6689 pkg.applicationInfo.secondaryCpuAbi, 6690 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6691 user, false); 6692 if (pkgSetting == null) { 6693 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6694 "Creating application package " + pkg.packageName + " failed"); 6695 } 6696 6697 if (pkgSetting.origPackage != null) { 6698 // If we are first transitioning from an original package, 6699 // fix up the new package's name now. We need to do this after 6700 // looking up the package under its new name, so getPackageLP 6701 // can take care of fiddling things correctly. 6702 pkg.setPackageName(origPackage.name); 6703 6704 // File a report about this. 6705 String msg = "New package " + pkgSetting.realName 6706 + " renamed to replace old package " + pkgSetting.name; 6707 reportSettingsProblem(Log.WARN, msg); 6708 6709 // Make a note of it. 6710 mTransferedPackages.add(origPackage.name); 6711 6712 // No longer need to retain this. 6713 pkgSetting.origPackage = null; 6714 } 6715 6716 if (realName != null) { 6717 // Make a note of it. 6718 mTransferedPackages.add(pkg.packageName); 6719 } 6720 6721 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6722 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6723 } 6724 6725 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6726 // Check all shared libraries and map to their actual file path. 6727 // We only do this here for apps not on a system dir, because those 6728 // are the only ones that can fail an install due to this. We 6729 // will take care of the system apps by updating all of their 6730 // library paths after the scan is done. 6731 updateSharedLibrariesLPw(pkg, null); 6732 } 6733 6734 if (mFoundPolicyFile) { 6735 SELinuxMMAC.assignSeinfoValue(pkg); 6736 } 6737 6738 pkg.applicationInfo.uid = pkgSetting.appId; 6739 pkg.mExtras = pkgSetting; 6740 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6741 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6742 // We just determined the app is signed correctly, so bring 6743 // over the latest parsed certs. 6744 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6745 } else { 6746 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6747 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6748 "Package " + pkg.packageName + " upgrade keys do not match the " 6749 + "previously installed version"); 6750 } else { 6751 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6752 String msg = "System package " + pkg.packageName 6753 + " signature changed; retaining data."; 6754 reportSettingsProblem(Log.WARN, msg); 6755 } 6756 } 6757 } else { 6758 try { 6759 verifySignaturesLP(pkgSetting, pkg); 6760 // We just determined the app is signed correctly, so bring 6761 // over the latest parsed certs. 6762 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6763 } catch (PackageManagerException e) { 6764 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6765 throw e; 6766 } 6767 // The signature has changed, but this package is in the system 6768 // image... let's recover! 6769 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6770 // However... if this package is part of a shared user, but it 6771 // doesn't match the signature of the shared user, let's fail. 6772 // What this means is that you can't change the signatures 6773 // associated with an overall shared user, which doesn't seem all 6774 // that unreasonable. 6775 if (pkgSetting.sharedUser != null) { 6776 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6777 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6778 throw new PackageManagerException( 6779 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6780 "Signature mismatch for shared user : " 6781 + pkgSetting.sharedUser); 6782 } 6783 } 6784 // File a report about this. 6785 String msg = "System package " + pkg.packageName 6786 + " signature changed; retaining data."; 6787 reportSettingsProblem(Log.WARN, msg); 6788 } 6789 } 6790 // Verify that this new package doesn't have any content providers 6791 // that conflict with existing packages. Only do this if the 6792 // package isn't already installed, since we don't want to break 6793 // things that are installed. 6794 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6795 final int N = pkg.providers.size(); 6796 int i; 6797 for (i=0; i<N; i++) { 6798 PackageParser.Provider p = pkg.providers.get(i); 6799 if (p.info.authority != null) { 6800 String names[] = p.info.authority.split(";"); 6801 for (int j = 0; j < names.length; j++) { 6802 if (mProvidersByAuthority.containsKey(names[j])) { 6803 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6804 final String otherPackageName = 6805 ((other != null && other.getComponentName() != null) ? 6806 other.getComponentName().getPackageName() : "?"); 6807 throw new PackageManagerException( 6808 INSTALL_FAILED_CONFLICTING_PROVIDER, 6809 "Can't install because provider name " + names[j] 6810 + " (in package " + pkg.applicationInfo.packageName 6811 + ") is already used by " + otherPackageName); 6812 } 6813 } 6814 } 6815 } 6816 } 6817 6818 if (pkg.mAdoptPermissions != null) { 6819 // This package wants to adopt ownership of permissions from 6820 // another package. 6821 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6822 final String origName = pkg.mAdoptPermissions.get(i); 6823 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6824 if (orig != null) { 6825 if (verifyPackageUpdateLPr(orig, pkg)) { 6826 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6827 + pkg.packageName); 6828 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6829 } 6830 } 6831 } 6832 } 6833 } 6834 6835 final String pkgName = pkg.packageName; 6836 6837 final long scanFileTime = scanFile.lastModified(); 6838 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6839 pkg.applicationInfo.processName = fixProcessName( 6840 pkg.applicationInfo.packageName, 6841 pkg.applicationInfo.processName, 6842 pkg.applicationInfo.uid); 6843 6844 File dataPath; 6845 if (mPlatformPackage == pkg) { 6846 // The system package is special. 6847 dataPath = new File(Environment.getDataDirectory(), "system"); 6848 6849 pkg.applicationInfo.dataDir = dataPath.getPath(); 6850 6851 } else { 6852 // This is a normal package, need to make its data directory. 6853 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6854 UserHandle.USER_OWNER, pkg.packageName); 6855 6856 boolean uidError = false; 6857 if (dataPath.exists()) { 6858 int currentUid = 0; 6859 try { 6860 StructStat stat = Os.stat(dataPath.getPath()); 6861 currentUid = stat.st_uid; 6862 } catch (ErrnoException e) { 6863 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6864 } 6865 6866 // If we have mismatched owners for the data path, we have a problem. 6867 if (currentUid != pkg.applicationInfo.uid) { 6868 boolean recovered = false; 6869 if (currentUid == 0) { 6870 // The directory somehow became owned by root. Wow. 6871 // This is probably because the system was stopped while 6872 // installd was in the middle of messing with its libs 6873 // directory. Ask installd to fix that. 6874 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6875 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6876 if (ret >= 0) { 6877 recovered = true; 6878 String msg = "Package " + pkg.packageName 6879 + " unexpectedly changed to uid 0; recovered to " + 6880 + pkg.applicationInfo.uid; 6881 reportSettingsProblem(Log.WARN, msg); 6882 } 6883 } 6884 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6885 || (scanFlags&SCAN_BOOTING) != 0)) { 6886 // If this is a system app, we can at least delete its 6887 // current data so the application will still work. 6888 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6889 if (ret >= 0) { 6890 // TODO: Kill the processes first 6891 // Old data gone! 6892 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6893 ? "System package " : "Third party package "; 6894 String msg = prefix + pkg.packageName 6895 + " has changed from uid: " 6896 + currentUid + " to " 6897 + pkg.applicationInfo.uid + "; old data erased"; 6898 reportSettingsProblem(Log.WARN, msg); 6899 recovered = true; 6900 6901 // And now re-install the app. 6902 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6903 pkg.applicationInfo.seinfo); 6904 if (ret == -1) { 6905 // Ack should not happen! 6906 msg = prefix + pkg.packageName 6907 + " could not have data directory re-created after delete."; 6908 reportSettingsProblem(Log.WARN, msg); 6909 throw new PackageManagerException( 6910 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6911 } 6912 } 6913 if (!recovered) { 6914 mHasSystemUidErrors = true; 6915 } 6916 } else if (!recovered) { 6917 // If we allow this install to proceed, we will be broken. 6918 // Abort, abort! 6919 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6920 "scanPackageLI"); 6921 } 6922 if (!recovered) { 6923 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6924 + pkg.applicationInfo.uid + "/fs_" 6925 + currentUid; 6926 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6927 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6928 String msg = "Package " + pkg.packageName 6929 + " has mismatched uid: " 6930 + currentUid + " on disk, " 6931 + pkg.applicationInfo.uid + " in settings"; 6932 // writer 6933 synchronized (mPackages) { 6934 mSettings.mReadMessages.append(msg); 6935 mSettings.mReadMessages.append('\n'); 6936 uidError = true; 6937 if (!pkgSetting.uidError) { 6938 reportSettingsProblem(Log.ERROR, msg); 6939 } 6940 } 6941 } 6942 } 6943 pkg.applicationInfo.dataDir = dataPath.getPath(); 6944 if (mShouldRestoreconData) { 6945 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6946 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6947 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6948 } 6949 } else { 6950 if (DEBUG_PACKAGE_SCANNING) { 6951 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6952 Log.v(TAG, "Want this data dir: " + dataPath); 6953 } 6954 //invoke installer to do the actual installation 6955 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6956 pkg.applicationInfo.seinfo); 6957 if (ret < 0) { 6958 // Error from installer 6959 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6960 "Unable to create data dirs [errorCode=" + ret + "]"); 6961 } 6962 6963 if (dataPath.exists()) { 6964 pkg.applicationInfo.dataDir = dataPath.getPath(); 6965 } else { 6966 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6967 pkg.applicationInfo.dataDir = null; 6968 } 6969 } 6970 6971 pkgSetting.uidError = uidError; 6972 } 6973 6974 final String path = scanFile.getPath(); 6975 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6976 6977 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6978 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6979 6980 // Some system apps still use directory structure for native libraries 6981 // in which case we might end up not detecting abi solely based on apk 6982 // structure. Try to detect abi based on directory structure. 6983 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6984 pkg.applicationInfo.primaryCpuAbi == null) { 6985 setBundledAppAbisAndRoots(pkg, pkgSetting); 6986 setNativeLibraryPaths(pkg); 6987 } 6988 6989 } else { 6990 if ((scanFlags & SCAN_MOVE) != 0) { 6991 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6992 // but we already have this packages package info in the PackageSetting. We just 6993 // use that and derive the native library path based on the new codepath. 6994 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6995 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6996 } 6997 6998 // Set native library paths again. For moves, the path will be updated based on the 6999 // ABIs we've determined above. For non-moves, the path will be updated based on the 7000 // ABIs we determined during compilation, but the path will depend on the final 7001 // package path (after the rename away from the stage path). 7002 setNativeLibraryPaths(pkg); 7003 } 7004 7005 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7006 final int[] userIds = sUserManager.getUserIds(); 7007 synchronized (mInstallLock) { 7008 // Make sure all user data directories are ready to roll; we're okay 7009 // if they already exist 7010 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7011 for (int userId : userIds) { 7012 if (userId != 0) { 7013 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7014 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7015 pkg.applicationInfo.seinfo); 7016 } 7017 } 7018 } 7019 7020 // Create a native library symlink only if we have native libraries 7021 // and if the native libraries are 32 bit libraries. We do not provide 7022 // this symlink for 64 bit libraries. 7023 if (pkg.applicationInfo.primaryCpuAbi != null && 7024 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7025 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7026 for (int userId : userIds) { 7027 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7028 nativeLibPath, userId) < 0) { 7029 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7030 "Failed linking native library dir (user=" + userId + ")"); 7031 } 7032 } 7033 } 7034 } 7035 7036 // This is a special case for the "system" package, where the ABI is 7037 // dictated by the zygote configuration (and init.rc). We should keep track 7038 // of this ABI so that we can deal with "normal" applications that run under 7039 // the same UID correctly. 7040 if (mPlatformPackage == pkg) { 7041 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7042 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7043 } 7044 7045 // If there's a mismatch between the abi-override in the package setting 7046 // and the abiOverride specified for the install. Warn about this because we 7047 // would've already compiled the app without taking the package setting into 7048 // account. 7049 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7050 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7051 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7052 " for package: " + pkg.packageName); 7053 } 7054 } 7055 7056 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7057 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7058 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7059 7060 // Copy the derived override back to the parsed package, so that we can 7061 // update the package settings accordingly. 7062 pkg.cpuAbiOverride = cpuAbiOverride; 7063 7064 if (DEBUG_ABI_SELECTION) { 7065 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7066 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7067 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7068 } 7069 7070 // Push the derived path down into PackageSettings so we know what to 7071 // clean up at uninstall time. 7072 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7073 7074 if (DEBUG_ABI_SELECTION) { 7075 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7076 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7077 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7078 } 7079 7080 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7081 // We don't do this here during boot because we can do it all 7082 // at once after scanning all existing packages. 7083 // 7084 // We also do this *before* we perform dexopt on this package, so that 7085 // we can avoid redundant dexopts, and also to make sure we've got the 7086 // code and package path correct. 7087 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7088 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7089 } 7090 7091 if ((scanFlags & SCAN_NO_DEX) == 0) { 7092 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7093 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7094 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7095 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7096 } 7097 } 7098 if (mFactoryTest && pkg.requestedPermissions.contains( 7099 android.Manifest.permission.FACTORY_TEST)) { 7100 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7101 } 7102 7103 ArrayList<PackageParser.Package> clientLibPkgs = null; 7104 7105 // writer 7106 synchronized (mPackages) { 7107 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7108 // Only system apps can add new shared libraries. 7109 if (pkg.libraryNames != null) { 7110 for (int i=0; i<pkg.libraryNames.size(); i++) { 7111 String name = pkg.libraryNames.get(i); 7112 boolean allowed = false; 7113 if (pkg.isUpdatedSystemApp()) { 7114 // New library entries can only be added through the 7115 // system image. This is important to get rid of a lot 7116 // of nasty edge cases: for example if we allowed a non- 7117 // system update of the app to add a library, then uninstalling 7118 // the update would make the library go away, and assumptions 7119 // we made such as through app install filtering would now 7120 // have allowed apps on the device which aren't compatible 7121 // with it. Better to just have the restriction here, be 7122 // conservative, and create many fewer cases that can negatively 7123 // impact the user experience. 7124 final PackageSetting sysPs = mSettings 7125 .getDisabledSystemPkgLPr(pkg.packageName); 7126 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7127 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7128 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7129 allowed = true; 7130 allowed = true; 7131 break; 7132 } 7133 } 7134 } 7135 } else { 7136 allowed = true; 7137 } 7138 if (allowed) { 7139 if (!mSharedLibraries.containsKey(name)) { 7140 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7141 } else if (!name.equals(pkg.packageName)) { 7142 Slog.w(TAG, "Package " + pkg.packageName + " library " 7143 + name + " already exists; skipping"); 7144 } 7145 } else { 7146 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7147 + name + " that is not declared on system image; skipping"); 7148 } 7149 } 7150 if ((scanFlags&SCAN_BOOTING) == 0) { 7151 // If we are not booting, we need to update any applications 7152 // that are clients of our shared library. If we are booting, 7153 // this will all be done once the scan is complete. 7154 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7155 } 7156 } 7157 } 7158 } 7159 7160 // We also need to dexopt any apps that are dependent on this library. Note that 7161 // if these fail, we should abort the install since installing the library will 7162 // result in some apps being broken. 7163 if (clientLibPkgs != null) { 7164 if ((scanFlags & SCAN_NO_DEX) == 0) { 7165 for (int i = 0; i < clientLibPkgs.size(); i++) { 7166 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7167 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7168 null /* instruction sets */, forceDex, 7169 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7170 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7171 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7172 "scanPackageLI failed to dexopt clientLibPkgs"); 7173 } 7174 } 7175 } 7176 } 7177 7178 // Request the ActivityManager to kill the process(only for existing packages) 7179 // so that we do not end up in a confused state while the user is still using the older 7180 // version of the application while the new one gets installed. 7181 if ((scanFlags & SCAN_REPLACING) != 0) { 7182 killApplication(pkg.applicationInfo.packageName, 7183 pkg.applicationInfo.uid, "replace pkg"); 7184 } 7185 7186 // Also need to kill any apps that are dependent on the library. 7187 if (clientLibPkgs != null) { 7188 for (int i=0; i<clientLibPkgs.size(); i++) { 7189 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7190 killApplication(clientPkg.applicationInfo.packageName, 7191 clientPkg.applicationInfo.uid, "update lib"); 7192 } 7193 } 7194 7195 // Make sure we're not adding any bogus keyset info 7196 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7197 ksms.assertScannedPackageValid(pkg); 7198 7199 // writer 7200 synchronized (mPackages) { 7201 // We don't expect installation to fail beyond this point 7202 7203 // Add the new setting to mSettings 7204 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7205 // Add the new setting to mPackages 7206 mPackages.put(pkg.applicationInfo.packageName, pkg); 7207 // Make sure we don't accidentally delete its data. 7208 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7209 while (iter.hasNext()) { 7210 PackageCleanItem item = iter.next(); 7211 if (pkgName.equals(item.packageName)) { 7212 iter.remove(); 7213 } 7214 } 7215 7216 // Take care of first install / last update times. 7217 if (currentTime != 0) { 7218 if (pkgSetting.firstInstallTime == 0) { 7219 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7220 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7221 pkgSetting.lastUpdateTime = currentTime; 7222 } 7223 } else if (pkgSetting.firstInstallTime == 0) { 7224 // We need *something*. Take time time stamp of the file. 7225 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7226 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7227 if (scanFileTime != pkgSetting.timeStamp) { 7228 // A package on the system image has changed; consider this 7229 // to be an update. 7230 pkgSetting.lastUpdateTime = scanFileTime; 7231 } 7232 } 7233 7234 // Add the package's KeySets to the global KeySetManagerService 7235 ksms.addScannedPackageLPw(pkg); 7236 7237 int N = pkg.providers.size(); 7238 StringBuilder r = null; 7239 int i; 7240 for (i=0; i<N; i++) { 7241 PackageParser.Provider p = pkg.providers.get(i); 7242 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7243 p.info.processName, pkg.applicationInfo.uid); 7244 mProviders.addProvider(p); 7245 p.syncable = p.info.isSyncable; 7246 if (p.info.authority != null) { 7247 String names[] = p.info.authority.split(";"); 7248 p.info.authority = null; 7249 for (int j = 0; j < names.length; j++) { 7250 if (j == 1 && p.syncable) { 7251 // We only want the first authority for a provider to possibly be 7252 // syncable, so if we already added this provider using a different 7253 // authority clear the syncable flag. We copy the provider before 7254 // changing it because the mProviders object contains a reference 7255 // to a provider that we don't want to change. 7256 // Only do this for the second authority since the resulting provider 7257 // object can be the same for all future authorities for this provider. 7258 p = new PackageParser.Provider(p); 7259 p.syncable = false; 7260 } 7261 if (!mProvidersByAuthority.containsKey(names[j])) { 7262 mProvidersByAuthority.put(names[j], p); 7263 if (p.info.authority == null) { 7264 p.info.authority = names[j]; 7265 } else { 7266 p.info.authority = p.info.authority + ";" + names[j]; 7267 } 7268 if (DEBUG_PACKAGE_SCANNING) { 7269 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7270 Log.d(TAG, "Registered content provider: " + names[j] 7271 + ", className = " + p.info.name + ", isSyncable = " 7272 + p.info.isSyncable); 7273 } 7274 } else { 7275 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7276 Slog.w(TAG, "Skipping provider name " + names[j] + 7277 " (in package " + pkg.applicationInfo.packageName + 7278 "): name already used by " 7279 + ((other != null && other.getComponentName() != null) 7280 ? other.getComponentName().getPackageName() : "?")); 7281 } 7282 } 7283 } 7284 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7285 if (r == null) { 7286 r = new StringBuilder(256); 7287 } else { 7288 r.append(' '); 7289 } 7290 r.append(p.info.name); 7291 } 7292 } 7293 if (r != null) { 7294 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7295 } 7296 7297 N = pkg.services.size(); 7298 r = null; 7299 for (i=0; i<N; i++) { 7300 PackageParser.Service s = pkg.services.get(i); 7301 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7302 s.info.processName, pkg.applicationInfo.uid); 7303 mServices.addService(s); 7304 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7305 if (r == null) { 7306 r = new StringBuilder(256); 7307 } else { 7308 r.append(' '); 7309 } 7310 r.append(s.info.name); 7311 } 7312 } 7313 if (r != null) { 7314 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7315 } 7316 7317 N = pkg.receivers.size(); 7318 r = null; 7319 for (i=0; i<N; i++) { 7320 PackageParser.Activity a = pkg.receivers.get(i); 7321 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7322 a.info.processName, pkg.applicationInfo.uid); 7323 mReceivers.addActivity(a, "receiver"); 7324 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7325 if (r == null) { 7326 r = new StringBuilder(256); 7327 } else { 7328 r.append(' '); 7329 } 7330 r.append(a.info.name); 7331 } 7332 } 7333 if (r != null) { 7334 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7335 } 7336 7337 N = pkg.activities.size(); 7338 r = null; 7339 for (i=0; i<N; i++) { 7340 PackageParser.Activity a = pkg.activities.get(i); 7341 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7342 a.info.processName, pkg.applicationInfo.uid); 7343 mActivities.addActivity(a, "activity"); 7344 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7345 if (r == null) { 7346 r = new StringBuilder(256); 7347 } else { 7348 r.append(' '); 7349 } 7350 r.append(a.info.name); 7351 } 7352 } 7353 if (r != null) { 7354 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7355 } 7356 7357 N = pkg.permissionGroups.size(); 7358 r = null; 7359 for (i=0; i<N; i++) { 7360 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7361 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7362 if (cur == null) { 7363 mPermissionGroups.put(pg.info.name, pg); 7364 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7365 if (r == null) { 7366 r = new StringBuilder(256); 7367 } else { 7368 r.append(' '); 7369 } 7370 r.append(pg.info.name); 7371 } 7372 } else { 7373 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7374 + pg.info.packageName + " ignored: original from " 7375 + cur.info.packageName); 7376 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7377 if (r == null) { 7378 r = new StringBuilder(256); 7379 } else { 7380 r.append(' '); 7381 } 7382 r.append("DUP:"); 7383 r.append(pg.info.name); 7384 } 7385 } 7386 } 7387 if (r != null) { 7388 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7389 } 7390 7391 N = pkg.permissions.size(); 7392 r = null; 7393 for (i=0; i<N; i++) { 7394 PackageParser.Permission p = pkg.permissions.get(i); 7395 7396 // Assume by default that we did not install this permission into the system. 7397 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7398 7399 // Now that permission groups have a special meaning, we ignore permission 7400 // groups for legacy apps to prevent unexpected behavior. In particular, 7401 // permissions for one app being granted to someone just becuase they happen 7402 // to be in a group defined by another app (before this had no implications). 7403 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7404 p.group = mPermissionGroups.get(p.info.group); 7405 // Warn for a permission in an unknown group. 7406 if (p.info.group != null && p.group == null) { 7407 Slog.w(TAG, "Permission " + p.info.name + " from package " 7408 + p.info.packageName + " in an unknown group " + p.info.group); 7409 } 7410 } 7411 7412 ArrayMap<String, BasePermission> permissionMap = 7413 p.tree ? mSettings.mPermissionTrees 7414 : mSettings.mPermissions; 7415 BasePermission bp = permissionMap.get(p.info.name); 7416 7417 // Allow system apps to redefine non-system permissions 7418 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7419 final boolean currentOwnerIsSystem = (bp.perm != null 7420 && isSystemApp(bp.perm.owner)); 7421 if (isSystemApp(p.owner)) { 7422 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7423 // It's a built-in permission and no owner, take ownership now 7424 bp.packageSetting = pkgSetting; 7425 bp.perm = p; 7426 bp.uid = pkg.applicationInfo.uid; 7427 bp.sourcePackage = p.info.packageName; 7428 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7429 } else if (!currentOwnerIsSystem) { 7430 String msg = "New decl " + p.owner + " of permission " 7431 + p.info.name + " is system; overriding " + bp.sourcePackage; 7432 reportSettingsProblem(Log.WARN, msg); 7433 bp = null; 7434 } 7435 } 7436 } 7437 7438 if (bp == null) { 7439 bp = new BasePermission(p.info.name, p.info.packageName, 7440 BasePermission.TYPE_NORMAL); 7441 permissionMap.put(p.info.name, bp); 7442 } 7443 7444 if (bp.perm == null) { 7445 if (bp.sourcePackage == null 7446 || bp.sourcePackage.equals(p.info.packageName)) { 7447 BasePermission tree = findPermissionTreeLP(p.info.name); 7448 if (tree == null 7449 || tree.sourcePackage.equals(p.info.packageName)) { 7450 bp.packageSetting = pkgSetting; 7451 bp.perm = p; 7452 bp.uid = pkg.applicationInfo.uid; 7453 bp.sourcePackage = p.info.packageName; 7454 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7455 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7456 if (r == null) { 7457 r = new StringBuilder(256); 7458 } else { 7459 r.append(' '); 7460 } 7461 r.append(p.info.name); 7462 } 7463 } else { 7464 Slog.w(TAG, "Permission " + p.info.name + " from package " 7465 + p.info.packageName + " ignored: base tree " 7466 + tree.name + " is from package " 7467 + tree.sourcePackage); 7468 } 7469 } else { 7470 Slog.w(TAG, "Permission " + p.info.name + " from package " 7471 + p.info.packageName + " ignored: original from " 7472 + bp.sourcePackage); 7473 } 7474 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7475 if (r == null) { 7476 r = new StringBuilder(256); 7477 } else { 7478 r.append(' '); 7479 } 7480 r.append("DUP:"); 7481 r.append(p.info.name); 7482 } 7483 if (bp.perm == p) { 7484 bp.protectionLevel = p.info.protectionLevel; 7485 } 7486 } 7487 7488 if (r != null) { 7489 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7490 } 7491 7492 N = pkg.instrumentation.size(); 7493 r = null; 7494 for (i=0; i<N; i++) { 7495 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7496 a.info.packageName = pkg.applicationInfo.packageName; 7497 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7498 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7499 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7500 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7501 a.info.dataDir = pkg.applicationInfo.dataDir; 7502 7503 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7504 // need other information about the application, like the ABI and what not ? 7505 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7506 mInstrumentation.put(a.getComponentName(), a); 7507 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7508 if (r == null) { 7509 r = new StringBuilder(256); 7510 } else { 7511 r.append(' '); 7512 } 7513 r.append(a.info.name); 7514 } 7515 } 7516 if (r != null) { 7517 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7518 } 7519 7520 if (pkg.protectedBroadcasts != null) { 7521 N = pkg.protectedBroadcasts.size(); 7522 for (i=0; i<N; i++) { 7523 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7524 } 7525 } 7526 7527 pkgSetting.setTimeStamp(scanFileTime); 7528 7529 // Create idmap files for pairs of (packages, overlay packages). 7530 // Note: "android", ie framework-res.apk, is handled by native layers. 7531 if (pkg.mOverlayTarget != null) { 7532 // This is an overlay package. 7533 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7534 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7535 mOverlays.put(pkg.mOverlayTarget, 7536 new ArrayMap<String, PackageParser.Package>()); 7537 } 7538 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7539 map.put(pkg.packageName, pkg); 7540 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7541 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7542 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7543 "scanPackageLI failed to createIdmap"); 7544 } 7545 } 7546 } else if (mOverlays.containsKey(pkg.packageName) && 7547 !pkg.packageName.equals("android")) { 7548 // This is a regular package, with one or more known overlay packages. 7549 createIdmapsForPackageLI(pkg); 7550 } 7551 } 7552 7553 return pkg; 7554 } 7555 7556 /** 7557 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7558 * is derived purely on the basis of the contents of {@code scanFile} and 7559 * {@code cpuAbiOverride}. 7560 * 7561 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7562 */ 7563 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7564 String cpuAbiOverride, boolean extractLibs) 7565 throws PackageManagerException { 7566 // TODO: We can probably be smarter about this stuff. For installed apps, 7567 // we can calculate this information at install time once and for all. For 7568 // system apps, we can probably assume that this information doesn't change 7569 // after the first boot scan. As things stand, we do lots of unnecessary work. 7570 7571 // Give ourselves some initial paths; we'll come back for another 7572 // pass once we've determined ABI below. 7573 setNativeLibraryPaths(pkg); 7574 7575 // We would never need to extract libs for forward-locked and external packages, 7576 // since the container service will do it for us. We shouldn't attempt to 7577 // extract libs from system app when it was not updated. 7578 if (pkg.isForwardLocked() || isExternal(pkg) || 7579 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7580 extractLibs = false; 7581 } 7582 7583 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7584 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7585 7586 NativeLibraryHelper.Handle handle = null; 7587 try { 7588 handle = NativeLibraryHelper.Handle.create(scanFile); 7589 // TODO(multiArch): This can be null for apps that didn't go through the 7590 // usual installation process. We can calculate it again, like we 7591 // do during install time. 7592 // 7593 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7594 // unnecessary. 7595 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7596 7597 // Null out the abis so that they can be recalculated. 7598 pkg.applicationInfo.primaryCpuAbi = null; 7599 pkg.applicationInfo.secondaryCpuAbi = null; 7600 if (isMultiArch(pkg.applicationInfo)) { 7601 // Warn if we've set an abiOverride for multi-lib packages.. 7602 // By definition, we need to copy both 32 and 64 bit libraries for 7603 // such packages. 7604 if (pkg.cpuAbiOverride != null 7605 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7606 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7607 } 7608 7609 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7610 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7611 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7612 if (extractLibs) { 7613 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7614 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7615 useIsaSpecificSubdirs); 7616 } else { 7617 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7618 } 7619 } 7620 7621 maybeThrowExceptionForMultiArchCopy( 7622 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7623 7624 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7625 if (extractLibs) { 7626 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7627 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7628 useIsaSpecificSubdirs); 7629 } else { 7630 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7631 } 7632 } 7633 7634 maybeThrowExceptionForMultiArchCopy( 7635 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7636 7637 if (abi64 >= 0) { 7638 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7639 } 7640 7641 if (abi32 >= 0) { 7642 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7643 if (abi64 >= 0) { 7644 pkg.applicationInfo.secondaryCpuAbi = abi; 7645 } else { 7646 pkg.applicationInfo.primaryCpuAbi = abi; 7647 } 7648 } 7649 } else { 7650 String[] abiList = (cpuAbiOverride != null) ? 7651 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7652 7653 // Enable gross and lame hacks for apps that are built with old 7654 // SDK tools. We must scan their APKs for renderscript bitcode and 7655 // not launch them if it's present. Don't bother checking on devices 7656 // that don't have 64 bit support. 7657 boolean needsRenderScriptOverride = false; 7658 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7659 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7660 abiList = Build.SUPPORTED_32_BIT_ABIS; 7661 needsRenderScriptOverride = true; 7662 } 7663 7664 final int copyRet; 7665 if (extractLibs) { 7666 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7667 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7668 } else { 7669 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7670 } 7671 7672 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7673 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7674 "Error unpackaging native libs for app, errorCode=" + copyRet); 7675 } 7676 7677 if (copyRet >= 0) { 7678 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7679 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7680 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7681 } else if (needsRenderScriptOverride) { 7682 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7683 } 7684 } 7685 } catch (IOException ioe) { 7686 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7687 } finally { 7688 IoUtils.closeQuietly(handle); 7689 } 7690 7691 // Now that we've calculated the ABIs and determined if it's an internal app, 7692 // we will go ahead and populate the nativeLibraryPath. 7693 setNativeLibraryPaths(pkg); 7694 } 7695 7696 /** 7697 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7698 * i.e, so that all packages can be run inside a single process if required. 7699 * 7700 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7701 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7702 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7703 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7704 * updating a package that belongs to a shared user. 7705 * 7706 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7707 * adds unnecessary complexity. 7708 */ 7709 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7710 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7711 String requiredInstructionSet = null; 7712 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7713 requiredInstructionSet = VMRuntime.getInstructionSet( 7714 scannedPackage.applicationInfo.primaryCpuAbi); 7715 } 7716 7717 PackageSetting requirer = null; 7718 for (PackageSetting ps : packagesForUser) { 7719 // If packagesForUser contains scannedPackage, we skip it. This will happen 7720 // when scannedPackage is an update of an existing package. Without this check, 7721 // we will never be able to change the ABI of any package belonging to a shared 7722 // user, even if it's compatible with other packages. 7723 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7724 if (ps.primaryCpuAbiString == null) { 7725 continue; 7726 } 7727 7728 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7729 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7730 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7731 // this but there's not much we can do. 7732 String errorMessage = "Instruction set mismatch, " 7733 + ((requirer == null) ? "[caller]" : requirer) 7734 + " requires " + requiredInstructionSet + " whereas " + ps 7735 + " requires " + instructionSet; 7736 Slog.w(TAG, errorMessage); 7737 } 7738 7739 if (requiredInstructionSet == null) { 7740 requiredInstructionSet = instructionSet; 7741 requirer = ps; 7742 } 7743 } 7744 } 7745 7746 if (requiredInstructionSet != null) { 7747 String adjustedAbi; 7748 if (requirer != null) { 7749 // requirer != null implies that either scannedPackage was null or that scannedPackage 7750 // did not require an ABI, in which case we have to adjust scannedPackage to match 7751 // the ABI of the set (which is the same as requirer's ABI) 7752 adjustedAbi = requirer.primaryCpuAbiString; 7753 if (scannedPackage != null) { 7754 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7755 } 7756 } else { 7757 // requirer == null implies that we're updating all ABIs in the set to 7758 // match scannedPackage. 7759 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7760 } 7761 7762 for (PackageSetting ps : packagesForUser) { 7763 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7764 if (ps.primaryCpuAbiString != null) { 7765 continue; 7766 } 7767 7768 ps.primaryCpuAbiString = adjustedAbi; 7769 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7770 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7771 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7772 7773 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7774 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7775 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7776 ps.primaryCpuAbiString = null; 7777 ps.pkg.applicationInfo.primaryCpuAbi = null; 7778 return; 7779 } else { 7780 mInstaller.rmdex(ps.codePathString, 7781 getDexCodeInstructionSet(getPreferredInstructionSet())); 7782 } 7783 } 7784 } 7785 } 7786 } 7787 } 7788 7789 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7790 synchronized (mPackages) { 7791 mResolverReplaced = true; 7792 // Set up information for custom user intent resolution activity. 7793 mResolveActivity.applicationInfo = pkg.applicationInfo; 7794 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7795 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7796 mResolveActivity.processName = pkg.applicationInfo.packageName; 7797 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7798 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7799 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7800 mResolveActivity.theme = 0; 7801 mResolveActivity.exported = true; 7802 mResolveActivity.enabled = true; 7803 mResolveInfo.activityInfo = mResolveActivity; 7804 mResolveInfo.priority = 0; 7805 mResolveInfo.preferredOrder = 0; 7806 mResolveInfo.match = 0; 7807 mResolveComponentName = mCustomResolverComponentName; 7808 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7809 mResolveComponentName); 7810 } 7811 } 7812 7813 private static String calculateBundledApkRoot(final String codePathString) { 7814 final File codePath = new File(codePathString); 7815 final File codeRoot; 7816 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7817 codeRoot = Environment.getRootDirectory(); 7818 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7819 codeRoot = Environment.getOemDirectory(); 7820 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7821 codeRoot = Environment.getVendorDirectory(); 7822 } else { 7823 // Unrecognized code path; take its top real segment as the apk root: 7824 // e.g. /something/app/blah.apk => /something 7825 try { 7826 File f = codePath.getCanonicalFile(); 7827 File parent = f.getParentFile(); // non-null because codePath is a file 7828 File tmp; 7829 while ((tmp = parent.getParentFile()) != null) { 7830 f = parent; 7831 parent = tmp; 7832 } 7833 codeRoot = f; 7834 Slog.w(TAG, "Unrecognized code path " 7835 + codePath + " - using " + codeRoot); 7836 } catch (IOException e) { 7837 // Can't canonicalize the code path -- shenanigans? 7838 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7839 return Environment.getRootDirectory().getPath(); 7840 } 7841 } 7842 return codeRoot.getPath(); 7843 } 7844 7845 /** 7846 * Derive and set the location of native libraries for the given package, 7847 * which varies depending on where and how the package was installed. 7848 */ 7849 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7850 final ApplicationInfo info = pkg.applicationInfo; 7851 final String codePath = pkg.codePath; 7852 final File codeFile = new File(codePath); 7853 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7854 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7855 7856 info.nativeLibraryRootDir = null; 7857 info.nativeLibraryRootRequiresIsa = false; 7858 info.nativeLibraryDir = null; 7859 info.secondaryNativeLibraryDir = null; 7860 7861 if (isApkFile(codeFile)) { 7862 // Monolithic install 7863 if (bundledApp) { 7864 // If "/system/lib64/apkname" exists, assume that is the per-package 7865 // native library directory to use; otherwise use "/system/lib/apkname". 7866 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7867 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7868 getPrimaryInstructionSet(info)); 7869 7870 // This is a bundled system app so choose the path based on the ABI. 7871 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7872 // is just the default path. 7873 final String apkName = deriveCodePathName(codePath); 7874 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7875 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7876 apkName).getAbsolutePath(); 7877 7878 if (info.secondaryCpuAbi != null) { 7879 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7880 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7881 secondaryLibDir, apkName).getAbsolutePath(); 7882 } 7883 } else if (asecApp) { 7884 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7885 .getAbsolutePath(); 7886 } else { 7887 final String apkName = deriveCodePathName(codePath); 7888 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7889 .getAbsolutePath(); 7890 } 7891 7892 info.nativeLibraryRootRequiresIsa = false; 7893 info.nativeLibraryDir = info.nativeLibraryRootDir; 7894 } else { 7895 // Cluster install 7896 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7897 info.nativeLibraryRootRequiresIsa = true; 7898 7899 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7900 getPrimaryInstructionSet(info)).getAbsolutePath(); 7901 7902 if (info.secondaryCpuAbi != null) { 7903 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7904 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7905 } 7906 } 7907 } 7908 7909 /** 7910 * Calculate the abis and roots for a bundled app. These can uniquely 7911 * be determined from the contents of the system partition, i.e whether 7912 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7913 * of this information, and instead assume that the system was built 7914 * sensibly. 7915 */ 7916 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7917 PackageSetting pkgSetting) { 7918 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7919 7920 // If "/system/lib64/apkname" exists, assume that is the per-package 7921 // native library directory to use; otherwise use "/system/lib/apkname". 7922 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7923 setBundledAppAbi(pkg, apkRoot, apkName); 7924 // pkgSetting might be null during rescan following uninstall of updates 7925 // to a bundled app, so accommodate that possibility. The settings in 7926 // that case will be established later from the parsed package. 7927 // 7928 // If the settings aren't null, sync them up with what we've just derived. 7929 // note that apkRoot isn't stored in the package settings. 7930 if (pkgSetting != null) { 7931 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7932 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7933 } 7934 } 7935 7936 /** 7937 * Deduces the ABI of a bundled app and sets the relevant fields on the 7938 * parsed pkg object. 7939 * 7940 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7941 * under which system libraries are installed. 7942 * @param apkName the name of the installed package. 7943 */ 7944 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7945 final File codeFile = new File(pkg.codePath); 7946 7947 final boolean has64BitLibs; 7948 final boolean has32BitLibs; 7949 if (isApkFile(codeFile)) { 7950 // Monolithic install 7951 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7952 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7953 } else { 7954 // Cluster install 7955 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7956 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7957 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7958 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7959 has64BitLibs = (new File(rootDir, isa)).exists(); 7960 } else { 7961 has64BitLibs = false; 7962 } 7963 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7964 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7965 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7966 has32BitLibs = (new File(rootDir, isa)).exists(); 7967 } else { 7968 has32BitLibs = false; 7969 } 7970 } 7971 7972 if (has64BitLibs && !has32BitLibs) { 7973 // The package has 64 bit libs, but not 32 bit libs. Its primary 7974 // ABI should be 64 bit. We can safely assume here that the bundled 7975 // native libraries correspond to the most preferred ABI in the list. 7976 7977 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7978 pkg.applicationInfo.secondaryCpuAbi = null; 7979 } else if (has32BitLibs && !has64BitLibs) { 7980 // The package has 32 bit libs but not 64 bit libs. Its primary 7981 // ABI should be 32 bit. 7982 7983 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7984 pkg.applicationInfo.secondaryCpuAbi = null; 7985 } else if (has32BitLibs && has64BitLibs) { 7986 // The application has both 64 and 32 bit bundled libraries. We check 7987 // here that the app declares multiArch support, and warn if it doesn't. 7988 // 7989 // We will be lenient here and record both ABIs. The primary will be the 7990 // ABI that's higher on the list, i.e, a device that's configured to prefer 7991 // 64 bit apps will see a 64 bit primary ABI, 7992 7993 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7994 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7995 } 7996 7997 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7998 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7999 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8000 } else { 8001 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8002 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8003 } 8004 } else { 8005 pkg.applicationInfo.primaryCpuAbi = null; 8006 pkg.applicationInfo.secondaryCpuAbi = null; 8007 } 8008 } 8009 8010 private void killApplication(String pkgName, int appId, String reason) { 8011 // Request the ActivityManager to kill the process(only for existing packages) 8012 // so that we do not end up in a confused state while the user is still using the older 8013 // version of the application while the new one gets installed. 8014 IActivityManager am = ActivityManagerNative.getDefault(); 8015 if (am != null) { 8016 try { 8017 am.killApplicationWithAppId(pkgName, appId, reason); 8018 } catch (RemoteException e) { 8019 } 8020 } 8021 } 8022 8023 void removePackageLI(PackageSetting ps, boolean chatty) { 8024 if (DEBUG_INSTALL) { 8025 if (chatty) 8026 Log.d(TAG, "Removing package " + ps.name); 8027 } 8028 8029 // writer 8030 synchronized (mPackages) { 8031 mPackages.remove(ps.name); 8032 final PackageParser.Package pkg = ps.pkg; 8033 if (pkg != null) { 8034 cleanPackageDataStructuresLILPw(pkg, chatty); 8035 } 8036 } 8037 } 8038 8039 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8040 if (DEBUG_INSTALL) { 8041 if (chatty) 8042 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8043 } 8044 8045 // writer 8046 synchronized (mPackages) { 8047 mPackages.remove(pkg.applicationInfo.packageName); 8048 cleanPackageDataStructuresLILPw(pkg, chatty); 8049 } 8050 } 8051 8052 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8053 int N = pkg.providers.size(); 8054 StringBuilder r = null; 8055 int i; 8056 for (i=0; i<N; i++) { 8057 PackageParser.Provider p = pkg.providers.get(i); 8058 mProviders.removeProvider(p); 8059 if (p.info.authority == null) { 8060 8061 /* There was another ContentProvider with this authority when 8062 * this app was installed so this authority is null, 8063 * Ignore it as we don't have to unregister the provider. 8064 */ 8065 continue; 8066 } 8067 String names[] = p.info.authority.split(";"); 8068 for (int j = 0; j < names.length; j++) { 8069 if (mProvidersByAuthority.get(names[j]) == p) { 8070 mProvidersByAuthority.remove(names[j]); 8071 if (DEBUG_REMOVE) { 8072 if (chatty) 8073 Log.d(TAG, "Unregistered content provider: " + names[j] 8074 + ", className = " + p.info.name + ", isSyncable = " 8075 + p.info.isSyncable); 8076 } 8077 } 8078 } 8079 if (DEBUG_REMOVE && chatty) { 8080 if (r == null) { 8081 r = new StringBuilder(256); 8082 } else { 8083 r.append(' '); 8084 } 8085 r.append(p.info.name); 8086 } 8087 } 8088 if (r != null) { 8089 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8090 } 8091 8092 N = pkg.services.size(); 8093 r = null; 8094 for (i=0; i<N; i++) { 8095 PackageParser.Service s = pkg.services.get(i); 8096 mServices.removeService(s); 8097 if (chatty) { 8098 if (r == null) { 8099 r = new StringBuilder(256); 8100 } else { 8101 r.append(' '); 8102 } 8103 r.append(s.info.name); 8104 } 8105 } 8106 if (r != null) { 8107 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8108 } 8109 8110 N = pkg.receivers.size(); 8111 r = null; 8112 for (i=0; i<N; i++) { 8113 PackageParser.Activity a = pkg.receivers.get(i); 8114 mReceivers.removeActivity(a, "receiver"); 8115 if (DEBUG_REMOVE && chatty) { 8116 if (r == null) { 8117 r = new StringBuilder(256); 8118 } else { 8119 r.append(' '); 8120 } 8121 r.append(a.info.name); 8122 } 8123 } 8124 if (r != null) { 8125 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8126 } 8127 8128 N = pkg.activities.size(); 8129 r = null; 8130 for (i=0; i<N; i++) { 8131 PackageParser.Activity a = pkg.activities.get(i); 8132 mActivities.removeActivity(a, "activity"); 8133 if (DEBUG_REMOVE && chatty) { 8134 if (r == null) { 8135 r = new StringBuilder(256); 8136 } else { 8137 r.append(' '); 8138 } 8139 r.append(a.info.name); 8140 } 8141 } 8142 if (r != null) { 8143 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8144 } 8145 8146 N = pkg.permissions.size(); 8147 r = null; 8148 for (i=0; i<N; i++) { 8149 PackageParser.Permission p = pkg.permissions.get(i); 8150 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8151 if (bp == null) { 8152 bp = mSettings.mPermissionTrees.get(p.info.name); 8153 } 8154 if (bp != null && bp.perm == p) { 8155 bp.perm = null; 8156 if (DEBUG_REMOVE && chatty) { 8157 if (r == null) { 8158 r = new StringBuilder(256); 8159 } else { 8160 r.append(' '); 8161 } 8162 r.append(p.info.name); 8163 } 8164 } 8165 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8166 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8167 if (appOpPerms != null) { 8168 appOpPerms.remove(pkg.packageName); 8169 } 8170 } 8171 } 8172 if (r != null) { 8173 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8174 } 8175 8176 N = pkg.requestedPermissions.size(); 8177 r = null; 8178 for (i=0; i<N; i++) { 8179 String perm = pkg.requestedPermissions.get(i); 8180 BasePermission bp = mSettings.mPermissions.get(perm); 8181 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8182 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8183 if (appOpPerms != null) { 8184 appOpPerms.remove(pkg.packageName); 8185 if (appOpPerms.isEmpty()) { 8186 mAppOpPermissionPackages.remove(perm); 8187 } 8188 } 8189 } 8190 } 8191 if (r != null) { 8192 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8193 } 8194 8195 N = pkg.instrumentation.size(); 8196 r = null; 8197 for (i=0; i<N; i++) { 8198 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8199 mInstrumentation.remove(a.getComponentName()); 8200 if (DEBUG_REMOVE && chatty) { 8201 if (r == null) { 8202 r = new StringBuilder(256); 8203 } else { 8204 r.append(' '); 8205 } 8206 r.append(a.info.name); 8207 } 8208 } 8209 if (r != null) { 8210 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8211 } 8212 8213 r = null; 8214 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8215 // Only system apps can hold shared libraries. 8216 if (pkg.libraryNames != null) { 8217 for (i=0; i<pkg.libraryNames.size(); i++) { 8218 String name = pkg.libraryNames.get(i); 8219 SharedLibraryEntry cur = mSharedLibraries.get(name); 8220 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8221 mSharedLibraries.remove(name); 8222 if (DEBUG_REMOVE && chatty) { 8223 if (r == null) { 8224 r = new StringBuilder(256); 8225 } else { 8226 r.append(' '); 8227 } 8228 r.append(name); 8229 } 8230 } 8231 } 8232 } 8233 } 8234 if (r != null) { 8235 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8236 } 8237 } 8238 8239 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8240 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8241 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8242 return true; 8243 } 8244 } 8245 return false; 8246 } 8247 8248 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8249 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8250 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8251 8252 private void updatePermissionsLPw(String changingPkg, 8253 PackageParser.Package pkgInfo, int flags) { 8254 // Make sure there are no dangling permission trees. 8255 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8256 while (it.hasNext()) { 8257 final BasePermission bp = it.next(); 8258 if (bp.packageSetting == null) { 8259 // We may not yet have parsed the package, so just see if 8260 // we still know about its settings. 8261 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8262 } 8263 if (bp.packageSetting == null) { 8264 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8265 + " from package " + bp.sourcePackage); 8266 it.remove(); 8267 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8268 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8269 Slog.i(TAG, "Removing old permission tree: " + bp.name 8270 + " from package " + bp.sourcePackage); 8271 flags |= UPDATE_PERMISSIONS_ALL; 8272 it.remove(); 8273 } 8274 } 8275 } 8276 8277 // Make sure all dynamic permissions have been assigned to a package, 8278 // and make sure there are no dangling permissions. 8279 it = mSettings.mPermissions.values().iterator(); 8280 while (it.hasNext()) { 8281 final BasePermission bp = it.next(); 8282 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8283 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8284 + bp.name + " pkg=" + bp.sourcePackage 8285 + " info=" + bp.pendingInfo); 8286 if (bp.packageSetting == null && bp.pendingInfo != null) { 8287 final BasePermission tree = findPermissionTreeLP(bp.name); 8288 if (tree != null && tree.perm != null) { 8289 bp.packageSetting = tree.packageSetting; 8290 bp.perm = new PackageParser.Permission(tree.perm.owner, 8291 new PermissionInfo(bp.pendingInfo)); 8292 bp.perm.info.packageName = tree.perm.info.packageName; 8293 bp.perm.info.name = bp.name; 8294 bp.uid = tree.uid; 8295 } 8296 } 8297 } 8298 if (bp.packageSetting == null) { 8299 // We may not yet have parsed the package, so just see if 8300 // we still know about its settings. 8301 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8302 } 8303 if (bp.packageSetting == null) { 8304 Slog.w(TAG, "Removing dangling permission: " + bp.name 8305 + " from package " + bp.sourcePackage); 8306 it.remove(); 8307 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8308 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8309 Slog.i(TAG, "Removing old permission: " + bp.name 8310 + " from package " + bp.sourcePackage); 8311 flags |= UPDATE_PERMISSIONS_ALL; 8312 it.remove(); 8313 } 8314 } 8315 } 8316 8317 // Now update the permissions for all packages, in particular 8318 // replace the granted permissions of the system packages. 8319 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8320 for (PackageParser.Package pkg : mPackages.values()) { 8321 if (pkg != pkgInfo) { 8322 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8323 changingPkg); 8324 } 8325 } 8326 } 8327 8328 if (pkgInfo != null) { 8329 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8330 } 8331 } 8332 8333 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8334 String packageOfInterest) { 8335 // IMPORTANT: There are two types of permissions: install and runtime. 8336 // Install time permissions are granted when the app is installed to 8337 // all device users and users added in the future. Runtime permissions 8338 // are granted at runtime explicitly to specific users. Normal and signature 8339 // protected permissions are install time permissions. Dangerous permissions 8340 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8341 // otherwise they are runtime permissions. This function does not manage 8342 // runtime permissions except for the case an app targeting Lollipop MR1 8343 // being upgraded to target a newer SDK, in which case dangerous permissions 8344 // are transformed from install time to runtime ones. 8345 8346 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8347 if (ps == null) { 8348 return; 8349 } 8350 8351 PermissionsState permissionsState = ps.getPermissionsState(); 8352 PermissionsState origPermissions = permissionsState; 8353 8354 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8355 8356 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8357 8358 boolean changedInstallPermission = false; 8359 8360 if (replace) { 8361 ps.installPermissionsFixed = false; 8362 if (!ps.isSharedUser()) { 8363 origPermissions = new PermissionsState(permissionsState); 8364 permissionsState.reset(); 8365 } 8366 } 8367 8368 permissionsState.setGlobalGids(mGlobalGids); 8369 8370 final int N = pkg.requestedPermissions.size(); 8371 for (int i=0; i<N; i++) { 8372 final String name = pkg.requestedPermissions.get(i); 8373 final BasePermission bp = mSettings.mPermissions.get(name); 8374 8375 if (DEBUG_INSTALL) { 8376 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8377 } 8378 8379 if (bp == null || bp.packageSetting == null) { 8380 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8381 Slog.w(TAG, "Unknown permission " + name 8382 + " in package " + pkg.packageName); 8383 } 8384 continue; 8385 } 8386 8387 final String perm = bp.name; 8388 boolean allowedSig = false; 8389 int grant = GRANT_DENIED; 8390 8391 // Keep track of app op permissions. 8392 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8393 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8394 if (pkgs == null) { 8395 pkgs = new ArraySet<>(); 8396 mAppOpPermissionPackages.put(bp.name, pkgs); 8397 } 8398 pkgs.add(pkg.packageName); 8399 } 8400 8401 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8402 switch (level) { 8403 case PermissionInfo.PROTECTION_NORMAL: { 8404 // For all apps normal permissions are install time ones. 8405 grant = GRANT_INSTALL; 8406 } break; 8407 8408 case PermissionInfo.PROTECTION_DANGEROUS: { 8409 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8410 // For legacy apps dangerous permissions are install time ones. 8411 grant = GRANT_INSTALL_LEGACY; 8412 } else if (origPermissions.hasInstallPermission(bp.name)) { 8413 // For legacy apps that became modern, install becomes runtime. 8414 grant = GRANT_UPGRADE; 8415 } else if (mPromoteSystemApps 8416 && isSystemApp(ps) 8417 && mExistingSystemPackages.contains(ps.name)) { 8418 // For legacy system apps, install becomes runtime. 8419 // We cannot check hasInstallPermission() for system apps since those 8420 // permissions were granted implicitly and not persisted pre-M. 8421 grant = GRANT_UPGRADE; 8422 } else { 8423 // For modern apps keep runtime permissions unchanged. 8424 grant = GRANT_RUNTIME; 8425 } 8426 } break; 8427 8428 case PermissionInfo.PROTECTION_SIGNATURE: { 8429 // For all apps signature permissions are install time ones. 8430 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8431 if (allowedSig) { 8432 grant = GRANT_INSTALL; 8433 } 8434 } break; 8435 } 8436 8437 if (DEBUG_INSTALL) { 8438 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8439 } 8440 8441 if (grant != GRANT_DENIED) { 8442 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8443 // If this is an existing, non-system package, then 8444 // we can't add any new permissions to it. 8445 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8446 // Except... if this is a permission that was added 8447 // to the platform (note: need to only do this when 8448 // updating the platform). 8449 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8450 grant = GRANT_DENIED; 8451 } 8452 } 8453 } 8454 8455 switch (grant) { 8456 case GRANT_INSTALL: { 8457 // Revoke this as runtime permission to handle the case of 8458 // a runtime permission being downgraded to an install one. 8459 for (int userId : UserManagerService.getInstance().getUserIds()) { 8460 if (origPermissions.getRuntimePermissionState( 8461 bp.name, userId) != null) { 8462 // Revoke the runtime permission and clear the flags. 8463 origPermissions.revokeRuntimePermission(bp, userId); 8464 origPermissions.updatePermissionFlags(bp, userId, 8465 PackageManager.MASK_PERMISSION_FLAGS, 0); 8466 // If we revoked a permission permission, we have to write. 8467 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8468 changedRuntimePermissionUserIds, userId); 8469 } 8470 } 8471 // Grant an install permission. 8472 if (permissionsState.grantInstallPermission(bp) != 8473 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8474 changedInstallPermission = true; 8475 } 8476 } break; 8477 8478 case GRANT_INSTALL_LEGACY: { 8479 // Grant an install permission. 8480 if (permissionsState.grantInstallPermission(bp) != 8481 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8482 changedInstallPermission = true; 8483 } 8484 } break; 8485 8486 case GRANT_RUNTIME: { 8487 // Grant previously granted runtime permissions. 8488 for (int userId : UserManagerService.getInstance().getUserIds()) { 8489 PermissionState permissionState = origPermissions 8490 .getRuntimePermissionState(bp.name, userId); 8491 final int flags = permissionState != null 8492 ? permissionState.getFlags() : 0; 8493 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8494 if (permissionsState.grantRuntimePermission(bp, userId) == 8495 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8496 // If we cannot put the permission as it was, we have to write. 8497 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8498 changedRuntimePermissionUserIds, userId); 8499 } 8500 } 8501 // Propagate the permission flags. 8502 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8503 } 8504 } break; 8505 8506 case GRANT_UPGRADE: { 8507 // Grant runtime permissions for a previously held install permission. 8508 PermissionState permissionState = origPermissions 8509 .getInstallPermissionState(bp.name); 8510 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8511 8512 if (origPermissions.revokeInstallPermission(bp) 8513 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8514 // We will be transferring the permission flags, so clear them. 8515 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8516 PackageManager.MASK_PERMISSION_FLAGS, 0); 8517 changedInstallPermission = true; 8518 } 8519 8520 // If the permission is not to be promoted to runtime we ignore it and 8521 // also its other flags as they are not applicable to install permissions. 8522 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8523 for (int userId : currentUserIds) { 8524 if (permissionsState.grantRuntimePermission(bp, userId) != 8525 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8526 // Transfer the permission flags. 8527 permissionsState.updatePermissionFlags(bp, userId, 8528 flags, flags); 8529 // If we granted the permission, we have to write. 8530 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8531 changedRuntimePermissionUserIds, userId); 8532 } 8533 } 8534 } 8535 } break; 8536 8537 default: { 8538 if (packageOfInterest == null 8539 || packageOfInterest.equals(pkg.packageName)) { 8540 Slog.w(TAG, "Not granting permission " + perm 8541 + " to package " + pkg.packageName 8542 + " because it was previously installed without"); 8543 } 8544 } break; 8545 } 8546 } else { 8547 if (permissionsState.revokeInstallPermission(bp) != 8548 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8549 // Also drop the permission flags. 8550 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8551 PackageManager.MASK_PERMISSION_FLAGS, 0); 8552 changedInstallPermission = true; 8553 Slog.i(TAG, "Un-granting permission " + perm 8554 + " from package " + pkg.packageName 8555 + " (protectionLevel=" + bp.protectionLevel 8556 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8557 + ")"); 8558 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8559 // Don't print warning for app op permissions, since it is fine for them 8560 // not to be granted, there is a UI for the user to decide. 8561 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8562 Slog.w(TAG, "Not granting permission " + perm 8563 + " to package " + pkg.packageName 8564 + " (protectionLevel=" + bp.protectionLevel 8565 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8566 + ")"); 8567 } 8568 } 8569 } 8570 } 8571 8572 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8573 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8574 // This is the first that we have heard about this package, so the 8575 // permissions we have now selected are fixed until explicitly 8576 // changed. 8577 ps.installPermissionsFixed = true; 8578 } 8579 8580 // Persist the runtime permissions state for users with changes. 8581 for (int userId : changedRuntimePermissionUserIds) { 8582 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8583 } 8584 } 8585 8586 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8587 boolean allowed = false; 8588 final int NP = PackageParser.NEW_PERMISSIONS.length; 8589 for (int ip=0; ip<NP; ip++) { 8590 final PackageParser.NewPermissionInfo npi 8591 = PackageParser.NEW_PERMISSIONS[ip]; 8592 if (npi.name.equals(perm) 8593 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8594 allowed = true; 8595 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8596 + pkg.packageName); 8597 break; 8598 } 8599 } 8600 return allowed; 8601 } 8602 8603 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8604 BasePermission bp, PermissionsState origPermissions) { 8605 boolean allowed; 8606 allowed = (compareSignatures( 8607 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8608 == PackageManager.SIGNATURE_MATCH) 8609 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8610 == PackageManager.SIGNATURE_MATCH); 8611 if (!allowed && (bp.protectionLevel 8612 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8613 if (isSystemApp(pkg)) { 8614 // For updated system applications, a system permission 8615 // is granted only if it had been defined by the original application. 8616 if (pkg.isUpdatedSystemApp()) { 8617 final PackageSetting sysPs = mSettings 8618 .getDisabledSystemPkgLPr(pkg.packageName); 8619 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8620 // If the original was granted this permission, we take 8621 // that grant decision as read and propagate it to the 8622 // update. 8623 if (sysPs.isPrivileged()) { 8624 allowed = true; 8625 } 8626 } else { 8627 // The system apk may have been updated with an older 8628 // version of the one on the data partition, but which 8629 // granted a new system permission that it didn't have 8630 // before. In this case we do want to allow the app to 8631 // now get the new permission if the ancestral apk is 8632 // privileged to get it. 8633 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8634 for (int j=0; 8635 j<sysPs.pkg.requestedPermissions.size(); j++) { 8636 if (perm.equals( 8637 sysPs.pkg.requestedPermissions.get(j))) { 8638 allowed = true; 8639 break; 8640 } 8641 } 8642 } 8643 } 8644 } else { 8645 allowed = isPrivilegedApp(pkg); 8646 } 8647 } 8648 } 8649 if (!allowed) { 8650 if (!allowed && (bp.protectionLevel 8651 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8652 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8653 // If this was a previously normal/dangerous permission that got moved 8654 // to a system permission as part of the runtime permission redesign, then 8655 // we still want to blindly grant it to old apps. 8656 allowed = true; 8657 } 8658 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8659 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8660 // If this permission is to be granted to the system installer and 8661 // this app is an installer, then it gets the permission. 8662 allowed = true; 8663 } 8664 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8665 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8666 // If this permission is to be granted to the system verifier and 8667 // this app is a verifier, then it gets the permission. 8668 allowed = true; 8669 } 8670 if (!allowed && (bp.protectionLevel 8671 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8672 && isSystemApp(pkg)) { 8673 // Any pre-installed system app is allowed to get this permission. 8674 allowed = true; 8675 } 8676 if (!allowed && (bp.protectionLevel 8677 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8678 // For development permissions, a development permission 8679 // is granted only if it was already granted. 8680 allowed = origPermissions.hasInstallPermission(perm); 8681 } 8682 } 8683 return allowed; 8684 } 8685 8686 final class ActivityIntentResolver 8687 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8688 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8689 boolean defaultOnly, int userId) { 8690 if (!sUserManager.exists(userId)) return null; 8691 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8692 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8693 } 8694 8695 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8696 int userId) { 8697 if (!sUserManager.exists(userId)) return null; 8698 mFlags = flags; 8699 return super.queryIntent(intent, resolvedType, 8700 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8701 } 8702 8703 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8704 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8705 if (!sUserManager.exists(userId)) return null; 8706 if (packageActivities == null) { 8707 return null; 8708 } 8709 mFlags = flags; 8710 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8711 final int N = packageActivities.size(); 8712 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8713 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8714 8715 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8716 for (int i = 0; i < N; ++i) { 8717 intentFilters = packageActivities.get(i).intents; 8718 if (intentFilters != null && intentFilters.size() > 0) { 8719 PackageParser.ActivityIntentInfo[] array = 8720 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8721 intentFilters.toArray(array); 8722 listCut.add(array); 8723 } 8724 } 8725 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8726 } 8727 8728 public final void addActivity(PackageParser.Activity a, String type) { 8729 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8730 mActivities.put(a.getComponentName(), a); 8731 if (DEBUG_SHOW_INFO) 8732 Log.v( 8733 TAG, " " + type + " " + 8734 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8735 if (DEBUG_SHOW_INFO) 8736 Log.v(TAG, " Class=" + a.info.name); 8737 final int NI = a.intents.size(); 8738 for (int j=0; j<NI; j++) { 8739 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8740 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8741 intent.setPriority(0); 8742 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8743 + a.className + " with priority > 0, forcing to 0"); 8744 } 8745 if (DEBUG_SHOW_INFO) { 8746 Log.v(TAG, " IntentFilter:"); 8747 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8748 } 8749 if (!intent.debugCheck()) { 8750 Log.w(TAG, "==> For Activity " + a.info.name); 8751 } 8752 addFilter(intent); 8753 } 8754 } 8755 8756 public final void removeActivity(PackageParser.Activity a, String type) { 8757 mActivities.remove(a.getComponentName()); 8758 if (DEBUG_SHOW_INFO) { 8759 Log.v(TAG, " " + type + " " 8760 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8761 : a.info.name) + ":"); 8762 Log.v(TAG, " Class=" + a.info.name); 8763 } 8764 final int NI = a.intents.size(); 8765 for (int j=0; j<NI; j++) { 8766 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8767 if (DEBUG_SHOW_INFO) { 8768 Log.v(TAG, " IntentFilter:"); 8769 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8770 } 8771 removeFilter(intent); 8772 } 8773 } 8774 8775 @Override 8776 protected boolean allowFilterResult( 8777 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8778 ActivityInfo filterAi = filter.activity.info; 8779 for (int i=dest.size()-1; i>=0; i--) { 8780 ActivityInfo destAi = dest.get(i).activityInfo; 8781 if (destAi.name == filterAi.name 8782 && destAi.packageName == filterAi.packageName) { 8783 return false; 8784 } 8785 } 8786 return true; 8787 } 8788 8789 @Override 8790 protected ActivityIntentInfo[] newArray(int size) { 8791 return new ActivityIntentInfo[size]; 8792 } 8793 8794 @Override 8795 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8796 if (!sUserManager.exists(userId)) return true; 8797 PackageParser.Package p = filter.activity.owner; 8798 if (p != null) { 8799 PackageSetting ps = (PackageSetting)p.mExtras; 8800 if (ps != null) { 8801 // System apps are never considered stopped for purposes of 8802 // filtering, because there may be no way for the user to 8803 // actually re-launch them. 8804 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8805 && ps.getStopped(userId); 8806 } 8807 } 8808 return false; 8809 } 8810 8811 @Override 8812 protected boolean isPackageForFilter(String packageName, 8813 PackageParser.ActivityIntentInfo info) { 8814 return packageName.equals(info.activity.owner.packageName); 8815 } 8816 8817 @Override 8818 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8819 int match, int userId) { 8820 if (!sUserManager.exists(userId)) return null; 8821 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8822 return null; 8823 } 8824 final PackageParser.Activity activity = info.activity; 8825 if (mSafeMode && (activity.info.applicationInfo.flags 8826 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8827 return null; 8828 } 8829 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8830 if (ps == null) { 8831 return null; 8832 } 8833 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8834 ps.readUserState(userId), userId); 8835 if (ai == null) { 8836 return null; 8837 } 8838 final ResolveInfo res = new ResolveInfo(); 8839 res.activityInfo = ai; 8840 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8841 res.filter = info; 8842 } 8843 if (info != null) { 8844 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8845 } 8846 res.priority = info.getPriority(); 8847 res.preferredOrder = activity.owner.mPreferredOrder; 8848 //System.out.println("Result: " + res.activityInfo.className + 8849 // " = " + res.priority); 8850 res.match = match; 8851 res.isDefault = info.hasDefault; 8852 res.labelRes = info.labelRes; 8853 res.nonLocalizedLabel = info.nonLocalizedLabel; 8854 if (userNeedsBadging(userId)) { 8855 res.noResourceId = true; 8856 } else { 8857 res.icon = info.icon; 8858 } 8859 res.iconResourceId = info.icon; 8860 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8861 return res; 8862 } 8863 8864 @Override 8865 protected void sortResults(List<ResolveInfo> results) { 8866 Collections.sort(results, mResolvePrioritySorter); 8867 } 8868 8869 @Override 8870 protected void dumpFilter(PrintWriter out, String prefix, 8871 PackageParser.ActivityIntentInfo filter) { 8872 out.print(prefix); out.print( 8873 Integer.toHexString(System.identityHashCode(filter.activity))); 8874 out.print(' '); 8875 filter.activity.printComponentShortName(out); 8876 out.print(" filter "); 8877 out.println(Integer.toHexString(System.identityHashCode(filter))); 8878 } 8879 8880 @Override 8881 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8882 return filter.activity; 8883 } 8884 8885 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8886 PackageParser.Activity activity = (PackageParser.Activity)label; 8887 out.print(prefix); out.print( 8888 Integer.toHexString(System.identityHashCode(activity))); 8889 out.print(' '); 8890 activity.printComponentShortName(out); 8891 if (count > 1) { 8892 out.print(" ("); out.print(count); out.print(" filters)"); 8893 } 8894 out.println(); 8895 } 8896 8897// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8898// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8899// final List<ResolveInfo> retList = Lists.newArrayList(); 8900// while (i.hasNext()) { 8901// final ResolveInfo resolveInfo = i.next(); 8902// if (isEnabledLP(resolveInfo.activityInfo)) { 8903// retList.add(resolveInfo); 8904// } 8905// } 8906// return retList; 8907// } 8908 8909 // Keys are String (activity class name), values are Activity. 8910 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8911 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8912 private int mFlags; 8913 } 8914 8915 private final class ServiceIntentResolver 8916 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8917 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8918 boolean defaultOnly, int userId) { 8919 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8920 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8921 } 8922 8923 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8924 int userId) { 8925 if (!sUserManager.exists(userId)) return null; 8926 mFlags = flags; 8927 return super.queryIntent(intent, resolvedType, 8928 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8929 } 8930 8931 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8932 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8933 if (!sUserManager.exists(userId)) return null; 8934 if (packageServices == null) { 8935 return null; 8936 } 8937 mFlags = flags; 8938 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8939 final int N = packageServices.size(); 8940 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8941 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8942 8943 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8944 for (int i = 0; i < N; ++i) { 8945 intentFilters = packageServices.get(i).intents; 8946 if (intentFilters != null && intentFilters.size() > 0) { 8947 PackageParser.ServiceIntentInfo[] array = 8948 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8949 intentFilters.toArray(array); 8950 listCut.add(array); 8951 } 8952 } 8953 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8954 } 8955 8956 public final void addService(PackageParser.Service s) { 8957 mServices.put(s.getComponentName(), s); 8958 if (DEBUG_SHOW_INFO) { 8959 Log.v(TAG, " " 8960 + (s.info.nonLocalizedLabel != null 8961 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8962 Log.v(TAG, " Class=" + s.info.name); 8963 } 8964 final int NI = s.intents.size(); 8965 int j; 8966 for (j=0; j<NI; j++) { 8967 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8968 if (DEBUG_SHOW_INFO) { 8969 Log.v(TAG, " IntentFilter:"); 8970 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8971 } 8972 if (!intent.debugCheck()) { 8973 Log.w(TAG, "==> For Service " + s.info.name); 8974 } 8975 addFilter(intent); 8976 } 8977 } 8978 8979 public final void removeService(PackageParser.Service s) { 8980 mServices.remove(s.getComponentName()); 8981 if (DEBUG_SHOW_INFO) { 8982 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8983 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8984 Log.v(TAG, " Class=" + s.info.name); 8985 } 8986 final int NI = s.intents.size(); 8987 int j; 8988 for (j=0; j<NI; j++) { 8989 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8990 if (DEBUG_SHOW_INFO) { 8991 Log.v(TAG, " IntentFilter:"); 8992 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8993 } 8994 removeFilter(intent); 8995 } 8996 } 8997 8998 @Override 8999 protected boolean allowFilterResult( 9000 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9001 ServiceInfo filterSi = filter.service.info; 9002 for (int i=dest.size()-1; i>=0; i--) { 9003 ServiceInfo destAi = dest.get(i).serviceInfo; 9004 if (destAi.name == filterSi.name 9005 && destAi.packageName == filterSi.packageName) { 9006 return false; 9007 } 9008 } 9009 return true; 9010 } 9011 9012 @Override 9013 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9014 return new PackageParser.ServiceIntentInfo[size]; 9015 } 9016 9017 @Override 9018 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9019 if (!sUserManager.exists(userId)) return true; 9020 PackageParser.Package p = filter.service.owner; 9021 if (p != null) { 9022 PackageSetting ps = (PackageSetting)p.mExtras; 9023 if (ps != null) { 9024 // System apps are never considered stopped for purposes of 9025 // filtering, because there may be no way for the user to 9026 // actually re-launch them. 9027 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9028 && ps.getStopped(userId); 9029 } 9030 } 9031 return false; 9032 } 9033 9034 @Override 9035 protected boolean isPackageForFilter(String packageName, 9036 PackageParser.ServiceIntentInfo info) { 9037 return packageName.equals(info.service.owner.packageName); 9038 } 9039 9040 @Override 9041 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9042 int match, int userId) { 9043 if (!sUserManager.exists(userId)) return null; 9044 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9045 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9046 return null; 9047 } 9048 final PackageParser.Service service = info.service; 9049 if (mSafeMode && (service.info.applicationInfo.flags 9050 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9051 return null; 9052 } 9053 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9054 if (ps == null) { 9055 return null; 9056 } 9057 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9058 ps.readUserState(userId), userId); 9059 if (si == null) { 9060 return null; 9061 } 9062 final ResolveInfo res = new ResolveInfo(); 9063 res.serviceInfo = si; 9064 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9065 res.filter = filter; 9066 } 9067 res.priority = info.getPriority(); 9068 res.preferredOrder = service.owner.mPreferredOrder; 9069 res.match = match; 9070 res.isDefault = info.hasDefault; 9071 res.labelRes = info.labelRes; 9072 res.nonLocalizedLabel = info.nonLocalizedLabel; 9073 res.icon = info.icon; 9074 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9075 return res; 9076 } 9077 9078 @Override 9079 protected void sortResults(List<ResolveInfo> results) { 9080 Collections.sort(results, mResolvePrioritySorter); 9081 } 9082 9083 @Override 9084 protected void dumpFilter(PrintWriter out, String prefix, 9085 PackageParser.ServiceIntentInfo filter) { 9086 out.print(prefix); out.print( 9087 Integer.toHexString(System.identityHashCode(filter.service))); 9088 out.print(' '); 9089 filter.service.printComponentShortName(out); 9090 out.print(" filter "); 9091 out.println(Integer.toHexString(System.identityHashCode(filter))); 9092 } 9093 9094 @Override 9095 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9096 return filter.service; 9097 } 9098 9099 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9100 PackageParser.Service service = (PackageParser.Service)label; 9101 out.print(prefix); out.print( 9102 Integer.toHexString(System.identityHashCode(service))); 9103 out.print(' '); 9104 service.printComponentShortName(out); 9105 if (count > 1) { 9106 out.print(" ("); out.print(count); out.print(" filters)"); 9107 } 9108 out.println(); 9109 } 9110 9111// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9112// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9113// final List<ResolveInfo> retList = Lists.newArrayList(); 9114// while (i.hasNext()) { 9115// final ResolveInfo resolveInfo = (ResolveInfo) i; 9116// if (isEnabledLP(resolveInfo.serviceInfo)) { 9117// retList.add(resolveInfo); 9118// } 9119// } 9120// return retList; 9121// } 9122 9123 // Keys are String (activity class name), values are Activity. 9124 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9125 = new ArrayMap<ComponentName, PackageParser.Service>(); 9126 private int mFlags; 9127 }; 9128 9129 private final class ProviderIntentResolver 9130 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9131 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9132 boolean defaultOnly, int userId) { 9133 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9134 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9135 } 9136 9137 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9138 int userId) { 9139 if (!sUserManager.exists(userId)) 9140 return null; 9141 mFlags = flags; 9142 return super.queryIntent(intent, resolvedType, 9143 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9144 } 9145 9146 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9147 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9148 if (!sUserManager.exists(userId)) 9149 return null; 9150 if (packageProviders == null) { 9151 return null; 9152 } 9153 mFlags = flags; 9154 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9155 final int N = packageProviders.size(); 9156 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9157 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9158 9159 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9160 for (int i = 0; i < N; ++i) { 9161 intentFilters = packageProviders.get(i).intents; 9162 if (intentFilters != null && intentFilters.size() > 0) { 9163 PackageParser.ProviderIntentInfo[] array = 9164 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9165 intentFilters.toArray(array); 9166 listCut.add(array); 9167 } 9168 } 9169 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9170 } 9171 9172 public final void addProvider(PackageParser.Provider p) { 9173 if (mProviders.containsKey(p.getComponentName())) { 9174 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9175 return; 9176 } 9177 9178 mProviders.put(p.getComponentName(), p); 9179 if (DEBUG_SHOW_INFO) { 9180 Log.v(TAG, " " 9181 + (p.info.nonLocalizedLabel != null 9182 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9183 Log.v(TAG, " Class=" + p.info.name); 9184 } 9185 final int NI = p.intents.size(); 9186 int j; 9187 for (j = 0; j < NI; j++) { 9188 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9189 if (DEBUG_SHOW_INFO) { 9190 Log.v(TAG, " IntentFilter:"); 9191 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9192 } 9193 if (!intent.debugCheck()) { 9194 Log.w(TAG, "==> For Provider " + p.info.name); 9195 } 9196 addFilter(intent); 9197 } 9198 } 9199 9200 public final void removeProvider(PackageParser.Provider p) { 9201 mProviders.remove(p.getComponentName()); 9202 if (DEBUG_SHOW_INFO) { 9203 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9204 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9205 Log.v(TAG, " Class=" + p.info.name); 9206 } 9207 final int NI = p.intents.size(); 9208 int j; 9209 for (j = 0; j < NI; j++) { 9210 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9211 if (DEBUG_SHOW_INFO) { 9212 Log.v(TAG, " IntentFilter:"); 9213 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9214 } 9215 removeFilter(intent); 9216 } 9217 } 9218 9219 @Override 9220 protected boolean allowFilterResult( 9221 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9222 ProviderInfo filterPi = filter.provider.info; 9223 for (int i = dest.size() - 1; i >= 0; i--) { 9224 ProviderInfo destPi = dest.get(i).providerInfo; 9225 if (destPi.name == filterPi.name 9226 && destPi.packageName == filterPi.packageName) { 9227 return false; 9228 } 9229 } 9230 return true; 9231 } 9232 9233 @Override 9234 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9235 return new PackageParser.ProviderIntentInfo[size]; 9236 } 9237 9238 @Override 9239 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9240 if (!sUserManager.exists(userId)) 9241 return true; 9242 PackageParser.Package p = filter.provider.owner; 9243 if (p != null) { 9244 PackageSetting ps = (PackageSetting) p.mExtras; 9245 if (ps != null) { 9246 // System apps are never considered stopped for purposes of 9247 // filtering, because there may be no way for the user to 9248 // actually re-launch them. 9249 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9250 && ps.getStopped(userId); 9251 } 9252 } 9253 return false; 9254 } 9255 9256 @Override 9257 protected boolean isPackageForFilter(String packageName, 9258 PackageParser.ProviderIntentInfo info) { 9259 return packageName.equals(info.provider.owner.packageName); 9260 } 9261 9262 @Override 9263 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9264 int match, int userId) { 9265 if (!sUserManager.exists(userId)) 9266 return null; 9267 final PackageParser.ProviderIntentInfo info = filter; 9268 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9269 return null; 9270 } 9271 final PackageParser.Provider provider = info.provider; 9272 if (mSafeMode && (provider.info.applicationInfo.flags 9273 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9274 return null; 9275 } 9276 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9277 if (ps == null) { 9278 return null; 9279 } 9280 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9281 ps.readUserState(userId), userId); 9282 if (pi == null) { 9283 return null; 9284 } 9285 final ResolveInfo res = new ResolveInfo(); 9286 res.providerInfo = pi; 9287 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9288 res.filter = filter; 9289 } 9290 res.priority = info.getPriority(); 9291 res.preferredOrder = provider.owner.mPreferredOrder; 9292 res.match = match; 9293 res.isDefault = info.hasDefault; 9294 res.labelRes = info.labelRes; 9295 res.nonLocalizedLabel = info.nonLocalizedLabel; 9296 res.icon = info.icon; 9297 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9298 return res; 9299 } 9300 9301 @Override 9302 protected void sortResults(List<ResolveInfo> results) { 9303 Collections.sort(results, mResolvePrioritySorter); 9304 } 9305 9306 @Override 9307 protected void dumpFilter(PrintWriter out, String prefix, 9308 PackageParser.ProviderIntentInfo filter) { 9309 out.print(prefix); 9310 out.print( 9311 Integer.toHexString(System.identityHashCode(filter.provider))); 9312 out.print(' '); 9313 filter.provider.printComponentShortName(out); 9314 out.print(" filter "); 9315 out.println(Integer.toHexString(System.identityHashCode(filter))); 9316 } 9317 9318 @Override 9319 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9320 return filter.provider; 9321 } 9322 9323 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9324 PackageParser.Provider provider = (PackageParser.Provider)label; 9325 out.print(prefix); out.print( 9326 Integer.toHexString(System.identityHashCode(provider))); 9327 out.print(' '); 9328 provider.printComponentShortName(out); 9329 if (count > 1) { 9330 out.print(" ("); out.print(count); out.print(" filters)"); 9331 } 9332 out.println(); 9333 } 9334 9335 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9336 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9337 private int mFlags; 9338 }; 9339 9340 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9341 new Comparator<ResolveInfo>() { 9342 public int compare(ResolveInfo r1, ResolveInfo r2) { 9343 int v1 = r1.priority; 9344 int v2 = r2.priority; 9345 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9346 if (v1 != v2) { 9347 return (v1 > v2) ? -1 : 1; 9348 } 9349 v1 = r1.preferredOrder; 9350 v2 = r2.preferredOrder; 9351 if (v1 != v2) { 9352 return (v1 > v2) ? -1 : 1; 9353 } 9354 if (r1.isDefault != r2.isDefault) { 9355 return r1.isDefault ? -1 : 1; 9356 } 9357 v1 = r1.match; 9358 v2 = r2.match; 9359 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9360 if (v1 != v2) { 9361 return (v1 > v2) ? -1 : 1; 9362 } 9363 if (r1.system != r2.system) { 9364 return r1.system ? -1 : 1; 9365 } 9366 return 0; 9367 } 9368 }; 9369 9370 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9371 new Comparator<ProviderInfo>() { 9372 public int compare(ProviderInfo p1, ProviderInfo p2) { 9373 final int v1 = p1.initOrder; 9374 final int v2 = p2.initOrder; 9375 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9376 } 9377 }; 9378 9379 final void sendPackageBroadcast(final String action, final String pkg, 9380 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9381 final int[] userIds) { 9382 mHandler.post(new Runnable() { 9383 @Override 9384 public void run() { 9385 try { 9386 final IActivityManager am = ActivityManagerNative.getDefault(); 9387 if (am == null) return; 9388 final int[] resolvedUserIds; 9389 if (userIds == null) { 9390 resolvedUserIds = am.getRunningUserIds(); 9391 } else { 9392 resolvedUserIds = userIds; 9393 } 9394 for (int id : resolvedUserIds) { 9395 final Intent intent = new Intent(action, 9396 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9397 if (extras != null) { 9398 intent.putExtras(extras); 9399 } 9400 if (targetPkg != null) { 9401 intent.setPackage(targetPkg); 9402 } 9403 // Modify the UID when posting to other users 9404 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9405 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9406 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9407 intent.putExtra(Intent.EXTRA_UID, uid); 9408 } 9409 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9410 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9411 if (DEBUG_BROADCASTS) { 9412 RuntimeException here = new RuntimeException("here"); 9413 here.fillInStackTrace(); 9414 Slog.d(TAG, "Sending to user " + id + ": " 9415 + intent.toShortString(false, true, false, false) 9416 + " " + intent.getExtras(), here); 9417 } 9418 am.broadcastIntent(null, intent, null, finishedReceiver, 9419 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9420 null, finishedReceiver != null, false, id); 9421 } 9422 } catch (RemoteException ex) { 9423 } 9424 } 9425 }); 9426 } 9427 9428 /** 9429 * Check if the external storage media is available. This is true if there 9430 * is a mounted external storage medium or if the external storage is 9431 * emulated. 9432 */ 9433 private boolean isExternalMediaAvailable() { 9434 return mMediaMounted || Environment.isExternalStorageEmulated(); 9435 } 9436 9437 @Override 9438 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9439 // writer 9440 synchronized (mPackages) { 9441 if (!isExternalMediaAvailable()) { 9442 // If the external storage is no longer mounted at this point, 9443 // the caller may not have been able to delete all of this 9444 // packages files and can not delete any more. Bail. 9445 return null; 9446 } 9447 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9448 if (lastPackage != null) { 9449 pkgs.remove(lastPackage); 9450 } 9451 if (pkgs.size() > 0) { 9452 return pkgs.get(0); 9453 } 9454 } 9455 return null; 9456 } 9457 9458 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9459 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9460 userId, andCode ? 1 : 0, packageName); 9461 if (mSystemReady) { 9462 msg.sendToTarget(); 9463 } else { 9464 if (mPostSystemReadyMessages == null) { 9465 mPostSystemReadyMessages = new ArrayList<>(); 9466 } 9467 mPostSystemReadyMessages.add(msg); 9468 } 9469 } 9470 9471 void startCleaningPackages() { 9472 // reader 9473 synchronized (mPackages) { 9474 if (!isExternalMediaAvailable()) { 9475 return; 9476 } 9477 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9478 return; 9479 } 9480 } 9481 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9482 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9483 IActivityManager am = ActivityManagerNative.getDefault(); 9484 if (am != null) { 9485 try { 9486 am.startService(null, intent, null, mContext.getOpPackageName(), 9487 UserHandle.USER_OWNER); 9488 } catch (RemoteException e) { 9489 } 9490 } 9491 } 9492 9493 @Override 9494 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9495 int installFlags, String installerPackageName, VerificationParams verificationParams, 9496 String packageAbiOverride) { 9497 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9498 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9499 } 9500 9501 @Override 9502 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9503 int installFlags, String installerPackageName, VerificationParams verificationParams, 9504 String packageAbiOverride, int userId) { 9505 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9506 9507 final int callingUid = Binder.getCallingUid(); 9508 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9509 9510 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9511 try { 9512 if (observer != null) { 9513 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9514 } 9515 } catch (RemoteException re) { 9516 } 9517 return; 9518 } 9519 9520 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9521 installFlags |= PackageManager.INSTALL_FROM_ADB; 9522 9523 } else { 9524 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9525 // about installerPackageName. 9526 9527 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9528 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9529 } 9530 9531 UserHandle user; 9532 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9533 user = UserHandle.ALL; 9534 } else { 9535 user = new UserHandle(userId); 9536 } 9537 9538 // Only system components can circumvent runtime permissions when installing. 9539 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9540 && mContext.checkCallingOrSelfPermission(Manifest.permission 9541 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9542 throw new SecurityException("You need the " 9543 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9544 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9545 } 9546 9547 verificationParams.setInstallerUid(callingUid); 9548 9549 final File originFile = new File(originPath); 9550 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9551 9552 final Message msg = mHandler.obtainMessage(INIT_COPY); 9553 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9554 null, verificationParams, user, packageAbiOverride, null); 9555 mHandler.sendMessage(msg); 9556 } 9557 9558 void installStage(String packageName, File stagedDir, String stagedCid, 9559 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9560 String installerPackageName, int installerUid, UserHandle user) { 9561 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9562 params.referrerUri, installerUid, null); 9563 verifParams.setInstallerUid(installerUid); 9564 9565 final OriginInfo origin; 9566 if (stagedDir != null) { 9567 origin = OriginInfo.fromStagedFile(stagedDir); 9568 } else { 9569 origin = OriginInfo.fromStagedContainer(stagedCid); 9570 } 9571 9572 final Message msg = mHandler.obtainMessage(INIT_COPY); 9573 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9574 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9575 params.grantedRuntimePermissions); 9576 mHandler.sendMessage(msg); 9577 } 9578 9579 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9580 Bundle extras = new Bundle(1); 9581 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9582 9583 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9584 packageName, extras, null, null, new int[] {userId}); 9585 try { 9586 IActivityManager am = ActivityManagerNative.getDefault(); 9587 final boolean isSystem = 9588 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9589 if (isSystem && am.isUserRunning(userId, false)) { 9590 // The just-installed/enabled app is bundled on the system, so presumed 9591 // to be able to run automatically without needing an explicit launch. 9592 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9593 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9594 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9595 .setPackage(packageName); 9596 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9597 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9598 } 9599 } catch (RemoteException e) { 9600 // shouldn't happen 9601 Slog.w(TAG, "Unable to bootstrap installed package", e); 9602 } 9603 } 9604 9605 @Override 9606 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9607 int userId) { 9608 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9609 PackageSetting pkgSetting; 9610 final int uid = Binder.getCallingUid(); 9611 enforceCrossUserPermission(uid, userId, true, true, 9612 "setApplicationHiddenSetting for user " + userId); 9613 9614 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9615 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9616 return false; 9617 } 9618 9619 long callingId = Binder.clearCallingIdentity(); 9620 try { 9621 boolean sendAdded = false; 9622 boolean sendRemoved = false; 9623 // writer 9624 synchronized (mPackages) { 9625 pkgSetting = mSettings.mPackages.get(packageName); 9626 if (pkgSetting == null) { 9627 return false; 9628 } 9629 if (pkgSetting.getHidden(userId) != hidden) { 9630 pkgSetting.setHidden(hidden, userId); 9631 mSettings.writePackageRestrictionsLPr(userId); 9632 if (hidden) { 9633 sendRemoved = true; 9634 } else { 9635 sendAdded = true; 9636 } 9637 } 9638 } 9639 if (sendAdded) { 9640 sendPackageAddedForUser(packageName, pkgSetting, userId); 9641 return true; 9642 } 9643 if (sendRemoved) { 9644 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9645 "hiding pkg"); 9646 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9647 return true; 9648 } 9649 } finally { 9650 Binder.restoreCallingIdentity(callingId); 9651 } 9652 return false; 9653 } 9654 9655 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9656 int userId) { 9657 final PackageRemovedInfo info = new PackageRemovedInfo(); 9658 info.removedPackage = packageName; 9659 info.removedUsers = new int[] {userId}; 9660 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9661 info.sendBroadcast(false, false, false); 9662 } 9663 9664 /** 9665 * Returns true if application is not found or there was an error. Otherwise it returns 9666 * the hidden state of the package for the given user. 9667 */ 9668 @Override 9669 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9670 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9671 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9672 false, "getApplicationHidden for user " + userId); 9673 PackageSetting pkgSetting; 9674 long callingId = Binder.clearCallingIdentity(); 9675 try { 9676 // writer 9677 synchronized (mPackages) { 9678 pkgSetting = mSettings.mPackages.get(packageName); 9679 if (pkgSetting == null) { 9680 return true; 9681 } 9682 return pkgSetting.getHidden(userId); 9683 } 9684 } finally { 9685 Binder.restoreCallingIdentity(callingId); 9686 } 9687 } 9688 9689 /** 9690 * @hide 9691 */ 9692 @Override 9693 public int installExistingPackageAsUser(String packageName, int userId) { 9694 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9695 null); 9696 PackageSetting pkgSetting; 9697 final int uid = Binder.getCallingUid(); 9698 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9699 + userId); 9700 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9701 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9702 } 9703 9704 long callingId = Binder.clearCallingIdentity(); 9705 try { 9706 boolean sendAdded = false; 9707 9708 // writer 9709 synchronized (mPackages) { 9710 pkgSetting = mSettings.mPackages.get(packageName); 9711 if (pkgSetting == null) { 9712 return PackageManager.INSTALL_FAILED_INVALID_URI; 9713 } 9714 if (!pkgSetting.getInstalled(userId)) { 9715 pkgSetting.setInstalled(true, userId); 9716 pkgSetting.setHidden(false, userId); 9717 mSettings.writePackageRestrictionsLPr(userId); 9718 sendAdded = true; 9719 } 9720 } 9721 9722 if (sendAdded) { 9723 sendPackageAddedForUser(packageName, pkgSetting, userId); 9724 } 9725 } finally { 9726 Binder.restoreCallingIdentity(callingId); 9727 } 9728 9729 return PackageManager.INSTALL_SUCCEEDED; 9730 } 9731 9732 boolean isUserRestricted(int userId, String restrictionKey) { 9733 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9734 if (restrictions.getBoolean(restrictionKey, false)) { 9735 Log.w(TAG, "User is restricted: " + restrictionKey); 9736 return true; 9737 } 9738 return false; 9739 } 9740 9741 @Override 9742 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9743 mContext.enforceCallingOrSelfPermission( 9744 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9745 "Only package verification agents can verify applications"); 9746 9747 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9748 final PackageVerificationResponse response = new PackageVerificationResponse( 9749 verificationCode, Binder.getCallingUid()); 9750 msg.arg1 = id; 9751 msg.obj = response; 9752 mHandler.sendMessage(msg); 9753 } 9754 9755 @Override 9756 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9757 long millisecondsToDelay) { 9758 mContext.enforceCallingOrSelfPermission( 9759 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9760 "Only package verification agents can extend verification timeouts"); 9761 9762 final PackageVerificationState state = mPendingVerification.get(id); 9763 final PackageVerificationResponse response = new PackageVerificationResponse( 9764 verificationCodeAtTimeout, Binder.getCallingUid()); 9765 9766 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9767 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9768 } 9769 if (millisecondsToDelay < 0) { 9770 millisecondsToDelay = 0; 9771 } 9772 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9773 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9774 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9775 } 9776 9777 if ((state != null) && !state.timeoutExtended()) { 9778 state.extendTimeout(); 9779 9780 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9781 msg.arg1 = id; 9782 msg.obj = response; 9783 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9784 } 9785 } 9786 9787 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9788 int verificationCode, UserHandle user) { 9789 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9790 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9791 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9792 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9793 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9794 9795 mContext.sendBroadcastAsUser(intent, user, 9796 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9797 } 9798 9799 private ComponentName matchComponentForVerifier(String packageName, 9800 List<ResolveInfo> receivers) { 9801 ActivityInfo targetReceiver = null; 9802 9803 final int NR = receivers.size(); 9804 for (int i = 0; i < NR; i++) { 9805 final ResolveInfo info = receivers.get(i); 9806 if (info.activityInfo == null) { 9807 continue; 9808 } 9809 9810 if (packageName.equals(info.activityInfo.packageName)) { 9811 targetReceiver = info.activityInfo; 9812 break; 9813 } 9814 } 9815 9816 if (targetReceiver == null) { 9817 return null; 9818 } 9819 9820 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9821 } 9822 9823 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9824 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9825 if (pkgInfo.verifiers.length == 0) { 9826 return null; 9827 } 9828 9829 final int N = pkgInfo.verifiers.length; 9830 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9831 for (int i = 0; i < N; i++) { 9832 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9833 9834 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9835 receivers); 9836 if (comp == null) { 9837 continue; 9838 } 9839 9840 final int verifierUid = getUidForVerifier(verifierInfo); 9841 if (verifierUid == -1) { 9842 continue; 9843 } 9844 9845 if (DEBUG_VERIFY) { 9846 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9847 + " with the correct signature"); 9848 } 9849 sufficientVerifiers.add(comp); 9850 verificationState.addSufficientVerifier(verifierUid); 9851 } 9852 9853 return sufficientVerifiers; 9854 } 9855 9856 private int getUidForVerifier(VerifierInfo verifierInfo) { 9857 synchronized (mPackages) { 9858 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9859 if (pkg == null) { 9860 return -1; 9861 } else if (pkg.mSignatures.length != 1) { 9862 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9863 + " has more than one signature; ignoring"); 9864 return -1; 9865 } 9866 9867 /* 9868 * If the public key of the package's signature does not match 9869 * our expected public key, then this is a different package and 9870 * we should skip. 9871 */ 9872 9873 final byte[] expectedPublicKey; 9874 try { 9875 final Signature verifierSig = pkg.mSignatures[0]; 9876 final PublicKey publicKey = verifierSig.getPublicKey(); 9877 expectedPublicKey = publicKey.getEncoded(); 9878 } catch (CertificateException e) { 9879 return -1; 9880 } 9881 9882 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9883 9884 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9885 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9886 + " does not have the expected public key; ignoring"); 9887 return -1; 9888 } 9889 9890 return pkg.applicationInfo.uid; 9891 } 9892 } 9893 9894 @Override 9895 public void finishPackageInstall(int token) { 9896 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9897 9898 if (DEBUG_INSTALL) { 9899 Slog.v(TAG, "BM finishing package install for " + token); 9900 } 9901 9902 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9903 mHandler.sendMessage(msg); 9904 } 9905 9906 /** 9907 * Get the verification agent timeout. 9908 * 9909 * @return verification timeout in milliseconds 9910 */ 9911 private long getVerificationTimeout() { 9912 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9913 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9914 DEFAULT_VERIFICATION_TIMEOUT); 9915 } 9916 9917 /** 9918 * Get the default verification agent response code. 9919 * 9920 * @return default verification response code 9921 */ 9922 private int getDefaultVerificationResponse() { 9923 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9924 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9925 DEFAULT_VERIFICATION_RESPONSE); 9926 } 9927 9928 /** 9929 * Check whether or not package verification has been enabled. 9930 * 9931 * @return true if verification should be performed 9932 */ 9933 private boolean isVerificationEnabled(int userId, int installFlags) { 9934 if (!DEFAULT_VERIFY_ENABLE) { 9935 return false; 9936 } 9937 9938 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9939 9940 // Check if installing from ADB 9941 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9942 // Do not run verification in a test harness environment 9943 if (ActivityManager.isRunningInTestHarness()) { 9944 return false; 9945 } 9946 if (ensureVerifyAppsEnabled) { 9947 return true; 9948 } 9949 // Check if the developer does not want package verification for ADB installs 9950 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9951 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9952 return false; 9953 } 9954 } 9955 9956 if (ensureVerifyAppsEnabled) { 9957 return true; 9958 } 9959 9960 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9961 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9962 } 9963 9964 @Override 9965 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9966 throws RemoteException { 9967 mContext.enforceCallingOrSelfPermission( 9968 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9969 "Only intentfilter verification agents can verify applications"); 9970 9971 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9972 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9973 Binder.getCallingUid(), verificationCode, failedDomains); 9974 msg.arg1 = id; 9975 msg.obj = response; 9976 mHandler.sendMessage(msg); 9977 } 9978 9979 @Override 9980 public int getIntentVerificationStatus(String packageName, int userId) { 9981 synchronized (mPackages) { 9982 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9983 } 9984 } 9985 9986 @Override 9987 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9988 mContext.enforceCallingOrSelfPermission( 9989 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9990 9991 boolean result = false; 9992 synchronized (mPackages) { 9993 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9994 } 9995 if (result) { 9996 scheduleWritePackageRestrictionsLocked(userId); 9997 } 9998 return result; 9999 } 10000 10001 @Override 10002 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10003 synchronized (mPackages) { 10004 return mSettings.getIntentFilterVerificationsLPr(packageName); 10005 } 10006 } 10007 10008 @Override 10009 public List<IntentFilter> getAllIntentFilters(String packageName) { 10010 if (TextUtils.isEmpty(packageName)) { 10011 return Collections.<IntentFilter>emptyList(); 10012 } 10013 synchronized (mPackages) { 10014 PackageParser.Package pkg = mPackages.get(packageName); 10015 if (pkg == null || pkg.activities == null) { 10016 return Collections.<IntentFilter>emptyList(); 10017 } 10018 final int count = pkg.activities.size(); 10019 ArrayList<IntentFilter> result = new ArrayList<>(); 10020 for (int n=0; n<count; n++) { 10021 PackageParser.Activity activity = pkg.activities.get(n); 10022 if (activity.intents != null || activity.intents.size() > 0) { 10023 result.addAll(activity.intents); 10024 } 10025 } 10026 return result; 10027 } 10028 } 10029 10030 @Override 10031 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10032 mContext.enforceCallingOrSelfPermission( 10033 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10034 10035 synchronized (mPackages) { 10036 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10037 if (packageName != null) { 10038 result |= updateIntentVerificationStatus(packageName, 10039 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10040 userId); 10041 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10042 packageName, userId); 10043 } 10044 return result; 10045 } 10046 } 10047 10048 @Override 10049 public String getDefaultBrowserPackageName(int userId) { 10050 synchronized (mPackages) { 10051 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10052 } 10053 } 10054 10055 /** 10056 * Get the "allow unknown sources" setting. 10057 * 10058 * @return the current "allow unknown sources" setting 10059 */ 10060 private int getUnknownSourcesSettings() { 10061 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10062 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10063 -1); 10064 } 10065 10066 @Override 10067 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10068 final int uid = Binder.getCallingUid(); 10069 // writer 10070 synchronized (mPackages) { 10071 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10072 if (targetPackageSetting == null) { 10073 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10074 } 10075 10076 PackageSetting installerPackageSetting; 10077 if (installerPackageName != null) { 10078 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10079 if (installerPackageSetting == null) { 10080 throw new IllegalArgumentException("Unknown installer package: " 10081 + installerPackageName); 10082 } 10083 } else { 10084 installerPackageSetting = null; 10085 } 10086 10087 Signature[] callerSignature; 10088 Object obj = mSettings.getUserIdLPr(uid); 10089 if (obj != null) { 10090 if (obj instanceof SharedUserSetting) { 10091 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10092 } else if (obj instanceof PackageSetting) { 10093 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10094 } else { 10095 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10096 } 10097 } else { 10098 throw new SecurityException("Unknown calling uid " + uid); 10099 } 10100 10101 // Verify: can't set installerPackageName to a package that is 10102 // not signed with the same cert as the caller. 10103 if (installerPackageSetting != null) { 10104 if (compareSignatures(callerSignature, 10105 installerPackageSetting.signatures.mSignatures) 10106 != PackageManager.SIGNATURE_MATCH) { 10107 throw new SecurityException( 10108 "Caller does not have same cert as new installer package " 10109 + installerPackageName); 10110 } 10111 } 10112 10113 // Verify: if target already has an installer package, it must 10114 // be signed with the same cert as the caller. 10115 if (targetPackageSetting.installerPackageName != null) { 10116 PackageSetting setting = mSettings.mPackages.get( 10117 targetPackageSetting.installerPackageName); 10118 // If the currently set package isn't valid, then it's always 10119 // okay to change it. 10120 if (setting != null) { 10121 if (compareSignatures(callerSignature, 10122 setting.signatures.mSignatures) 10123 != PackageManager.SIGNATURE_MATCH) { 10124 throw new SecurityException( 10125 "Caller does not have same cert as old installer package " 10126 + targetPackageSetting.installerPackageName); 10127 } 10128 } 10129 } 10130 10131 // Okay! 10132 targetPackageSetting.installerPackageName = installerPackageName; 10133 scheduleWriteSettingsLocked(); 10134 } 10135 } 10136 10137 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10138 // Queue up an async operation since the package installation may take a little while. 10139 mHandler.post(new Runnable() { 10140 public void run() { 10141 mHandler.removeCallbacks(this); 10142 // Result object to be returned 10143 PackageInstalledInfo res = new PackageInstalledInfo(); 10144 res.returnCode = currentStatus; 10145 res.uid = -1; 10146 res.pkg = null; 10147 res.removedInfo = new PackageRemovedInfo(); 10148 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10149 args.doPreInstall(res.returnCode); 10150 synchronized (mInstallLock) { 10151 installPackageLI(args, res); 10152 } 10153 args.doPostInstall(res.returnCode, res.uid); 10154 } 10155 10156 // A restore should be performed at this point if (a) the install 10157 // succeeded, (b) the operation is not an update, and (c) the new 10158 // package has not opted out of backup participation. 10159 final boolean update = res.removedInfo.removedPackage != null; 10160 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10161 boolean doRestore = !update 10162 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10163 10164 // Set up the post-install work request bookkeeping. This will be used 10165 // and cleaned up by the post-install event handling regardless of whether 10166 // there's a restore pass performed. Token values are >= 1. 10167 int token; 10168 if (mNextInstallToken < 0) mNextInstallToken = 1; 10169 token = mNextInstallToken++; 10170 10171 PostInstallData data = new PostInstallData(args, res); 10172 mRunningInstalls.put(token, data); 10173 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10174 10175 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10176 // Pass responsibility to the Backup Manager. It will perform a 10177 // restore if appropriate, then pass responsibility back to the 10178 // Package Manager to run the post-install observer callbacks 10179 // and broadcasts. 10180 IBackupManager bm = IBackupManager.Stub.asInterface( 10181 ServiceManager.getService(Context.BACKUP_SERVICE)); 10182 if (bm != null) { 10183 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10184 + " to BM for possible restore"); 10185 try { 10186 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10187 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10188 } else { 10189 doRestore = false; 10190 } 10191 } catch (RemoteException e) { 10192 // can't happen; the backup manager is local 10193 } catch (Exception e) { 10194 Slog.e(TAG, "Exception trying to enqueue restore", e); 10195 doRestore = false; 10196 } 10197 } else { 10198 Slog.e(TAG, "Backup Manager not found!"); 10199 doRestore = false; 10200 } 10201 } 10202 10203 if (!doRestore) { 10204 // No restore possible, or the Backup Manager was mysteriously not 10205 // available -- just fire the post-install work request directly. 10206 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10207 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10208 mHandler.sendMessage(msg); 10209 } 10210 } 10211 }); 10212 } 10213 10214 private abstract class HandlerParams { 10215 private static final int MAX_RETRIES = 4; 10216 10217 /** 10218 * Number of times startCopy() has been attempted and had a non-fatal 10219 * error. 10220 */ 10221 private int mRetries = 0; 10222 10223 /** User handle for the user requesting the information or installation. */ 10224 private final UserHandle mUser; 10225 10226 HandlerParams(UserHandle user) { 10227 mUser = user; 10228 } 10229 10230 UserHandle getUser() { 10231 return mUser; 10232 } 10233 10234 final boolean startCopy() { 10235 boolean res; 10236 try { 10237 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10238 10239 if (++mRetries > MAX_RETRIES) { 10240 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10241 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10242 handleServiceError(); 10243 return false; 10244 } else { 10245 handleStartCopy(); 10246 res = true; 10247 } 10248 } catch (RemoteException e) { 10249 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10250 mHandler.sendEmptyMessage(MCS_RECONNECT); 10251 res = false; 10252 } 10253 handleReturnCode(); 10254 return res; 10255 } 10256 10257 final void serviceError() { 10258 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10259 handleServiceError(); 10260 handleReturnCode(); 10261 } 10262 10263 abstract void handleStartCopy() throws RemoteException; 10264 abstract void handleServiceError(); 10265 abstract void handleReturnCode(); 10266 } 10267 10268 class MeasureParams extends HandlerParams { 10269 private final PackageStats mStats; 10270 private boolean mSuccess; 10271 10272 private final IPackageStatsObserver mObserver; 10273 10274 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10275 super(new UserHandle(stats.userHandle)); 10276 mObserver = observer; 10277 mStats = stats; 10278 } 10279 10280 @Override 10281 public String toString() { 10282 return "MeasureParams{" 10283 + Integer.toHexString(System.identityHashCode(this)) 10284 + " " + mStats.packageName + "}"; 10285 } 10286 10287 @Override 10288 void handleStartCopy() throws RemoteException { 10289 synchronized (mInstallLock) { 10290 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10291 } 10292 10293 if (mSuccess) { 10294 final boolean mounted; 10295 if (Environment.isExternalStorageEmulated()) { 10296 mounted = true; 10297 } else { 10298 final String status = Environment.getExternalStorageState(); 10299 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10300 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10301 } 10302 10303 if (mounted) { 10304 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10305 10306 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10307 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10308 10309 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10310 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10311 10312 // Always subtract cache size, since it's a subdirectory 10313 mStats.externalDataSize -= mStats.externalCacheSize; 10314 10315 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10316 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10317 10318 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10319 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10320 } 10321 } 10322 } 10323 10324 @Override 10325 void handleReturnCode() { 10326 if (mObserver != null) { 10327 try { 10328 mObserver.onGetStatsCompleted(mStats, mSuccess); 10329 } catch (RemoteException e) { 10330 Slog.i(TAG, "Observer no longer exists."); 10331 } 10332 } 10333 } 10334 10335 @Override 10336 void handleServiceError() { 10337 Slog.e(TAG, "Could not measure application " + mStats.packageName 10338 + " external storage"); 10339 } 10340 } 10341 10342 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10343 throws RemoteException { 10344 long result = 0; 10345 for (File path : paths) { 10346 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10347 } 10348 return result; 10349 } 10350 10351 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10352 for (File path : paths) { 10353 try { 10354 mcs.clearDirectory(path.getAbsolutePath()); 10355 } catch (RemoteException e) { 10356 } 10357 } 10358 } 10359 10360 static class OriginInfo { 10361 /** 10362 * Location where install is coming from, before it has been 10363 * copied/renamed into place. This could be a single monolithic APK 10364 * file, or a cluster directory. This location may be untrusted. 10365 */ 10366 final File file; 10367 final String cid; 10368 10369 /** 10370 * Flag indicating that {@link #file} or {@link #cid} has already been 10371 * staged, meaning downstream users don't need to defensively copy the 10372 * contents. 10373 */ 10374 final boolean staged; 10375 10376 /** 10377 * Flag indicating that {@link #file} or {@link #cid} is an already 10378 * installed app that is being moved. 10379 */ 10380 final boolean existing; 10381 10382 final String resolvedPath; 10383 final File resolvedFile; 10384 10385 static OriginInfo fromNothing() { 10386 return new OriginInfo(null, null, false, false); 10387 } 10388 10389 static OriginInfo fromUntrustedFile(File file) { 10390 return new OriginInfo(file, null, false, false); 10391 } 10392 10393 static OriginInfo fromExistingFile(File file) { 10394 return new OriginInfo(file, null, false, true); 10395 } 10396 10397 static OriginInfo fromStagedFile(File file) { 10398 return new OriginInfo(file, null, true, false); 10399 } 10400 10401 static OriginInfo fromStagedContainer(String cid) { 10402 return new OriginInfo(null, cid, true, false); 10403 } 10404 10405 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10406 this.file = file; 10407 this.cid = cid; 10408 this.staged = staged; 10409 this.existing = existing; 10410 10411 if (cid != null) { 10412 resolvedPath = PackageHelper.getSdDir(cid); 10413 resolvedFile = new File(resolvedPath); 10414 } else if (file != null) { 10415 resolvedPath = file.getAbsolutePath(); 10416 resolvedFile = file; 10417 } else { 10418 resolvedPath = null; 10419 resolvedFile = null; 10420 } 10421 } 10422 } 10423 10424 class MoveInfo { 10425 final int moveId; 10426 final String fromUuid; 10427 final String toUuid; 10428 final String packageName; 10429 final String dataAppName; 10430 final int appId; 10431 final String seinfo; 10432 10433 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10434 String dataAppName, int appId, String seinfo) { 10435 this.moveId = moveId; 10436 this.fromUuid = fromUuid; 10437 this.toUuid = toUuid; 10438 this.packageName = packageName; 10439 this.dataAppName = dataAppName; 10440 this.appId = appId; 10441 this.seinfo = seinfo; 10442 } 10443 } 10444 10445 class InstallParams extends HandlerParams { 10446 final OriginInfo origin; 10447 final MoveInfo move; 10448 final IPackageInstallObserver2 observer; 10449 int installFlags; 10450 final String installerPackageName; 10451 final String volumeUuid; 10452 final VerificationParams verificationParams; 10453 private InstallArgs mArgs; 10454 private int mRet; 10455 final String packageAbiOverride; 10456 final String[] grantedRuntimePermissions; 10457 10458 10459 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10460 int installFlags, String installerPackageName, String volumeUuid, 10461 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10462 String[] grantedPermissions) { 10463 super(user); 10464 this.origin = origin; 10465 this.move = move; 10466 this.observer = observer; 10467 this.installFlags = installFlags; 10468 this.installerPackageName = installerPackageName; 10469 this.volumeUuid = volumeUuid; 10470 this.verificationParams = verificationParams; 10471 this.packageAbiOverride = packageAbiOverride; 10472 this.grantedRuntimePermissions = grantedPermissions; 10473 } 10474 10475 @Override 10476 public String toString() { 10477 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10478 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10479 } 10480 10481 public ManifestDigest getManifestDigest() { 10482 if (verificationParams == null) { 10483 return null; 10484 } 10485 return verificationParams.getManifestDigest(); 10486 } 10487 10488 private int installLocationPolicy(PackageInfoLite pkgLite) { 10489 String packageName = pkgLite.packageName; 10490 int installLocation = pkgLite.installLocation; 10491 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10492 // reader 10493 synchronized (mPackages) { 10494 PackageParser.Package pkg = mPackages.get(packageName); 10495 if (pkg != null) { 10496 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10497 // Check for downgrading. 10498 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10499 try { 10500 checkDowngrade(pkg, pkgLite); 10501 } catch (PackageManagerException e) { 10502 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10503 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10504 } 10505 } 10506 // Check for updated system application. 10507 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10508 if (onSd) { 10509 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10510 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10511 } 10512 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10513 } else { 10514 if (onSd) { 10515 // Install flag overrides everything. 10516 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10517 } 10518 // If current upgrade specifies particular preference 10519 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10520 // Application explicitly specified internal. 10521 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10522 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10523 // App explictly prefers external. Let policy decide 10524 } else { 10525 // Prefer previous location 10526 if (isExternal(pkg)) { 10527 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10528 } 10529 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10530 } 10531 } 10532 } else { 10533 // Invalid install. Return error code 10534 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10535 } 10536 } 10537 } 10538 // All the special cases have been taken care of. 10539 // Return result based on recommended install location. 10540 if (onSd) { 10541 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10542 } 10543 return pkgLite.recommendedInstallLocation; 10544 } 10545 10546 /* 10547 * Invoke remote method to get package information and install 10548 * location values. Override install location based on default 10549 * policy if needed and then create install arguments based 10550 * on the install location. 10551 */ 10552 public void handleStartCopy() throws RemoteException { 10553 int ret = PackageManager.INSTALL_SUCCEEDED; 10554 10555 // If we're already staged, we've firmly committed to an install location 10556 if (origin.staged) { 10557 if (origin.file != null) { 10558 installFlags |= PackageManager.INSTALL_INTERNAL; 10559 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10560 } else if (origin.cid != null) { 10561 installFlags |= PackageManager.INSTALL_EXTERNAL; 10562 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10563 } else { 10564 throw new IllegalStateException("Invalid stage location"); 10565 } 10566 } 10567 10568 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10569 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10570 10571 PackageInfoLite pkgLite = null; 10572 10573 if (onInt && onSd) { 10574 // Check if both bits are set. 10575 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10576 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10577 } else { 10578 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10579 packageAbiOverride); 10580 10581 /* 10582 * If we have too little free space, try to free cache 10583 * before giving up. 10584 */ 10585 if (!origin.staged && pkgLite.recommendedInstallLocation 10586 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10587 // TODO: focus freeing disk space on the target device 10588 final StorageManager storage = StorageManager.from(mContext); 10589 final long lowThreshold = storage.getStorageLowBytes( 10590 Environment.getDataDirectory()); 10591 10592 final long sizeBytes = mContainerService.calculateInstalledSize( 10593 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10594 10595 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10596 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10597 installFlags, packageAbiOverride); 10598 } 10599 10600 /* 10601 * The cache free must have deleted the file we 10602 * downloaded to install. 10603 * 10604 * TODO: fix the "freeCache" call to not delete 10605 * the file we care about. 10606 */ 10607 if (pkgLite.recommendedInstallLocation 10608 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10609 pkgLite.recommendedInstallLocation 10610 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10611 } 10612 } 10613 } 10614 10615 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10616 int loc = pkgLite.recommendedInstallLocation; 10617 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10618 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10619 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10620 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10621 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10622 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10623 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10624 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10625 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10626 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10627 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10628 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10629 } else { 10630 // Override with defaults if needed. 10631 loc = installLocationPolicy(pkgLite); 10632 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10633 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10634 } else if (!onSd && !onInt) { 10635 // Override install location with flags 10636 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10637 // Set the flag to install on external media. 10638 installFlags |= PackageManager.INSTALL_EXTERNAL; 10639 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10640 } else { 10641 // Make sure the flag for installing on external 10642 // media is unset 10643 installFlags |= PackageManager.INSTALL_INTERNAL; 10644 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10645 } 10646 } 10647 } 10648 } 10649 10650 final InstallArgs args = createInstallArgs(this); 10651 mArgs = args; 10652 10653 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10654 /* 10655 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10656 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10657 */ 10658 int userIdentifier = getUser().getIdentifier(); 10659 if (userIdentifier == UserHandle.USER_ALL 10660 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10661 userIdentifier = UserHandle.USER_OWNER; 10662 } 10663 10664 /* 10665 * Determine if we have any installed package verifiers. If we 10666 * do, then we'll defer to them to verify the packages. 10667 */ 10668 final int requiredUid = mRequiredVerifierPackage == null ? -1 10669 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10670 if (!origin.existing && requiredUid != -1 10671 && isVerificationEnabled(userIdentifier, installFlags)) { 10672 final Intent verification = new Intent( 10673 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10674 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10675 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10676 PACKAGE_MIME_TYPE); 10677 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10678 10679 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10680 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10681 0 /* TODO: Which userId? */); 10682 10683 if (DEBUG_VERIFY) { 10684 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10685 + verification.toString() + " with " + pkgLite.verifiers.length 10686 + " optional verifiers"); 10687 } 10688 10689 final int verificationId = mPendingVerificationToken++; 10690 10691 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10692 10693 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10694 installerPackageName); 10695 10696 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10697 installFlags); 10698 10699 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10700 pkgLite.packageName); 10701 10702 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10703 pkgLite.versionCode); 10704 10705 if (verificationParams != null) { 10706 if (verificationParams.getVerificationURI() != null) { 10707 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10708 verificationParams.getVerificationURI()); 10709 } 10710 if (verificationParams.getOriginatingURI() != null) { 10711 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10712 verificationParams.getOriginatingURI()); 10713 } 10714 if (verificationParams.getReferrer() != null) { 10715 verification.putExtra(Intent.EXTRA_REFERRER, 10716 verificationParams.getReferrer()); 10717 } 10718 if (verificationParams.getOriginatingUid() >= 0) { 10719 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10720 verificationParams.getOriginatingUid()); 10721 } 10722 if (verificationParams.getInstallerUid() >= 0) { 10723 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10724 verificationParams.getInstallerUid()); 10725 } 10726 } 10727 10728 final PackageVerificationState verificationState = new PackageVerificationState( 10729 requiredUid, args); 10730 10731 mPendingVerification.append(verificationId, verificationState); 10732 10733 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10734 receivers, verificationState); 10735 10736 // Apps installed for "all" users use the device owner to verify the app 10737 UserHandle verifierUser = getUser(); 10738 if (verifierUser == UserHandle.ALL) { 10739 verifierUser = UserHandle.OWNER; 10740 } 10741 10742 /* 10743 * If any sufficient verifiers were listed in the package 10744 * manifest, attempt to ask them. 10745 */ 10746 if (sufficientVerifiers != null) { 10747 final int N = sufficientVerifiers.size(); 10748 if (N == 0) { 10749 Slog.i(TAG, "Additional verifiers required, but none installed."); 10750 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10751 } else { 10752 for (int i = 0; i < N; i++) { 10753 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10754 10755 final Intent sufficientIntent = new Intent(verification); 10756 sufficientIntent.setComponent(verifierComponent); 10757 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10758 } 10759 } 10760 } 10761 10762 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10763 mRequiredVerifierPackage, receivers); 10764 if (ret == PackageManager.INSTALL_SUCCEEDED 10765 && mRequiredVerifierPackage != null) { 10766 /* 10767 * Send the intent to the required verification agent, 10768 * but only start the verification timeout after the 10769 * target BroadcastReceivers have run. 10770 */ 10771 verification.setComponent(requiredVerifierComponent); 10772 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10773 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10774 new BroadcastReceiver() { 10775 @Override 10776 public void onReceive(Context context, Intent intent) { 10777 final Message msg = mHandler 10778 .obtainMessage(CHECK_PENDING_VERIFICATION); 10779 msg.arg1 = verificationId; 10780 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10781 } 10782 }, null, 0, null, null); 10783 10784 /* 10785 * We don't want the copy to proceed until verification 10786 * succeeds, so null out this field. 10787 */ 10788 mArgs = null; 10789 } 10790 } else { 10791 /* 10792 * No package verification is enabled, so immediately start 10793 * the remote call to initiate copy using temporary file. 10794 */ 10795 ret = args.copyApk(mContainerService, true); 10796 } 10797 } 10798 10799 mRet = ret; 10800 } 10801 10802 @Override 10803 void handleReturnCode() { 10804 // If mArgs is null, then MCS couldn't be reached. When it 10805 // reconnects, it will try again to install. At that point, this 10806 // will succeed. 10807 if (mArgs != null) { 10808 processPendingInstall(mArgs, mRet); 10809 } 10810 } 10811 10812 @Override 10813 void handleServiceError() { 10814 mArgs = createInstallArgs(this); 10815 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10816 } 10817 10818 public boolean isForwardLocked() { 10819 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10820 } 10821 } 10822 10823 /** 10824 * Used during creation of InstallArgs 10825 * 10826 * @param installFlags package installation flags 10827 * @return true if should be installed on external storage 10828 */ 10829 private static boolean installOnExternalAsec(int installFlags) { 10830 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10831 return false; 10832 } 10833 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10834 return true; 10835 } 10836 return false; 10837 } 10838 10839 /** 10840 * Used during creation of InstallArgs 10841 * 10842 * @param installFlags package installation flags 10843 * @return true if should be installed as forward locked 10844 */ 10845 private static boolean installForwardLocked(int installFlags) { 10846 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10847 } 10848 10849 private InstallArgs createInstallArgs(InstallParams params) { 10850 if (params.move != null) { 10851 return new MoveInstallArgs(params); 10852 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10853 return new AsecInstallArgs(params); 10854 } else { 10855 return new FileInstallArgs(params); 10856 } 10857 } 10858 10859 /** 10860 * Create args that describe an existing installed package. Typically used 10861 * when cleaning up old installs, or used as a move source. 10862 */ 10863 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10864 String resourcePath, String[] instructionSets) { 10865 final boolean isInAsec; 10866 if (installOnExternalAsec(installFlags)) { 10867 /* Apps on SD card are always in ASEC containers. */ 10868 isInAsec = true; 10869 } else if (installForwardLocked(installFlags) 10870 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10871 /* 10872 * Forward-locked apps are only in ASEC containers if they're the 10873 * new style 10874 */ 10875 isInAsec = true; 10876 } else { 10877 isInAsec = false; 10878 } 10879 10880 if (isInAsec) { 10881 return new AsecInstallArgs(codePath, instructionSets, 10882 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10883 } else { 10884 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10885 } 10886 } 10887 10888 static abstract class InstallArgs { 10889 /** @see InstallParams#origin */ 10890 final OriginInfo origin; 10891 /** @see InstallParams#move */ 10892 final MoveInfo move; 10893 10894 final IPackageInstallObserver2 observer; 10895 // Always refers to PackageManager flags only 10896 final int installFlags; 10897 final String installerPackageName; 10898 final String volumeUuid; 10899 final ManifestDigest manifestDigest; 10900 final UserHandle user; 10901 final String abiOverride; 10902 final String[] installGrantPermissions; 10903 10904 // The list of instruction sets supported by this app. This is currently 10905 // only used during the rmdex() phase to clean up resources. We can get rid of this 10906 // if we move dex files under the common app path. 10907 /* nullable */ String[] instructionSets; 10908 10909 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10910 int installFlags, String installerPackageName, String volumeUuid, 10911 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10912 String abiOverride, String[] installGrantPermissions) { 10913 this.origin = origin; 10914 this.move = move; 10915 this.installFlags = installFlags; 10916 this.observer = observer; 10917 this.installerPackageName = installerPackageName; 10918 this.volumeUuid = volumeUuid; 10919 this.manifestDigest = manifestDigest; 10920 this.user = user; 10921 this.instructionSets = instructionSets; 10922 this.abiOverride = abiOverride; 10923 this.installGrantPermissions = installGrantPermissions; 10924 } 10925 10926 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10927 abstract int doPreInstall(int status); 10928 10929 /** 10930 * Rename package into final resting place. All paths on the given 10931 * scanned package should be updated to reflect the rename. 10932 */ 10933 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10934 abstract int doPostInstall(int status, int uid); 10935 10936 /** @see PackageSettingBase#codePathString */ 10937 abstract String getCodePath(); 10938 /** @see PackageSettingBase#resourcePathString */ 10939 abstract String getResourcePath(); 10940 10941 // Need installer lock especially for dex file removal. 10942 abstract void cleanUpResourcesLI(); 10943 abstract boolean doPostDeleteLI(boolean delete); 10944 10945 /** 10946 * Called before the source arguments are copied. This is used mostly 10947 * for MoveParams when it needs to read the source file to put it in the 10948 * destination. 10949 */ 10950 int doPreCopy() { 10951 return PackageManager.INSTALL_SUCCEEDED; 10952 } 10953 10954 /** 10955 * Called after the source arguments are copied. This is used mostly for 10956 * MoveParams when it needs to read the source file to put it in the 10957 * destination. 10958 * 10959 * @return 10960 */ 10961 int doPostCopy(int uid) { 10962 return PackageManager.INSTALL_SUCCEEDED; 10963 } 10964 10965 protected boolean isFwdLocked() { 10966 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10967 } 10968 10969 protected boolean isExternalAsec() { 10970 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10971 } 10972 10973 UserHandle getUser() { 10974 return user; 10975 } 10976 } 10977 10978 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10979 if (!allCodePaths.isEmpty()) { 10980 if (instructionSets == null) { 10981 throw new IllegalStateException("instructionSet == null"); 10982 } 10983 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10984 for (String codePath : allCodePaths) { 10985 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10986 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10987 if (retCode < 0) { 10988 Slog.w(TAG, "Couldn't remove dex file for package: " 10989 + " at location " + codePath + ", retcode=" + retCode); 10990 // we don't consider this to be a failure of the core package deletion 10991 } 10992 } 10993 } 10994 } 10995 } 10996 10997 /** 10998 * Logic to handle installation of non-ASEC applications, including copying 10999 * and renaming logic. 11000 */ 11001 class FileInstallArgs extends InstallArgs { 11002 private File codeFile; 11003 private File resourceFile; 11004 11005 // Example topology: 11006 // /data/app/com.example/base.apk 11007 // /data/app/com.example/split_foo.apk 11008 // /data/app/com.example/lib/arm/libfoo.so 11009 // /data/app/com.example/lib/arm64/libfoo.so 11010 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11011 11012 /** New install */ 11013 FileInstallArgs(InstallParams params) { 11014 super(params.origin, params.move, params.observer, params.installFlags, 11015 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11016 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11017 params.grantedRuntimePermissions); 11018 if (isFwdLocked()) { 11019 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11020 } 11021 } 11022 11023 /** Existing install */ 11024 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11025 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11026 null, null); 11027 this.codeFile = (codePath != null) ? new File(codePath) : null; 11028 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11029 } 11030 11031 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11032 if (origin.staged) { 11033 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11034 codeFile = origin.file; 11035 resourceFile = origin.file; 11036 return PackageManager.INSTALL_SUCCEEDED; 11037 } 11038 11039 try { 11040 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11041 codeFile = tempDir; 11042 resourceFile = tempDir; 11043 } catch (IOException e) { 11044 Slog.w(TAG, "Failed to create copy file: " + e); 11045 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11046 } 11047 11048 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11049 @Override 11050 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11051 if (!FileUtils.isValidExtFilename(name)) { 11052 throw new IllegalArgumentException("Invalid filename: " + name); 11053 } 11054 try { 11055 final File file = new File(codeFile, name); 11056 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11057 O_RDWR | O_CREAT, 0644); 11058 Os.chmod(file.getAbsolutePath(), 0644); 11059 return new ParcelFileDescriptor(fd); 11060 } catch (ErrnoException e) { 11061 throw new RemoteException("Failed to open: " + e.getMessage()); 11062 } 11063 } 11064 }; 11065 11066 int ret = PackageManager.INSTALL_SUCCEEDED; 11067 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11068 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11069 Slog.e(TAG, "Failed to copy package"); 11070 return ret; 11071 } 11072 11073 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11074 NativeLibraryHelper.Handle handle = null; 11075 try { 11076 handle = NativeLibraryHelper.Handle.create(codeFile); 11077 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11078 abiOverride); 11079 } catch (IOException e) { 11080 Slog.e(TAG, "Copying native libraries failed", e); 11081 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11082 } finally { 11083 IoUtils.closeQuietly(handle); 11084 } 11085 11086 return ret; 11087 } 11088 11089 int doPreInstall(int status) { 11090 if (status != PackageManager.INSTALL_SUCCEEDED) { 11091 cleanUp(); 11092 } 11093 return status; 11094 } 11095 11096 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11097 if (status != PackageManager.INSTALL_SUCCEEDED) { 11098 cleanUp(); 11099 return false; 11100 } 11101 11102 final File targetDir = codeFile.getParentFile(); 11103 final File beforeCodeFile = codeFile; 11104 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11105 11106 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11107 try { 11108 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11109 } catch (ErrnoException e) { 11110 Slog.w(TAG, "Failed to rename", e); 11111 return false; 11112 } 11113 11114 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11115 Slog.w(TAG, "Failed to restorecon"); 11116 return false; 11117 } 11118 11119 // Reflect the rename internally 11120 codeFile = afterCodeFile; 11121 resourceFile = afterCodeFile; 11122 11123 // Reflect the rename in scanned details 11124 pkg.codePath = afterCodeFile.getAbsolutePath(); 11125 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11126 pkg.baseCodePath); 11127 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11128 pkg.splitCodePaths); 11129 11130 // Reflect the rename in app info 11131 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11132 pkg.applicationInfo.setCodePath(pkg.codePath); 11133 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11134 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11135 pkg.applicationInfo.setResourcePath(pkg.codePath); 11136 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11137 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11138 11139 return true; 11140 } 11141 11142 int doPostInstall(int status, int uid) { 11143 if (status != PackageManager.INSTALL_SUCCEEDED) { 11144 cleanUp(); 11145 } 11146 return status; 11147 } 11148 11149 @Override 11150 String getCodePath() { 11151 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11152 } 11153 11154 @Override 11155 String getResourcePath() { 11156 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11157 } 11158 11159 private boolean cleanUp() { 11160 if (codeFile == null || !codeFile.exists()) { 11161 return false; 11162 } 11163 11164 if (codeFile.isDirectory()) { 11165 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11166 } else { 11167 codeFile.delete(); 11168 } 11169 11170 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11171 resourceFile.delete(); 11172 } 11173 11174 return true; 11175 } 11176 11177 void cleanUpResourcesLI() { 11178 // Try enumerating all code paths before deleting 11179 List<String> allCodePaths = Collections.EMPTY_LIST; 11180 if (codeFile != null && codeFile.exists()) { 11181 try { 11182 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11183 allCodePaths = pkg.getAllCodePaths(); 11184 } catch (PackageParserException e) { 11185 // Ignored; we tried our best 11186 } 11187 } 11188 11189 cleanUp(); 11190 removeDexFiles(allCodePaths, instructionSets); 11191 } 11192 11193 boolean doPostDeleteLI(boolean delete) { 11194 // XXX err, shouldn't we respect the delete flag? 11195 cleanUpResourcesLI(); 11196 return true; 11197 } 11198 } 11199 11200 private boolean isAsecExternal(String cid) { 11201 final String asecPath = PackageHelper.getSdFilesystem(cid); 11202 return !asecPath.startsWith(mAsecInternalPath); 11203 } 11204 11205 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11206 PackageManagerException { 11207 if (copyRet < 0) { 11208 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11209 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11210 throw new PackageManagerException(copyRet, message); 11211 } 11212 } 11213 } 11214 11215 /** 11216 * Extract the MountService "container ID" from the full code path of an 11217 * .apk. 11218 */ 11219 static String cidFromCodePath(String fullCodePath) { 11220 int eidx = fullCodePath.lastIndexOf("/"); 11221 String subStr1 = fullCodePath.substring(0, eidx); 11222 int sidx = subStr1.lastIndexOf("/"); 11223 return subStr1.substring(sidx+1, eidx); 11224 } 11225 11226 /** 11227 * Logic to handle installation of ASEC applications, including copying and 11228 * renaming logic. 11229 */ 11230 class AsecInstallArgs extends InstallArgs { 11231 static final String RES_FILE_NAME = "pkg.apk"; 11232 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11233 11234 String cid; 11235 String packagePath; 11236 String resourcePath; 11237 11238 /** New install */ 11239 AsecInstallArgs(InstallParams params) { 11240 super(params.origin, params.move, params.observer, params.installFlags, 11241 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11242 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11243 params.grantedRuntimePermissions); 11244 } 11245 11246 /** Existing install */ 11247 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11248 boolean isExternal, boolean isForwardLocked) { 11249 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11250 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11251 instructionSets, null, null); 11252 // Hackily pretend we're still looking at a full code path 11253 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11254 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11255 } 11256 11257 // Extract cid from fullCodePath 11258 int eidx = fullCodePath.lastIndexOf("/"); 11259 String subStr1 = fullCodePath.substring(0, eidx); 11260 int sidx = subStr1.lastIndexOf("/"); 11261 cid = subStr1.substring(sidx+1, eidx); 11262 setMountPath(subStr1); 11263 } 11264 11265 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11266 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11267 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11268 instructionSets, null, null); 11269 this.cid = cid; 11270 setMountPath(PackageHelper.getSdDir(cid)); 11271 } 11272 11273 void createCopyFile() { 11274 cid = mInstallerService.allocateExternalStageCidLegacy(); 11275 } 11276 11277 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11278 if (origin.staged) { 11279 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11280 cid = origin.cid; 11281 setMountPath(PackageHelper.getSdDir(cid)); 11282 return PackageManager.INSTALL_SUCCEEDED; 11283 } 11284 11285 if (temp) { 11286 createCopyFile(); 11287 } else { 11288 /* 11289 * Pre-emptively destroy the container since it's destroyed if 11290 * copying fails due to it existing anyway. 11291 */ 11292 PackageHelper.destroySdDir(cid); 11293 } 11294 11295 final String newMountPath = imcs.copyPackageToContainer( 11296 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11297 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11298 11299 if (newMountPath != null) { 11300 setMountPath(newMountPath); 11301 return PackageManager.INSTALL_SUCCEEDED; 11302 } else { 11303 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11304 } 11305 } 11306 11307 @Override 11308 String getCodePath() { 11309 return packagePath; 11310 } 11311 11312 @Override 11313 String getResourcePath() { 11314 return resourcePath; 11315 } 11316 11317 int doPreInstall(int status) { 11318 if (status != PackageManager.INSTALL_SUCCEEDED) { 11319 // Destroy container 11320 PackageHelper.destroySdDir(cid); 11321 } else { 11322 boolean mounted = PackageHelper.isContainerMounted(cid); 11323 if (!mounted) { 11324 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11325 Process.SYSTEM_UID); 11326 if (newMountPath != null) { 11327 setMountPath(newMountPath); 11328 } else { 11329 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11330 } 11331 } 11332 } 11333 return status; 11334 } 11335 11336 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11337 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11338 String newMountPath = null; 11339 if (PackageHelper.isContainerMounted(cid)) { 11340 // Unmount the container 11341 if (!PackageHelper.unMountSdDir(cid)) { 11342 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11343 return false; 11344 } 11345 } 11346 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11347 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11348 " which might be stale. Will try to clean up."); 11349 // Clean up the stale container and proceed to recreate. 11350 if (!PackageHelper.destroySdDir(newCacheId)) { 11351 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11352 return false; 11353 } 11354 // Successfully cleaned up stale container. Try to rename again. 11355 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11356 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11357 + " inspite of cleaning it up."); 11358 return false; 11359 } 11360 } 11361 if (!PackageHelper.isContainerMounted(newCacheId)) { 11362 Slog.w(TAG, "Mounting container " + newCacheId); 11363 newMountPath = PackageHelper.mountSdDir(newCacheId, 11364 getEncryptKey(), Process.SYSTEM_UID); 11365 } else { 11366 newMountPath = PackageHelper.getSdDir(newCacheId); 11367 } 11368 if (newMountPath == null) { 11369 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11370 return false; 11371 } 11372 Log.i(TAG, "Succesfully renamed " + cid + 11373 " to " + newCacheId + 11374 " at new path: " + newMountPath); 11375 cid = newCacheId; 11376 11377 final File beforeCodeFile = new File(packagePath); 11378 setMountPath(newMountPath); 11379 final File afterCodeFile = new File(packagePath); 11380 11381 // Reflect the rename in scanned details 11382 pkg.codePath = afterCodeFile.getAbsolutePath(); 11383 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11384 pkg.baseCodePath); 11385 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11386 pkg.splitCodePaths); 11387 11388 // Reflect the rename in app info 11389 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11390 pkg.applicationInfo.setCodePath(pkg.codePath); 11391 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11392 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11393 pkg.applicationInfo.setResourcePath(pkg.codePath); 11394 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11395 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11396 11397 return true; 11398 } 11399 11400 private void setMountPath(String mountPath) { 11401 final File mountFile = new File(mountPath); 11402 11403 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11404 if (monolithicFile.exists()) { 11405 packagePath = monolithicFile.getAbsolutePath(); 11406 if (isFwdLocked()) { 11407 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11408 } else { 11409 resourcePath = packagePath; 11410 } 11411 } else { 11412 packagePath = mountFile.getAbsolutePath(); 11413 resourcePath = packagePath; 11414 } 11415 } 11416 11417 int doPostInstall(int status, int uid) { 11418 if (status != PackageManager.INSTALL_SUCCEEDED) { 11419 cleanUp(); 11420 } else { 11421 final int groupOwner; 11422 final String protectedFile; 11423 if (isFwdLocked()) { 11424 groupOwner = UserHandle.getSharedAppGid(uid); 11425 protectedFile = RES_FILE_NAME; 11426 } else { 11427 groupOwner = -1; 11428 protectedFile = null; 11429 } 11430 11431 if (uid < Process.FIRST_APPLICATION_UID 11432 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11433 Slog.e(TAG, "Failed to finalize " + cid); 11434 PackageHelper.destroySdDir(cid); 11435 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11436 } 11437 11438 boolean mounted = PackageHelper.isContainerMounted(cid); 11439 if (!mounted) { 11440 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11441 } 11442 } 11443 return status; 11444 } 11445 11446 private void cleanUp() { 11447 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11448 11449 // Destroy secure container 11450 PackageHelper.destroySdDir(cid); 11451 } 11452 11453 private List<String> getAllCodePaths() { 11454 final File codeFile = new File(getCodePath()); 11455 if (codeFile != null && codeFile.exists()) { 11456 try { 11457 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11458 return pkg.getAllCodePaths(); 11459 } catch (PackageParserException e) { 11460 // Ignored; we tried our best 11461 } 11462 } 11463 return Collections.EMPTY_LIST; 11464 } 11465 11466 void cleanUpResourcesLI() { 11467 // Enumerate all code paths before deleting 11468 cleanUpResourcesLI(getAllCodePaths()); 11469 } 11470 11471 private void cleanUpResourcesLI(List<String> allCodePaths) { 11472 cleanUp(); 11473 removeDexFiles(allCodePaths, instructionSets); 11474 } 11475 11476 String getPackageName() { 11477 return getAsecPackageName(cid); 11478 } 11479 11480 boolean doPostDeleteLI(boolean delete) { 11481 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11482 final List<String> allCodePaths = getAllCodePaths(); 11483 boolean mounted = PackageHelper.isContainerMounted(cid); 11484 if (mounted) { 11485 // Unmount first 11486 if (PackageHelper.unMountSdDir(cid)) { 11487 mounted = false; 11488 } 11489 } 11490 if (!mounted && delete) { 11491 cleanUpResourcesLI(allCodePaths); 11492 } 11493 return !mounted; 11494 } 11495 11496 @Override 11497 int doPreCopy() { 11498 if (isFwdLocked()) { 11499 if (!PackageHelper.fixSdPermissions(cid, 11500 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11501 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11502 } 11503 } 11504 11505 return PackageManager.INSTALL_SUCCEEDED; 11506 } 11507 11508 @Override 11509 int doPostCopy(int uid) { 11510 if (isFwdLocked()) { 11511 if (uid < Process.FIRST_APPLICATION_UID 11512 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11513 RES_FILE_NAME)) { 11514 Slog.e(TAG, "Failed to finalize " + cid); 11515 PackageHelper.destroySdDir(cid); 11516 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11517 } 11518 } 11519 11520 return PackageManager.INSTALL_SUCCEEDED; 11521 } 11522 } 11523 11524 /** 11525 * Logic to handle movement of existing installed applications. 11526 */ 11527 class MoveInstallArgs extends InstallArgs { 11528 private File codeFile; 11529 private File resourceFile; 11530 11531 /** New install */ 11532 MoveInstallArgs(InstallParams params) { 11533 super(params.origin, params.move, params.observer, params.installFlags, 11534 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11535 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11536 params.grantedRuntimePermissions); 11537 } 11538 11539 int copyApk(IMediaContainerService imcs, boolean temp) { 11540 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11541 + move.fromUuid + " to " + move.toUuid); 11542 synchronized (mInstaller) { 11543 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11544 move.dataAppName, move.appId, move.seinfo) != 0) { 11545 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11546 } 11547 } 11548 11549 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11550 resourceFile = codeFile; 11551 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11552 11553 return PackageManager.INSTALL_SUCCEEDED; 11554 } 11555 11556 int doPreInstall(int status) { 11557 if (status != PackageManager.INSTALL_SUCCEEDED) { 11558 cleanUp(move.toUuid); 11559 } 11560 return status; 11561 } 11562 11563 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11564 if (status != PackageManager.INSTALL_SUCCEEDED) { 11565 cleanUp(move.toUuid); 11566 return false; 11567 } 11568 11569 // Reflect the move in app info 11570 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11571 pkg.applicationInfo.setCodePath(pkg.codePath); 11572 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11573 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11574 pkg.applicationInfo.setResourcePath(pkg.codePath); 11575 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11576 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11577 11578 return true; 11579 } 11580 11581 int doPostInstall(int status, int uid) { 11582 if (status == PackageManager.INSTALL_SUCCEEDED) { 11583 cleanUp(move.fromUuid); 11584 } else { 11585 cleanUp(move.toUuid); 11586 } 11587 return status; 11588 } 11589 11590 @Override 11591 String getCodePath() { 11592 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11593 } 11594 11595 @Override 11596 String getResourcePath() { 11597 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11598 } 11599 11600 private boolean cleanUp(String volumeUuid) { 11601 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11602 move.dataAppName); 11603 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11604 synchronized (mInstallLock) { 11605 // Clean up both app data and code 11606 removeDataDirsLI(volumeUuid, move.packageName); 11607 if (codeFile.isDirectory()) { 11608 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11609 } else { 11610 codeFile.delete(); 11611 } 11612 } 11613 return true; 11614 } 11615 11616 void cleanUpResourcesLI() { 11617 throw new UnsupportedOperationException(); 11618 } 11619 11620 boolean doPostDeleteLI(boolean delete) { 11621 throw new UnsupportedOperationException(); 11622 } 11623 } 11624 11625 static String getAsecPackageName(String packageCid) { 11626 int idx = packageCid.lastIndexOf("-"); 11627 if (idx == -1) { 11628 return packageCid; 11629 } 11630 return packageCid.substring(0, idx); 11631 } 11632 11633 // Utility method used to create code paths based on package name and available index. 11634 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11635 String idxStr = ""; 11636 int idx = 1; 11637 // Fall back to default value of idx=1 if prefix is not 11638 // part of oldCodePath 11639 if (oldCodePath != null) { 11640 String subStr = oldCodePath; 11641 // Drop the suffix right away 11642 if (suffix != null && subStr.endsWith(suffix)) { 11643 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11644 } 11645 // If oldCodePath already contains prefix find out the 11646 // ending index to either increment or decrement. 11647 int sidx = subStr.lastIndexOf(prefix); 11648 if (sidx != -1) { 11649 subStr = subStr.substring(sidx + prefix.length()); 11650 if (subStr != null) { 11651 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11652 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11653 } 11654 try { 11655 idx = Integer.parseInt(subStr); 11656 if (idx <= 1) { 11657 idx++; 11658 } else { 11659 idx--; 11660 } 11661 } catch(NumberFormatException e) { 11662 } 11663 } 11664 } 11665 } 11666 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11667 return prefix + idxStr; 11668 } 11669 11670 private File getNextCodePath(File targetDir, String packageName) { 11671 int suffix = 1; 11672 File result; 11673 do { 11674 result = new File(targetDir, packageName + "-" + suffix); 11675 suffix++; 11676 } while (result.exists()); 11677 return result; 11678 } 11679 11680 // Utility method that returns the relative package path with respect 11681 // to the installation directory. Like say for /data/data/com.test-1.apk 11682 // string com.test-1 is returned. 11683 static String deriveCodePathName(String codePath) { 11684 if (codePath == null) { 11685 return null; 11686 } 11687 final File codeFile = new File(codePath); 11688 final String name = codeFile.getName(); 11689 if (codeFile.isDirectory()) { 11690 return name; 11691 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11692 final int lastDot = name.lastIndexOf('.'); 11693 return name.substring(0, lastDot); 11694 } else { 11695 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11696 return null; 11697 } 11698 } 11699 11700 class PackageInstalledInfo { 11701 String name; 11702 int uid; 11703 // The set of users that originally had this package installed. 11704 int[] origUsers; 11705 // The set of users that now have this package installed. 11706 int[] newUsers; 11707 PackageParser.Package pkg; 11708 int returnCode; 11709 String returnMsg; 11710 PackageRemovedInfo removedInfo; 11711 11712 public void setError(int code, String msg) { 11713 returnCode = code; 11714 returnMsg = msg; 11715 Slog.w(TAG, msg); 11716 } 11717 11718 public void setError(String msg, PackageParserException e) { 11719 returnCode = e.error; 11720 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11721 Slog.w(TAG, msg, e); 11722 } 11723 11724 public void setError(String msg, PackageManagerException e) { 11725 returnCode = e.error; 11726 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11727 Slog.w(TAG, msg, e); 11728 } 11729 11730 // In some error cases we want to convey more info back to the observer 11731 String origPackage; 11732 String origPermission; 11733 } 11734 11735 /* 11736 * Install a non-existing package. 11737 */ 11738 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11739 UserHandle user, String installerPackageName, String volumeUuid, 11740 PackageInstalledInfo res) { 11741 // Remember this for later, in case we need to rollback this install 11742 String pkgName = pkg.packageName; 11743 11744 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11745 final boolean dataDirExists = Environment 11746 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11747 synchronized(mPackages) { 11748 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11749 // A package with the same name is already installed, though 11750 // it has been renamed to an older name. The package we 11751 // are trying to install should be installed as an update to 11752 // the existing one, but that has not been requested, so bail. 11753 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11754 + " without first uninstalling package running as " 11755 + mSettings.mRenamedPackages.get(pkgName)); 11756 return; 11757 } 11758 if (mPackages.containsKey(pkgName)) { 11759 // Don't allow installation over an existing package with the same name. 11760 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11761 + " without first uninstalling."); 11762 return; 11763 } 11764 } 11765 11766 try { 11767 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11768 System.currentTimeMillis(), user); 11769 11770 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11771 // delete the partially installed application. the data directory will have to be 11772 // restored if it was already existing 11773 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11774 // remove package from internal structures. Note that we want deletePackageX to 11775 // delete the package data and cache directories that it created in 11776 // scanPackageLocked, unless those directories existed before we even tried to 11777 // install. 11778 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11779 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11780 res.removedInfo, true); 11781 } 11782 11783 } catch (PackageManagerException e) { 11784 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11785 } 11786 } 11787 11788 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11789 // Can't rotate keys during boot or if sharedUser. 11790 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11791 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11792 return false; 11793 } 11794 // app is using upgradeKeySets; make sure all are valid 11795 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11796 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11797 for (int i = 0; i < upgradeKeySets.length; i++) { 11798 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11799 Slog.wtf(TAG, "Package " 11800 + (oldPs.name != null ? oldPs.name : "<null>") 11801 + " contains upgrade-key-set reference to unknown key-set: " 11802 + upgradeKeySets[i] 11803 + " reverting to signatures check."); 11804 return false; 11805 } 11806 } 11807 return true; 11808 } 11809 11810 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11811 // Upgrade keysets are being used. Determine if new package has a superset of the 11812 // required keys. 11813 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11814 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11815 for (int i = 0; i < upgradeKeySets.length; i++) { 11816 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11817 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11818 return true; 11819 } 11820 } 11821 return false; 11822 } 11823 11824 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11825 UserHandle user, String installerPackageName, String volumeUuid, 11826 PackageInstalledInfo res) { 11827 final PackageParser.Package oldPackage; 11828 final String pkgName = pkg.packageName; 11829 final int[] allUsers; 11830 final boolean[] perUserInstalled; 11831 11832 // First find the old package info and check signatures 11833 synchronized(mPackages) { 11834 oldPackage = mPackages.get(pkgName); 11835 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11836 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11837 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11838 if(!checkUpgradeKeySetLP(ps, pkg)) { 11839 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11840 "New package not signed by keys specified by upgrade-keysets: " 11841 + pkgName); 11842 return; 11843 } 11844 } else { 11845 // default to original signature matching 11846 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11847 != PackageManager.SIGNATURE_MATCH) { 11848 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11849 "New package has a different signature: " + pkgName); 11850 return; 11851 } 11852 } 11853 11854 // In case of rollback, remember per-user/profile install state 11855 allUsers = sUserManager.getUserIds(); 11856 perUserInstalled = new boolean[allUsers.length]; 11857 for (int i = 0; i < allUsers.length; i++) { 11858 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11859 } 11860 } 11861 11862 boolean sysPkg = (isSystemApp(oldPackage)); 11863 if (sysPkg) { 11864 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11865 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11866 } else { 11867 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11868 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11869 } 11870 } 11871 11872 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11873 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11874 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11875 String volumeUuid, PackageInstalledInfo res) { 11876 String pkgName = deletedPackage.packageName; 11877 boolean deletedPkg = true; 11878 boolean updatedSettings = false; 11879 11880 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11881 + deletedPackage); 11882 long origUpdateTime; 11883 if (pkg.mExtras != null) { 11884 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11885 } else { 11886 origUpdateTime = 0; 11887 } 11888 11889 // First delete the existing package while retaining the data directory 11890 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11891 res.removedInfo, true)) { 11892 // If the existing package wasn't successfully deleted 11893 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11894 deletedPkg = false; 11895 } else { 11896 // Successfully deleted the old package; proceed with replace. 11897 11898 // If deleted package lived in a container, give users a chance to 11899 // relinquish resources before killing. 11900 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11901 if (DEBUG_INSTALL) { 11902 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11903 } 11904 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11905 final ArrayList<String> pkgList = new ArrayList<String>(1); 11906 pkgList.add(deletedPackage.applicationInfo.packageName); 11907 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11908 } 11909 11910 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11911 try { 11912 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11913 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11914 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11915 perUserInstalled, res, user); 11916 updatedSettings = true; 11917 } catch (PackageManagerException e) { 11918 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11919 } 11920 } 11921 11922 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11923 // remove package from internal structures. Note that we want deletePackageX to 11924 // delete the package data and cache directories that it created in 11925 // scanPackageLocked, unless those directories existed before we even tried to 11926 // install. 11927 if(updatedSettings) { 11928 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11929 deletePackageLI( 11930 pkgName, null, true, allUsers, perUserInstalled, 11931 PackageManager.DELETE_KEEP_DATA, 11932 res.removedInfo, true); 11933 } 11934 // Since we failed to install the new package we need to restore the old 11935 // package that we deleted. 11936 if (deletedPkg) { 11937 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11938 File restoreFile = new File(deletedPackage.codePath); 11939 // Parse old package 11940 boolean oldExternal = isExternal(deletedPackage); 11941 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11942 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11943 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11944 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11945 try { 11946 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11947 } catch (PackageManagerException e) { 11948 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11949 + e.getMessage()); 11950 return; 11951 } 11952 // Restore of old package succeeded. Update permissions. 11953 // writer 11954 synchronized (mPackages) { 11955 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11956 UPDATE_PERMISSIONS_ALL); 11957 // can downgrade to reader 11958 mSettings.writeLPr(); 11959 } 11960 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11961 } 11962 } 11963 } 11964 11965 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11966 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11967 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11968 String volumeUuid, PackageInstalledInfo res) { 11969 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11970 + ", old=" + deletedPackage); 11971 boolean disabledSystem = false; 11972 boolean updatedSettings = false; 11973 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11974 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11975 != 0) { 11976 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11977 } 11978 String packageName = deletedPackage.packageName; 11979 if (packageName == null) { 11980 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11981 "Attempt to delete null packageName."); 11982 return; 11983 } 11984 PackageParser.Package oldPkg; 11985 PackageSetting oldPkgSetting; 11986 // reader 11987 synchronized (mPackages) { 11988 oldPkg = mPackages.get(packageName); 11989 oldPkgSetting = mSettings.mPackages.get(packageName); 11990 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11991 (oldPkgSetting == null)) { 11992 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11993 "Couldn't find package:" + packageName + " information"); 11994 return; 11995 } 11996 } 11997 11998 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 11999 12000 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12001 res.removedInfo.removedPackage = packageName; 12002 // Remove existing system package 12003 removePackageLI(oldPkgSetting, true); 12004 // writer 12005 synchronized (mPackages) { 12006 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12007 if (!disabledSystem && deletedPackage != null) { 12008 // We didn't need to disable the .apk as a current system package, 12009 // which means we are replacing another update that is already 12010 // installed. We need to make sure to delete the older one's .apk. 12011 res.removedInfo.args = createInstallArgsForExisting(0, 12012 deletedPackage.applicationInfo.getCodePath(), 12013 deletedPackage.applicationInfo.getResourcePath(), 12014 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12015 } else { 12016 res.removedInfo.args = null; 12017 } 12018 } 12019 12020 // Successfully disabled the old package. Now proceed with re-installation 12021 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12022 12023 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12024 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12025 12026 PackageParser.Package newPackage = null; 12027 try { 12028 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 12029 if (newPackage.mExtras != null) { 12030 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12031 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12032 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12033 12034 // is the update attempting to change shared user? that isn't going to work... 12035 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12036 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12037 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12038 + " to " + newPkgSetting.sharedUser); 12039 updatedSettings = true; 12040 } 12041 } 12042 12043 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12044 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12045 perUserInstalled, res, user); 12046 updatedSettings = true; 12047 } 12048 12049 } catch (PackageManagerException e) { 12050 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12051 } 12052 12053 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12054 // Re installation failed. Restore old information 12055 // Remove new pkg information 12056 if (newPackage != null) { 12057 removeInstalledPackageLI(newPackage, true); 12058 } 12059 // Add back the old system package 12060 try { 12061 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12062 } catch (PackageManagerException e) { 12063 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12064 } 12065 // Restore the old system information in Settings 12066 synchronized (mPackages) { 12067 if (disabledSystem) { 12068 mSettings.enableSystemPackageLPw(packageName); 12069 } 12070 if (updatedSettings) { 12071 mSettings.setInstallerPackageName(packageName, 12072 oldPkgSetting.installerPackageName); 12073 } 12074 mSettings.writeLPr(); 12075 } 12076 } 12077 } 12078 12079 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12080 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12081 UserHandle user) { 12082 String pkgName = newPackage.packageName; 12083 synchronized (mPackages) { 12084 //write settings. the installStatus will be incomplete at this stage. 12085 //note that the new package setting would have already been 12086 //added to mPackages. It hasn't been persisted yet. 12087 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12088 mSettings.writeLPr(); 12089 } 12090 12091 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12092 12093 synchronized (mPackages) { 12094 updatePermissionsLPw(newPackage.packageName, newPackage, 12095 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12096 ? UPDATE_PERMISSIONS_ALL : 0)); 12097 // For system-bundled packages, we assume that installing an upgraded version 12098 // of the package implies that the user actually wants to run that new code, 12099 // so we enable the package. 12100 PackageSetting ps = mSettings.mPackages.get(pkgName); 12101 if (ps != null) { 12102 if (isSystemApp(newPackage)) { 12103 // NB: implicit assumption that system package upgrades apply to all users 12104 if (DEBUG_INSTALL) { 12105 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12106 } 12107 if (res.origUsers != null) { 12108 for (int userHandle : res.origUsers) { 12109 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12110 userHandle, installerPackageName); 12111 } 12112 } 12113 // Also convey the prior install/uninstall state 12114 if (allUsers != null && perUserInstalled != null) { 12115 for (int i = 0; i < allUsers.length; i++) { 12116 if (DEBUG_INSTALL) { 12117 Slog.d(TAG, " user " + allUsers[i] 12118 + " => " + perUserInstalled[i]); 12119 } 12120 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12121 } 12122 // these install state changes will be persisted in the 12123 // upcoming call to mSettings.writeLPr(). 12124 } 12125 } 12126 // It's implied that when a user requests installation, they want the app to be 12127 // installed and enabled. 12128 int userId = user.getIdentifier(); 12129 if (userId != UserHandle.USER_ALL) { 12130 ps.setInstalled(true, userId); 12131 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12132 } 12133 } 12134 res.name = pkgName; 12135 res.uid = newPackage.applicationInfo.uid; 12136 res.pkg = newPackage; 12137 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12138 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12139 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12140 //to update install status 12141 mSettings.writeLPr(); 12142 } 12143 } 12144 12145 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12146 final int installFlags = args.installFlags; 12147 final String installerPackageName = args.installerPackageName; 12148 final String volumeUuid = args.volumeUuid; 12149 final File tmpPackageFile = new File(args.getCodePath()); 12150 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12151 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12152 || (args.volumeUuid != null)); 12153 boolean replace = false; 12154 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12155 if (args.move != null) { 12156 // moving a complete application; perfom an initial scan on the new install location 12157 scanFlags |= SCAN_INITIAL; 12158 } 12159 // Result object to be returned 12160 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12161 12162 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12163 // Retrieve PackageSettings and parse package 12164 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12165 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12166 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12167 PackageParser pp = new PackageParser(); 12168 pp.setSeparateProcesses(mSeparateProcesses); 12169 pp.setDisplayMetrics(mMetrics); 12170 12171 final PackageParser.Package pkg; 12172 try { 12173 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12174 } catch (PackageParserException e) { 12175 res.setError("Failed parse during installPackageLI", e); 12176 return; 12177 } 12178 12179 // Mark that we have an install time CPU ABI override. 12180 pkg.cpuAbiOverride = args.abiOverride; 12181 12182 String pkgName = res.name = pkg.packageName; 12183 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12184 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12185 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12186 return; 12187 } 12188 } 12189 12190 try { 12191 pp.collectCertificates(pkg, parseFlags); 12192 pp.collectManifestDigest(pkg); 12193 } catch (PackageParserException e) { 12194 res.setError("Failed collect during installPackageLI", e); 12195 return; 12196 } 12197 12198 /* If the installer passed in a manifest digest, compare it now. */ 12199 if (args.manifestDigest != null) { 12200 if (DEBUG_INSTALL) { 12201 final String parsedManifest = pkg.manifestDigest == null ? "null" 12202 : pkg.manifestDigest.toString(); 12203 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12204 + parsedManifest); 12205 } 12206 12207 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12208 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12209 return; 12210 } 12211 } else if (DEBUG_INSTALL) { 12212 final String parsedManifest = pkg.manifestDigest == null 12213 ? "null" : pkg.manifestDigest.toString(); 12214 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12215 } 12216 12217 // Get rid of all references to package scan path via parser. 12218 pp = null; 12219 String oldCodePath = null; 12220 boolean systemApp = false; 12221 synchronized (mPackages) { 12222 // Check if installing already existing package 12223 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12224 String oldName = mSettings.mRenamedPackages.get(pkgName); 12225 if (pkg.mOriginalPackages != null 12226 && pkg.mOriginalPackages.contains(oldName) 12227 && mPackages.containsKey(oldName)) { 12228 // This package is derived from an original package, 12229 // and this device has been updating from that original 12230 // name. We must continue using the original name, so 12231 // rename the new package here. 12232 pkg.setPackageName(oldName); 12233 pkgName = pkg.packageName; 12234 replace = true; 12235 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12236 + oldName + " pkgName=" + pkgName); 12237 } else if (mPackages.containsKey(pkgName)) { 12238 // This package, under its official name, already exists 12239 // on the device; we should replace it. 12240 replace = true; 12241 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12242 } 12243 12244 // Prevent apps opting out from runtime permissions 12245 if (replace) { 12246 PackageParser.Package oldPackage = mPackages.get(pkgName); 12247 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12248 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12249 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12250 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12251 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12252 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12253 + " doesn't support runtime permissions but the old" 12254 + " target SDK " + oldTargetSdk + " does."); 12255 return; 12256 } 12257 } 12258 } 12259 12260 PackageSetting ps = mSettings.mPackages.get(pkgName); 12261 if (ps != null) { 12262 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12263 12264 // Quick sanity check that we're signed correctly if updating; 12265 // we'll check this again later when scanning, but we want to 12266 // bail early here before tripping over redefined permissions. 12267 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12268 if (!checkUpgradeKeySetLP(ps, pkg)) { 12269 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12270 + pkg.packageName + " upgrade keys do not match the " 12271 + "previously installed version"); 12272 return; 12273 } 12274 } else { 12275 try { 12276 verifySignaturesLP(ps, pkg); 12277 } catch (PackageManagerException e) { 12278 res.setError(e.error, e.getMessage()); 12279 return; 12280 } 12281 } 12282 12283 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12284 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12285 systemApp = (ps.pkg.applicationInfo.flags & 12286 ApplicationInfo.FLAG_SYSTEM) != 0; 12287 } 12288 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12289 } 12290 12291 // Check whether the newly-scanned package wants to define an already-defined perm 12292 int N = pkg.permissions.size(); 12293 for (int i = N-1; i >= 0; i--) { 12294 PackageParser.Permission perm = pkg.permissions.get(i); 12295 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12296 if (bp != null) { 12297 // If the defining package is signed with our cert, it's okay. This 12298 // also includes the "updating the same package" case, of course. 12299 // "updating same package" could also involve key-rotation. 12300 final boolean sigsOk; 12301 if (bp.sourcePackage.equals(pkg.packageName) 12302 && (bp.packageSetting instanceof PackageSetting) 12303 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12304 scanFlags))) { 12305 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12306 } else { 12307 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12308 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12309 } 12310 if (!sigsOk) { 12311 // If the owning package is the system itself, we log but allow 12312 // install to proceed; we fail the install on all other permission 12313 // redefinitions. 12314 if (!bp.sourcePackage.equals("android")) { 12315 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12316 + pkg.packageName + " attempting to redeclare permission " 12317 + perm.info.name + " already owned by " + bp.sourcePackage); 12318 res.origPermission = perm.info.name; 12319 res.origPackage = bp.sourcePackage; 12320 return; 12321 } else { 12322 Slog.w(TAG, "Package " + pkg.packageName 12323 + " attempting to redeclare system permission " 12324 + perm.info.name + "; ignoring new declaration"); 12325 pkg.permissions.remove(i); 12326 } 12327 } 12328 } 12329 } 12330 12331 } 12332 12333 if (systemApp && onExternal) { 12334 // Disable updates to system apps on sdcard 12335 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12336 "Cannot install updates to system apps on sdcard"); 12337 return; 12338 } 12339 12340 if (args.move != null) { 12341 // We did an in-place move, so dex is ready to roll 12342 scanFlags |= SCAN_NO_DEX; 12343 scanFlags |= SCAN_MOVE; 12344 12345 synchronized (mPackages) { 12346 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12347 if (ps == null) { 12348 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12349 "Missing settings for moved package " + pkgName); 12350 } 12351 12352 // We moved the entire application as-is, so bring over the 12353 // previously derived ABI information. 12354 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12355 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12356 } 12357 12358 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12359 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12360 scanFlags |= SCAN_NO_DEX; 12361 12362 try { 12363 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12364 true /* extract libs */); 12365 } catch (PackageManagerException pme) { 12366 Slog.e(TAG, "Error deriving application ABI", pme); 12367 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12368 return; 12369 } 12370 12371 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12372 int result = mPackageDexOptimizer 12373 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12374 false /* defer */, false /* inclDependencies */); 12375 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12376 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12377 return; 12378 } 12379 } 12380 12381 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12382 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12383 return; 12384 } 12385 12386 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12387 12388 if (replace) { 12389 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12390 installerPackageName, volumeUuid, res); 12391 } else { 12392 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12393 args.user, installerPackageName, volumeUuid, res); 12394 } 12395 synchronized (mPackages) { 12396 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12397 if (ps != null) { 12398 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12399 } 12400 } 12401 } 12402 12403 private void startIntentFilterVerifications(int userId, boolean replacing, 12404 PackageParser.Package pkg) { 12405 if (mIntentFilterVerifierComponent == null) { 12406 Slog.w(TAG, "No IntentFilter verification will not be done as " 12407 + "there is no IntentFilterVerifier available!"); 12408 return; 12409 } 12410 12411 final int verifierUid = getPackageUid( 12412 mIntentFilterVerifierComponent.getPackageName(), 12413 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12414 12415 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12416 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12417 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12418 mHandler.sendMessage(msg); 12419 } 12420 12421 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12422 PackageParser.Package pkg) { 12423 int size = pkg.activities.size(); 12424 if (size == 0) { 12425 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12426 "No activity, so no need to verify any IntentFilter!"); 12427 return; 12428 } 12429 12430 final boolean hasDomainURLs = hasDomainURLs(pkg); 12431 if (!hasDomainURLs) { 12432 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12433 "No domain URLs, so no need to verify any IntentFilter!"); 12434 return; 12435 } 12436 12437 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12438 + " if any IntentFilter from the " + size 12439 + " Activities needs verification ..."); 12440 12441 int count = 0; 12442 final String packageName = pkg.packageName; 12443 12444 synchronized (mPackages) { 12445 // If this is a new install and we see that we've already run verification for this 12446 // package, we have nothing to do: it means the state was restored from backup. 12447 if (!replacing) { 12448 IntentFilterVerificationInfo ivi = 12449 mSettings.getIntentFilterVerificationLPr(packageName); 12450 if (ivi != null) { 12451 if (DEBUG_DOMAIN_VERIFICATION) { 12452 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12453 + ivi.getStatusString()); 12454 } 12455 return; 12456 } 12457 } 12458 12459 // If any filters need to be verified, then all need to be. 12460 boolean needToVerify = false; 12461 for (PackageParser.Activity a : pkg.activities) { 12462 for (ActivityIntentInfo filter : a.intents) { 12463 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12464 if (DEBUG_DOMAIN_VERIFICATION) { 12465 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12466 } 12467 needToVerify = true; 12468 break; 12469 } 12470 } 12471 } 12472 12473 if (needToVerify) { 12474 final int verificationId = mIntentFilterVerificationToken++; 12475 for (PackageParser.Activity a : pkg.activities) { 12476 for (ActivityIntentInfo filter : a.intents) { 12477 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12478 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12479 "Verification needed for IntentFilter:" + filter.toString()); 12480 mIntentFilterVerifier.addOneIntentFilterVerification( 12481 verifierUid, userId, verificationId, filter, packageName); 12482 count++; 12483 } 12484 } 12485 } 12486 } 12487 } 12488 12489 if (count > 0) { 12490 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12491 + " IntentFilter verification" + (count > 1 ? "s" : "") 12492 + " for userId:" + userId); 12493 mIntentFilterVerifier.startVerifications(userId); 12494 } else { 12495 if (DEBUG_DOMAIN_VERIFICATION) { 12496 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12497 } 12498 } 12499 } 12500 12501 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12502 final ComponentName cn = filter.activity.getComponentName(); 12503 final String packageName = cn.getPackageName(); 12504 12505 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12506 packageName); 12507 if (ivi == null) { 12508 return true; 12509 } 12510 int status = ivi.getStatus(); 12511 switch (status) { 12512 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12513 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12514 return true; 12515 12516 default: 12517 // Nothing to do 12518 return false; 12519 } 12520 } 12521 12522 private static boolean isMultiArch(PackageSetting ps) { 12523 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12524 } 12525 12526 private static boolean isMultiArch(ApplicationInfo info) { 12527 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12528 } 12529 12530 private static boolean isExternal(PackageParser.Package pkg) { 12531 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12532 } 12533 12534 private static boolean isExternal(PackageSetting ps) { 12535 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12536 } 12537 12538 private static boolean isExternal(ApplicationInfo info) { 12539 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12540 } 12541 12542 private static boolean isSystemApp(PackageParser.Package pkg) { 12543 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12544 } 12545 12546 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12547 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12548 } 12549 12550 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12551 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12552 } 12553 12554 private static boolean isSystemApp(PackageSetting ps) { 12555 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12556 } 12557 12558 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12559 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12560 } 12561 12562 private int packageFlagsToInstallFlags(PackageSetting ps) { 12563 int installFlags = 0; 12564 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12565 // This existing package was an external ASEC install when we have 12566 // the external flag without a UUID 12567 installFlags |= PackageManager.INSTALL_EXTERNAL; 12568 } 12569 if (ps.isForwardLocked()) { 12570 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12571 } 12572 return installFlags; 12573 } 12574 12575 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12576 if (isExternal(pkg)) { 12577 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12578 return mSettings.getExternalVersion(); 12579 } else { 12580 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12581 } 12582 } else { 12583 return mSettings.getInternalVersion(); 12584 } 12585 } 12586 12587 private void deleteTempPackageFiles() { 12588 final FilenameFilter filter = new FilenameFilter() { 12589 public boolean accept(File dir, String name) { 12590 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12591 } 12592 }; 12593 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12594 file.delete(); 12595 } 12596 } 12597 12598 @Override 12599 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12600 int flags) { 12601 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12602 flags); 12603 } 12604 12605 @Override 12606 public void deletePackage(final String packageName, 12607 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12608 mContext.enforceCallingOrSelfPermission( 12609 android.Manifest.permission.DELETE_PACKAGES, null); 12610 Preconditions.checkNotNull(packageName); 12611 Preconditions.checkNotNull(observer); 12612 final int uid = Binder.getCallingUid(); 12613 if (UserHandle.getUserId(uid) != userId) { 12614 mContext.enforceCallingPermission( 12615 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12616 "deletePackage for user " + userId); 12617 } 12618 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12619 try { 12620 observer.onPackageDeleted(packageName, 12621 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12622 } catch (RemoteException re) { 12623 } 12624 return; 12625 } 12626 12627 boolean uninstallBlocked = false; 12628 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12629 int[] users = sUserManager.getUserIds(); 12630 for (int i = 0; i < users.length; ++i) { 12631 if (getBlockUninstallForUser(packageName, users[i])) { 12632 uninstallBlocked = true; 12633 break; 12634 } 12635 } 12636 } else { 12637 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12638 } 12639 if (uninstallBlocked) { 12640 try { 12641 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12642 null); 12643 } catch (RemoteException re) { 12644 } 12645 return; 12646 } 12647 12648 if (DEBUG_REMOVE) { 12649 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12650 } 12651 // Queue up an async operation since the package deletion may take a little while. 12652 mHandler.post(new Runnable() { 12653 public void run() { 12654 mHandler.removeCallbacks(this); 12655 final int returnCode = deletePackageX(packageName, userId, flags); 12656 if (observer != null) { 12657 try { 12658 observer.onPackageDeleted(packageName, returnCode, null); 12659 } catch (RemoteException e) { 12660 Log.i(TAG, "Observer no longer exists."); 12661 } //end catch 12662 } //end if 12663 } //end run 12664 }); 12665 } 12666 12667 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12668 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12669 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12670 try { 12671 if (dpm != null) { 12672 if (dpm.isDeviceOwner(packageName)) { 12673 return true; 12674 } 12675 int[] users; 12676 if (userId == UserHandle.USER_ALL) { 12677 users = sUserManager.getUserIds(); 12678 } else { 12679 users = new int[]{userId}; 12680 } 12681 for (int i = 0; i < users.length; ++i) { 12682 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12683 return true; 12684 } 12685 } 12686 } 12687 } catch (RemoteException e) { 12688 } 12689 return false; 12690 } 12691 12692 /** 12693 * This method is an internal method that could be get invoked either 12694 * to delete an installed package or to clean up a failed installation. 12695 * After deleting an installed package, a broadcast is sent to notify any 12696 * listeners that the package has been installed. For cleaning up a failed 12697 * installation, the broadcast is not necessary since the package's 12698 * installation wouldn't have sent the initial broadcast either 12699 * The key steps in deleting a package are 12700 * deleting the package information in internal structures like mPackages, 12701 * deleting the packages base directories through installd 12702 * updating mSettings to reflect current status 12703 * persisting settings for later use 12704 * sending a broadcast if necessary 12705 */ 12706 private int deletePackageX(String packageName, int userId, int flags) { 12707 final PackageRemovedInfo info = new PackageRemovedInfo(); 12708 final boolean res; 12709 12710 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12711 ? UserHandle.ALL : new UserHandle(userId); 12712 12713 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12714 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12715 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12716 } 12717 12718 boolean removedForAllUsers = false; 12719 boolean systemUpdate = false; 12720 12721 // for the uninstall-updates case and restricted profiles, remember the per- 12722 // userhandle installed state 12723 int[] allUsers; 12724 boolean[] perUserInstalled; 12725 synchronized (mPackages) { 12726 PackageSetting ps = mSettings.mPackages.get(packageName); 12727 allUsers = sUserManager.getUserIds(); 12728 perUserInstalled = new boolean[allUsers.length]; 12729 for (int i = 0; i < allUsers.length; i++) { 12730 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12731 } 12732 } 12733 12734 synchronized (mInstallLock) { 12735 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12736 res = deletePackageLI(packageName, removeForUser, 12737 true, allUsers, perUserInstalled, 12738 flags | REMOVE_CHATTY, info, true); 12739 systemUpdate = info.isRemovedPackageSystemUpdate; 12740 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12741 removedForAllUsers = true; 12742 } 12743 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12744 + " removedForAllUsers=" + removedForAllUsers); 12745 } 12746 12747 if (res) { 12748 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12749 12750 // If the removed package was a system update, the old system package 12751 // was re-enabled; we need to broadcast this information 12752 if (systemUpdate) { 12753 Bundle extras = new Bundle(1); 12754 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12755 ? info.removedAppId : info.uid); 12756 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12757 12758 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12759 extras, null, null, null); 12760 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12761 extras, null, null, null); 12762 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12763 null, packageName, null, null); 12764 } 12765 } 12766 // Force a gc here. 12767 Runtime.getRuntime().gc(); 12768 // Delete the resources here after sending the broadcast to let 12769 // other processes clean up before deleting resources. 12770 if (info.args != null) { 12771 synchronized (mInstallLock) { 12772 info.args.doPostDeleteLI(true); 12773 } 12774 } 12775 12776 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12777 } 12778 12779 class PackageRemovedInfo { 12780 String removedPackage; 12781 int uid = -1; 12782 int removedAppId = -1; 12783 int[] removedUsers = null; 12784 boolean isRemovedPackageSystemUpdate = false; 12785 // Clean up resources deleted packages. 12786 InstallArgs args = null; 12787 12788 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12789 Bundle extras = new Bundle(1); 12790 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12791 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12792 if (replacing) { 12793 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12794 } 12795 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12796 if (removedPackage != null) { 12797 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12798 extras, null, null, removedUsers); 12799 if (fullRemove && !replacing) { 12800 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12801 extras, null, null, removedUsers); 12802 } 12803 } 12804 if (removedAppId >= 0) { 12805 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12806 removedUsers); 12807 } 12808 } 12809 } 12810 12811 /* 12812 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12813 * flag is not set, the data directory is removed as well. 12814 * make sure this flag is set for partially installed apps. If not its meaningless to 12815 * delete a partially installed application. 12816 */ 12817 private void removePackageDataLI(PackageSetting ps, 12818 int[] allUserHandles, boolean[] perUserInstalled, 12819 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12820 String packageName = ps.name; 12821 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12822 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12823 // Retrieve object to delete permissions for shared user later on 12824 final PackageSetting deletedPs; 12825 // reader 12826 synchronized (mPackages) { 12827 deletedPs = mSettings.mPackages.get(packageName); 12828 if (outInfo != null) { 12829 outInfo.removedPackage = packageName; 12830 outInfo.removedUsers = deletedPs != null 12831 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12832 : null; 12833 } 12834 } 12835 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12836 removeDataDirsLI(ps.volumeUuid, packageName); 12837 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12838 } 12839 // writer 12840 synchronized (mPackages) { 12841 if (deletedPs != null) { 12842 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12843 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12844 clearDefaultBrowserIfNeeded(packageName); 12845 if (outInfo != null) { 12846 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12847 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12848 } 12849 updatePermissionsLPw(deletedPs.name, null, 0); 12850 if (deletedPs.sharedUser != null) { 12851 // Remove permissions associated with package. Since runtime 12852 // permissions are per user we have to kill the removed package 12853 // or packages running under the shared user of the removed 12854 // package if revoking the permissions requested only by the removed 12855 // package is successful and this causes a change in gids. 12856 for (int userId : UserManagerService.getInstance().getUserIds()) { 12857 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12858 userId); 12859 if (userIdToKill == UserHandle.USER_ALL 12860 || userIdToKill >= UserHandle.USER_OWNER) { 12861 // If gids changed for this user, kill all affected packages. 12862 mHandler.post(new Runnable() { 12863 @Override 12864 public void run() { 12865 // This has to happen with no lock held. 12866 killApplication(deletedPs.name, deletedPs.appId, 12867 KILL_APP_REASON_GIDS_CHANGED); 12868 } 12869 }); 12870 break; 12871 } 12872 } 12873 } 12874 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12875 } 12876 // make sure to preserve per-user disabled state if this removal was just 12877 // a downgrade of a system app to the factory package 12878 if (allUserHandles != null && perUserInstalled != null) { 12879 if (DEBUG_REMOVE) { 12880 Slog.d(TAG, "Propagating install state across downgrade"); 12881 } 12882 for (int i = 0; i < allUserHandles.length; i++) { 12883 if (DEBUG_REMOVE) { 12884 Slog.d(TAG, " user " + allUserHandles[i] 12885 + " => " + perUserInstalled[i]); 12886 } 12887 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12888 } 12889 } 12890 } 12891 // can downgrade to reader 12892 if (writeSettings) { 12893 // Save settings now 12894 mSettings.writeLPr(); 12895 } 12896 } 12897 if (outInfo != null) { 12898 // A user ID was deleted here. Go through all users and remove it 12899 // from KeyStore. 12900 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12901 } 12902 } 12903 12904 static boolean locationIsPrivileged(File path) { 12905 try { 12906 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12907 .getCanonicalPath(); 12908 return path.getCanonicalPath().startsWith(privilegedAppDir); 12909 } catch (IOException e) { 12910 Slog.e(TAG, "Unable to access code path " + path); 12911 } 12912 return false; 12913 } 12914 12915 /* 12916 * Tries to delete system package. 12917 */ 12918 private boolean deleteSystemPackageLI(PackageSetting newPs, 12919 int[] allUserHandles, boolean[] perUserInstalled, 12920 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12921 final boolean applyUserRestrictions 12922 = (allUserHandles != null) && (perUserInstalled != null); 12923 PackageSetting disabledPs = null; 12924 // Confirm if the system package has been updated 12925 // An updated system app can be deleted. This will also have to restore 12926 // the system pkg from system partition 12927 // reader 12928 synchronized (mPackages) { 12929 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12930 } 12931 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12932 + " disabledPs=" + disabledPs); 12933 if (disabledPs == null) { 12934 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12935 return false; 12936 } else if (DEBUG_REMOVE) { 12937 Slog.d(TAG, "Deleting system pkg from data partition"); 12938 } 12939 if (DEBUG_REMOVE) { 12940 if (applyUserRestrictions) { 12941 Slog.d(TAG, "Remembering install states:"); 12942 for (int i = 0; i < allUserHandles.length; i++) { 12943 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12944 } 12945 } 12946 } 12947 // Delete the updated package 12948 outInfo.isRemovedPackageSystemUpdate = true; 12949 if (disabledPs.versionCode < newPs.versionCode) { 12950 // Delete data for downgrades 12951 flags &= ~PackageManager.DELETE_KEEP_DATA; 12952 } else { 12953 // Preserve data by setting flag 12954 flags |= PackageManager.DELETE_KEEP_DATA; 12955 } 12956 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12957 allUserHandles, perUserInstalled, outInfo, writeSettings); 12958 if (!ret) { 12959 return false; 12960 } 12961 // writer 12962 synchronized (mPackages) { 12963 // Reinstate the old system package 12964 mSettings.enableSystemPackageLPw(newPs.name); 12965 // Remove any native libraries from the upgraded package. 12966 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12967 } 12968 // Install the system package 12969 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12970 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12971 if (locationIsPrivileged(disabledPs.codePath)) { 12972 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12973 } 12974 12975 final PackageParser.Package newPkg; 12976 try { 12977 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12978 } catch (PackageManagerException e) { 12979 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12980 return false; 12981 } 12982 12983 // writer 12984 synchronized (mPackages) { 12985 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12986 12987 // Propagate the permissions state as we do not want to drop on the floor 12988 // runtime permissions. The update permissions method below will take 12989 // care of removing obsolete permissions and grant install permissions. 12990 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 12991 updatePermissionsLPw(newPkg.packageName, newPkg, 12992 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12993 12994 if (applyUserRestrictions) { 12995 if (DEBUG_REMOVE) { 12996 Slog.d(TAG, "Propagating install state across reinstall"); 12997 } 12998 for (int i = 0; i < allUserHandles.length; i++) { 12999 if (DEBUG_REMOVE) { 13000 Slog.d(TAG, " user " + allUserHandles[i] 13001 + " => " + perUserInstalled[i]); 13002 } 13003 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13004 13005 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13006 } 13007 // Regardless of writeSettings we need to ensure that this restriction 13008 // state propagation is persisted 13009 mSettings.writeAllUsersPackageRestrictionsLPr(); 13010 } 13011 // can downgrade to reader here 13012 if (writeSettings) { 13013 mSettings.writeLPr(); 13014 } 13015 } 13016 return true; 13017 } 13018 13019 private boolean deleteInstalledPackageLI(PackageSetting ps, 13020 boolean deleteCodeAndResources, int flags, 13021 int[] allUserHandles, boolean[] perUserInstalled, 13022 PackageRemovedInfo outInfo, boolean writeSettings) { 13023 if (outInfo != null) { 13024 outInfo.uid = ps.appId; 13025 } 13026 13027 // Delete package data from internal structures and also remove data if flag is set 13028 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13029 13030 // Delete application code and resources 13031 if (deleteCodeAndResources && (outInfo != null)) { 13032 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13033 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13034 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13035 } 13036 return true; 13037 } 13038 13039 @Override 13040 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13041 int userId) { 13042 mContext.enforceCallingOrSelfPermission( 13043 android.Manifest.permission.DELETE_PACKAGES, null); 13044 synchronized (mPackages) { 13045 PackageSetting ps = mSettings.mPackages.get(packageName); 13046 if (ps == null) { 13047 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13048 return false; 13049 } 13050 if (!ps.getInstalled(userId)) { 13051 // Can't block uninstall for an app that is not installed or enabled. 13052 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13053 return false; 13054 } 13055 ps.setBlockUninstall(blockUninstall, userId); 13056 mSettings.writePackageRestrictionsLPr(userId); 13057 } 13058 return true; 13059 } 13060 13061 @Override 13062 public boolean getBlockUninstallForUser(String packageName, int userId) { 13063 synchronized (mPackages) { 13064 PackageSetting ps = mSettings.mPackages.get(packageName); 13065 if (ps == null) { 13066 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13067 return false; 13068 } 13069 return ps.getBlockUninstall(userId); 13070 } 13071 } 13072 13073 /* 13074 * This method handles package deletion in general 13075 */ 13076 private boolean deletePackageLI(String packageName, UserHandle user, 13077 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13078 int flags, PackageRemovedInfo outInfo, 13079 boolean writeSettings) { 13080 if (packageName == null) { 13081 Slog.w(TAG, "Attempt to delete null packageName."); 13082 return false; 13083 } 13084 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13085 PackageSetting ps; 13086 boolean dataOnly = false; 13087 int removeUser = -1; 13088 int appId = -1; 13089 synchronized (mPackages) { 13090 ps = mSettings.mPackages.get(packageName); 13091 if (ps == null) { 13092 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13093 return false; 13094 } 13095 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13096 && user.getIdentifier() != UserHandle.USER_ALL) { 13097 // The caller is asking that the package only be deleted for a single 13098 // user. To do this, we just mark its uninstalled state and delete 13099 // its data. If this is a system app, we only allow this to happen if 13100 // they have set the special DELETE_SYSTEM_APP which requests different 13101 // semantics than normal for uninstalling system apps. 13102 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13103 final int userId = user.getIdentifier(); 13104 ps.setUserState(userId, 13105 COMPONENT_ENABLED_STATE_DEFAULT, 13106 false, //installed 13107 true, //stopped 13108 true, //notLaunched 13109 false, //hidden 13110 null, null, null, 13111 false, // blockUninstall 13112 ps.readUserState(userId).domainVerificationStatus, 0); 13113 if (!isSystemApp(ps)) { 13114 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13115 // Other user still have this package installed, so all 13116 // we need to do is clear this user's data and save that 13117 // it is uninstalled. 13118 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13119 removeUser = user.getIdentifier(); 13120 appId = ps.appId; 13121 scheduleWritePackageRestrictionsLocked(removeUser); 13122 } else { 13123 // We need to set it back to 'installed' so the uninstall 13124 // broadcasts will be sent correctly. 13125 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13126 ps.setInstalled(true, user.getIdentifier()); 13127 } 13128 } else { 13129 // This is a system app, so we assume that the 13130 // other users still have this package installed, so all 13131 // we need to do is clear this user's data and save that 13132 // it is uninstalled. 13133 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13134 removeUser = user.getIdentifier(); 13135 appId = ps.appId; 13136 scheduleWritePackageRestrictionsLocked(removeUser); 13137 } 13138 } 13139 } 13140 13141 if (removeUser >= 0) { 13142 // From above, we determined that we are deleting this only 13143 // for a single user. Continue the work here. 13144 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13145 if (outInfo != null) { 13146 outInfo.removedPackage = packageName; 13147 outInfo.removedAppId = appId; 13148 outInfo.removedUsers = new int[] {removeUser}; 13149 } 13150 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13151 removeKeystoreDataIfNeeded(removeUser, appId); 13152 schedulePackageCleaning(packageName, removeUser, false); 13153 synchronized (mPackages) { 13154 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13155 scheduleWritePackageRestrictionsLocked(removeUser); 13156 } 13157 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13158 } 13159 return true; 13160 } 13161 13162 if (dataOnly) { 13163 // Delete application data first 13164 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13165 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13166 return true; 13167 } 13168 13169 boolean ret = false; 13170 if (isSystemApp(ps)) { 13171 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13172 // When an updated system application is deleted we delete the existing resources as well and 13173 // fall back to existing code in system partition 13174 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13175 flags, outInfo, writeSettings); 13176 } else { 13177 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13178 // Kill application pre-emptively especially for apps on sd. 13179 killApplication(packageName, ps.appId, "uninstall pkg"); 13180 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13181 allUserHandles, perUserInstalled, 13182 outInfo, writeSettings); 13183 } 13184 13185 return ret; 13186 } 13187 13188 private final class ClearStorageConnection implements ServiceConnection { 13189 IMediaContainerService mContainerService; 13190 13191 @Override 13192 public void onServiceConnected(ComponentName name, IBinder service) { 13193 synchronized (this) { 13194 mContainerService = IMediaContainerService.Stub.asInterface(service); 13195 notifyAll(); 13196 } 13197 } 13198 13199 @Override 13200 public void onServiceDisconnected(ComponentName name) { 13201 } 13202 } 13203 13204 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13205 final boolean mounted; 13206 if (Environment.isExternalStorageEmulated()) { 13207 mounted = true; 13208 } else { 13209 final String status = Environment.getExternalStorageState(); 13210 13211 mounted = status.equals(Environment.MEDIA_MOUNTED) 13212 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13213 } 13214 13215 if (!mounted) { 13216 return; 13217 } 13218 13219 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13220 int[] users; 13221 if (userId == UserHandle.USER_ALL) { 13222 users = sUserManager.getUserIds(); 13223 } else { 13224 users = new int[] { userId }; 13225 } 13226 final ClearStorageConnection conn = new ClearStorageConnection(); 13227 if (mContext.bindServiceAsUser( 13228 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13229 try { 13230 for (int curUser : users) { 13231 long timeout = SystemClock.uptimeMillis() + 5000; 13232 synchronized (conn) { 13233 long now = SystemClock.uptimeMillis(); 13234 while (conn.mContainerService == null && now < timeout) { 13235 try { 13236 conn.wait(timeout - now); 13237 } catch (InterruptedException e) { 13238 } 13239 } 13240 } 13241 if (conn.mContainerService == null) { 13242 return; 13243 } 13244 13245 final UserEnvironment userEnv = new UserEnvironment(curUser); 13246 clearDirectory(conn.mContainerService, 13247 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13248 if (allData) { 13249 clearDirectory(conn.mContainerService, 13250 userEnv.buildExternalStorageAppDataDirs(packageName)); 13251 clearDirectory(conn.mContainerService, 13252 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13253 } 13254 } 13255 } finally { 13256 mContext.unbindService(conn); 13257 } 13258 } 13259 } 13260 13261 @Override 13262 public void clearApplicationUserData(final String packageName, 13263 final IPackageDataObserver observer, final int userId) { 13264 mContext.enforceCallingOrSelfPermission( 13265 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13266 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13267 // Queue up an async operation since the package deletion may take a little while. 13268 mHandler.post(new Runnable() { 13269 public void run() { 13270 mHandler.removeCallbacks(this); 13271 final boolean succeeded; 13272 synchronized (mInstallLock) { 13273 succeeded = clearApplicationUserDataLI(packageName, userId); 13274 } 13275 clearExternalStorageDataSync(packageName, userId, true); 13276 if (succeeded) { 13277 // invoke DeviceStorageMonitor's update method to clear any notifications 13278 DeviceStorageMonitorInternal 13279 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13280 if (dsm != null) { 13281 dsm.checkMemory(); 13282 } 13283 } 13284 if(observer != null) { 13285 try { 13286 observer.onRemoveCompleted(packageName, succeeded); 13287 } catch (RemoteException e) { 13288 Log.i(TAG, "Observer no longer exists."); 13289 } 13290 } //end if observer 13291 } //end run 13292 }); 13293 } 13294 13295 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13296 if (packageName == null) { 13297 Slog.w(TAG, "Attempt to delete null packageName."); 13298 return false; 13299 } 13300 13301 // Try finding details about the requested package 13302 PackageParser.Package pkg; 13303 synchronized (mPackages) { 13304 pkg = mPackages.get(packageName); 13305 if (pkg == null) { 13306 final PackageSetting ps = mSettings.mPackages.get(packageName); 13307 if (ps != null) { 13308 pkg = ps.pkg; 13309 } 13310 } 13311 13312 if (pkg == null) { 13313 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13314 return false; 13315 } 13316 13317 PackageSetting ps = (PackageSetting) pkg.mExtras; 13318 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13319 } 13320 13321 // Always delete data directories for package, even if we found no other 13322 // record of app. This helps users recover from UID mismatches without 13323 // resorting to a full data wipe. 13324 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13325 if (retCode < 0) { 13326 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13327 return false; 13328 } 13329 13330 final int appId = pkg.applicationInfo.uid; 13331 removeKeystoreDataIfNeeded(userId, appId); 13332 13333 // Create a native library symlink only if we have native libraries 13334 // and if the native libraries are 32 bit libraries. We do not provide 13335 // this symlink for 64 bit libraries. 13336 if (pkg.applicationInfo.primaryCpuAbi != null && 13337 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13338 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13339 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13340 nativeLibPath, userId) < 0) { 13341 Slog.w(TAG, "Failed linking native library dir"); 13342 return false; 13343 } 13344 } 13345 13346 return true; 13347 } 13348 13349 /** 13350 * Reverts user permission state changes (permissions and flags) in 13351 * all packages for a given user. 13352 * 13353 * @param userId The device user for which to do a reset. 13354 */ 13355 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13356 final int packageCount = mPackages.size(); 13357 for (int i = 0; i < packageCount; i++) { 13358 PackageParser.Package pkg = mPackages.valueAt(i); 13359 PackageSetting ps = (PackageSetting) pkg.mExtras; 13360 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13361 } 13362 } 13363 13364 /** 13365 * Reverts user permission state changes (permissions and flags). 13366 * 13367 * @param ps The package for which to reset. 13368 * @param userId The device user for which to do a reset. 13369 */ 13370 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13371 final PackageSetting ps, final int userId) { 13372 if (ps.pkg == null) { 13373 return; 13374 } 13375 13376 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13377 | FLAG_PERMISSION_USER_FIXED 13378 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13379 13380 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13381 | FLAG_PERMISSION_POLICY_FIXED; 13382 13383 boolean writeInstallPermissions = false; 13384 boolean writeRuntimePermissions = false; 13385 13386 final int permissionCount = ps.pkg.requestedPermissions.size(); 13387 for (int i = 0; i < permissionCount; i++) { 13388 String permission = ps.pkg.requestedPermissions.get(i); 13389 13390 BasePermission bp = mSettings.mPermissions.get(permission); 13391 if (bp == null) { 13392 continue; 13393 } 13394 13395 // If shared user we just reset the state to which only this app contributed. 13396 if (ps.sharedUser != null) { 13397 boolean used = false; 13398 final int packageCount = ps.sharedUser.packages.size(); 13399 for (int j = 0; j < packageCount; j++) { 13400 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13401 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13402 && pkg.pkg.requestedPermissions.contains(permission)) { 13403 used = true; 13404 break; 13405 } 13406 } 13407 if (used) { 13408 continue; 13409 } 13410 } 13411 13412 PermissionsState permissionsState = ps.getPermissionsState(); 13413 13414 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13415 13416 // Always clear the user settable flags. 13417 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13418 bp.name) != null; 13419 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13420 if (hasInstallState) { 13421 writeInstallPermissions = true; 13422 } else { 13423 writeRuntimePermissions = true; 13424 } 13425 } 13426 13427 // Below is only runtime permission handling. 13428 if (!bp.isRuntime()) { 13429 continue; 13430 } 13431 13432 // Never clobber system or policy. 13433 if ((oldFlags & policyOrSystemFlags) != 0) { 13434 continue; 13435 } 13436 13437 // If this permission was granted by default, make sure it is. 13438 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13439 if (permissionsState.grantRuntimePermission(bp, userId) 13440 != PERMISSION_OPERATION_FAILURE) { 13441 writeRuntimePermissions = true; 13442 } 13443 } else { 13444 // Otherwise, reset the permission. 13445 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13446 switch (revokeResult) { 13447 case PERMISSION_OPERATION_SUCCESS: { 13448 writeRuntimePermissions = true; 13449 } break; 13450 13451 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13452 writeRuntimePermissions = true; 13453 final int appId = ps.appId; 13454 mHandler.post(new Runnable() { 13455 @Override 13456 public void run() { 13457 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13458 } 13459 }); 13460 } break; 13461 } 13462 } 13463 } 13464 13465 // Synchronously write as we are taking permissions away. 13466 if (writeRuntimePermissions) { 13467 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13468 } 13469 13470 // Synchronously write as we are taking permissions away. 13471 if (writeInstallPermissions) { 13472 mSettings.writeLPr(); 13473 } 13474 } 13475 13476 /** 13477 * Remove entries from the keystore daemon. Will only remove it if the 13478 * {@code appId} is valid. 13479 */ 13480 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13481 if (appId < 0) { 13482 return; 13483 } 13484 13485 final KeyStore keyStore = KeyStore.getInstance(); 13486 if (keyStore != null) { 13487 if (userId == UserHandle.USER_ALL) { 13488 for (final int individual : sUserManager.getUserIds()) { 13489 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13490 } 13491 } else { 13492 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13493 } 13494 } else { 13495 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13496 } 13497 } 13498 13499 @Override 13500 public void deleteApplicationCacheFiles(final String packageName, 13501 final IPackageDataObserver observer) { 13502 mContext.enforceCallingOrSelfPermission( 13503 android.Manifest.permission.DELETE_CACHE_FILES, null); 13504 // Queue up an async operation since the package deletion may take a little while. 13505 final int userId = UserHandle.getCallingUserId(); 13506 mHandler.post(new Runnable() { 13507 public void run() { 13508 mHandler.removeCallbacks(this); 13509 final boolean succeded; 13510 synchronized (mInstallLock) { 13511 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13512 } 13513 clearExternalStorageDataSync(packageName, userId, false); 13514 if (observer != null) { 13515 try { 13516 observer.onRemoveCompleted(packageName, succeded); 13517 } catch (RemoteException e) { 13518 Log.i(TAG, "Observer no longer exists."); 13519 } 13520 } //end if observer 13521 } //end run 13522 }); 13523 } 13524 13525 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13526 if (packageName == null) { 13527 Slog.w(TAG, "Attempt to delete null packageName."); 13528 return false; 13529 } 13530 PackageParser.Package p; 13531 synchronized (mPackages) { 13532 p = mPackages.get(packageName); 13533 } 13534 if (p == null) { 13535 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13536 return false; 13537 } 13538 final ApplicationInfo applicationInfo = p.applicationInfo; 13539 if (applicationInfo == null) { 13540 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13541 return false; 13542 } 13543 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13544 if (retCode < 0) { 13545 Slog.w(TAG, "Couldn't remove cache files for package: " 13546 + packageName + " u" + userId); 13547 return false; 13548 } 13549 return true; 13550 } 13551 13552 @Override 13553 public void getPackageSizeInfo(final String packageName, int userHandle, 13554 final IPackageStatsObserver observer) { 13555 mContext.enforceCallingOrSelfPermission( 13556 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13557 if (packageName == null) { 13558 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13559 } 13560 13561 PackageStats stats = new PackageStats(packageName, userHandle); 13562 13563 /* 13564 * Queue up an async operation since the package measurement may take a 13565 * little while. 13566 */ 13567 Message msg = mHandler.obtainMessage(INIT_COPY); 13568 msg.obj = new MeasureParams(stats, observer); 13569 mHandler.sendMessage(msg); 13570 } 13571 13572 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13573 PackageStats pStats) { 13574 if (packageName == null) { 13575 Slog.w(TAG, "Attempt to get size of null packageName."); 13576 return false; 13577 } 13578 PackageParser.Package p; 13579 boolean dataOnly = false; 13580 String libDirRoot = null; 13581 String asecPath = null; 13582 PackageSetting ps = null; 13583 synchronized (mPackages) { 13584 p = mPackages.get(packageName); 13585 ps = mSettings.mPackages.get(packageName); 13586 if(p == null) { 13587 dataOnly = true; 13588 if((ps == null) || (ps.pkg == null)) { 13589 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13590 return false; 13591 } 13592 p = ps.pkg; 13593 } 13594 if (ps != null) { 13595 libDirRoot = ps.legacyNativeLibraryPathString; 13596 } 13597 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13598 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13599 if (secureContainerId != null) { 13600 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13601 } 13602 } 13603 } 13604 String publicSrcDir = null; 13605 if(!dataOnly) { 13606 final ApplicationInfo applicationInfo = p.applicationInfo; 13607 if (applicationInfo == null) { 13608 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13609 return false; 13610 } 13611 if (p.isForwardLocked()) { 13612 publicSrcDir = applicationInfo.getBaseResourcePath(); 13613 } 13614 } 13615 // TODO: extend to measure size of split APKs 13616 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13617 // not just the first level. 13618 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13619 // just the primary. 13620 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13621 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13622 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13623 if (res < 0) { 13624 return false; 13625 } 13626 13627 // Fix-up for forward-locked applications in ASEC containers. 13628 if (!isExternal(p)) { 13629 pStats.codeSize += pStats.externalCodeSize; 13630 pStats.externalCodeSize = 0L; 13631 } 13632 13633 return true; 13634 } 13635 13636 13637 @Override 13638 public void addPackageToPreferred(String packageName) { 13639 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13640 } 13641 13642 @Override 13643 public void removePackageFromPreferred(String packageName) { 13644 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13645 } 13646 13647 @Override 13648 public List<PackageInfo> getPreferredPackages(int flags) { 13649 return new ArrayList<PackageInfo>(); 13650 } 13651 13652 private int getUidTargetSdkVersionLockedLPr(int uid) { 13653 Object obj = mSettings.getUserIdLPr(uid); 13654 if (obj instanceof SharedUserSetting) { 13655 final SharedUserSetting sus = (SharedUserSetting) obj; 13656 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13657 final Iterator<PackageSetting> it = sus.packages.iterator(); 13658 while (it.hasNext()) { 13659 final PackageSetting ps = it.next(); 13660 if (ps.pkg != null) { 13661 int v = ps.pkg.applicationInfo.targetSdkVersion; 13662 if (v < vers) vers = v; 13663 } 13664 } 13665 return vers; 13666 } else if (obj instanceof PackageSetting) { 13667 final PackageSetting ps = (PackageSetting) obj; 13668 if (ps.pkg != null) { 13669 return ps.pkg.applicationInfo.targetSdkVersion; 13670 } 13671 } 13672 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13673 } 13674 13675 @Override 13676 public void addPreferredActivity(IntentFilter filter, int match, 13677 ComponentName[] set, ComponentName activity, int userId) { 13678 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13679 "Adding preferred"); 13680 } 13681 13682 private void addPreferredActivityInternal(IntentFilter filter, int match, 13683 ComponentName[] set, ComponentName activity, boolean always, int userId, 13684 String opname) { 13685 // writer 13686 int callingUid = Binder.getCallingUid(); 13687 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13688 if (filter.countActions() == 0) { 13689 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13690 return; 13691 } 13692 synchronized (mPackages) { 13693 if (mContext.checkCallingOrSelfPermission( 13694 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13695 != PackageManager.PERMISSION_GRANTED) { 13696 if (getUidTargetSdkVersionLockedLPr(callingUid) 13697 < Build.VERSION_CODES.FROYO) { 13698 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13699 + callingUid); 13700 return; 13701 } 13702 mContext.enforceCallingOrSelfPermission( 13703 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13704 } 13705 13706 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13707 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13708 + userId + ":"); 13709 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13710 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13711 scheduleWritePackageRestrictionsLocked(userId); 13712 } 13713 } 13714 13715 @Override 13716 public void replacePreferredActivity(IntentFilter filter, int match, 13717 ComponentName[] set, ComponentName activity, int userId) { 13718 if (filter.countActions() != 1) { 13719 throw new IllegalArgumentException( 13720 "replacePreferredActivity expects filter to have only 1 action."); 13721 } 13722 if (filter.countDataAuthorities() != 0 13723 || filter.countDataPaths() != 0 13724 || filter.countDataSchemes() > 1 13725 || filter.countDataTypes() != 0) { 13726 throw new IllegalArgumentException( 13727 "replacePreferredActivity expects filter to have no data authorities, " + 13728 "paths, or types; and at most one scheme."); 13729 } 13730 13731 final int callingUid = Binder.getCallingUid(); 13732 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13733 synchronized (mPackages) { 13734 if (mContext.checkCallingOrSelfPermission( 13735 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13736 != PackageManager.PERMISSION_GRANTED) { 13737 if (getUidTargetSdkVersionLockedLPr(callingUid) 13738 < Build.VERSION_CODES.FROYO) { 13739 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13740 + Binder.getCallingUid()); 13741 return; 13742 } 13743 mContext.enforceCallingOrSelfPermission( 13744 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13745 } 13746 13747 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13748 if (pir != null) { 13749 // Get all of the existing entries that exactly match this filter. 13750 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13751 if (existing != null && existing.size() == 1) { 13752 PreferredActivity cur = existing.get(0); 13753 if (DEBUG_PREFERRED) { 13754 Slog.i(TAG, "Checking replace of preferred:"); 13755 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13756 if (!cur.mPref.mAlways) { 13757 Slog.i(TAG, " -- CUR; not mAlways!"); 13758 } else { 13759 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13760 Slog.i(TAG, " -- CUR: mSet=" 13761 + Arrays.toString(cur.mPref.mSetComponents)); 13762 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13763 Slog.i(TAG, " -- NEW: mMatch=" 13764 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13765 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13766 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13767 } 13768 } 13769 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13770 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13771 && cur.mPref.sameSet(set)) { 13772 // Setting the preferred activity to what it happens to be already 13773 if (DEBUG_PREFERRED) { 13774 Slog.i(TAG, "Replacing with same preferred activity " 13775 + cur.mPref.mShortComponent + " for user " 13776 + userId + ":"); 13777 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13778 } 13779 return; 13780 } 13781 } 13782 13783 if (existing != null) { 13784 if (DEBUG_PREFERRED) { 13785 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13786 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13787 } 13788 for (int i = 0; i < existing.size(); i++) { 13789 PreferredActivity pa = existing.get(i); 13790 if (DEBUG_PREFERRED) { 13791 Slog.i(TAG, "Removing existing preferred activity " 13792 + pa.mPref.mComponent + ":"); 13793 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13794 } 13795 pir.removeFilter(pa); 13796 } 13797 } 13798 } 13799 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13800 "Replacing preferred"); 13801 } 13802 } 13803 13804 @Override 13805 public void clearPackagePreferredActivities(String packageName) { 13806 final int uid = Binder.getCallingUid(); 13807 // writer 13808 synchronized (mPackages) { 13809 PackageParser.Package pkg = mPackages.get(packageName); 13810 if (pkg == null || pkg.applicationInfo.uid != uid) { 13811 if (mContext.checkCallingOrSelfPermission( 13812 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13813 != PackageManager.PERMISSION_GRANTED) { 13814 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13815 < Build.VERSION_CODES.FROYO) { 13816 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13817 + Binder.getCallingUid()); 13818 return; 13819 } 13820 mContext.enforceCallingOrSelfPermission( 13821 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13822 } 13823 } 13824 13825 int user = UserHandle.getCallingUserId(); 13826 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13827 scheduleWritePackageRestrictionsLocked(user); 13828 } 13829 } 13830 } 13831 13832 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13833 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13834 ArrayList<PreferredActivity> removed = null; 13835 boolean changed = false; 13836 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13837 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13838 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13839 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13840 continue; 13841 } 13842 Iterator<PreferredActivity> it = pir.filterIterator(); 13843 while (it.hasNext()) { 13844 PreferredActivity pa = it.next(); 13845 // Mark entry for removal only if it matches the package name 13846 // and the entry is of type "always". 13847 if (packageName == null || 13848 (pa.mPref.mComponent.getPackageName().equals(packageName) 13849 && pa.mPref.mAlways)) { 13850 if (removed == null) { 13851 removed = new ArrayList<PreferredActivity>(); 13852 } 13853 removed.add(pa); 13854 } 13855 } 13856 if (removed != null) { 13857 for (int j=0; j<removed.size(); j++) { 13858 PreferredActivity pa = removed.get(j); 13859 pir.removeFilter(pa); 13860 } 13861 changed = true; 13862 } 13863 } 13864 return changed; 13865 } 13866 13867 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13868 private void clearIntentFilterVerificationsLPw(int userId) { 13869 final int packageCount = mPackages.size(); 13870 for (int i = 0; i < packageCount; i++) { 13871 PackageParser.Package pkg = mPackages.valueAt(i); 13872 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13873 } 13874 } 13875 13876 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13877 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13878 if (userId == UserHandle.USER_ALL) { 13879 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13880 sUserManager.getUserIds())) { 13881 for (int oneUserId : sUserManager.getUserIds()) { 13882 scheduleWritePackageRestrictionsLocked(oneUserId); 13883 } 13884 } 13885 } else { 13886 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13887 scheduleWritePackageRestrictionsLocked(userId); 13888 } 13889 } 13890 } 13891 13892 void clearDefaultBrowserIfNeeded(String packageName) { 13893 for (int oneUserId : sUserManager.getUserIds()) { 13894 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13895 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13896 if (packageName.equals(defaultBrowserPackageName)) { 13897 setDefaultBrowserPackageName(null, oneUserId); 13898 } 13899 } 13900 } 13901 13902 @Override 13903 public void resetApplicationPreferences(int userId) { 13904 mContext.enforceCallingOrSelfPermission( 13905 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13906 // writer 13907 synchronized (mPackages) { 13908 final long identity = Binder.clearCallingIdentity(); 13909 try { 13910 clearPackagePreferredActivitiesLPw(null, userId); 13911 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13912 // TODO: We have to reset the default SMS and Phone. This requires 13913 // significant refactoring to keep all default apps in the package 13914 // manager (cleaner but more work) or have the services provide 13915 // callbacks to the package manager to request a default app reset. 13916 applyFactoryDefaultBrowserLPw(userId); 13917 clearIntentFilterVerificationsLPw(userId); 13918 primeDomainVerificationsLPw(userId); 13919 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 13920 scheduleWritePackageRestrictionsLocked(userId); 13921 } finally { 13922 Binder.restoreCallingIdentity(identity); 13923 } 13924 } 13925 } 13926 13927 @Override 13928 public int getPreferredActivities(List<IntentFilter> outFilters, 13929 List<ComponentName> outActivities, String packageName) { 13930 13931 int num = 0; 13932 final int userId = UserHandle.getCallingUserId(); 13933 // reader 13934 synchronized (mPackages) { 13935 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13936 if (pir != null) { 13937 final Iterator<PreferredActivity> it = pir.filterIterator(); 13938 while (it.hasNext()) { 13939 final PreferredActivity pa = it.next(); 13940 if (packageName == null 13941 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13942 && pa.mPref.mAlways)) { 13943 if (outFilters != null) { 13944 outFilters.add(new IntentFilter(pa)); 13945 } 13946 if (outActivities != null) { 13947 outActivities.add(pa.mPref.mComponent); 13948 } 13949 } 13950 } 13951 } 13952 } 13953 13954 return num; 13955 } 13956 13957 @Override 13958 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13959 int userId) { 13960 int callingUid = Binder.getCallingUid(); 13961 if (callingUid != Process.SYSTEM_UID) { 13962 throw new SecurityException( 13963 "addPersistentPreferredActivity can only be run by the system"); 13964 } 13965 if (filter.countActions() == 0) { 13966 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13967 return; 13968 } 13969 synchronized (mPackages) { 13970 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13971 " :"); 13972 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13973 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13974 new PersistentPreferredActivity(filter, activity)); 13975 scheduleWritePackageRestrictionsLocked(userId); 13976 } 13977 } 13978 13979 @Override 13980 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13981 int callingUid = Binder.getCallingUid(); 13982 if (callingUid != Process.SYSTEM_UID) { 13983 throw new SecurityException( 13984 "clearPackagePersistentPreferredActivities can only be run by the system"); 13985 } 13986 ArrayList<PersistentPreferredActivity> removed = null; 13987 boolean changed = false; 13988 synchronized (mPackages) { 13989 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13990 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13991 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13992 .valueAt(i); 13993 if (userId != thisUserId) { 13994 continue; 13995 } 13996 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13997 while (it.hasNext()) { 13998 PersistentPreferredActivity ppa = it.next(); 13999 // Mark entry for removal only if it matches the package name. 14000 if (ppa.mComponent.getPackageName().equals(packageName)) { 14001 if (removed == null) { 14002 removed = new ArrayList<PersistentPreferredActivity>(); 14003 } 14004 removed.add(ppa); 14005 } 14006 } 14007 if (removed != null) { 14008 for (int j=0; j<removed.size(); j++) { 14009 PersistentPreferredActivity ppa = removed.get(j); 14010 ppir.removeFilter(ppa); 14011 } 14012 changed = true; 14013 } 14014 } 14015 14016 if (changed) { 14017 scheduleWritePackageRestrictionsLocked(userId); 14018 } 14019 } 14020 } 14021 14022 /** 14023 * Common machinery for picking apart a restored XML blob and passing 14024 * it to a caller-supplied functor to be applied to the running system. 14025 */ 14026 private void restoreFromXml(XmlPullParser parser, int userId, 14027 String expectedStartTag, BlobXmlRestorer functor) 14028 throws IOException, XmlPullParserException { 14029 int type; 14030 while ((type = parser.next()) != XmlPullParser.START_TAG 14031 && type != XmlPullParser.END_DOCUMENT) { 14032 } 14033 if (type != XmlPullParser.START_TAG) { 14034 // oops didn't find a start tag?! 14035 if (DEBUG_BACKUP) { 14036 Slog.e(TAG, "Didn't find start tag during restore"); 14037 } 14038 return; 14039 } 14040 14041 // this is supposed to be TAG_PREFERRED_BACKUP 14042 if (!expectedStartTag.equals(parser.getName())) { 14043 if (DEBUG_BACKUP) { 14044 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14045 } 14046 return; 14047 } 14048 14049 // skip interfering stuff, then we're aligned with the backing implementation 14050 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14051 functor.apply(parser, userId); 14052 } 14053 14054 private interface BlobXmlRestorer { 14055 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14056 } 14057 14058 /** 14059 * Non-Binder method, support for the backup/restore mechanism: write the 14060 * full set of preferred activities in its canonical XML format. Returns the 14061 * XML output as a byte array, or null if there is none. 14062 */ 14063 @Override 14064 public byte[] getPreferredActivityBackup(int userId) { 14065 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14066 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14067 } 14068 14069 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14070 try { 14071 final XmlSerializer serializer = new FastXmlSerializer(); 14072 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14073 serializer.startDocument(null, true); 14074 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14075 14076 synchronized (mPackages) { 14077 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14078 } 14079 14080 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14081 serializer.endDocument(); 14082 serializer.flush(); 14083 } catch (Exception e) { 14084 if (DEBUG_BACKUP) { 14085 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14086 } 14087 return null; 14088 } 14089 14090 return dataStream.toByteArray(); 14091 } 14092 14093 @Override 14094 public void restorePreferredActivities(byte[] backup, int userId) { 14095 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14096 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14097 } 14098 14099 try { 14100 final XmlPullParser parser = Xml.newPullParser(); 14101 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14102 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14103 new BlobXmlRestorer() { 14104 @Override 14105 public void apply(XmlPullParser parser, int userId) 14106 throws XmlPullParserException, IOException { 14107 synchronized (mPackages) { 14108 mSettings.readPreferredActivitiesLPw(parser, userId); 14109 } 14110 } 14111 } ); 14112 } catch (Exception e) { 14113 if (DEBUG_BACKUP) { 14114 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14115 } 14116 } 14117 } 14118 14119 /** 14120 * Non-Binder method, support for the backup/restore mechanism: write the 14121 * default browser (etc) settings in its canonical XML format. Returns the default 14122 * browser XML representation as a byte array, or null if there is none. 14123 */ 14124 @Override 14125 public byte[] getDefaultAppsBackup(int userId) { 14126 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14127 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14128 } 14129 14130 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14131 try { 14132 final XmlSerializer serializer = new FastXmlSerializer(); 14133 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14134 serializer.startDocument(null, true); 14135 serializer.startTag(null, TAG_DEFAULT_APPS); 14136 14137 synchronized (mPackages) { 14138 mSettings.writeDefaultAppsLPr(serializer, userId); 14139 } 14140 14141 serializer.endTag(null, TAG_DEFAULT_APPS); 14142 serializer.endDocument(); 14143 serializer.flush(); 14144 } catch (Exception e) { 14145 if (DEBUG_BACKUP) { 14146 Slog.e(TAG, "Unable to write default apps for backup", e); 14147 } 14148 return null; 14149 } 14150 14151 return dataStream.toByteArray(); 14152 } 14153 14154 @Override 14155 public void restoreDefaultApps(byte[] backup, int userId) { 14156 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14157 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14158 } 14159 14160 try { 14161 final XmlPullParser parser = Xml.newPullParser(); 14162 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14163 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14164 new BlobXmlRestorer() { 14165 @Override 14166 public void apply(XmlPullParser parser, int userId) 14167 throws XmlPullParserException, IOException { 14168 synchronized (mPackages) { 14169 mSettings.readDefaultAppsLPw(parser, userId); 14170 } 14171 } 14172 } ); 14173 } catch (Exception e) { 14174 if (DEBUG_BACKUP) { 14175 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14176 } 14177 } 14178 } 14179 14180 @Override 14181 public byte[] getIntentFilterVerificationBackup(int userId) { 14182 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14183 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14184 } 14185 14186 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14187 try { 14188 final XmlSerializer serializer = new FastXmlSerializer(); 14189 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14190 serializer.startDocument(null, true); 14191 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14192 14193 synchronized (mPackages) { 14194 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14195 } 14196 14197 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14198 serializer.endDocument(); 14199 serializer.flush(); 14200 } catch (Exception e) { 14201 if (DEBUG_BACKUP) { 14202 Slog.e(TAG, "Unable to write default apps for backup", e); 14203 } 14204 return null; 14205 } 14206 14207 return dataStream.toByteArray(); 14208 } 14209 14210 @Override 14211 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14212 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14213 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14214 } 14215 14216 try { 14217 final XmlPullParser parser = Xml.newPullParser(); 14218 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14219 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14220 new BlobXmlRestorer() { 14221 @Override 14222 public void apply(XmlPullParser parser, int userId) 14223 throws XmlPullParserException, IOException { 14224 synchronized (mPackages) { 14225 mSettings.readAllDomainVerificationsLPr(parser, userId); 14226 mSettings.writeLPr(); 14227 } 14228 } 14229 } ); 14230 } catch (Exception e) { 14231 if (DEBUG_BACKUP) { 14232 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14233 } 14234 } 14235 } 14236 14237 @Override 14238 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14239 int sourceUserId, int targetUserId, int flags) { 14240 mContext.enforceCallingOrSelfPermission( 14241 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14242 int callingUid = Binder.getCallingUid(); 14243 enforceOwnerRights(ownerPackage, callingUid); 14244 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14245 if (intentFilter.countActions() == 0) { 14246 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14247 return; 14248 } 14249 synchronized (mPackages) { 14250 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14251 ownerPackage, targetUserId, flags); 14252 CrossProfileIntentResolver resolver = 14253 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14254 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14255 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14256 if (existing != null) { 14257 int size = existing.size(); 14258 for (int i = 0; i < size; i++) { 14259 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14260 return; 14261 } 14262 } 14263 } 14264 resolver.addFilter(newFilter); 14265 scheduleWritePackageRestrictionsLocked(sourceUserId); 14266 } 14267 } 14268 14269 @Override 14270 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14271 mContext.enforceCallingOrSelfPermission( 14272 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14273 int callingUid = Binder.getCallingUid(); 14274 enforceOwnerRights(ownerPackage, callingUid); 14275 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14276 synchronized (mPackages) { 14277 CrossProfileIntentResolver resolver = 14278 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14279 ArraySet<CrossProfileIntentFilter> set = 14280 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14281 for (CrossProfileIntentFilter filter : set) { 14282 if (filter.getOwnerPackage().equals(ownerPackage)) { 14283 resolver.removeFilter(filter); 14284 } 14285 } 14286 scheduleWritePackageRestrictionsLocked(sourceUserId); 14287 } 14288 } 14289 14290 // Enforcing that callingUid is owning pkg on userId 14291 private void enforceOwnerRights(String pkg, int callingUid) { 14292 // The system owns everything. 14293 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14294 return; 14295 } 14296 int callingUserId = UserHandle.getUserId(callingUid); 14297 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14298 if (pi == null) { 14299 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14300 + callingUserId); 14301 } 14302 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14303 throw new SecurityException("Calling uid " + callingUid 14304 + " does not own package " + pkg); 14305 } 14306 } 14307 14308 @Override 14309 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14310 Intent intent = new Intent(Intent.ACTION_MAIN); 14311 intent.addCategory(Intent.CATEGORY_HOME); 14312 14313 final int callingUserId = UserHandle.getCallingUserId(); 14314 List<ResolveInfo> list = queryIntentActivities(intent, null, 14315 PackageManager.GET_META_DATA, callingUserId); 14316 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14317 true, false, false, callingUserId); 14318 14319 allHomeCandidates.clear(); 14320 if (list != null) { 14321 for (ResolveInfo ri : list) { 14322 allHomeCandidates.add(ri); 14323 } 14324 } 14325 return (preferred == null || preferred.activityInfo == null) 14326 ? null 14327 : new ComponentName(preferred.activityInfo.packageName, 14328 preferred.activityInfo.name); 14329 } 14330 14331 @Override 14332 public void setApplicationEnabledSetting(String appPackageName, 14333 int newState, int flags, int userId, String callingPackage) { 14334 if (!sUserManager.exists(userId)) return; 14335 if (callingPackage == null) { 14336 callingPackage = Integer.toString(Binder.getCallingUid()); 14337 } 14338 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14339 } 14340 14341 @Override 14342 public void setComponentEnabledSetting(ComponentName componentName, 14343 int newState, int flags, int userId) { 14344 if (!sUserManager.exists(userId)) return; 14345 setEnabledSetting(componentName.getPackageName(), 14346 componentName.getClassName(), newState, flags, userId, null); 14347 } 14348 14349 private void setEnabledSetting(final String packageName, String className, int newState, 14350 final int flags, int userId, String callingPackage) { 14351 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14352 || newState == COMPONENT_ENABLED_STATE_ENABLED 14353 || newState == COMPONENT_ENABLED_STATE_DISABLED 14354 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14355 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14356 throw new IllegalArgumentException("Invalid new component state: " 14357 + newState); 14358 } 14359 PackageSetting pkgSetting; 14360 final int uid = Binder.getCallingUid(); 14361 final int permission = mContext.checkCallingOrSelfPermission( 14362 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14363 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14364 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14365 boolean sendNow = false; 14366 boolean isApp = (className == null); 14367 String componentName = isApp ? packageName : className; 14368 int packageUid = -1; 14369 ArrayList<String> components; 14370 14371 // writer 14372 synchronized (mPackages) { 14373 pkgSetting = mSettings.mPackages.get(packageName); 14374 if (pkgSetting == null) { 14375 if (className == null) { 14376 throw new IllegalArgumentException( 14377 "Unknown package: " + packageName); 14378 } 14379 throw new IllegalArgumentException( 14380 "Unknown component: " + packageName 14381 + "/" + className); 14382 } 14383 // Allow root and verify that userId is not being specified by a different user 14384 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14385 throw new SecurityException( 14386 "Permission Denial: attempt to change component state from pid=" 14387 + Binder.getCallingPid() 14388 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14389 } 14390 if (className == null) { 14391 // We're dealing with an application/package level state change 14392 if (pkgSetting.getEnabled(userId) == newState) { 14393 // Nothing to do 14394 return; 14395 } 14396 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14397 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14398 // Don't care about who enables an app. 14399 callingPackage = null; 14400 } 14401 pkgSetting.setEnabled(newState, userId, callingPackage); 14402 // pkgSetting.pkg.mSetEnabled = newState; 14403 } else { 14404 // We're dealing with a component level state change 14405 // First, verify that this is a valid class name. 14406 PackageParser.Package pkg = pkgSetting.pkg; 14407 if (pkg == null || !pkg.hasComponentClassName(className)) { 14408 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14409 throw new IllegalArgumentException("Component class " + className 14410 + " does not exist in " + packageName); 14411 } else { 14412 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14413 + className + " does not exist in " + packageName); 14414 } 14415 } 14416 switch (newState) { 14417 case COMPONENT_ENABLED_STATE_ENABLED: 14418 if (!pkgSetting.enableComponentLPw(className, userId)) { 14419 return; 14420 } 14421 break; 14422 case COMPONENT_ENABLED_STATE_DISABLED: 14423 if (!pkgSetting.disableComponentLPw(className, userId)) { 14424 return; 14425 } 14426 break; 14427 case COMPONENT_ENABLED_STATE_DEFAULT: 14428 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14429 return; 14430 } 14431 break; 14432 default: 14433 Slog.e(TAG, "Invalid new component state: " + newState); 14434 return; 14435 } 14436 } 14437 scheduleWritePackageRestrictionsLocked(userId); 14438 components = mPendingBroadcasts.get(userId, packageName); 14439 final boolean newPackage = components == null; 14440 if (newPackage) { 14441 components = new ArrayList<String>(); 14442 } 14443 if (!components.contains(componentName)) { 14444 components.add(componentName); 14445 } 14446 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14447 sendNow = true; 14448 // Purge entry from pending broadcast list if another one exists already 14449 // since we are sending one right away. 14450 mPendingBroadcasts.remove(userId, packageName); 14451 } else { 14452 if (newPackage) { 14453 mPendingBroadcasts.put(userId, packageName, components); 14454 } 14455 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14456 // Schedule a message 14457 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14458 } 14459 } 14460 } 14461 14462 long callingId = Binder.clearCallingIdentity(); 14463 try { 14464 if (sendNow) { 14465 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14466 sendPackageChangedBroadcast(packageName, 14467 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14468 } 14469 } finally { 14470 Binder.restoreCallingIdentity(callingId); 14471 } 14472 } 14473 14474 private void sendPackageChangedBroadcast(String packageName, 14475 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14476 if (DEBUG_INSTALL) 14477 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14478 + componentNames); 14479 Bundle extras = new Bundle(4); 14480 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14481 String nameList[] = new String[componentNames.size()]; 14482 componentNames.toArray(nameList); 14483 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14484 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14485 extras.putInt(Intent.EXTRA_UID, packageUid); 14486 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14487 new int[] {UserHandle.getUserId(packageUid)}); 14488 } 14489 14490 @Override 14491 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14492 if (!sUserManager.exists(userId)) return; 14493 final int uid = Binder.getCallingUid(); 14494 final int permission = mContext.checkCallingOrSelfPermission( 14495 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14496 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14497 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14498 // writer 14499 synchronized (mPackages) { 14500 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14501 allowedByPermission, uid, userId)) { 14502 scheduleWritePackageRestrictionsLocked(userId); 14503 } 14504 } 14505 } 14506 14507 @Override 14508 public String getInstallerPackageName(String packageName) { 14509 // reader 14510 synchronized (mPackages) { 14511 return mSettings.getInstallerPackageNameLPr(packageName); 14512 } 14513 } 14514 14515 @Override 14516 public int getApplicationEnabledSetting(String packageName, int userId) { 14517 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14518 int uid = Binder.getCallingUid(); 14519 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14520 // reader 14521 synchronized (mPackages) { 14522 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14523 } 14524 } 14525 14526 @Override 14527 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14528 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14529 int uid = Binder.getCallingUid(); 14530 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14531 // reader 14532 synchronized (mPackages) { 14533 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14534 } 14535 } 14536 14537 @Override 14538 public void enterSafeMode() { 14539 enforceSystemOrRoot("Only the system can request entering safe mode"); 14540 14541 if (!mSystemReady) { 14542 mSafeMode = true; 14543 } 14544 } 14545 14546 @Override 14547 public void systemReady() { 14548 mSystemReady = true; 14549 14550 // Read the compatibilty setting when the system is ready. 14551 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14552 mContext.getContentResolver(), 14553 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14554 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14555 if (DEBUG_SETTINGS) { 14556 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14557 } 14558 14559 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14560 14561 synchronized (mPackages) { 14562 // Verify that all of the preferred activity components actually 14563 // exist. It is possible for applications to be updated and at 14564 // that point remove a previously declared activity component that 14565 // had been set as a preferred activity. We try to clean this up 14566 // the next time we encounter that preferred activity, but it is 14567 // possible for the user flow to never be able to return to that 14568 // situation so here we do a sanity check to make sure we haven't 14569 // left any junk around. 14570 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14571 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14572 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14573 removed.clear(); 14574 for (PreferredActivity pa : pir.filterSet()) { 14575 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14576 removed.add(pa); 14577 } 14578 } 14579 if (removed.size() > 0) { 14580 for (int r=0; r<removed.size(); r++) { 14581 PreferredActivity pa = removed.get(r); 14582 Slog.w(TAG, "Removing dangling preferred activity: " 14583 + pa.mPref.mComponent); 14584 pir.removeFilter(pa); 14585 } 14586 mSettings.writePackageRestrictionsLPr( 14587 mSettings.mPreferredActivities.keyAt(i)); 14588 } 14589 } 14590 14591 for (int userId : UserManagerService.getInstance().getUserIds()) { 14592 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14593 grantPermissionsUserIds = ArrayUtils.appendInt( 14594 grantPermissionsUserIds, userId); 14595 } 14596 } 14597 } 14598 sUserManager.systemReady(); 14599 14600 // If we upgraded grant all default permissions before kicking off. 14601 for (int userId : grantPermissionsUserIds) { 14602 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14603 } 14604 14605 // Kick off any messages waiting for system ready 14606 if (mPostSystemReadyMessages != null) { 14607 for (Message msg : mPostSystemReadyMessages) { 14608 msg.sendToTarget(); 14609 } 14610 mPostSystemReadyMessages = null; 14611 } 14612 14613 // Watch for external volumes that come and go over time 14614 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14615 storage.registerListener(mStorageListener); 14616 14617 mInstallerService.systemReady(); 14618 mPackageDexOptimizer.systemReady(); 14619 14620 MountServiceInternal mountServiceInternal = LocalServices.getService( 14621 MountServiceInternal.class); 14622 mountServiceInternal.addExternalStoragePolicy( 14623 new MountServiceInternal.ExternalStorageMountPolicy() { 14624 @Override 14625 public int getMountMode(int uid, String packageName) { 14626 if (Process.isIsolated(uid)) { 14627 return Zygote.MOUNT_EXTERNAL_NONE; 14628 } 14629 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14630 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14631 } 14632 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14633 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14634 } 14635 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14636 return Zygote.MOUNT_EXTERNAL_READ; 14637 } 14638 return Zygote.MOUNT_EXTERNAL_WRITE; 14639 } 14640 14641 @Override 14642 public boolean hasExternalStorage(int uid, String packageName) { 14643 return true; 14644 } 14645 }); 14646 } 14647 14648 @Override 14649 public boolean isSafeMode() { 14650 return mSafeMode; 14651 } 14652 14653 @Override 14654 public boolean hasSystemUidErrors() { 14655 return mHasSystemUidErrors; 14656 } 14657 14658 static String arrayToString(int[] array) { 14659 StringBuffer buf = new StringBuffer(128); 14660 buf.append('['); 14661 if (array != null) { 14662 for (int i=0; i<array.length; i++) { 14663 if (i > 0) buf.append(", "); 14664 buf.append(array[i]); 14665 } 14666 } 14667 buf.append(']'); 14668 return buf.toString(); 14669 } 14670 14671 static class DumpState { 14672 public static final int DUMP_LIBS = 1 << 0; 14673 public static final int DUMP_FEATURES = 1 << 1; 14674 public static final int DUMP_RESOLVERS = 1 << 2; 14675 public static final int DUMP_PERMISSIONS = 1 << 3; 14676 public static final int DUMP_PACKAGES = 1 << 4; 14677 public static final int DUMP_SHARED_USERS = 1 << 5; 14678 public static final int DUMP_MESSAGES = 1 << 6; 14679 public static final int DUMP_PROVIDERS = 1 << 7; 14680 public static final int DUMP_VERIFIERS = 1 << 8; 14681 public static final int DUMP_PREFERRED = 1 << 9; 14682 public static final int DUMP_PREFERRED_XML = 1 << 10; 14683 public static final int DUMP_KEYSETS = 1 << 11; 14684 public static final int DUMP_VERSION = 1 << 12; 14685 public static final int DUMP_INSTALLS = 1 << 13; 14686 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14687 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14688 14689 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14690 14691 private int mTypes; 14692 14693 private int mOptions; 14694 14695 private boolean mTitlePrinted; 14696 14697 private SharedUserSetting mSharedUser; 14698 14699 public boolean isDumping(int type) { 14700 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14701 return true; 14702 } 14703 14704 return (mTypes & type) != 0; 14705 } 14706 14707 public void setDump(int type) { 14708 mTypes |= type; 14709 } 14710 14711 public boolean isOptionEnabled(int option) { 14712 return (mOptions & option) != 0; 14713 } 14714 14715 public void setOptionEnabled(int option) { 14716 mOptions |= option; 14717 } 14718 14719 public boolean onTitlePrinted() { 14720 final boolean printed = mTitlePrinted; 14721 mTitlePrinted = true; 14722 return printed; 14723 } 14724 14725 public boolean getTitlePrinted() { 14726 return mTitlePrinted; 14727 } 14728 14729 public void setTitlePrinted(boolean enabled) { 14730 mTitlePrinted = enabled; 14731 } 14732 14733 public SharedUserSetting getSharedUser() { 14734 return mSharedUser; 14735 } 14736 14737 public void setSharedUser(SharedUserSetting user) { 14738 mSharedUser = user; 14739 } 14740 } 14741 14742 @Override 14743 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14744 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14745 != PackageManager.PERMISSION_GRANTED) { 14746 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14747 + Binder.getCallingPid() 14748 + ", uid=" + Binder.getCallingUid() 14749 + " without permission " 14750 + android.Manifest.permission.DUMP); 14751 return; 14752 } 14753 14754 DumpState dumpState = new DumpState(); 14755 boolean fullPreferred = false; 14756 boolean checkin = false; 14757 14758 String packageName = null; 14759 ArraySet<String> permissionNames = null; 14760 14761 int opti = 0; 14762 while (opti < args.length) { 14763 String opt = args[opti]; 14764 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14765 break; 14766 } 14767 opti++; 14768 14769 if ("-a".equals(opt)) { 14770 // Right now we only know how to print all. 14771 } else if ("-h".equals(opt)) { 14772 pw.println("Package manager dump options:"); 14773 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14774 pw.println(" --checkin: dump for a checkin"); 14775 pw.println(" -f: print details of intent filters"); 14776 pw.println(" -h: print this help"); 14777 pw.println(" cmd may be one of:"); 14778 pw.println(" l[ibraries]: list known shared libraries"); 14779 pw.println(" f[ibraries]: list device features"); 14780 pw.println(" k[eysets]: print known keysets"); 14781 pw.println(" r[esolvers]: dump intent resolvers"); 14782 pw.println(" perm[issions]: dump permissions"); 14783 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14784 pw.println(" pref[erred]: print preferred package settings"); 14785 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14786 pw.println(" prov[iders]: dump content providers"); 14787 pw.println(" p[ackages]: dump installed packages"); 14788 pw.println(" s[hared-users]: dump shared user IDs"); 14789 pw.println(" m[essages]: print collected runtime messages"); 14790 pw.println(" v[erifiers]: print package verifier info"); 14791 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14792 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14793 pw.println(" version: print database version info"); 14794 pw.println(" write: write current settings now"); 14795 pw.println(" installs: details about install sessions"); 14796 pw.println(" <package.name>: info about given package"); 14797 return; 14798 } else if ("--checkin".equals(opt)) { 14799 checkin = true; 14800 } else if ("-f".equals(opt)) { 14801 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14802 } else { 14803 pw.println("Unknown argument: " + opt + "; use -h for help"); 14804 } 14805 } 14806 14807 // Is the caller requesting to dump a particular piece of data? 14808 if (opti < args.length) { 14809 String cmd = args[opti]; 14810 opti++; 14811 // Is this a package name? 14812 if ("android".equals(cmd) || cmd.contains(".")) { 14813 packageName = cmd; 14814 // When dumping a single package, we always dump all of its 14815 // filter information since the amount of data will be reasonable. 14816 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14817 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14818 dumpState.setDump(DumpState.DUMP_LIBS); 14819 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14820 dumpState.setDump(DumpState.DUMP_FEATURES); 14821 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14822 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14823 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14824 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14825 } else if ("permission".equals(cmd)) { 14826 if (opti >= args.length) { 14827 pw.println("Error: permission requires permission name"); 14828 return; 14829 } 14830 permissionNames = new ArraySet<>(); 14831 while (opti < args.length) { 14832 permissionNames.add(args[opti]); 14833 opti++; 14834 } 14835 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14836 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14837 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14838 dumpState.setDump(DumpState.DUMP_PREFERRED); 14839 } else if ("preferred-xml".equals(cmd)) { 14840 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14841 if (opti < args.length && "--full".equals(args[opti])) { 14842 fullPreferred = true; 14843 opti++; 14844 } 14845 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14846 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14847 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14848 dumpState.setDump(DumpState.DUMP_PACKAGES); 14849 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14850 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14851 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14852 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14853 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14854 dumpState.setDump(DumpState.DUMP_MESSAGES); 14855 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14856 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14857 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14858 || "intent-filter-verifiers".equals(cmd)) { 14859 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14860 } else if ("version".equals(cmd)) { 14861 dumpState.setDump(DumpState.DUMP_VERSION); 14862 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14863 dumpState.setDump(DumpState.DUMP_KEYSETS); 14864 } else if ("installs".equals(cmd)) { 14865 dumpState.setDump(DumpState.DUMP_INSTALLS); 14866 } else if ("write".equals(cmd)) { 14867 synchronized (mPackages) { 14868 mSettings.writeLPr(); 14869 pw.println("Settings written."); 14870 return; 14871 } 14872 } 14873 } 14874 14875 if (checkin) { 14876 pw.println("vers,1"); 14877 } 14878 14879 // reader 14880 synchronized (mPackages) { 14881 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14882 if (!checkin) { 14883 if (dumpState.onTitlePrinted()) 14884 pw.println(); 14885 pw.println("Database versions:"); 14886 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 14887 } 14888 } 14889 14890 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14891 if (!checkin) { 14892 if (dumpState.onTitlePrinted()) 14893 pw.println(); 14894 pw.println("Verifiers:"); 14895 pw.print(" Required: "); 14896 pw.print(mRequiredVerifierPackage); 14897 pw.print(" (uid="); 14898 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14899 pw.println(")"); 14900 } else if (mRequiredVerifierPackage != null) { 14901 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14902 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14903 } 14904 } 14905 14906 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14907 packageName == null) { 14908 if (mIntentFilterVerifierComponent != null) { 14909 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14910 if (!checkin) { 14911 if (dumpState.onTitlePrinted()) 14912 pw.println(); 14913 pw.println("Intent Filter Verifier:"); 14914 pw.print(" Using: "); 14915 pw.print(verifierPackageName); 14916 pw.print(" (uid="); 14917 pw.print(getPackageUid(verifierPackageName, 0)); 14918 pw.println(")"); 14919 } else if (verifierPackageName != null) { 14920 pw.print("ifv,"); pw.print(verifierPackageName); 14921 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14922 } 14923 } else { 14924 pw.println(); 14925 pw.println("No Intent Filter Verifier available!"); 14926 } 14927 } 14928 14929 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14930 boolean printedHeader = false; 14931 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14932 while (it.hasNext()) { 14933 String name = it.next(); 14934 SharedLibraryEntry ent = mSharedLibraries.get(name); 14935 if (!checkin) { 14936 if (!printedHeader) { 14937 if (dumpState.onTitlePrinted()) 14938 pw.println(); 14939 pw.println("Libraries:"); 14940 printedHeader = true; 14941 } 14942 pw.print(" "); 14943 } else { 14944 pw.print("lib,"); 14945 } 14946 pw.print(name); 14947 if (!checkin) { 14948 pw.print(" -> "); 14949 } 14950 if (ent.path != null) { 14951 if (!checkin) { 14952 pw.print("(jar) "); 14953 pw.print(ent.path); 14954 } else { 14955 pw.print(",jar,"); 14956 pw.print(ent.path); 14957 } 14958 } else { 14959 if (!checkin) { 14960 pw.print("(apk) "); 14961 pw.print(ent.apk); 14962 } else { 14963 pw.print(",apk,"); 14964 pw.print(ent.apk); 14965 } 14966 } 14967 pw.println(); 14968 } 14969 } 14970 14971 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14972 if (dumpState.onTitlePrinted()) 14973 pw.println(); 14974 if (!checkin) { 14975 pw.println("Features:"); 14976 } 14977 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14978 while (it.hasNext()) { 14979 String name = it.next(); 14980 if (!checkin) { 14981 pw.print(" "); 14982 } else { 14983 pw.print("feat,"); 14984 } 14985 pw.println(name); 14986 } 14987 } 14988 14989 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14990 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14991 : "Activity Resolver Table:", " ", packageName, 14992 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14993 dumpState.setTitlePrinted(true); 14994 } 14995 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14996 : "Receiver Resolver Table:", " ", packageName, 14997 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14998 dumpState.setTitlePrinted(true); 14999 } 15000 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15001 : "Service Resolver Table:", " ", packageName, 15002 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15003 dumpState.setTitlePrinted(true); 15004 } 15005 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15006 : "Provider Resolver Table:", " ", packageName, 15007 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15008 dumpState.setTitlePrinted(true); 15009 } 15010 } 15011 15012 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15013 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15014 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15015 int user = mSettings.mPreferredActivities.keyAt(i); 15016 if (pir.dump(pw, 15017 dumpState.getTitlePrinted() 15018 ? "\nPreferred Activities User " + user + ":" 15019 : "Preferred Activities User " + user + ":", " ", 15020 packageName, true, false)) { 15021 dumpState.setTitlePrinted(true); 15022 } 15023 } 15024 } 15025 15026 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15027 pw.flush(); 15028 FileOutputStream fout = new FileOutputStream(fd); 15029 BufferedOutputStream str = new BufferedOutputStream(fout); 15030 XmlSerializer serializer = new FastXmlSerializer(); 15031 try { 15032 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15033 serializer.startDocument(null, true); 15034 serializer.setFeature( 15035 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15036 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15037 serializer.endDocument(); 15038 serializer.flush(); 15039 } catch (IllegalArgumentException e) { 15040 pw.println("Failed writing: " + e); 15041 } catch (IllegalStateException e) { 15042 pw.println("Failed writing: " + e); 15043 } catch (IOException e) { 15044 pw.println("Failed writing: " + e); 15045 } 15046 } 15047 15048 if (!checkin 15049 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15050 && packageName == null) { 15051 pw.println(); 15052 int count = mSettings.mPackages.size(); 15053 if (count == 0) { 15054 pw.println("No applications!"); 15055 pw.println(); 15056 } else { 15057 final String prefix = " "; 15058 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15059 if (allPackageSettings.size() == 0) { 15060 pw.println("No domain preferred apps!"); 15061 pw.println(); 15062 } else { 15063 pw.println("App verification status:"); 15064 pw.println(); 15065 count = 0; 15066 for (PackageSetting ps : allPackageSettings) { 15067 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15068 if (ivi == null || ivi.getPackageName() == null) continue; 15069 pw.println(prefix + "Package: " + ivi.getPackageName()); 15070 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15071 pw.println(prefix + "Status: " + ivi.getStatusString()); 15072 pw.println(); 15073 count++; 15074 } 15075 if (count == 0) { 15076 pw.println(prefix + "No app verification established."); 15077 pw.println(); 15078 } 15079 for (int userId : sUserManager.getUserIds()) { 15080 pw.println("App linkages for user " + userId + ":"); 15081 pw.println(); 15082 count = 0; 15083 for (PackageSetting ps : allPackageSettings) { 15084 final long status = ps.getDomainVerificationStatusForUser(userId); 15085 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15086 continue; 15087 } 15088 pw.println(prefix + "Package: " + ps.name); 15089 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15090 String statusStr = IntentFilterVerificationInfo. 15091 getStatusStringFromValue(status); 15092 pw.println(prefix + "Status: " + statusStr); 15093 pw.println(); 15094 count++; 15095 } 15096 if (count == 0) { 15097 pw.println(prefix + "No configured app linkages."); 15098 pw.println(); 15099 } 15100 } 15101 } 15102 } 15103 } 15104 15105 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15106 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15107 if (packageName == null && permissionNames == null) { 15108 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15109 if (iperm == 0) { 15110 if (dumpState.onTitlePrinted()) 15111 pw.println(); 15112 pw.println("AppOp Permissions:"); 15113 } 15114 pw.print(" AppOp Permission "); 15115 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15116 pw.println(":"); 15117 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15118 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15119 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15120 } 15121 } 15122 } 15123 } 15124 15125 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15126 boolean printedSomething = false; 15127 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15128 if (packageName != null && !packageName.equals(p.info.packageName)) { 15129 continue; 15130 } 15131 if (!printedSomething) { 15132 if (dumpState.onTitlePrinted()) 15133 pw.println(); 15134 pw.println("Registered ContentProviders:"); 15135 printedSomething = true; 15136 } 15137 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15138 pw.print(" "); pw.println(p.toString()); 15139 } 15140 printedSomething = false; 15141 for (Map.Entry<String, PackageParser.Provider> entry : 15142 mProvidersByAuthority.entrySet()) { 15143 PackageParser.Provider p = entry.getValue(); 15144 if (packageName != null && !packageName.equals(p.info.packageName)) { 15145 continue; 15146 } 15147 if (!printedSomething) { 15148 if (dumpState.onTitlePrinted()) 15149 pw.println(); 15150 pw.println("ContentProvider Authorities:"); 15151 printedSomething = true; 15152 } 15153 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15154 pw.print(" "); pw.println(p.toString()); 15155 if (p.info != null && p.info.applicationInfo != null) { 15156 final String appInfo = p.info.applicationInfo.toString(); 15157 pw.print(" applicationInfo="); pw.println(appInfo); 15158 } 15159 } 15160 } 15161 15162 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15163 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15164 } 15165 15166 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15167 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15168 } 15169 15170 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15171 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15172 } 15173 15174 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15175 // XXX should handle packageName != null by dumping only install data that 15176 // the given package is involved with. 15177 if (dumpState.onTitlePrinted()) pw.println(); 15178 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15179 } 15180 15181 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15182 if (dumpState.onTitlePrinted()) pw.println(); 15183 mSettings.dumpReadMessagesLPr(pw, dumpState); 15184 15185 pw.println(); 15186 pw.println("Package warning messages:"); 15187 BufferedReader in = null; 15188 String line = null; 15189 try { 15190 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15191 while ((line = in.readLine()) != null) { 15192 if (line.contains("ignored: updated version")) continue; 15193 pw.println(line); 15194 } 15195 } catch (IOException ignored) { 15196 } finally { 15197 IoUtils.closeQuietly(in); 15198 } 15199 } 15200 15201 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15202 BufferedReader in = null; 15203 String line = null; 15204 try { 15205 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15206 while ((line = in.readLine()) != null) { 15207 if (line.contains("ignored: updated version")) continue; 15208 pw.print("msg,"); 15209 pw.println(line); 15210 } 15211 } catch (IOException ignored) { 15212 } finally { 15213 IoUtils.closeQuietly(in); 15214 } 15215 } 15216 } 15217 } 15218 15219 private String dumpDomainString(String packageName) { 15220 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15221 List<IntentFilter> filters = getAllIntentFilters(packageName); 15222 15223 ArraySet<String> result = new ArraySet<>(); 15224 if (iviList.size() > 0) { 15225 for (IntentFilterVerificationInfo ivi : iviList) { 15226 for (String host : ivi.getDomains()) { 15227 result.add(host); 15228 } 15229 } 15230 } 15231 if (filters != null && filters.size() > 0) { 15232 for (IntentFilter filter : filters) { 15233 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15234 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15235 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15236 result.addAll(filter.getHostsList()); 15237 } 15238 } 15239 } 15240 15241 StringBuilder sb = new StringBuilder(result.size() * 16); 15242 for (String domain : result) { 15243 if (sb.length() > 0) sb.append(" "); 15244 sb.append(domain); 15245 } 15246 return sb.toString(); 15247 } 15248 15249 // ------- apps on sdcard specific code ------- 15250 static final boolean DEBUG_SD_INSTALL = false; 15251 15252 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15253 15254 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15255 15256 private boolean mMediaMounted = false; 15257 15258 static String getEncryptKey() { 15259 try { 15260 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15261 SD_ENCRYPTION_KEYSTORE_NAME); 15262 if (sdEncKey == null) { 15263 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15264 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15265 if (sdEncKey == null) { 15266 Slog.e(TAG, "Failed to create encryption keys"); 15267 return null; 15268 } 15269 } 15270 return sdEncKey; 15271 } catch (NoSuchAlgorithmException nsae) { 15272 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15273 return null; 15274 } catch (IOException ioe) { 15275 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15276 return null; 15277 } 15278 } 15279 15280 /* 15281 * Update media status on PackageManager. 15282 */ 15283 @Override 15284 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15285 int callingUid = Binder.getCallingUid(); 15286 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15287 throw new SecurityException("Media status can only be updated by the system"); 15288 } 15289 // reader; this apparently protects mMediaMounted, but should probably 15290 // be a different lock in that case. 15291 synchronized (mPackages) { 15292 Log.i(TAG, "Updating external media status from " 15293 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15294 + (mediaStatus ? "mounted" : "unmounted")); 15295 if (DEBUG_SD_INSTALL) 15296 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15297 + ", mMediaMounted=" + mMediaMounted); 15298 if (mediaStatus == mMediaMounted) { 15299 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15300 : 0, -1); 15301 mHandler.sendMessage(msg); 15302 return; 15303 } 15304 mMediaMounted = mediaStatus; 15305 } 15306 // Queue up an async operation since the package installation may take a 15307 // little while. 15308 mHandler.post(new Runnable() { 15309 public void run() { 15310 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15311 } 15312 }); 15313 } 15314 15315 /** 15316 * Called by MountService when the initial ASECs to scan are available. 15317 * Should block until all the ASEC containers are finished being scanned. 15318 */ 15319 public void scanAvailableAsecs() { 15320 updateExternalMediaStatusInner(true, false, false); 15321 if (mShouldRestoreconData) { 15322 SELinuxMMAC.setRestoreconDone(); 15323 mShouldRestoreconData = false; 15324 } 15325 } 15326 15327 /* 15328 * Collect information of applications on external media, map them against 15329 * existing containers and update information based on current mount status. 15330 * Please note that we always have to report status if reportStatus has been 15331 * set to true especially when unloading packages. 15332 */ 15333 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15334 boolean externalStorage) { 15335 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15336 int[] uidArr = EmptyArray.INT; 15337 15338 final String[] list = PackageHelper.getSecureContainerList(); 15339 if (ArrayUtils.isEmpty(list)) { 15340 Log.i(TAG, "No secure containers found"); 15341 } else { 15342 // Process list of secure containers and categorize them 15343 // as active or stale based on their package internal state. 15344 15345 // reader 15346 synchronized (mPackages) { 15347 for (String cid : list) { 15348 // Leave stages untouched for now; installer service owns them 15349 if (PackageInstallerService.isStageName(cid)) continue; 15350 15351 if (DEBUG_SD_INSTALL) 15352 Log.i(TAG, "Processing container " + cid); 15353 String pkgName = getAsecPackageName(cid); 15354 if (pkgName == null) { 15355 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15356 continue; 15357 } 15358 if (DEBUG_SD_INSTALL) 15359 Log.i(TAG, "Looking for pkg : " + pkgName); 15360 15361 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15362 if (ps == null) { 15363 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15364 continue; 15365 } 15366 15367 /* 15368 * Skip packages that are not external if we're unmounting 15369 * external storage. 15370 */ 15371 if (externalStorage && !isMounted && !isExternal(ps)) { 15372 continue; 15373 } 15374 15375 final AsecInstallArgs args = new AsecInstallArgs(cid, 15376 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15377 // The package status is changed only if the code path 15378 // matches between settings and the container id. 15379 if (ps.codePathString != null 15380 && ps.codePathString.startsWith(args.getCodePath())) { 15381 if (DEBUG_SD_INSTALL) { 15382 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15383 + " at code path: " + ps.codePathString); 15384 } 15385 15386 // We do have a valid package installed on sdcard 15387 processCids.put(args, ps.codePathString); 15388 final int uid = ps.appId; 15389 if (uid != -1) { 15390 uidArr = ArrayUtils.appendInt(uidArr, uid); 15391 } 15392 } else { 15393 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15394 + ps.codePathString); 15395 } 15396 } 15397 } 15398 15399 Arrays.sort(uidArr); 15400 } 15401 15402 // Process packages with valid entries. 15403 if (isMounted) { 15404 if (DEBUG_SD_INSTALL) 15405 Log.i(TAG, "Loading packages"); 15406 loadMediaPackages(processCids, uidArr); 15407 startCleaningPackages(); 15408 mInstallerService.onSecureContainersAvailable(); 15409 } else { 15410 if (DEBUG_SD_INSTALL) 15411 Log.i(TAG, "Unloading packages"); 15412 unloadMediaPackages(processCids, uidArr, reportStatus); 15413 } 15414 } 15415 15416 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15417 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15418 final int size = infos.size(); 15419 final String[] packageNames = new String[size]; 15420 final int[] packageUids = new int[size]; 15421 for (int i = 0; i < size; i++) { 15422 final ApplicationInfo info = infos.get(i); 15423 packageNames[i] = info.packageName; 15424 packageUids[i] = info.uid; 15425 } 15426 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15427 finishedReceiver); 15428 } 15429 15430 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15431 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15432 sendResourcesChangedBroadcast(mediaStatus, replacing, 15433 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15434 } 15435 15436 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15437 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15438 int size = pkgList.length; 15439 if (size > 0) { 15440 // Send broadcasts here 15441 Bundle extras = new Bundle(); 15442 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15443 if (uidArr != null) { 15444 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15445 } 15446 if (replacing) { 15447 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15448 } 15449 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15450 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15451 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15452 } 15453 } 15454 15455 /* 15456 * Look at potentially valid container ids from processCids If package 15457 * information doesn't match the one on record or package scanning fails, 15458 * the cid is added to list of removeCids. We currently don't delete stale 15459 * containers. 15460 */ 15461 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15462 ArrayList<String> pkgList = new ArrayList<String>(); 15463 Set<AsecInstallArgs> keys = processCids.keySet(); 15464 15465 for (AsecInstallArgs args : keys) { 15466 String codePath = processCids.get(args); 15467 if (DEBUG_SD_INSTALL) 15468 Log.i(TAG, "Loading container : " + args.cid); 15469 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15470 try { 15471 // Make sure there are no container errors first. 15472 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15473 Slog.e(TAG, "Failed to mount cid : " + args.cid 15474 + " when installing from sdcard"); 15475 continue; 15476 } 15477 // Check code path here. 15478 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15479 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15480 + " does not match one in settings " + codePath); 15481 continue; 15482 } 15483 // Parse package 15484 int parseFlags = mDefParseFlags; 15485 if (args.isExternalAsec()) { 15486 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15487 } 15488 if (args.isFwdLocked()) { 15489 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15490 } 15491 15492 synchronized (mInstallLock) { 15493 PackageParser.Package pkg = null; 15494 try { 15495 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15496 } catch (PackageManagerException e) { 15497 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15498 } 15499 // Scan the package 15500 if (pkg != null) { 15501 /* 15502 * TODO why is the lock being held? doPostInstall is 15503 * called in other places without the lock. This needs 15504 * to be straightened out. 15505 */ 15506 // writer 15507 synchronized (mPackages) { 15508 retCode = PackageManager.INSTALL_SUCCEEDED; 15509 pkgList.add(pkg.packageName); 15510 // Post process args 15511 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15512 pkg.applicationInfo.uid); 15513 } 15514 } else { 15515 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15516 } 15517 } 15518 15519 } finally { 15520 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15521 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15522 } 15523 } 15524 } 15525 // writer 15526 synchronized (mPackages) { 15527 // If the platform SDK has changed since the last time we booted, 15528 // we need to re-grant app permission to catch any new ones that 15529 // appear. This is really a hack, and means that apps can in some 15530 // cases get permissions that the user didn't initially explicitly 15531 // allow... it would be nice to have some better way to handle 15532 // this situation. 15533 final VersionInfo ver = mSettings.getExternalVersion(); 15534 15535 int updateFlags = UPDATE_PERMISSIONS_ALL; 15536 if (ver.sdkVersion != mSdkVersion) { 15537 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15538 + mSdkVersion + "; regranting permissions for external"); 15539 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15540 } 15541 updatePermissionsLPw(null, null, updateFlags); 15542 15543 // Yay, everything is now upgraded 15544 ver.forceCurrent(); 15545 15546 // can downgrade to reader 15547 // Persist settings 15548 mSettings.writeLPr(); 15549 } 15550 // Send a broadcast to let everyone know we are done processing 15551 if (pkgList.size() > 0) { 15552 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15553 } 15554 } 15555 15556 /* 15557 * Utility method to unload a list of specified containers 15558 */ 15559 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15560 // Just unmount all valid containers. 15561 for (AsecInstallArgs arg : cidArgs) { 15562 synchronized (mInstallLock) { 15563 arg.doPostDeleteLI(false); 15564 } 15565 } 15566 } 15567 15568 /* 15569 * Unload packages mounted on external media. This involves deleting package 15570 * data from internal structures, sending broadcasts about diabled packages, 15571 * gc'ing to free up references, unmounting all secure containers 15572 * corresponding to packages on external media, and posting a 15573 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15574 * that we always have to post this message if status has been requested no 15575 * matter what. 15576 */ 15577 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15578 final boolean reportStatus) { 15579 if (DEBUG_SD_INSTALL) 15580 Log.i(TAG, "unloading media packages"); 15581 ArrayList<String> pkgList = new ArrayList<String>(); 15582 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15583 final Set<AsecInstallArgs> keys = processCids.keySet(); 15584 for (AsecInstallArgs args : keys) { 15585 String pkgName = args.getPackageName(); 15586 if (DEBUG_SD_INSTALL) 15587 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15588 // Delete package internally 15589 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15590 synchronized (mInstallLock) { 15591 boolean res = deletePackageLI(pkgName, null, false, null, null, 15592 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15593 if (res) { 15594 pkgList.add(pkgName); 15595 } else { 15596 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15597 failedList.add(args); 15598 } 15599 } 15600 } 15601 15602 // reader 15603 synchronized (mPackages) { 15604 // We didn't update the settings after removing each package; 15605 // write them now for all packages. 15606 mSettings.writeLPr(); 15607 } 15608 15609 // We have to absolutely send UPDATED_MEDIA_STATUS only 15610 // after confirming that all the receivers processed the ordered 15611 // broadcast when packages get disabled, force a gc to clean things up. 15612 // and unload all the containers. 15613 if (pkgList.size() > 0) { 15614 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15615 new IIntentReceiver.Stub() { 15616 public void performReceive(Intent intent, int resultCode, String data, 15617 Bundle extras, boolean ordered, boolean sticky, 15618 int sendingUser) throws RemoteException { 15619 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15620 reportStatus ? 1 : 0, 1, keys); 15621 mHandler.sendMessage(msg); 15622 } 15623 }); 15624 } else { 15625 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15626 keys); 15627 mHandler.sendMessage(msg); 15628 } 15629 } 15630 15631 private void loadPrivatePackages(VolumeInfo vol) { 15632 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15633 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15634 synchronized (mInstallLock) { 15635 synchronized (mPackages) { 15636 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15637 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15638 for (PackageSetting ps : packages) { 15639 final PackageParser.Package pkg; 15640 try { 15641 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15642 loaded.add(pkg.applicationInfo); 15643 } catch (PackageManagerException e) { 15644 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15645 } 15646 15647 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15648 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15649 } 15650 } 15651 15652 int updateFlags = UPDATE_PERMISSIONS_ALL; 15653 if (ver.sdkVersion != mSdkVersion) { 15654 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15655 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15656 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15657 } 15658 updatePermissionsLPw(null, null, updateFlags); 15659 15660 // Yay, everything is now upgraded 15661 ver.forceCurrent(); 15662 15663 mSettings.writeLPr(); 15664 } 15665 } 15666 15667 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15668 sendResourcesChangedBroadcast(true, false, loaded, null); 15669 } 15670 15671 private void unloadPrivatePackages(VolumeInfo vol) { 15672 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15673 synchronized (mInstallLock) { 15674 synchronized (mPackages) { 15675 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15676 for (PackageSetting ps : packages) { 15677 if (ps.pkg == null) continue; 15678 15679 final ApplicationInfo info = ps.pkg.applicationInfo; 15680 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15681 if (deletePackageLI(ps.name, null, false, null, null, 15682 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15683 unloaded.add(info); 15684 } else { 15685 Slog.w(TAG, "Failed to unload " + ps.codePath); 15686 } 15687 } 15688 15689 mSettings.writeLPr(); 15690 } 15691 } 15692 15693 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15694 sendResourcesChangedBroadcast(false, false, unloaded, null); 15695 } 15696 15697 /** 15698 * Examine all users present on given mounted volume, and destroy data 15699 * belonging to users that are no longer valid, or whose user ID has been 15700 * recycled. 15701 */ 15702 private void reconcileUsers(String volumeUuid) { 15703 final File[] files = FileUtils 15704 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15705 for (File file : files) { 15706 if (!file.isDirectory()) continue; 15707 15708 final int userId; 15709 final UserInfo info; 15710 try { 15711 userId = Integer.parseInt(file.getName()); 15712 info = sUserManager.getUserInfo(userId); 15713 } catch (NumberFormatException e) { 15714 Slog.w(TAG, "Invalid user directory " + file); 15715 continue; 15716 } 15717 15718 boolean destroyUser = false; 15719 if (info == null) { 15720 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15721 + " because no matching user was found"); 15722 destroyUser = true; 15723 } else { 15724 try { 15725 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15726 } catch (IOException e) { 15727 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15728 + " because we failed to enforce serial number: " + e); 15729 destroyUser = true; 15730 } 15731 } 15732 15733 if (destroyUser) { 15734 synchronized (mInstallLock) { 15735 mInstaller.removeUserDataDirs(volumeUuid, userId); 15736 } 15737 } 15738 } 15739 15740 final UserManager um = mContext.getSystemService(UserManager.class); 15741 for (UserInfo user : um.getUsers()) { 15742 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15743 if (userDir.exists()) continue; 15744 15745 try { 15746 UserManagerService.prepareUserDirectory(userDir); 15747 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15748 } catch (IOException e) { 15749 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15750 } 15751 } 15752 } 15753 15754 /** 15755 * Examine all apps present on given mounted volume, and destroy apps that 15756 * aren't expected, either due to uninstallation or reinstallation on 15757 * another volume. 15758 */ 15759 private void reconcileApps(String volumeUuid) { 15760 final File[] files = FileUtils 15761 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15762 for (File file : files) { 15763 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15764 && !PackageInstallerService.isStageName(file.getName()); 15765 if (!isPackage) { 15766 // Ignore entries which are not packages 15767 continue; 15768 } 15769 15770 boolean destroyApp = false; 15771 String packageName = null; 15772 try { 15773 final PackageLite pkg = PackageParser.parsePackageLite(file, 15774 PackageParser.PARSE_MUST_BE_APK); 15775 packageName = pkg.packageName; 15776 15777 synchronized (mPackages) { 15778 final PackageSetting ps = mSettings.mPackages.get(packageName); 15779 if (ps == null) { 15780 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15781 + volumeUuid + " because we found no install record"); 15782 destroyApp = true; 15783 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15784 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15785 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15786 destroyApp = true; 15787 } 15788 } 15789 15790 } catch (PackageParserException e) { 15791 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15792 destroyApp = true; 15793 } 15794 15795 if (destroyApp) { 15796 synchronized (mInstallLock) { 15797 if (packageName != null) { 15798 removeDataDirsLI(volumeUuid, packageName); 15799 } 15800 if (file.isDirectory()) { 15801 mInstaller.rmPackageDir(file.getAbsolutePath()); 15802 } else { 15803 file.delete(); 15804 } 15805 } 15806 } 15807 } 15808 } 15809 15810 private void unfreezePackage(String packageName) { 15811 synchronized (mPackages) { 15812 final PackageSetting ps = mSettings.mPackages.get(packageName); 15813 if (ps != null) { 15814 ps.frozen = false; 15815 } 15816 } 15817 } 15818 15819 @Override 15820 public int movePackage(final String packageName, final String volumeUuid) { 15821 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15822 15823 final int moveId = mNextMoveId.getAndIncrement(); 15824 try { 15825 movePackageInternal(packageName, volumeUuid, moveId); 15826 } catch (PackageManagerException e) { 15827 Slog.w(TAG, "Failed to move " + packageName, e); 15828 mMoveCallbacks.notifyStatusChanged(moveId, 15829 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15830 } 15831 return moveId; 15832 } 15833 15834 private void movePackageInternal(final String packageName, final String volumeUuid, 15835 final int moveId) throws PackageManagerException { 15836 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15837 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15838 final PackageManager pm = mContext.getPackageManager(); 15839 15840 final boolean currentAsec; 15841 final String currentVolumeUuid; 15842 final File codeFile; 15843 final String installerPackageName; 15844 final String packageAbiOverride; 15845 final int appId; 15846 final String seinfo; 15847 final String label; 15848 15849 // reader 15850 synchronized (mPackages) { 15851 final PackageParser.Package pkg = mPackages.get(packageName); 15852 final PackageSetting ps = mSettings.mPackages.get(packageName); 15853 if (pkg == null || ps == null) { 15854 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15855 } 15856 15857 if (pkg.applicationInfo.isSystemApp()) { 15858 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15859 "Cannot move system application"); 15860 } 15861 15862 if (pkg.applicationInfo.isExternalAsec()) { 15863 currentAsec = true; 15864 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 15865 } else if (pkg.applicationInfo.isForwardLocked()) { 15866 currentAsec = true; 15867 currentVolumeUuid = "forward_locked"; 15868 } else { 15869 currentAsec = false; 15870 currentVolumeUuid = ps.volumeUuid; 15871 15872 final File probe = new File(pkg.codePath); 15873 final File probeOat = new File(probe, "oat"); 15874 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15875 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15876 "Move only supported for modern cluster style installs"); 15877 } 15878 } 15879 15880 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 15881 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15882 "Package already moved to " + volumeUuid); 15883 } 15884 15885 if (ps.frozen) { 15886 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15887 "Failed to move already frozen package"); 15888 } 15889 ps.frozen = true; 15890 15891 codeFile = new File(pkg.codePath); 15892 installerPackageName = ps.installerPackageName; 15893 packageAbiOverride = ps.cpuAbiOverrideString; 15894 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15895 seinfo = pkg.applicationInfo.seinfo; 15896 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15897 } 15898 15899 // Now that we're guarded by frozen state, kill app during move 15900 final long token = Binder.clearCallingIdentity(); 15901 try { 15902 killApplication(packageName, appId, "move pkg"); 15903 } finally { 15904 Binder.restoreCallingIdentity(token); 15905 } 15906 15907 final Bundle extras = new Bundle(); 15908 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15909 extras.putString(Intent.EXTRA_TITLE, label); 15910 mMoveCallbacks.notifyCreated(moveId, extras); 15911 15912 int installFlags; 15913 final boolean moveCompleteApp; 15914 final File measurePath; 15915 15916 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15917 installFlags = INSTALL_INTERNAL; 15918 moveCompleteApp = !currentAsec; 15919 measurePath = Environment.getDataAppDirectory(volumeUuid); 15920 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15921 installFlags = INSTALL_EXTERNAL; 15922 moveCompleteApp = false; 15923 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15924 } else { 15925 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15926 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15927 || !volume.isMountedWritable()) { 15928 unfreezePackage(packageName); 15929 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15930 "Move location not mounted private volume"); 15931 } 15932 15933 Preconditions.checkState(!currentAsec); 15934 15935 installFlags = INSTALL_INTERNAL; 15936 moveCompleteApp = true; 15937 measurePath = Environment.getDataAppDirectory(volumeUuid); 15938 } 15939 15940 final PackageStats stats = new PackageStats(null, -1); 15941 synchronized (mInstaller) { 15942 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15943 unfreezePackage(packageName); 15944 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15945 "Failed to measure package size"); 15946 } 15947 } 15948 15949 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15950 + stats.dataSize); 15951 15952 final long startFreeBytes = measurePath.getFreeSpace(); 15953 final long sizeBytes; 15954 if (moveCompleteApp) { 15955 sizeBytes = stats.codeSize + stats.dataSize; 15956 } else { 15957 sizeBytes = stats.codeSize; 15958 } 15959 15960 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15961 unfreezePackage(packageName); 15962 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15963 "Not enough free space to move"); 15964 } 15965 15966 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15967 15968 final CountDownLatch installedLatch = new CountDownLatch(1); 15969 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15970 @Override 15971 public void onUserActionRequired(Intent intent) throws RemoteException { 15972 throw new IllegalStateException(); 15973 } 15974 15975 @Override 15976 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15977 Bundle extras) throws RemoteException { 15978 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15979 + PackageManager.installStatusToString(returnCode, msg)); 15980 15981 installedLatch.countDown(); 15982 15983 // Regardless of success or failure of the move operation, 15984 // always unfreeze the package 15985 unfreezePackage(packageName); 15986 15987 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15988 switch (status) { 15989 case PackageInstaller.STATUS_SUCCESS: 15990 mMoveCallbacks.notifyStatusChanged(moveId, 15991 PackageManager.MOVE_SUCCEEDED); 15992 break; 15993 case PackageInstaller.STATUS_FAILURE_STORAGE: 15994 mMoveCallbacks.notifyStatusChanged(moveId, 15995 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15996 break; 15997 default: 15998 mMoveCallbacks.notifyStatusChanged(moveId, 15999 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16000 break; 16001 } 16002 } 16003 }; 16004 16005 final MoveInfo move; 16006 if (moveCompleteApp) { 16007 // Kick off a thread to report progress estimates 16008 new Thread() { 16009 @Override 16010 public void run() { 16011 while (true) { 16012 try { 16013 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16014 break; 16015 } 16016 } catch (InterruptedException ignored) { 16017 } 16018 16019 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16020 final int progress = 10 + (int) MathUtils.constrain( 16021 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16022 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16023 } 16024 } 16025 }.start(); 16026 16027 final String dataAppName = codeFile.getName(); 16028 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16029 dataAppName, appId, seinfo); 16030 } else { 16031 move = null; 16032 } 16033 16034 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16035 16036 final Message msg = mHandler.obtainMessage(INIT_COPY); 16037 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16038 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 16039 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16040 mHandler.sendMessage(msg); 16041 } 16042 16043 @Override 16044 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16045 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16046 16047 final int realMoveId = mNextMoveId.getAndIncrement(); 16048 final Bundle extras = new Bundle(); 16049 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16050 mMoveCallbacks.notifyCreated(realMoveId, extras); 16051 16052 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16053 @Override 16054 public void onCreated(int moveId, Bundle extras) { 16055 // Ignored 16056 } 16057 16058 @Override 16059 public void onStatusChanged(int moveId, int status, long estMillis) { 16060 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16061 } 16062 }; 16063 16064 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16065 storage.setPrimaryStorageUuid(volumeUuid, callback); 16066 return realMoveId; 16067 } 16068 16069 @Override 16070 public int getMoveStatus(int moveId) { 16071 mContext.enforceCallingOrSelfPermission( 16072 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16073 return mMoveCallbacks.mLastStatus.get(moveId); 16074 } 16075 16076 @Override 16077 public void registerMoveCallback(IPackageMoveObserver callback) { 16078 mContext.enforceCallingOrSelfPermission( 16079 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16080 mMoveCallbacks.register(callback); 16081 } 16082 16083 @Override 16084 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16085 mContext.enforceCallingOrSelfPermission( 16086 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16087 mMoveCallbacks.unregister(callback); 16088 } 16089 16090 @Override 16091 public boolean setInstallLocation(int loc) { 16092 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16093 null); 16094 if (getInstallLocation() == loc) { 16095 return true; 16096 } 16097 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16098 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16099 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16100 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16101 return true; 16102 } 16103 return false; 16104 } 16105 16106 @Override 16107 public int getInstallLocation() { 16108 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16109 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16110 PackageHelper.APP_INSTALL_AUTO); 16111 } 16112 16113 /** Called by UserManagerService */ 16114 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16115 mDirtyUsers.remove(userHandle); 16116 mSettings.removeUserLPw(userHandle); 16117 mPendingBroadcasts.remove(userHandle); 16118 if (mInstaller != null) { 16119 // Technically, we shouldn't be doing this with the package lock 16120 // held. However, this is very rare, and there is already so much 16121 // other disk I/O going on, that we'll let it slide for now. 16122 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16123 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16124 final String volumeUuid = vol.getFsUuid(); 16125 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16126 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16127 } 16128 } 16129 mUserNeedsBadging.delete(userHandle); 16130 removeUnusedPackagesLILPw(userManager, userHandle); 16131 } 16132 16133 /** 16134 * We're removing userHandle and would like to remove any downloaded packages 16135 * that are no longer in use by any other user. 16136 * @param userHandle the user being removed 16137 */ 16138 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16139 final boolean DEBUG_CLEAN_APKS = false; 16140 int [] users = userManager.getUserIdsLPr(); 16141 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16142 while (psit.hasNext()) { 16143 PackageSetting ps = psit.next(); 16144 if (ps.pkg == null) { 16145 continue; 16146 } 16147 final String packageName = ps.pkg.packageName; 16148 // Skip over if system app 16149 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16150 continue; 16151 } 16152 if (DEBUG_CLEAN_APKS) { 16153 Slog.i(TAG, "Checking package " + packageName); 16154 } 16155 boolean keep = false; 16156 for (int i = 0; i < users.length; i++) { 16157 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16158 keep = true; 16159 if (DEBUG_CLEAN_APKS) { 16160 Slog.i(TAG, " Keeping package " + packageName + " for user " 16161 + users[i]); 16162 } 16163 break; 16164 } 16165 } 16166 if (!keep) { 16167 if (DEBUG_CLEAN_APKS) { 16168 Slog.i(TAG, " Removing package " + packageName); 16169 } 16170 mHandler.post(new Runnable() { 16171 public void run() { 16172 deletePackageX(packageName, userHandle, 0); 16173 } //end run 16174 }); 16175 } 16176 } 16177 } 16178 16179 /** Called by UserManagerService */ 16180 void createNewUserLILPw(int userHandle) { 16181 if (mInstaller != null) { 16182 mInstaller.createUserConfig(userHandle); 16183 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16184 applyFactoryDefaultBrowserLPw(userHandle); 16185 primeDomainVerificationsLPw(userHandle); 16186 } 16187 } 16188 16189 void newUserCreated(final int userHandle) { 16190 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16191 } 16192 16193 @Override 16194 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16195 mContext.enforceCallingOrSelfPermission( 16196 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16197 "Only package verification agents can read the verifier device identity"); 16198 16199 synchronized (mPackages) { 16200 return mSettings.getVerifierDeviceIdentityLPw(); 16201 } 16202 } 16203 16204 @Override 16205 public void setPermissionEnforced(String permission, boolean enforced) { 16206 // TODO: Now that we no longer change GID for storage, this should to away. 16207 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16208 "setPermissionEnforced"); 16209 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16210 synchronized (mPackages) { 16211 if (mSettings.mReadExternalStorageEnforced == null 16212 || mSettings.mReadExternalStorageEnforced != enforced) { 16213 mSettings.mReadExternalStorageEnforced = enforced; 16214 mSettings.writeLPr(); 16215 } 16216 } 16217 // kill any non-foreground processes so we restart them and 16218 // grant/revoke the GID. 16219 final IActivityManager am = ActivityManagerNative.getDefault(); 16220 if (am != null) { 16221 final long token = Binder.clearCallingIdentity(); 16222 try { 16223 am.killProcessesBelowForeground("setPermissionEnforcement"); 16224 } catch (RemoteException e) { 16225 } finally { 16226 Binder.restoreCallingIdentity(token); 16227 } 16228 } 16229 } else { 16230 throw new IllegalArgumentException("No selective enforcement for " + permission); 16231 } 16232 } 16233 16234 @Override 16235 @Deprecated 16236 public boolean isPermissionEnforced(String permission) { 16237 return true; 16238 } 16239 16240 @Override 16241 public boolean isStorageLow() { 16242 final long token = Binder.clearCallingIdentity(); 16243 try { 16244 final DeviceStorageMonitorInternal 16245 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16246 if (dsm != null) { 16247 return dsm.isMemoryLow(); 16248 } else { 16249 return false; 16250 } 16251 } finally { 16252 Binder.restoreCallingIdentity(token); 16253 } 16254 } 16255 16256 @Override 16257 public IPackageInstaller getPackageInstaller() { 16258 return mInstallerService; 16259 } 16260 16261 private boolean userNeedsBadging(int userId) { 16262 int index = mUserNeedsBadging.indexOfKey(userId); 16263 if (index < 0) { 16264 final UserInfo userInfo; 16265 final long token = Binder.clearCallingIdentity(); 16266 try { 16267 userInfo = sUserManager.getUserInfo(userId); 16268 } finally { 16269 Binder.restoreCallingIdentity(token); 16270 } 16271 final boolean b; 16272 if (userInfo != null && userInfo.isManagedProfile()) { 16273 b = true; 16274 } else { 16275 b = false; 16276 } 16277 mUserNeedsBadging.put(userId, b); 16278 return b; 16279 } 16280 return mUserNeedsBadging.valueAt(index); 16281 } 16282 16283 @Override 16284 public KeySet getKeySetByAlias(String packageName, String alias) { 16285 if (packageName == null || alias == null) { 16286 return null; 16287 } 16288 synchronized(mPackages) { 16289 final PackageParser.Package pkg = mPackages.get(packageName); 16290 if (pkg == null) { 16291 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16292 throw new IllegalArgumentException("Unknown package: " + packageName); 16293 } 16294 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16295 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16296 } 16297 } 16298 16299 @Override 16300 public KeySet getSigningKeySet(String packageName) { 16301 if (packageName == null) { 16302 return null; 16303 } 16304 synchronized(mPackages) { 16305 final PackageParser.Package pkg = mPackages.get(packageName); 16306 if (pkg == null) { 16307 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16308 throw new IllegalArgumentException("Unknown package: " + packageName); 16309 } 16310 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16311 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16312 throw new SecurityException("May not access signing KeySet of other apps."); 16313 } 16314 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16315 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16316 } 16317 } 16318 16319 @Override 16320 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16321 if (packageName == null || ks == null) { 16322 return false; 16323 } 16324 synchronized(mPackages) { 16325 final PackageParser.Package pkg = mPackages.get(packageName); 16326 if (pkg == null) { 16327 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16328 throw new IllegalArgumentException("Unknown package: " + packageName); 16329 } 16330 IBinder ksh = ks.getToken(); 16331 if (ksh instanceof KeySetHandle) { 16332 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16333 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16334 } 16335 return false; 16336 } 16337 } 16338 16339 @Override 16340 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16341 if (packageName == null || ks == null) { 16342 return false; 16343 } 16344 synchronized(mPackages) { 16345 final PackageParser.Package pkg = mPackages.get(packageName); 16346 if (pkg == null) { 16347 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16348 throw new IllegalArgumentException("Unknown package: " + packageName); 16349 } 16350 IBinder ksh = ks.getToken(); 16351 if (ksh instanceof KeySetHandle) { 16352 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16353 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16354 } 16355 return false; 16356 } 16357 } 16358 16359 public void getUsageStatsIfNoPackageUsageInfo() { 16360 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16361 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16362 if (usm == null) { 16363 throw new IllegalStateException("UsageStatsManager must be initialized"); 16364 } 16365 long now = System.currentTimeMillis(); 16366 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16367 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16368 String packageName = entry.getKey(); 16369 PackageParser.Package pkg = mPackages.get(packageName); 16370 if (pkg == null) { 16371 continue; 16372 } 16373 UsageStats usage = entry.getValue(); 16374 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16375 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16376 } 16377 } 16378 } 16379 16380 /** 16381 * Check and throw if the given before/after packages would be considered a 16382 * downgrade. 16383 */ 16384 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16385 throws PackageManagerException { 16386 if (after.versionCode < before.mVersionCode) { 16387 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16388 "Update version code " + after.versionCode + " is older than current " 16389 + before.mVersionCode); 16390 } else if (after.versionCode == before.mVersionCode) { 16391 if (after.baseRevisionCode < before.baseRevisionCode) { 16392 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16393 "Update base revision code " + after.baseRevisionCode 16394 + " is older than current " + before.baseRevisionCode); 16395 } 16396 16397 if (!ArrayUtils.isEmpty(after.splitNames)) { 16398 for (int i = 0; i < after.splitNames.length; i++) { 16399 final String splitName = after.splitNames[i]; 16400 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16401 if (j != -1) { 16402 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16403 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16404 "Update split " + splitName + " revision code " 16405 + after.splitRevisionCodes[i] + " is older than current " 16406 + before.splitRevisionCodes[j]); 16407 } 16408 } 16409 } 16410 } 16411 } 16412 } 16413 16414 private static class MoveCallbacks extends Handler { 16415 private static final int MSG_CREATED = 1; 16416 private static final int MSG_STATUS_CHANGED = 2; 16417 16418 private final RemoteCallbackList<IPackageMoveObserver> 16419 mCallbacks = new RemoteCallbackList<>(); 16420 16421 private final SparseIntArray mLastStatus = new SparseIntArray(); 16422 16423 public MoveCallbacks(Looper looper) { 16424 super(looper); 16425 } 16426 16427 public void register(IPackageMoveObserver callback) { 16428 mCallbacks.register(callback); 16429 } 16430 16431 public void unregister(IPackageMoveObserver callback) { 16432 mCallbacks.unregister(callback); 16433 } 16434 16435 @Override 16436 public void handleMessage(Message msg) { 16437 final SomeArgs args = (SomeArgs) msg.obj; 16438 final int n = mCallbacks.beginBroadcast(); 16439 for (int i = 0; i < n; i++) { 16440 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16441 try { 16442 invokeCallback(callback, msg.what, args); 16443 } catch (RemoteException ignored) { 16444 } 16445 } 16446 mCallbacks.finishBroadcast(); 16447 args.recycle(); 16448 } 16449 16450 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16451 throws RemoteException { 16452 switch (what) { 16453 case MSG_CREATED: { 16454 callback.onCreated(args.argi1, (Bundle) args.arg2); 16455 break; 16456 } 16457 case MSG_STATUS_CHANGED: { 16458 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16459 break; 16460 } 16461 } 16462 } 16463 16464 private void notifyCreated(int moveId, Bundle extras) { 16465 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16466 16467 final SomeArgs args = SomeArgs.obtain(); 16468 args.argi1 = moveId; 16469 args.arg2 = extras; 16470 obtainMessage(MSG_CREATED, args).sendToTarget(); 16471 } 16472 16473 private void notifyStatusChanged(int moveId, int status) { 16474 notifyStatusChanged(moveId, status, -1); 16475 } 16476 16477 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16478 Slog.v(TAG, "Move " + moveId + " status " + status); 16479 16480 final SomeArgs args = SomeArgs.obtain(); 16481 args.argi1 = moveId; 16482 args.argi2 = status; 16483 args.arg3 = estMillis; 16484 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16485 16486 synchronized (mLastStatus) { 16487 mLastStatus.put(moveId, status); 16488 } 16489 } 16490 } 16491 16492 private final class OnPermissionChangeListeners extends Handler { 16493 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16494 16495 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16496 new RemoteCallbackList<>(); 16497 16498 public OnPermissionChangeListeners(Looper looper) { 16499 super(looper); 16500 } 16501 16502 @Override 16503 public void handleMessage(Message msg) { 16504 switch (msg.what) { 16505 case MSG_ON_PERMISSIONS_CHANGED: { 16506 final int uid = msg.arg1; 16507 handleOnPermissionsChanged(uid); 16508 } break; 16509 } 16510 } 16511 16512 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16513 mPermissionListeners.register(listener); 16514 16515 } 16516 16517 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16518 mPermissionListeners.unregister(listener); 16519 } 16520 16521 public void onPermissionsChanged(int uid) { 16522 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16523 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16524 } 16525 } 16526 16527 private void handleOnPermissionsChanged(int uid) { 16528 final int count = mPermissionListeners.beginBroadcast(); 16529 try { 16530 for (int i = 0; i < count; i++) { 16531 IOnPermissionsChangeListener callback = mPermissionListeners 16532 .getBroadcastItem(i); 16533 try { 16534 callback.onPermissionsChanged(uid); 16535 } catch (RemoteException e) { 16536 Log.e(TAG, "Permission listener is dead", e); 16537 } 16538 } 16539 } finally { 16540 mPermissionListeners.finishBroadcast(); 16541 } 16542 } 16543 } 16544 16545 private class PackageManagerInternalImpl extends PackageManagerInternal { 16546 @Override 16547 public void setLocationPackagesProvider(PackagesProvider provider) { 16548 synchronized (mPackages) { 16549 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16550 } 16551 } 16552 16553 @Override 16554 public void setImePackagesProvider(PackagesProvider provider) { 16555 synchronized (mPackages) { 16556 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16557 } 16558 } 16559 16560 @Override 16561 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16562 synchronized (mPackages) { 16563 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16564 } 16565 } 16566 16567 @Override 16568 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16569 synchronized (mPackages) { 16570 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16571 } 16572 } 16573 16574 @Override 16575 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16576 synchronized (mPackages) { 16577 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16578 } 16579 } 16580 16581 @Override 16582 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16583 synchronized (mPackages) { 16584 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16585 } 16586 } 16587 16588 @Override 16589 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16590 synchronized (mPackages) { 16591 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16592 } 16593 } 16594 16595 @Override 16596 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16597 synchronized (mPackages) { 16598 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16599 packageName, userId); 16600 } 16601 } 16602 16603 @Override 16604 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16605 synchronized (mPackages) { 16606 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16607 packageName, userId); 16608 } 16609 } 16610 @Override 16611 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16612 synchronized (mPackages) { 16613 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16614 packageName, userId); 16615 } 16616 } 16617 } 16618 16619 @Override 16620 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16621 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16622 synchronized (mPackages) { 16623 final long identity = Binder.clearCallingIdentity(); 16624 try { 16625 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16626 packageNames, userId); 16627 } finally { 16628 Binder.restoreCallingIdentity(identity); 16629 } 16630 } 16631 } 16632 16633 private static void enforceSystemOrPhoneCaller(String tag) { 16634 int callingUid = Binder.getCallingUid(); 16635 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16636 throw new SecurityException( 16637 "Cannot call " + tag + " from UID " + callingUid); 16638 } 16639 } 16640} 16641