PackageManagerService.java revision bc57510e9f359929a55130d8a35c61a84dad4568
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 60import static android.content.pm.PackageManager.MATCH_ALL; 61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 65import static android.content.pm.PackageManager.PERMISSION_DENIED; 66import static android.content.pm.PackageManager.PERMISSION_GRANTED; 67import static android.content.pm.PackageParser.isApkFile; 68import static android.os.Process.PACKAGE_INFO_GID; 69import static android.os.Process.SYSTEM_UID; 70import static android.system.OsConstants.O_CREAT; 71import static android.system.OsConstants.O_RDWR; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 76import static com.android.internal.util.ArrayUtils.appendInt; 77import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 78import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 81import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 82import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 86 87import android.Manifest; 88import android.app.ActivityManager; 89import android.app.ActivityManagerNative; 90import android.app.AppGlobals; 91import android.app.IActivityManager; 92import android.app.admin.IDevicePolicyManager; 93import android.app.backup.IBackupManager; 94import android.app.usage.UsageStats; 95import android.app.usage.UsageStatsManager; 96import android.content.BroadcastReceiver; 97import android.content.ComponentName; 98import android.content.Context; 99import android.content.IIntentReceiver; 100import android.content.Intent; 101import android.content.IntentFilter; 102import android.content.IntentSender; 103import android.content.IntentSender.SendIntentException; 104import android.content.ServiceConnection; 105import android.content.pm.ActivityInfo; 106import android.content.pm.ApplicationInfo; 107import android.content.pm.FeatureInfo; 108import android.content.pm.IOnPermissionsChangeListener; 109import android.content.pm.IPackageDataObserver; 110import android.content.pm.IPackageDeleteObserver; 111import android.content.pm.IPackageDeleteObserver2; 112import android.content.pm.IPackageInstallObserver2; 113import android.content.pm.IPackageInstaller; 114import android.content.pm.IPackageManager; 115import android.content.pm.IPackageMoveObserver; 116import android.content.pm.IPackageStatsObserver; 117import android.content.pm.InstrumentationInfo; 118import android.content.pm.IntentFilterVerificationInfo; 119import android.content.pm.KeySet; 120import android.content.pm.ManifestDigest; 121import android.content.pm.PackageCleanItem; 122import android.content.pm.PackageInfo; 123import android.content.pm.PackageInfoLite; 124import android.content.pm.PackageInstaller; 125import android.content.pm.PackageManager; 126import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 127import android.content.pm.PackageManagerInternal; 128import android.content.pm.PackageParser; 129import android.content.pm.PackageParser.ActivityIntentInfo; 130import android.content.pm.PackageParser.PackageLite; 131import android.content.pm.PackageParser.PackageParserException; 132import android.content.pm.PackageStats; 133import android.content.pm.PackageUserState; 134import android.content.pm.ParceledListSlice; 135import android.content.pm.PermissionGroupInfo; 136import android.content.pm.PermissionInfo; 137import android.content.pm.ProviderInfo; 138import android.content.pm.ResolveInfo; 139import android.content.pm.ServiceInfo; 140import android.content.pm.Signature; 141import android.content.pm.UserInfo; 142import android.content.pm.VerificationParams; 143import android.content.pm.VerifierDeviceIdentity; 144import android.content.pm.VerifierInfo; 145import android.content.res.Resources; 146import android.hardware.display.DisplayManager; 147import android.net.Uri; 148import android.os.Debug; 149import android.os.Binder; 150import android.os.Build; 151import android.os.Bundle; 152import android.os.Environment; 153import android.os.Environment.UserEnvironment; 154import android.os.FileUtils; 155import android.os.Handler; 156import android.os.IBinder; 157import android.os.Looper; 158import android.os.Message; 159import android.os.Parcel; 160import android.os.ParcelFileDescriptor; 161import android.os.Process; 162import android.os.RemoteCallbackList; 163import android.os.RemoteException; 164import android.os.SELinux; 165import android.os.ServiceManager; 166import android.os.SystemClock; 167import android.os.SystemProperties; 168import android.os.UserHandle; 169import android.os.UserManager; 170import android.os.storage.IMountService; 171import android.os.storage.MountServiceInternal; 172import android.os.storage.StorageEventListener; 173import android.os.storage.StorageManager; 174import android.os.storage.VolumeInfo; 175import android.os.storage.VolumeRecord; 176import android.security.KeyStore; 177import android.security.SystemKeyStore; 178import android.system.ErrnoException; 179import android.system.Os; 180import android.system.StructStat; 181import android.text.TextUtils; 182import android.text.format.DateUtils; 183import android.util.ArrayMap; 184import android.util.ArraySet; 185import android.util.AtomicFile; 186import android.util.DisplayMetrics; 187import android.util.EventLog; 188import android.util.ExceptionUtils; 189import android.util.Log; 190import android.util.LogPrinter; 191import android.util.MathUtils; 192import android.util.PrintStreamPrinter; 193import android.util.Slog; 194import android.util.SparseArray; 195import android.util.SparseBooleanArray; 196import android.util.SparseIntArray; 197import android.util.Xml; 198import android.view.Display; 199 200import dalvik.system.DexFile; 201import dalvik.system.VMRuntime; 202 203import libcore.io.IoUtils; 204import libcore.util.EmptyArray; 205 206import com.android.internal.R; 207import com.android.internal.annotations.GuardedBy; 208import com.android.internal.app.IMediaContainerService; 209import com.android.internal.app.ResolverActivity; 210import com.android.internal.content.NativeLibraryHelper; 211import com.android.internal.content.PackageHelper; 212import com.android.internal.os.IParcelFileDescriptorFactory; 213import com.android.internal.os.SomeArgs; 214import com.android.internal.os.Zygote; 215import com.android.internal.util.ArrayUtils; 216import com.android.internal.util.FastPrintWriter; 217import com.android.internal.util.FastXmlSerializer; 218import com.android.internal.util.IndentingPrintWriter; 219import com.android.internal.util.Preconditions; 220import com.android.server.EventLogTags; 221import com.android.server.FgThread; 222import com.android.server.IntentResolver; 223import com.android.server.LocalServices; 224import com.android.server.ServiceThread; 225import com.android.server.SystemConfig; 226import com.android.server.Watchdog; 227import com.android.server.pm.PermissionsState.PermissionState; 228import com.android.server.pm.Settings.DatabaseVersion; 229import com.android.server.pm.Settings.VersionInfo; 230import com.android.server.storage.DeviceStorageMonitorInternal; 231 232import org.xmlpull.v1.XmlPullParser; 233import org.xmlpull.v1.XmlPullParserException; 234import org.xmlpull.v1.XmlSerializer; 235 236import java.io.BufferedInputStream; 237import java.io.BufferedOutputStream; 238import java.io.BufferedReader; 239import java.io.ByteArrayInputStream; 240import java.io.ByteArrayOutputStream; 241import java.io.File; 242import java.io.FileDescriptor; 243import java.io.FileNotFoundException; 244import java.io.FileOutputStream; 245import java.io.FileReader; 246import java.io.FilenameFilter; 247import java.io.IOException; 248import java.io.InputStream; 249import java.io.PrintWriter; 250import java.nio.charset.StandardCharsets; 251import java.security.NoSuchAlgorithmException; 252import java.security.PublicKey; 253import java.security.cert.CertificateEncodingException; 254import java.security.cert.CertificateException; 255import java.text.SimpleDateFormat; 256import java.util.ArrayList; 257import java.util.Arrays; 258import java.util.Collection; 259import java.util.Collections; 260import java.util.Comparator; 261import java.util.Date; 262import java.util.Iterator; 263import java.util.List; 264import java.util.Map; 265import java.util.Objects; 266import java.util.Set; 267import java.util.concurrent.CountDownLatch; 268import java.util.concurrent.TimeUnit; 269import java.util.concurrent.atomic.AtomicBoolean; 270import java.util.concurrent.atomic.AtomicInteger; 271import java.util.concurrent.atomic.AtomicLong; 272 273/** 274 * Keep track of all those .apks everywhere. 275 * 276 * This is very central to the platform's security; please run the unit 277 * tests whenever making modifications here: 278 * 279mmm frameworks/base/tests/AndroidTests 280adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 281adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 282 * 283 * {@hide} 284 */ 285public class PackageManagerService extends IPackageManager.Stub { 286 static final String TAG = "PackageManager"; 287 static final boolean DEBUG_SETTINGS = false; 288 static final boolean DEBUG_PREFERRED = false; 289 static final boolean DEBUG_UPGRADE = false; 290 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 291 private static final boolean DEBUG_BACKUP = false; 292 private static final boolean DEBUG_INSTALL = false; 293 private static final boolean DEBUG_REMOVE = false; 294 private static final boolean DEBUG_BROADCASTS = false; 295 private static final boolean DEBUG_SHOW_INFO = false; 296 private static final boolean DEBUG_PACKAGE_INFO = false; 297 private static final boolean DEBUG_INTENT_MATCHING = false; 298 private static final boolean DEBUG_PACKAGE_SCANNING = false; 299 private static final boolean DEBUG_VERIFY = false; 300 private static final boolean DEBUG_DEXOPT = false; 301 private static final boolean DEBUG_ABI_SELECTION = false; 302 303 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 304 305 private static final int RADIO_UID = Process.PHONE_UID; 306 private static final int LOG_UID = Process.LOG_UID; 307 private static final int NFC_UID = Process.NFC_UID; 308 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 309 private static final int SHELL_UID = Process.SHELL_UID; 310 311 // Cap the size of permission trees that 3rd party apps can define 312 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 313 314 // Suffix used during package installation when copying/moving 315 // package apks to install directory. 316 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 317 318 static final int SCAN_NO_DEX = 1<<1; 319 static final int SCAN_FORCE_DEX = 1<<2; 320 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 321 static final int SCAN_NEW_INSTALL = 1<<4; 322 static final int SCAN_NO_PATHS = 1<<5; 323 static final int SCAN_UPDATE_TIME = 1<<6; 324 static final int SCAN_DEFER_DEX = 1<<7; 325 static final int SCAN_BOOTING = 1<<8; 326 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 327 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 328 static final int SCAN_REPLACING = 1<<11; 329 static final int SCAN_REQUIRE_KNOWN = 1<<12; 330 static final int SCAN_MOVE = 1<<13; 331 static final int SCAN_INITIAL = 1<<14; 332 333 static final int REMOVE_CHATTY = 1<<16; 334 335 private static final int[] EMPTY_INT_ARRAY = new int[0]; 336 337 /** 338 * Timeout (in milliseconds) after which the watchdog should declare that 339 * our handler thread is wedged. The usual default for such things is one 340 * minute but we sometimes do very lengthy I/O operations on this thread, 341 * such as installing multi-gigabyte applications, so ours needs to be longer. 342 */ 343 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 344 345 /** 346 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 347 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 348 * settings entry if available, otherwise we use the hardcoded default. If it's been 349 * more than this long since the last fstrim, we force one during the boot sequence. 350 * 351 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 352 * one gets run at the next available charging+idle time. This final mandatory 353 * no-fstrim check kicks in only of the other scheduling criteria is never met. 354 */ 355 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 356 357 /** 358 * Whether verification is enabled by default. 359 */ 360 private static final boolean DEFAULT_VERIFY_ENABLE = true; 361 362 /** 363 * The default maximum time to wait for the verification agent to return in 364 * milliseconds. 365 */ 366 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 367 368 /** 369 * The default response for package verification timeout. 370 * 371 * This can be either PackageManager.VERIFICATION_ALLOW or 372 * PackageManager.VERIFICATION_REJECT. 373 */ 374 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 375 376 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 377 378 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 379 DEFAULT_CONTAINER_PACKAGE, 380 "com.android.defcontainer.DefaultContainerService"); 381 382 private static final String KILL_APP_REASON_GIDS_CHANGED = 383 "permission grant or revoke changed gids"; 384 385 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 386 "permissions revoked"; 387 388 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 389 390 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 391 392 /** Permission grant: not grant the permission. */ 393 private static final int GRANT_DENIED = 1; 394 395 /** Permission grant: grant the permission as an install permission. */ 396 private static final int GRANT_INSTALL = 2; 397 398 /** Permission grant: grant the permission as an install permission for a legacy app. */ 399 private static final int GRANT_INSTALL_LEGACY = 3; 400 401 /** Permission grant: grant the permission as a runtime one. */ 402 private static final int GRANT_RUNTIME = 4; 403 404 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 405 private static final int GRANT_UPGRADE = 5; 406 407 /** Canonical intent used to identify what counts as a "web browser" app */ 408 private static final Intent sBrowserIntent; 409 static { 410 sBrowserIntent = new Intent(); 411 sBrowserIntent.setAction(Intent.ACTION_VIEW); 412 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 413 sBrowserIntent.setData(Uri.parse("http:")); 414 } 415 416 final ServiceThread mHandlerThread; 417 418 final PackageHandler mHandler; 419 420 /** 421 * Messages for {@link #mHandler} that need to wait for system ready before 422 * being dispatched. 423 */ 424 private ArrayList<Message> mPostSystemReadyMessages; 425 426 final int mSdkVersion = Build.VERSION.SDK_INT; 427 428 final Context mContext; 429 final boolean mFactoryTest; 430 final boolean mOnlyCore; 431 final boolean mLazyDexOpt; 432 final long mDexOptLRUThresholdInMills; 433 final DisplayMetrics mMetrics; 434 final int mDefParseFlags; 435 final String[] mSeparateProcesses; 436 final boolean mIsUpgrade; 437 438 // This is where all application persistent data goes. 439 final File mAppDataDir; 440 441 // This is where all application persistent data goes for secondary users. 442 final File mUserAppDataDir; 443 444 /** The location for ASEC container files on internal storage. */ 445 final String mAsecInternalPath; 446 447 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 448 // LOCK HELD. Can be called with mInstallLock held. 449 @GuardedBy("mInstallLock") 450 final Installer mInstaller; 451 452 /** Directory where installed third-party apps stored */ 453 final File mAppInstallDir; 454 455 /** 456 * Directory to which applications installed internally have their 457 * 32 bit native libraries copied. 458 */ 459 private File mAppLib32InstallDir; 460 461 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 462 // apps. 463 final File mDrmAppPrivateInstallDir; 464 465 // ---------------------------------------------------------------- 466 467 // Lock for state used when installing and doing other long running 468 // operations. Methods that must be called with this lock held have 469 // the suffix "LI". 470 final Object mInstallLock = new Object(); 471 472 // ---------------------------------------------------------------- 473 474 // Keys are String (package name), values are Package. This also serves 475 // as the lock for the global state. Methods that must be called with 476 // this lock held have the prefix "LP". 477 @GuardedBy("mPackages") 478 final ArrayMap<String, PackageParser.Package> mPackages = 479 new ArrayMap<String, PackageParser.Package>(); 480 481 // Tracks available target package names -> overlay package paths. 482 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 483 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 484 485 /** 486 * Tracks new system packages [received in an OTA] that we expect to 487 * find updated user-installed versions. Keys are package name, values 488 * are package location. 489 */ 490 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 491 492 /** 493 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 494 */ 495 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 496 /** 497 * Whether or not system app permissions should be promoted from install to runtime. 498 */ 499 boolean mPromoteSystemApps; 500 501 final Settings mSettings; 502 boolean mRestoredSettings; 503 504 // System configuration read by SystemConfig. 505 final int[] mGlobalGids; 506 final SparseArray<ArraySet<String>> mSystemPermissions; 507 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 508 509 // If mac_permissions.xml was found for seinfo labeling. 510 boolean mFoundPolicyFile; 511 512 // If a recursive restorecon of /data/data/<pkg> is needed. 513 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 514 515 public static final class SharedLibraryEntry { 516 public final String path; 517 public final String apk; 518 519 SharedLibraryEntry(String _path, String _apk) { 520 path = _path; 521 apk = _apk; 522 } 523 } 524 525 // Currently known shared libraries. 526 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 527 new ArrayMap<String, SharedLibraryEntry>(); 528 529 // All available activities, for your resolving pleasure. 530 final ActivityIntentResolver mActivities = 531 new ActivityIntentResolver(); 532 533 // All available receivers, for your resolving pleasure. 534 final ActivityIntentResolver mReceivers = 535 new ActivityIntentResolver(); 536 537 // All available services, for your resolving pleasure. 538 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 539 540 // All available providers, for your resolving pleasure. 541 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 542 543 // Mapping from provider base names (first directory in content URI codePath) 544 // to the provider information. 545 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 546 new ArrayMap<String, PackageParser.Provider>(); 547 548 // Mapping from instrumentation class names to info about them. 549 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 550 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 551 552 // Mapping from permission names to info about them. 553 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 554 new ArrayMap<String, PackageParser.PermissionGroup>(); 555 556 // Packages whose data we have transfered into another package, thus 557 // should no longer exist. 558 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 559 560 // Broadcast actions that are only available to the system. 561 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 562 563 /** List of packages waiting for verification. */ 564 final SparseArray<PackageVerificationState> mPendingVerification 565 = new SparseArray<PackageVerificationState>(); 566 567 /** Set of packages associated with each app op permission. */ 568 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 569 570 final PackageInstallerService mInstallerService; 571 572 private final PackageDexOptimizer mPackageDexOptimizer; 573 574 private AtomicInteger mNextMoveId = new AtomicInteger(); 575 private final MoveCallbacks mMoveCallbacks; 576 577 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 578 579 // Cache of users who need badging. 580 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 581 582 /** Token for keys in mPendingVerification. */ 583 private int mPendingVerificationToken = 0; 584 585 volatile boolean mSystemReady; 586 volatile boolean mSafeMode; 587 volatile boolean mHasSystemUidErrors; 588 589 ApplicationInfo mAndroidApplication; 590 final ActivityInfo mResolveActivity = new ActivityInfo(); 591 final ResolveInfo mResolveInfo = new ResolveInfo(); 592 ComponentName mResolveComponentName; 593 PackageParser.Package mPlatformPackage; 594 ComponentName mCustomResolverComponentName; 595 596 boolean mResolverReplaced = false; 597 598 private final ComponentName mIntentFilterVerifierComponent; 599 private int mIntentFilterVerificationToken = 0; 600 601 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 602 = new SparseArray<IntentFilterVerificationState>(); 603 604 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 605 new DefaultPermissionGrantPolicy(this); 606 607 private static class IFVerificationParams { 608 PackageParser.Package pkg; 609 boolean replacing; 610 int userId; 611 int verifierUid; 612 613 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 614 int _userId, int _verifierUid) { 615 pkg = _pkg; 616 replacing = _replacing; 617 userId = _userId; 618 replacing = _replacing; 619 verifierUid = _verifierUid; 620 } 621 } 622 623 private interface IntentFilterVerifier<T extends IntentFilter> { 624 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 625 T filter, String packageName); 626 void startVerifications(int userId); 627 void receiveVerificationResponse(int verificationId); 628 } 629 630 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 631 private Context mContext; 632 private ComponentName mIntentFilterVerifierComponent; 633 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 634 635 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 636 mContext = context; 637 mIntentFilterVerifierComponent = verifierComponent; 638 } 639 640 private String getDefaultScheme() { 641 return IntentFilter.SCHEME_HTTPS; 642 } 643 644 @Override 645 public void startVerifications(int userId) { 646 // Launch verifications requests 647 int count = mCurrentIntentFilterVerifications.size(); 648 for (int n=0; n<count; n++) { 649 int verificationId = mCurrentIntentFilterVerifications.get(n); 650 final IntentFilterVerificationState ivs = 651 mIntentFilterVerificationStates.get(verificationId); 652 653 String packageName = ivs.getPackageName(); 654 655 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 656 final int filterCount = filters.size(); 657 ArraySet<String> domainsSet = new ArraySet<>(); 658 for (int m=0; m<filterCount; m++) { 659 PackageParser.ActivityIntentInfo filter = filters.get(m); 660 domainsSet.addAll(filter.getHostsList()); 661 } 662 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 663 synchronized (mPackages) { 664 if (mSettings.createIntentFilterVerificationIfNeededLPw( 665 packageName, domainsList) != null) { 666 scheduleWriteSettingsLocked(); 667 } 668 } 669 sendVerificationRequest(userId, verificationId, ivs); 670 } 671 mCurrentIntentFilterVerifications.clear(); 672 } 673 674 private void sendVerificationRequest(int userId, int verificationId, 675 IntentFilterVerificationState ivs) { 676 677 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 678 verificationIntent.putExtra( 679 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 680 verificationId); 681 verificationIntent.putExtra( 682 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 683 getDefaultScheme()); 684 verificationIntent.putExtra( 685 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 686 ivs.getHostsString()); 687 verificationIntent.putExtra( 688 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 689 ivs.getPackageName()); 690 verificationIntent.setComponent(mIntentFilterVerifierComponent); 691 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 692 693 UserHandle user = new UserHandle(userId); 694 mContext.sendBroadcastAsUser(verificationIntent, user); 695 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 696 "Sending IntentFilter verification broadcast"); 697 } 698 699 public void receiveVerificationResponse(int verificationId) { 700 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 701 702 final boolean verified = ivs.isVerified(); 703 704 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 705 final int count = filters.size(); 706 if (DEBUG_DOMAIN_VERIFICATION) { 707 Slog.i(TAG, "Received verification response " + verificationId 708 + " for " + count + " filters, verified=" + verified); 709 } 710 for (int n=0; n<count; n++) { 711 PackageParser.ActivityIntentInfo filter = filters.get(n); 712 filter.setVerified(verified); 713 714 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 715 + " verified with result:" + verified + " and hosts:" 716 + ivs.getHostsString()); 717 } 718 719 mIntentFilterVerificationStates.remove(verificationId); 720 721 final String packageName = ivs.getPackageName(); 722 IntentFilterVerificationInfo ivi = null; 723 724 synchronized (mPackages) { 725 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 726 } 727 if (ivi == null) { 728 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 729 + verificationId + " packageName:" + packageName); 730 return; 731 } 732 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 733 "Updating IntentFilterVerificationInfo for package " + packageName 734 +" verificationId:" + verificationId); 735 736 synchronized (mPackages) { 737 if (verified) { 738 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 739 } else { 740 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 741 } 742 scheduleWriteSettingsLocked(); 743 744 final int userId = ivs.getUserId(); 745 if (userId != UserHandle.USER_ALL) { 746 final int userStatus = 747 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 748 749 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 750 boolean needUpdate = false; 751 752 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 753 // already been set by the User thru the Disambiguation dialog 754 switch (userStatus) { 755 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 756 if (verified) { 757 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 758 } else { 759 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 760 } 761 needUpdate = true; 762 break; 763 764 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 765 if (verified) { 766 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 767 needUpdate = true; 768 } 769 break; 770 771 default: 772 // Nothing to do 773 } 774 775 if (needUpdate) { 776 mSettings.updateIntentFilterVerificationStatusLPw( 777 packageName, updatedStatus, userId); 778 scheduleWritePackageRestrictionsLocked(userId); 779 } 780 } 781 } 782 } 783 784 @Override 785 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 786 ActivityIntentInfo filter, String packageName) { 787 if (!hasValidDomains(filter)) { 788 return false; 789 } 790 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 791 if (ivs == null) { 792 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 793 packageName); 794 } 795 if (DEBUG_DOMAIN_VERIFICATION) { 796 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 797 } 798 ivs.addFilter(filter); 799 return true; 800 } 801 802 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 803 int userId, int verificationId, String packageName) { 804 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 805 verifierUid, userId, packageName); 806 ivs.setPendingState(); 807 synchronized (mPackages) { 808 mIntentFilterVerificationStates.append(verificationId, ivs); 809 mCurrentIntentFilterVerifications.add(verificationId); 810 } 811 return ivs; 812 } 813 } 814 815 private static boolean hasValidDomains(ActivityIntentInfo filter) { 816 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 817 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 818 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 819 } 820 821 private IntentFilterVerifier mIntentFilterVerifier; 822 823 // Set of pending broadcasts for aggregating enable/disable of components. 824 static class PendingPackageBroadcasts { 825 // for each user id, a map of <package name -> components within that package> 826 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 827 828 public PendingPackageBroadcasts() { 829 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 830 } 831 832 public ArrayList<String> get(int userId, String packageName) { 833 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 834 return packages.get(packageName); 835 } 836 837 public void put(int userId, String packageName, ArrayList<String> components) { 838 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 839 packages.put(packageName, components); 840 } 841 842 public void remove(int userId, String packageName) { 843 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 844 if (packages != null) { 845 packages.remove(packageName); 846 } 847 } 848 849 public void remove(int userId) { 850 mUidMap.remove(userId); 851 } 852 853 public int userIdCount() { 854 return mUidMap.size(); 855 } 856 857 public int userIdAt(int n) { 858 return mUidMap.keyAt(n); 859 } 860 861 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 862 return mUidMap.get(userId); 863 } 864 865 public int size() { 866 // total number of pending broadcast entries across all userIds 867 int num = 0; 868 for (int i = 0; i< mUidMap.size(); i++) { 869 num += mUidMap.valueAt(i).size(); 870 } 871 return num; 872 } 873 874 public void clear() { 875 mUidMap.clear(); 876 } 877 878 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 879 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 880 if (map == null) { 881 map = new ArrayMap<String, ArrayList<String>>(); 882 mUidMap.put(userId, map); 883 } 884 return map; 885 } 886 } 887 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 888 889 // Service Connection to remote media container service to copy 890 // package uri's from external media onto secure containers 891 // or internal storage. 892 private IMediaContainerService mContainerService = null; 893 894 static final int SEND_PENDING_BROADCAST = 1; 895 static final int MCS_BOUND = 3; 896 static final int END_COPY = 4; 897 static final int INIT_COPY = 5; 898 static final int MCS_UNBIND = 6; 899 static final int START_CLEANING_PACKAGE = 7; 900 static final int FIND_INSTALL_LOC = 8; 901 static final int POST_INSTALL = 9; 902 static final int MCS_RECONNECT = 10; 903 static final int MCS_GIVE_UP = 11; 904 static final int UPDATED_MEDIA_STATUS = 12; 905 static final int WRITE_SETTINGS = 13; 906 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 907 static final int PACKAGE_VERIFIED = 15; 908 static final int CHECK_PENDING_VERIFICATION = 16; 909 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 910 static final int INTENT_FILTER_VERIFIED = 18; 911 912 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 913 914 // Delay time in millisecs 915 static final int BROADCAST_DELAY = 10 * 1000; 916 917 static UserManagerService sUserManager; 918 919 // Stores a list of users whose package restrictions file needs to be updated 920 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 921 922 final private DefaultContainerConnection mDefContainerConn = 923 new DefaultContainerConnection(); 924 class DefaultContainerConnection implements ServiceConnection { 925 public void onServiceConnected(ComponentName name, IBinder service) { 926 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 927 IMediaContainerService imcs = 928 IMediaContainerService.Stub.asInterface(service); 929 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 930 } 931 932 public void onServiceDisconnected(ComponentName name) { 933 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 934 } 935 } 936 937 // Recordkeeping of restore-after-install operations that are currently in flight 938 // between the Package Manager and the Backup Manager 939 class PostInstallData { 940 public InstallArgs args; 941 public PackageInstalledInfo res; 942 943 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 944 args = _a; 945 res = _r; 946 } 947 } 948 949 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 950 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 951 952 // XML tags for backup/restore of various bits of state 953 private static final String TAG_PREFERRED_BACKUP = "pa"; 954 private static final String TAG_DEFAULT_APPS = "da"; 955 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 956 957 final String mRequiredVerifierPackage; 958 final String mRequiredInstallerPackage; 959 960 private final PackageUsage mPackageUsage = new PackageUsage(); 961 962 private class PackageUsage { 963 private static final int WRITE_INTERVAL 964 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 965 966 private final Object mFileLock = new Object(); 967 private final AtomicLong mLastWritten = new AtomicLong(0); 968 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 969 970 private boolean mIsHistoricalPackageUsageAvailable = true; 971 972 boolean isHistoricalPackageUsageAvailable() { 973 return mIsHistoricalPackageUsageAvailable; 974 } 975 976 void write(boolean force) { 977 if (force) { 978 writeInternal(); 979 return; 980 } 981 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 982 && !DEBUG_DEXOPT) { 983 return; 984 } 985 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 986 new Thread("PackageUsage_DiskWriter") { 987 @Override 988 public void run() { 989 try { 990 writeInternal(); 991 } finally { 992 mBackgroundWriteRunning.set(false); 993 } 994 } 995 }.start(); 996 } 997 } 998 999 private void writeInternal() { 1000 synchronized (mPackages) { 1001 synchronized (mFileLock) { 1002 AtomicFile file = getFile(); 1003 FileOutputStream f = null; 1004 try { 1005 f = file.startWrite(); 1006 BufferedOutputStream out = new BufferedOutputStream(f); 1007 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1008 StringBuilder sb = new StringBuilder(); 1009 for (PackageParser.Package pkg : mPackages.values()) { 1010 if (pkg.mLastPackageUsageTimeInMills == 0) { 1011 continue; 1012 } 1013 sb.setLength(0); 1014 sb.append(pkg.packageName); 1015 sb.append(' '); 1016 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1017 sb.append('\n'); 1018 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1019 } 1020 out.flush(); 1021 file.finishWrite(f); 1022 } catch (IOException e) { 1023 if (f != null) { 1024 file.failWrite(f); 1025 } 1026 Log.e(TAG, "Failed to write package usage times", e); 1027 } 1028 } 1029 } 1030 mLastWritten.set(SystemClock.elapsedRealtime()); 1031 } 1032 1033 void readLP() { 1034 synchronized (mFileLock) { 1035 AtomicFile file = getFile(); 1036 BufferedInputStream in = null; 1037 try { 1038 in = new BufferedInputStream(file.openRead()); 1039 StringBuffer sb = new StringBuffer(); 1040 while (true) { 1041 String packageName = readToken(in, sb, ' '); 1042 if (packageName == null) { 1043 break; 1044 } 1045 String timeInMillisString = readToken(in, sb, '\n'); 1046 if (timeInMillisString == null) { 1047 throw new IOException("Failed to find last usage time for package " 1048 + packageName); 1049 } 1050 PackageParser.Package pkg = mPackages.get(packageName); 1051 if (pkg == null) { 1052 continue; 1053 } 1054 long timeInMillis; 1055 try { 1056 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1057 } catch (NumberFormatException e) { 1058 throw new IOException("Failed to parse " + timeInMillisString 1059 + " as a long.", e); 1060 } 1061 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1062 } 1063 } catch (FileNotFoundException expected) { 1064 mIsHistoricalPackageUsageAvailable = false; 1065 } catch (IOException e) { 1066 Log.w(TAG, "Failed to read package usage times", e); 1067 } finally { 1068 IoUtils.closeQuietly(in); 1069 } 1070 } 1071 mLastWritten.set(SystemClock.elapsedRealtime()); 1072 } 1073 1074 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1075 throws IOException { 1076 sb.setLength(0); 1077 while (true) { 1078 int ch = in.read(); 1079 if (ch == -1) { 1080 if (sb.length() == 0) { 1081 return null; 1082 } 1083 throw new IOException("Unexpected EOF"); 1084 } 1085 if (ch == endOfToken) { 1086 return sb.toString(); 1087 } 1088 sb.append((char)ch); 1089 } 1090 } 1091 1092 private AtomicFile getFile() { 1093 File dataDir = Environment.getDataDirectory(); 1094 File systemDir = new File(dataDir, "system"); 1095 File fname = new File(systemDir, "package-usage.list"); 1096 return new AtomicFile(fname); 1097 } 1098 } 1099 1100 class PackageHandler extends Handler { 1101 private boolean mBound = false; 1102 final ArrayList<HandlerParams> mPendingInstalls = 1103 new ArrayList<HandlerParams>(); 1104 1105 private boolean connectToService() { 1106 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1107 " DefaultContainerService"); 1108 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1109 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1110 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1111 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1113 mBound = true; 1114 return true; 1115 } 1116 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1117 return false; 1118 } 1119 1120 private void disconnectService() { 1121 mContainerService = null; 1122 mBound = false; 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1124 mContext.unbindService(mDefContainerConn); 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } 1127 1128 PackageHandler(Looper looper) { 1129 super(looper); 1130 } 1131 1132 public void handleMessage(Message msg) { 1133 try { 1134 doHandleMessage(msg); 1135 } finally { 1136 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1137 } 1138 } 1139 1140 void doHandleMessage(Message msg) { 1141 switch (msg.what) { 1142 case INIT_COPY: { 1143 HandlerParams params = (HandlerParams) msg.obj; 1144 int idx = mPendingInstalls.size(); 1145 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1146 // If a bind was already initiated we dont really 1147 // need to do anything. The pending install 1148 // will be processed later on. 1149 if (!mBound) { 1150 // If this is the only one pending we might 1151 // have to bind to the service again. 1152 if (!connectToService()) { 1153 Slog.e(TAG, "Failed to bind to media container service"); 1154 params.serviceError(); 1155 return; 1156 } else { 1157 // Once we bind to the service, the first 1158 // pending request will be processed. 1159 mPendingInstalls.add(idx, params); 1160 } 1161 } else { 1162 mPendingInstalls.add(idx, params); 1163 // Already bound to the service. Just make 1164 // sure we trigger off processing the first request. 1165 if (idx == 0) { 1166 mHandler.sendEmptyMessage(MCS_BOUND); 1167 } 1168 } 1169 break; 1170 } 1171 case MCS_BOUND: { 1172 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1173 if (msg.obj != null) { 1174 mContainerService = (IMediaContainerService) msg.obj; 1175 } 1176 if (mContainerService == null) { 1177 if (!mBound) { 1178 // Something seriously wrong since we are not bound and we are not 1179 // waiting for connection. Bail out. 1180 Slog.e(TAG, "Cannot bind to media container service"); 1181 for (HandlerParams params : mPendingInstalls) { 1182 // Indicate service bind error 1183 params.serviceError(); 1184 } 1185 mPendingInstalls.clear(); 1186 } else { 1187 Slog.w(TAG, "Waiting to connect to media container service"); 1188 } 1189 } else if (mPendingInstalls.size() > 0) { 1190 HandlerParams params = mPendingInstalls.get(0); 1191 if (params != null) { 1192 if (params.startCopy()) { 1193 // We are done... look for more work or to 1194 // go idle. 1195 if (DEBUG_SD_INSTALL) Log.i(TAG, 1196 "Checking for more work or unbind..."); 1197 // Delete pending install 1198 if (mPendingInstalls.size() > 0) { 1199 mPendingInstalls.remove(0); 1200 } 1201 if (mPendingInstalls.size() == 0) { 1202 if (mBound) { 1203 if (DEBUG_SD_INSTALL) Log.i(TAG, 1204 "Posting delayed MCS_UNBIND"); 1205 removeMessages(MCS_UNBIND); 1206 Message ubmsg = obtainMessage(MCS_UNBIND); 1207 // Unbind after a little delay, to avoid 1208 // continual thrashing. 1209 sendMessageDelayed(ubmsg, 10000); 1210 } 1211 } else { 1212 // There are more pending requests in queue. 1213 // Just post MCS_BOUND message to trigger processing 1214 // of next pending install. 1215 if (DEBUG_SD_INSTALL) Log.i(TAG, 1216 "Posting MCS_BOUND for next work"); 1217 mHandler.sendEmptyMessage(MCS_BOUND); 1218 } 1219 } 1220 } 1221 } else { 1222 // Should never happen ideally. 1223 Slog.w(TAG, "Empty queue"); 1224 } 1225 break; 1226 } 1227 case MCS_RECONNECT: { 1228 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1229 if (mPendingInstalls.size() > 0) { 1230 if (mBound) { 1231 disconnectService(); 1232 } 1233 if (!connectToService()) { 1234 Slog.e(TAG, "Failed to bind to media container service"); 1235 for (HandlerParams params : mPendingInstalls) { 1236 // Indicate service bind error 1237 params.serviceError(); 1238 } 1239 mPendingInstalls.clear(); 1240 } 1241 } 1242 break; 1243 } 1244 case MCS_UNBIND: { 1245 // If there is no actual work left, then time to unbind. 1246 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1247 1248 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1249 if (mBound) { 1250 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1251 1252 disconnectService(); 1253 } 1254 } else if (mPendingInstalls.size() > 0) { 1255 // There are more pending requests in queue. 1256 // Just post MCS_BOUND message to trigger processing 1257 // of next pending install. 1258 mHandler.sendEmptyMessage(MCS_BOUND); 1259 } 1260 1261 break; 1262 } 1263 case MCS_GIVE_UP: { 1264 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1265 mPendingInstalls.remove(0); 1266 break; 1267 } 1268 case SEND_PENDING_BROADCAST: { 1269 String packages[]; 1270 ArrayList<String> components[]; 1271 int size = 0; 1272 int uids[]; 1273 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1274 synchronized (mPackages) { 1275 if (mPendingBroadcasts == null) { 1276 return; 1277 } 1278 size = mPendingBroadcasts.size(); 1279 if (size <= 0) { 1280 // Nothing to be done. Just return 1281 return; 1282 } 1283 packages = new String[size]; 1284 components = new ArrayList[size]; 1285 uids = new int[size]; 1286 int i = 0; // filling out the above arrays 1287 1288 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1289 int packageUserId = mPendingBroadcasts.userIdAt(n); 1290 Iterator<Map.Entry<String, ArrayList<String>>> it 1291 = mPendingBroadcasts.packagesForUserId(packageUserId) 1292 .entrySet().iterator(); 1293 while (it.hasNext() && i < size) { 1294 Map.Entry<String, ArrayList<String>> ent = it.next(); 1295 packages[i] = ent.getKey(); 1296 components[i] = ent.getValue(); 1297 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1298 uids[i] = (ps != null) 1299 ? UserHandle.getUid(packageUserId, ps.appId) 1300 : -1; 1301 i++; 1302 } 1303 } 1304 size = i; 1305 mPendingBroadcasts.clear(); 1306 } 1307 // Send broadcasts 1308 for (int i = 0; i < size; i++) { 1309 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1310 } 1311 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1312 break; 1313 } 1314 case START_CLEANING_PACKAGE: { 1315 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1316 final String packageName = (String)msg.obj; 1317 final int userId = msg.arg1; 1318 final boolean andCode = msg.arg2 != 0; 1319 synchronized (mPackages) { 1320 if (userId == UserHandle.USER_ALL) { 1321 int[] users = sUserManager.getUserIds(); 1322 for (int user : users) { 1323 mSettings.addPackageToCleanLPw( 1324 new PackageCleanItem(user, packageName, andCode)); 1325 } 1326 } else { 1327 mSettings.addPackageToCleanLPw( 1328 new PackageCleanItem(userId, packageName, andCode)); 1329 } 1330 } 1331 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1332 startCleaningPackages(); 1333 } break; 1334 case POST_INSTALL: { 1335 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1336 PostInstallData data = mRunningInstalls.get(msg.arg1); 1337 mRunningInstalls.delete(msg.arg1); 1338 boolean deleteOld = false; 1339 1340 if (data != null) { 1341 InstallArgs args = data.args; 1342 PackageInstalledInfo res = data.res; 1343 1344 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1345 final String packageName = res.pkg.applicationInfo.packageName; 1346 res.removedInfo.sendBroadcast(false, true, false); 1347 Bundle extras = new Bundle(1); 1348 extras.putInt(Intent.EXTRA_UID, res.uid); 1349 1350 // Now that we successfully installed the package, grant runtime 1351 // permissions if requested before broadcasting the install. 1352 if ((args.installFlags 1353 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1354 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1355 args.installGrantPermissions); 1356 } 1357 1358 // Determine the set of users who are adding this 1359 // package for the first time vs. those who are seeing 1360 // an update. 1361 int[] firstUsers; 1362 int[] updateUsers = new int[0]; 1363 if (res.origUsers == null || res.origUsers.length == 0) { 1364 firstUsers = res.newUsers; 1365 } else { 1366 firstUsers = new int[0]; 1367 for (int i=0; i<res.newUsers.length; i++) { 1368 int user = res.newUsers[i]; 1369 boolean isNew = true; 1370 for (int j=0; j<res.origUsers.length; j++) { 1371 if (res.origUsers[j] == user) { 1372 isNew = false; 1373 break; 1374 } 1375 } 1376 if (isNew) { 1377 int[] newFirst = new int[firstUsers.length+1]; 1378 System.arraycopy(firstUsers, 0, newFirst, 0, 1379 firstUsers.length); 1380 newFirst[firstUsers.length] = user; 1381 firstUsers = newFirst; 1382 } else { 1383 int[] newUpdate = new int[updateUsers.length+1]; 1384 System.arraycopy(updateUsers, 0, newUpdate, 0, 1385 updateUsers.length); 1386 newUpdate[updateUsers.length] = user; 1387 updateUsers = newUpdate; 1388 } 1389 } 1390 } 1391 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1392 packageName, extras, null, null, firstUsers); 1393 final boolean update = res.removedInfo.removedPackage != null; 1394 if (update) { 1395 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1396 } 1397 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1398 packageName, extras, null, null, updateUsers); 1399 if (update) { 1400 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1401 packageName, extras, null, null, updateUsers); 1402 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1403 null, null, packageName, null, updateUsers); 1404 1405 // treat asec-hosted packages like removable media on upgrade 1406 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1407 if (DEBUG_INSTALL) { 1408 Slog.i(TAG, "upgrading pkg " + res.pkg 1409 + " is ASEC-hosted -> AVAILABLE"); 1410 } 1411 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1412 ArrayList<String> pkgList = new ArrayList<String>(1); 1413 pkgList.add(packageName); 1414 sendResourcesChangedBroadcast(true, true, 1415 pkgList,uidArray, null); 1416 } 1417 } 1418 if (res.removedInfo.args != null) { 1419 // Remove the replaced package's older resources safely now 1420 deleteOld = true; 1421 } 1422 1423 // If this app is a browser and it's newly-installed for some 1424 // users, clear any default-browser state in those users 1425 if (firstUsers.length > 0) { 1426 // the app's nature doesn't depend on the user, so we can just 1427 // check its browser nature in any user and generalize. 1428 if (packageIsBrowser(packageName, firstUsers[0])) { 1429 synchronized (mPackages) { 1430 for (int userId : firstUsers) { 1431 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1432 } 1433 } 1434 } 1435 } 1436 // Log current value of "unknown sources" setting 1437 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1438 getUnknownSourcesSettings()); 1439 } 1440 // Force a gc to clear up things 1441 Runtime.getRuntime().gc(); 1442 // We delete after a gc for applications on sdcard. 1443 if (deleteOld) { 1444 synchronized (mInstallLock) { 1445 res.removedInfo.args.doPostDeleteLI(true); 1446 } 1447 } 1448 if (args.observer != null) { 1449 try { 1450 Bundle extras = extrasForInstallResult(res); 1451 args.observer.onPackageInstalled(res.name, res.returnCode, 1452 res.returnMsg, extras); 1453 } catch (RemoteException e) { 1454 Slog.i(TAG, "Observer no longer exists."); 1455 } 1456 } 1457 } else { 1458 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1459 } 1460 } break; 1461 case UPDATED_MEDIA_STATUS: { 1462 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1463 boolean reportStatus = msg.arg1 == 1; 1464 boolean doGc = msg.arg2 == 1; 1465 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1466 if (doGc) { 1467 // Force a gc to clear up stale containers. 1468 Runtime.getRuntime().gc(); 1469 } 1470 if (msg.obj != null) { 1471 @SuppressWarnings("unchecked") 1472 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1473 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1474 // Unload containers 1475 unloadAllContainers(args); 1476 } 1477 if (reportStatus) { 1478 try { 1479 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1480 PackageHelper.getMountService().finishMediaUpdate(); 1481 } catch (RemoteException e) { 1482 Log.e(TAG, "MountService not running?"); 1483 } 1484 } 1485 } break; 1486 case WRITE_SETTINGS: { 1487 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1488 synchronized (mPackages) { 1489 removeMessages(WRITE_SETTINGS); 1490 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1491 mSettings.writeLPr(); 1492 mDirtyUsers.clear(); 1493 } 1494 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1495 } break; 1496 case WRITE_PACKAGE_RESTRICTIONS: { 1497 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1498 synchronized (mPackages) { 1499 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1500 for (int userId : mDirtyUsers) { 1501 mSettings.writePackageRestrictionsLPr(userId); 1502 } 1503 mDirtyUsers.clear(); 1504 } 1505 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1506 } break; 1507 case CHECK_PENDING_VERIFICATION: { 1508 final int verificationId = msg.arg1; 1509 final PackageVerificationState state = mPendingVerification.get(verificationId); 1510 1511 if ((state != null) && !state.timeoutExtended()) { 1512 final InstallArgs args = state.getInstallArgs(); 1513 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1514 1515 Slog.i(TAG, "Verification timed out for " + originUri); 1516 mPendingVerification.remove(verificationId); 1517 1518 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1519 1520 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1521 Slog.i(TAG, "Continuing with installation of " + originUri); 1522 state.setVerifierResponse(Binder.getCallingUid(), 1523 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1524 broadcastPackageVerified(verificationId, originUri, 1525 PackageManager.VERIFICATION_ALLOW, 1526 state.getInstallArgs().getUser()); 1527 try { 1528 ret = args.copyApk(mContainerService, true); 1529 } catch (RemoteException e) { 1530 Slog.e(TAG, "Could not contact the ContainerService"); 1531 } 1532 } else { 1533 broadcastPackageVerified(verificationId, originUri, 1534 PackageManager.VERIFICATION_REJECT, 1535 state.getInstallArgs().getUser()); 1536 } 1537 1538 processPendingInstall(args, ret); 1539 mHandler.sendEmptyMessage(MCS_UNBIND); 1540 } 1541 break; 1542 } 1543 case PACKAGE_VERIFIED: { 1544 final int verificationId = msg.arg1; 1545 1546 final PackageVerificationState state = mPendingVerification.get(verificationId); 1547 if (state == null) { 1548 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1549 break; 1550 } 1551 1552 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1553 1554 state.setVerifierResponse(response.callerUid, response.code); 1555 1556 if (state.isVerificationComplete()) { 1557 mPendingVerification.remove(verificationId); 1558 1559 final InstallArgs args = state.getInstallArgs(); 1560 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1561 1562 int ret; 1563 if (state.isInstallAllowed()) { 1564 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1565 broadcastPackageVerified(verificationId, originUri, 1566 response.code, state.getInstallArgs().getUser()); 1567 try { 1568 ret = args.copyApk(mContainerService, true); 1569 } catch (RemoteException e) { 1570 Slog.e(TAG, "Could not contact the ContainerService"); 1571 } 1572 } else { 1573 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1574 } 1575 1576 processPendingInstall(args, ret); 1577 1578 mHandler.sendEmptyMessage(MCS_UNBIND); 1579 } 1580 1581 break; 1582 } 1583 case START_INTENT_FILTER_VERIFICATIONS: { 1584 IFVerificationParams params = (IFVerificationParams) msg.obj; 1585 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1586 params.replacing, params.pkg); 1587 break; 1588 } 1589 case INTENT_FILTER_VERIFIED: { 1590 final int verificationId = msg.arg1; 1591 1592 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1593 verificationId); 1594 if (state == null) { 1595 Slog.w(TAG, "Invalid IntentFilter verification token " 1596 + verificationId + " received"); 1597 break; 1598 } 1599 1600 final int userId = state.getUserId(); 1601 1602 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1603 "Processing IntentFilter verification with token:" 1604 + verificationId + " and userId:" + userId); 1605 1606 final IntentFilterVerificationResponse response = 1607 (IntentFilterVerificationResponse) msg.obj; 1608 1609 state.setVerifierResponse(response.callerUid, response.code); 1610 1611 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1612 "IntentFilter verification with token:" + verificationId 1613 + " and userId:" + userId 1614 + " is settings verifier response with response code:" 1615 + response.code); 1616 1617 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1618 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1619 + response.getFailedDomainsString()); 1620 } 1621 1622 if (state.isVerificationComplete()) { 1623 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1624 } else { 1625 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1626 "IntentFilter verification with token:" + verificationId 1627 + " was not said to be complete"); 1628 } 1629 1630 break; 1631 } 1632 } 1633 } 1634 } 1635 1636 private StorageEventListener mStorageListener = new StorageEventListener() { 1637 @Override 1638 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1639 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1640 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1641 final String volumeUuid = vol.getFsUuid(); 1642 1643 // Clean up any users or apps that were removed or recreated 1644 // while this volume was missing 1645 reconcileUsers(volumeUuid); 1646 reconcileApps(volumeUuid); 1647 1648 // Clean up any install sessions that expired or were 1649 // cancelled while this volume was missing 1650 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1651 1652 loadPrivatePackages(vol); 1653 1654 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1655 unloadPrivatePackages(vol); 1656 } 1657 } 1658 1659 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1660 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1661 updateExternalMediaStatus(true, false); 1662 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1663 updateExternalMediaStatus(false, false); 1664 } 1665 } 1666 } 1667 1668 @Override 1669 public void onVolumeForgotten(String fsUuid) { 1670 if (TextUtils.isEmpty(fsUuid)) { 1671 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1672 return; 1673 } 1674 1675 // Remove any apps installed on the forgotten volume 1676 synchronized (mPackages) { 1677 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1678 for (PackageSetting ps : packages) { 1679 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1680 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1681 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1682 } 1683 1684 mSettings.onVolumeForgotten(fsUuid); 1685 mSettings.writeLPr(); 1686 } 1687 } 1688 }; 1689 1690 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1691 String[] grantedPermissions) { 1692 if (userId >= UserHandle.USER_OWNER) { 1693 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1694 } else if (userId == UserHandle.USER_ALL) { 1695 final int[] userIds; 1696 synchronized (mPackages) { 1697 userIds = UserManagerService.getInstance().getUserIds(); 1698 } 1699 for (int someUserId : userIds) { 1700 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1701 } 1702 } 1703 1704 // We could have touched GID membership, so flush out packages.list 1705 synchronized (mPackages) { 1706 mSettings.writePackageListLPr(); 1707 } 1708 } 1709 1710 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1711 String[] grantedPermissions) { 1712 SettingBase sb = (SettingBase) pkg.mExtras; 1713 if (sb == null) { 1714 return; 1715 } 1716 1717 synchronized (mPackages) { 1718 for (String permission : pkg.requestedPermissions) { 1719 BasePermission bp = mSettings.mPermissions.get(permission); 1720 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1721 && (grantedPermissions == null 1722 || ArrayUtils.contains(grantedPermissions, permission))) { 1723 grantRuntimePermission(pkg.packageName, permission, userId); 1724 } 1725 } 1726 } 1727 } 1728 1729 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1730 Bundle extras = null; 1731 switch (res.returnCode) { 1732 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1733 extras = new Bundle(); 1734 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1735 res.origPermission); 1736 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1737 res.origPackage); 1738 break; 1739 } 1740 case PackageManager.INSTALL_SUCCEEDED: { 1741 extras = new Bundle(); 1742 extras.putBoolean(Intent.EXTRA_REPLACING, 1743 res.removedInfo != null && res.removedInfo.removedPackage != null); 1744 break; 1745 } 1746 } 1747 return extras; 1748 } 1749 1750 void scheduleWriteSettingsLocked() { 1751 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1752 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1753 } 1754 } 1755 1756 void scheduleWritePackageRestrictionsLocked(int userId) { 1757 if (!sUserManager.exists(userId)) return; 1758 mDirtyUsers.add(userId); 1759 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1760 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1761 } 1762 } 1763 1764 public static PackageManagerService main(Context context, Installer installer, 1765 boolean factoryTest, boolean onlyCore) { 1766 PackageManagerService m = new PackageManagerService(context, installer, 1767 factoryTest, onlyCore); 1768 ServiceManager.addService("package", m); 1769 return m; 1770 } 1771 1772 static String[] splitString(String str, char sep) { 1773 int count = 1; 1774 int i = 0; 1775 while ((i=str.indexOf(sep, i)) >= 0) { 1776 count++; 1777 i++; 1778 } 1779 1780 String[] res = new String[count]; 1781 i=0; 1782 count = 0; 1783 int lastI=0; 1784 while ((i=str.indexOf(sep, i)) >= 0) { 1785 res[count] = str.substring(lastI, i); 1786 count++; 1787 i++; 1788 lastI = i; 1789 } 1790 res[count] = str.substring(lastI, str.length()); 1791 return res; 1792 } 1793 1794 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1795 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1796 Context.DISPLAY_SERVICE); 1797 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1798 } 1799 1800 public PackageManagerService(Context context, Installer installer, 1801 boolean factoryTest, boolean onlyCore) { 1802 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1803 SystemClock.uptimeMillis()); 1804 1805 if (mSdkVersion <= 0) { 1806 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1807 } 1808 1809 mContext = context; 1810 mFactoryTest = factoryTest; 1811 mOnlyCore = onlyCore; 1812 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1813 mMetrics = new DisplayMetrics(); 1814 mSettings = new Settings(mPackages); 1815 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1816 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1817 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1818 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1819 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1820 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1821 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1822 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1823 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1824 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1825 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1826 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1827 1828 // TODO: add a property to control this? 1829 long dexOptLRUThresholdInMinutes; 1830 if (mLazyDexOpt) { 1831 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1832 } else { 1833 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1834 } 1835 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1836 1837 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1838 if (separateProcesses != null && separateProcesses.length() > 0) { 1839 if ("*".equals(separateProcesses)) { 1840 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1841 mSeparateProcesses = null; 1842 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1843 } else { 1844 mDefParseFlags = 0; 1845 mSeparateProcesses = separateProcesses.split(","); 1846 Slog.w(TAG, "Running with debug.separate_processes: " 1847 + separateProcesses); 1848 } 1849 } else { 1850 mDefParseFlags = 0; 1851 mSeparateProcesses = null; 1852 } 1853 1854 mInstaller = installer; 1855 mPackageDexOptimizer = new PackageDexOptimizer(this); 1856 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1857 1858 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1859 FgThread.get().getLooper()); 1860 1861 getDefaultDisplayMetrics(context, mMetrics); 1862 1863 SystemConfig systemConfig = SystemConfig.getInstance(); 1864 mGlobalGids = systemConfig.getGlobalGids(); 1865 mSystemPermissions = systemConfig.getSystemPermissions(); 1866 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1867 1868 synchronized (mInstallLock) { 1869 // writer 1870 synchronized (mPackages) { 1871 mHandlerThread = new ServiceThread(TAG, 1872 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1873 mHandlerThread.start(); 1874 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1875 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1876 1877 File dataDir = Environment.getDataDirectory(); 1878 mAppDataDir = new File(dataDir, "data"); 1879 mAppInstallDir = new File(dataDir, "app"); 1880 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1881 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1882 mUserAppDataDir = new File(dataDir, "user"); 1883 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1884 1885 sUserManager = new UserManagerService(context, this, 1886 mInstallLock, mPackages); 1887 1888 // Propagate permission configuration in to package manager. 1889 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1890 = systemConfig.getPermissions(); 1891 for (int i=0; i<permConfig.size(); i++) { 1892 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1893 BasePermission bp = mSettings.mPermissions.get(perm.name); 1894 if (bp == null) { 1895 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1896 mSettings.mPermissions.put(perm.name, bp); 1897 } 1898 if (perm.gids != null) { 1899 bp.setGids(perm.gids, perm.perUser); 1900 } 1901 } 1902 1903 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1904 for (int i=0; i<libConfig.size(); i++) { 1905 mSharedLibraries.put(libConfig.keyAt(i), 1906 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1907 } 1908 1909 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1910 1911 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1912 mSdkVersion, mOnlyCore); 1913 1914 String customResolverActivity = Resources.getSystem().getString( 1915 R.string.config_customResolverActivity); 1916 if (TextUtils.isEmpty(customResolverActivity)) { 1917 customResolverActivity = null; 1918 } else { 1919 mCustomResolverComponentName = ComponentName.unflattenFromString( 1920 customResolverActivity); 1921 } 1922 1923 long startTime = SystemClock.uptimeMillis(); 1924 1925 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1926 startTime); 1927 1928 // Set flag to monitor and not change apk file paths when 1929 // scanning install directories. 1930 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1931 1932 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1933 1934 /** 1935 * Add everything in the in the boot class path to the 1936 * list of process files because dexopt will have been run 1937 * if necessary during zygote startup. 1938 */ 1939 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1940 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1941 1942 if (bootClassPath != null) { 1943 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1944 for (String element : bootClassPathElements) { 1945 alreadyDexOpted.add(element); 1946 } 1947 } else { 1948 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1949 } 1950 1951 if (systemServerClassPath != null) { 1952 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1953 for (String element : systemServerClassPathElements) { 1954 alreadyDexOpted.add(element); 1955 } 1956 } else { 1957 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1958 } 1959 1960 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1961 final String[] dexCodeInstructionSets = 1962 getDexCodeInstructionSets( 1963 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1964 1965 /** 1966 * Ensure all external libraries have had dexopt run on them. 1967 */ 1968 if (mSharedLibraries.size() > 0) { 1969 // NOTE: For now, we're compiling these system "shared libraries" 1970 // (and framework jars) into all available architectures. It's possible 1971 // to compile them only when we come across an app that uses them (there's 1972 // already logic for that in scanPackageLI) but that adds some complexity. 1973 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1974 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1975 final String lib = libEntry.path; 1976 if (lib == null) { 1977 continue; 1978 } 1979 1980 try { 1981 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1982 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1983 alreadyDexOpted.add(lib); 1984 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 1985 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 1986 } 1987 } catch (FileNotFoundException e) { 1988 Slog.w(TAG, "Library not found: " + lib); 1989 } catch (IOException e) { 1990 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1991 + e.getMessage()); 1992 } 1993 } 1994 } 1995 } 1996 1997 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1998 1999 // Gross hack for now: we know this file doesn't contain any 2000 // code, so don't dexopt it to avoid the resulting log spew. 2001 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2002 2003 // Gross hack for now: we know this file is only part of 2004 // the boot class path for art, so don't dexopt it to 2005 // avoid the resulting log spew. 2006 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2007 2008 /** 2009 * There are a number of commands implemented in Java, which 2010 * we currently need to do the dexopt on so that they can be 2011 * run from a non-root shell. 2012 */ 2013 String[] frameworkFiles = frameworkDir.list(); 2014 if (frameworkFiles != null) { 2015 // TODO: We could compile these only for the most preferred ABI. We should 2016 // first double check that the dex files for these commands are not referenced 2017 // by other system apps. 2018 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2019 for (int i=0; i<frameworkFiles.length; i++) { 2020 File libPath = new File(frameworkDir, frameworkFiles[i]); 2021 String path = libPath.getPath(); 2022 // Skip the file if we already did it. 2023 if (alreadyDexOpted.contains(path)) { 2024 continue; 2025 } 2026 // Skip the file if it is not a type we want to dexopt. 2027 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2028 continue; 2029 } 2030 try { 2031 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2032 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2033 mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet, 2034 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2035 } 2036 } catch (FileNotFoundException e) { 2037 Slog.w(TAG, "Jar not found: " + path); 2038 } catch (IOException e) { 2039 Slog.w(TAG, "Exception reading jar: " + path, e); 2040 } 2041 } 2042 } 2043 } 2044 2045 final VersionInfo ver = mSettings.getInternalVersion(); 2046 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2047 // when upgrading from pre-M, promote system app permissions from install to runtime 2048 mPromoteSystemApps = 2049 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2050 2051 // save off the names of pre-existing system packages prior to scanning; we don't 2052 // want to automatically grant runtime permissions for new system apps 2053 if (mPromoteSystemApps) { 2054 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2055 while (pkgSettingIter.hasNext()) { 2056 PackageSetting ps = pkgSettingIter.next(); 2057 if (isSystemApp(ps)) { 2058 mExistingSystemPackages.add(ps.name); 2059 } 2060 } 2061 } 2062 2063 // Collect vendor overlay packages. 2064 // (Do this before scanning any apps.) 2065 // For security and version matching reason, only consider 2066 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2067 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2068 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2069 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2070 2071 // Find base frameworks (resource packages without code). 2072 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2073 | PackageParser.PARSE_IS_SYSTEM_DIR 2074 | PackageParser.PARSE_IS_PRIVILEGED, 2075 scanFlags | SCAN_NO_DEX, 0); 2076 2077 // Collected privileged system packages. 2078 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2079 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2080 | PackageParser.PARSE_IS_SYSTEM_DIR 2081 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2082 2083 // Collect ordinary system packages. 2084 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2085 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2086 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2087 2088 // Collect all vendor packages. 2089 File vendorAppDir = new File("/vendor/app"); 2090 try { 2091 vendorAppDir = vendorAppDir.getCanonicalFile(); 2092 } catch (IOException e) { 2093 // failed to look up canonical path, continue with original one 2094 } 2095 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2096 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2097 2098 // Collect all OEM packages. 2099 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2100 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2101 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2102 2103 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2104 mInstaller.moveFiles(); 2105 2106 // Prune any system packages that no longer exist. 2107 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2108 if (!mOnlyCore) { 2109 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2110 while (psit.hasNext()) { 2111 PackageSetting ps = psit.next(); 2112 2113 /* 2114 * If this is not a system app, it can't be a 2115 * disable system app. 2116 */ 2117 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2118 continue; 2119 } 2120 2121 /* 2122 * If the package is scanned, it's not erased. 2123 */ 2124 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2125 if (scannedPkg != null) { 2126 /* 2127 * If the system app is both scanned and in the 2128 * disabled packages list, then it must have been 2129 * added via OTA. Remove it from the currently 2130 * scanned package so the previously user-installed 2131 * application can be scanned. 2132 */ 2133 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2134 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2135 + ps.name + "; removing system app. Last known codePath=" 2136 + ps.codePathString + ", installStatus=" + ps.installStatus 2137 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2138 + scannedPkg.mVersionCode); 2139 removePackageLI(ps, true); 2140 mExpectingBetter.put(ps.name, ps.codePath); 2141 } 2142 2143 continue; 2144 } 2145 2146 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2147 psit.remove(); 2148 logCriticalInfo(Log.WARN, "System package " + ps.name 2149 + " no longer exists; wiping its data"); 2150 removeDataDirsLI(null, ps.name); 2151 } else { 2152 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2153 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2154 possiblyDeletedUpdatedSystemApps.add(ps.name); 2155 } 2156 } 2157 } 2158 } 2159 2160 //look for any incomplete package installations 2161 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2162 //clean up list 2163 for(int i = 0; i < deletePkgsList.size(); i++) { 2164 //clean up here 2165 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2166 } 2167 //delete tmp files 2168 deleteTempPackageFiles(); 2169 2170 // Remove any shared userIDs that have no associated packages 2171 mSettings.pruneSharedUsersLPw(); 2172 2173 if (!mOnlyCore) { 2174 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2175 SystemClock.uptimeMillis()); 2176 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2177 2178 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2179 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2180 2181 /** 2182 * Remove disable package settings for any updated system 2183 * apps that were removed via an OTA. If they're not a 2184 * previously-updated app, remove them completely. 2185 * Otherwise, just revoke their system-level permissions. 2186 */ 2187 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2188 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2189 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2190 2191 String msg; 2192 if (deletedPkg == null) { 2193 msg = "Updated system package " + deletedAppName 2194 + " no longer exists; wiping its data"; 2195 removeDataDirsLI(null, deletedAppName); 2196 } else { 2197 msg = "Updated system app + " + deletedAppName 2198 + " no longer present; removing system privileges for " 2199 + deletedAppName; 2200 2201 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2202 2203 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2204 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2205 } 2206 logCriticalInfo(Log.WARN, msg); 2207 } 2208 2209 /** 2210 * Make sure all system apps that we expected to appear on 2211 * the userdata partition actually showed up. If they never 2212 * appeared, crawl back and revive the system version. 2213 */ 2214 for (int i = 0; i < mExpectingBetter.size(); i++) { 2215 final String packageName = mExpectingBetter.keyAt(i); 2216 if (!mPackages.containsKey(packageName)) { 2217 final File scanFile = mExpectingBetter.valueAt(i); 2218 2219 logCriticalInfo(Log.WARN, "Expected better " + packageName 2220 + " but never showed up; reverting to system"); 2221 2222 final int reparseFlags; 2223 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2224 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2225 | PackageParser.PARSE_IS_SYSTEM_DIR 2226 | PackageParser.PARSE_IS_PRIVILEGED; 2227 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2228 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2229 | PackageParser.PARSE_IS_SYSTEM_DIR; 2230 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2231 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2232 | PackageParser.PARSE_IS_SYSTEM_DIR; 2233 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2234 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2235 | PackageParser.PARSE_IS_SYSTEM_DIR; 2236 } else { 2237 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2238 continue; 2239 } 2240 2241 mSettings.enableSystemPackageLPw(packageName); 2242 2243 try { 2244 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2245 } catch (PackageManagerException e) { 2246 Slog.e(TAG, "Failed to parse original system package: " 2247 + e.getMessage()); 2248 } 2249 } 2250 } 2251 } 2252 mExpectingBetter.clear(); 2253 2254 // Now that we know all of the shared libraries, update all clients to have 2255 // the correct library paths. 2256 updateAllSharedLibrariesLPw(); 2257 2258 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2259 // NOTE: We ignore potential failures here during a system scan (like 2260 // the rest of the commands above) because there's precious little we 2261 // can do about it. A settings error is reported, though. 2262 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2263 false /* force dexopt */, false /* defer dexopt */, 2264 false /* boot complete */); 2265 } 2266 2267 // Now that we know all the packages we are keeping, 2268 // read and update their last usage times. 2269 mPackageUsage.readLP(); 2270 2271 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2272 SystemClock.uptimeMillis()); 2273 Slog.i(TAG, "Time to scan packages: " 2274 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2275 + " seconds"); 2276 2277 // If the platform SDK has changed since the last time we booted, 2278 // we need to re-grant app permission to catch any new ones that 2279 // appear. This is really a hack, and means that apps can in some 2280 // cases get permissions that the user didn't initially explicitly 2281 // allow... it would be nice to have some better way to handle 2282 // this situation. 2283 int updateFlags = UPDATE_PERMISSIONS_ALL; 2284 if (ver.sdkVersion != mSdkVersion) { 2285 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2286 + mSdkVersion + "; regranting permissions for internal storage"); 2287 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2288 } 2289 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2290 ver.sdkVersion = mSdkVersion; 2291 2292 // If this is the first boot or an update from pre-M, and it is a normal 2293 // boot, then we need to initialize the default preferred apps across 2294 // all defined users. 2295 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2296 for (UserInfo user : sUserManager.getUsers(true)) { 2297 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2298 applyFactoryDefaultBrowserLPw(user.id); 2299 primeDomainVerificationsLPw(user.id); 2300 } 2301 } 2302 2303 // If this is first boot after an OTA, and a normal boot, then 2304 // we need to clear code cache directories. 2305 if (mIsUpgrade && !onlyCore) { 2306 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2307 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2308 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2309 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2310 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2311 } 2312 } 2313 ver.fingerprint = Build.FINGERPRINT; 2314 } 2315 2316 checkDefaultBrowser(); 2317 2318 // clear only after permissions and other defaults have been updated 2319 mExistingSystemPackages.clear(); 2320 mPromoteSystemApps = false; 2321 2322 // All the changes are done during package scanning. 2323 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2324 2325 // can downgrade to reader 2326 mSettings.writeLPr(); 2327 2328 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2329 SystemClock.uptimeMillis()); 2330 2331 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2332 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2333 2334 mInstallerService = new PackageInstallerService(context, this); 2335 2336 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2337 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2338 mIntentFilterVerifierComponent); 2339 2340 } // synchronized (mPackages) 2341 } // synchronized (mInstallLock) 2342 2343 // Now after opening every single application zip, make sure they 2344 // are all flushed. Not really needed, but keeps things nice and 2345 // tidy. 2346 Runtime.getRuntime().gc(); 2347 2348 // Expose private service for system components to use. 2349 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2350 } 2351 2352 @Override 2353 public boolean isFirstBoot() { 2354 return !mRestoredSettings; 2355 } 2356 2357 @Override 2358 public boolean isOnlyCoreApps() { 2359 return mOnlyCore; 2360 } 2361 2362 @Override 2363 public boolean isUpgrade() { 2364 return mIsUpgrade; 2365 } 2366 2367 private String getRequiredVerifierLPr() { 2368 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2369 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2370 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2371 2372 String requiredVerifier = null; 2373 2374 final int N = receivers.size(); 2375 for (int i = 0; i < N; i++) { 2376 final ResolveInfo info = receivers.get(i); 2377 2378 if (info.activityInfo == null) { 2379 continue; 2380 } 2381 2382 final String packageName = info.activityInfo.packageName; 2383 2384 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2385 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2386 continue; 2387 } 2388 2389 if (requiredVerifier != null) { 2390 throw new RuntimeException("There can be only one required verifier"); 2391 } 2392 2393 requiredVerifier = packageName; 2394 } 2395 2396 return requiredVerifier; 2397 } 2398 2399 private String getRequiredInstallerLPr() { 2400 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2401 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2402 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2403 2404 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2405 PACKAGE_MIME_TYPE, 0, 0); 2406 2407 String requiredInstaller = null; 2408 2409 final int N = installers.size(); 2410 for (int i = 0; i < N; i++) { 2411 final ResolveInfo info = installers.get(i); 2412 final String packageName = info.activityInfo.packageName; 2413 2414 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2415 continue; 2416 } 2417 2418 if (requiredInstaller != null) { 2419 throw new RuntimeException("There must be one required installer"); 2420 } 2421 2422 requiredInstaller = packageName; 2423 } 2424 2425 if (requiredInstaller == null) { 2426 throw new RuntimeException("There must be one required installer"); 2427 } 2428 2429 return requiredInstaller; 2430 } 2431 2432 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2433 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2434 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2435 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2436 2437 ComponentName verifierComponentName = null; 2438 2439 int priority = -1000; 2440 final int N = receivers.size(); 2441 for (int i = 0; i < N; i++) { 2442 final ResolveInfo info = receivers.get(i); 2443 2444 if (info.activityInfo == null) { 2445 continue; 2446 } 2447 2448 final String packageName = info.activityInfo.packageName; 2449 2450 final PackageSetting ps = mSettings.mPackages.get(packageName); 2451 if (ps == null) { 2452 continue; 2453 } 2454 2455 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2456 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2457 continue; 2458 } 2459 2460 // Select the IntentFilterVerifier with the highest priority 2461 if (priority < info.priority) { 2462 priority = info.priority; 2463 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2464 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2465 + verifierComponentName + " with priority: " + info.priority); 2466 } 2467 } 2468 2469 return verifierComponentName; 2470 } 2471 2472 private void primeDomainVerificationsLPw(int userId) { 2473 if (DEBUG_DOMAIN_VERIFICATION) { 2474 Slog.d(TAG, "Priming domain verifications in user " + userId); 2475 } 2476 2477 SystemConfig systemConfig = SystemConfig.getInstance(); 2478 ArraySet<String> packages = systemConfig.getLinkedApps(); 2479 ArraySet<String> domains = new ArraySet<String>(); 2480 2481 for (String packageName : packages) { 2482 PackageParser.Package pkg = mPackages.get(packageName); 2483 if (pkg != null) { 2484 if (!pkg.isSystemApp()) { 2485 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2486 continue; 2487 } 2488 2489 domains.clear(); 2490 for (PackageParser.Activity a : pkg.activities) { 2491 for (ActivityIntentInfo filter : a.intents) { 2492 if (hasValidDomains(filter)) { 2493 domains.addAll(filter.getHostsList()); 2494 } 2495 } 2496 } 2497 2498 if (domains.size() > 0) { 2499 if (DEBUG_DOMAIN_VERIFICATION) { 2500 Slog.v(TAG, " + " + packageName); 2501 } 2502 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2503 // state w.r.t. the formal app-linkage "no verification attempted" state; 2504 // and then 'always' in the per-user state actually used for intent resolution. 2505 final IntentFilterVerificationInfo ivi; 2506 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2507 new ArrayList<String>(domains)); 2508 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2509 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2510 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2511 } else { 2512 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2513 + "' does not handle web links"); 2514 } 2515 } else { 2516 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2517 } 2518 } 2519 2520 scheduleWritePackageRestrictionsLocked(userId); 2521 scheduleWriteSettingsLocked(); 2522 } 2523 2524 private void applyFactoryDefaultBrowserLPw(int userId) { 2525 // The default browser app's package name is stored in a string resource, 2526 // with a product-specific overlay used for vendor customization. 2527 String browserPkg = mContext.getResources().getString( 2528 com.android.internal.R.string.default_browser); 2529 if (!TextUtils.isEmpty(browserPkg)) { 2530 // non-empty string => required to be a known package 2531 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2532 if (ps == null) { 2533 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2534 browserPkg = null; 2535 } else { 2536 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2537 } 2538 } 2539 2540 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2541 // default. If there's more than one, just leave everything alone. 2542 if (browserPkg == null) { 2543 calculateDefaultBrowserLPw(userId); 2544 } 2545 } 2546 2547 private void calculateDefaultBrowserLPw(int userId) { 2548 List<String> allBrowsers = resolveAllBrowserApps(userId); 2549 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2550 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2551 } 2552 2553 private List<String> resolveAllBrowserApps(int userId) { 2554 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2555 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2556 PackageManager.MATCH_ALL, userId); 2557 2558 final int count = list.size(); 2559 List<String> result = new ArrayList<String>(count); 2560 for (int i=0; i<count; i++) { 2561 ResolveInfo info = list.get(i); 2562 if (info.activityInfo == null 2563 || !info.handleAllWebDataURI 2564 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2565 || result.contains(info.activityInfo.packageName)) { 2566 continue; 2567 } 2568 result.add(info.activityInfo.packageName); 2569 } 2570 2571 return result; 2572 } 2573 2574 private boolean packageIsBrowser(String packageName, int userId) { 2575 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2576 PackageManager.MATCH_ALL, userId); 2577 final int N = list.size(); 2578 for (int i = 0; i < N; i++) { 2579 ResolveInfo info = list.get(i); 2580 if (packageName.equals(info.activityInfo.packageName)) { 2581 return true; 2582 } 2583 } 2584 return false; 2585 } 2586 2587 private void checkDefaultBrowser() { 2588 final int myUserId = UserHandle.myUserId(); 2589 final String packageName = getDefaultBrowserPackageName(myUserId); 2590 if (packageName != null) { 2591 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2592 if (info == null) { 2593 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2594 synchronized (mPackages) { 2595 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2596 } 2597 } 2598 } 2599 } 2600 2601 @Override 2602 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2603 throws RemoteException { 2604 try { 2605 return super.onTransact(code, data, reply, flags); 2606 } catch (RuntimeException e) { 2607 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2608 Slog.wtf(TAG, "Package Manager Crash", e); 2609 } 2610 throw e; 2611 } 2612 } 2613 2614 void cleanupInstallFailedPackage(PackageSetting ps) { 2615 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2616 2617 removeDataDirsLI(ps.volumeUuid, ps.name); 2618 if (ps.codePath != null) { 2619 if (ps.codePath.isDirectory()) { 2620 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2621 } else { 2622 ps.codePath.delete(); 2623 } 2624 } 2625 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2626 if (ps.resourcePath.isDirectory()) { 2627 FileUtils.deleteContents(ps.resourcePath); 2628 } 2629 ps.resourcePath.delete(); 2630 } 2631 mSettings.removePackageLPw(ps.name); 2632 } 2633 2634 static int[] appendInts(int[] cur, int[] add) { 2635 if (add == null) return cur; 2636 if (cur == null) return add; 2637 final int N = add.length; 2638 for (int i=0; i<N; i++) { 2639 cur = appendInt(cur, add[i]); 2640 } 2641 return cur; 2642 } 2643 2644 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2645 if (!sUserManager.exists(userId)) return null; 2646 final PackageSetting ps = (PackageSetting) p.mExtras; 2647 if (ps == null) { 2648 return null; 2649 } 2650 2651 final PermissionsState permissionsState = ps.getPermissionsState(); 2652 2653 final int[] gids = permissionsState.computeGids(userId); 2654 final Set<String> permissions = permissionsState.getPermissions(userId); 2655 final PackageUserState state = ps.readUserState(userId); 2656 2657 return PackageParser.generatePackageInfo(p, gids, flags, 2658 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2659 } 2660 2661 @Override 2662 public boolean isPackageFrozen(String packageName) { 2663 synchronized (mPackages) { 2664 final PackageSetting ps = mSettings.mPackages.get(packageName); 2665 if (ps != null) { 2666 return ps.frozen; 2667 } 2668 } 2669 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2670 return true; 2671 } 2672 2673 @Override 2674 public boolean isPackageAvailable(String packageName, int userId) { 2675 if (!sUserManager.exists(userId)) return false; 2676 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2677 synchronized (mPackages) { 2678 PackageParser.Package p = mPackages.get(packageName); 2679 if (p != null) { 2680 final PackageSetting ps = (PackageSetting) p.mExtras; 2681 if (ps != null) { 2682 final PackageUserState state = ps.readUserState(userId); 2683 if (state != null) { 2684 return PackageParser.isAvailable(state); 2685 } 2686 } 2687 } 2688 } 2689 return false; 2690 } 2691 2692 @Override 2693 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2694 if (!sUserManager.exists(userId)) return null; 2695 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2696 // reader 2697 synchronized (mPackages) { 2698 PackageParser.Package p = mPackages.get(packageName); 2699 if (DEBUG_PACKAGE_INFO) 2700 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2701 if (p != null) { 2702 return generatePackageInfo(p, flags, userId); 2703 } 2704 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2705 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2706 } 2707 } 2708 return null; 2709 } 2710 2711 @Override 2712 public String[] currentToCanonicalPackageNames(String[] names) { 2713 String[] out = new String[names.length]; 2714 // reader 2715 synchronized (mPackages) { 2716 for (int i=names.length-1; i>=0; i--) { 2717 PackageSetting ps = mSettings.mPackages.get(names[i]); 2718 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2719 } 2720 } 2721 return out; 2722 } 2723 2724 @Override 2725 public String[] canonicalToCurrentPackageNames(String[] names) { 2726 String[] out = new String[names.length]; 2727 // reader 2728 synchronized (mPackages) { 2729 for (int i=names.length-1; i>=0; i--) { 2730 String cur = mSettings.mRenamedPackages.get(names[i]); 2731 out[i] = cur != null ? cur : names[i]; 2732 } 2733 } 2734 return out; 2735 } 2736 2737 @Override 2738 public int getPackageUid(String packageName, int userId) { 2739 if (!sUserManager.exists(userId)) return -1; 2740 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2741 2742 // reader 2743 synchronized (mPackages) { 2744 PackageParser.Package p = mPackages.get(packageName); 2745 if(p != null) { 2746 return UserHandle.getUid(userId, p.applicationInfo.uid); 2747 } 2748 PackageSetting ps = mSettings.mPackages.get(packageName); 2749 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2750 return -1; 2751 } 2752 p = ps.pkg; 2753 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2754 } 2755 } 2756 2757 @Override 2758 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2759 if (!sUserManager.exists(userId)) { 2760 return null; 2761 } 2762 2763 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2764 "getPackageGids"); 2765 2766 // reader 2767 synchronized (mPackages) { 2768 PackageParser.Package p = mPackages.get(packageName); 2769 if (DEBUG_PACKAGE_INFO) { 2770 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2771 } 2772 if (p != null) { 2773 PackageSetting ps = (PackageSetting) p.mExtras; 2774 return ps.getPermissionsState().computeGids(userId); 2775 } 2776 } 2777 2778 return null; 2779 } 2780 2781 static PermissionInfo generatePermissionInfo( 2782 BasePermission bp, int flags) { 2783 if (bp.perm != null) { 2784 return PackageParser.generatePermissionInfo(bp.perm, flags); 2785 } 2786 PermissionInfo pi = new PermissionInfo(); 2787 pi.name = bp.name; 2788 pi.packageName = bp.sourcePackage; 2789 pi.nonLocalizedLabel = bp.name; 2790 pi.protectionLevel = bp.protectionLevel; 2791 return pi; 2792 } 2793 2794 @Override 2795 public PermissionInfo getPermissionInfo(String name, int flags) { 2796 // reader 2797 synchronized (mPackages) { 2798 final BasePermission p = mSettings.mPermissions.get(name); 2799 if (p != null) { 2800 return generatePermissionInfo(p, flags); 2801 } 2802 return null; 2803 } 2804 } 2805 2806 @Override 2807 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2808 // reader 2809 synchronized (mPackages) { 2810 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2811 for (BasePermission p : mSettings.mPermissions.values()) { 2812 if (group == null) { 2813 if (p.perm == null || p.perm.info.group == null) { 2814 out.add(generatePermissionInfo(p, flags)); 2815 } 2816 } else { 2817 if (p.perm != null && group.equals(p.perm.info.group)) { 2818 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2819 } 2820 } 2821 } 2822 2823 if (out.size() > 0) { 2824 return out; 2825 } 2826 return mPermissionGroups.containsKey(group) ? out : null; 2827 } 2828 } 2829 2830 @Override 2831 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2832 // reader 2833 synchronized (mPackages) { 2834 return PackageParser.generatePermissionGroupInfo( 2835 mPermissionGroups.get(name), flags); 2836 } 2837 } 2838 2839 @Override 2840 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2841 // reader 2842 synchronized (mPackages) { 2843 final int N = mPermissionGroups.size(); 2844 ArrayList<PermissionGroupInfo> out 2845 = new ArrayList<PermissionGroupInfo>(N); 2846 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2847 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2848 } 2849 return out; 2850 } 2851 } 2852 2853 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2854 int userId) { 2855 if (!sUserManager.exists(userId)) return null; 2856 PackageSetting ps = mSettings.mPackages.get(packageName); 2857 if (ps != null) { 2858 if (ps.pkg == null) { 2859 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2860 flags, userId); 2861 if (pInfo != null) { 2862 return pInfo.applicationInfo; 2863 } 2864 return null; 2865 } 2866 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2867 ps.readUserState(userId), userId); 2868 } 2869 return null; 2870 } 2871 2872 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2873 int userId) { 2874 if (!sUserManager.exists(userId)) return null; 2875 PackageSetting ps = mSettings.mPackages.get(packageName); 2876 if (ps != null) { 2877 PackageParser.Package pkg = ps.pkg; 2878 if (pkg == null) { 2879 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2880 return null; 2881 } 2882 // Only data remains, so we aren't worried about code paths 2883 pkg = new PackageParser.Package(packageName); 2884 pkg.applicationInfo.packageName = packageName; 2885 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2886 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2887 pkg.applicationInfo.dataDir = Environment 2888 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2889 .getAbsolutePath(); 2890 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2891 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2892 } 2893 return generatePackageInfo(pkg, flags, userId); 2894 } 2895 return null; 2896 } 2897 2898 @Override 2899 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2900 if (!sUserManager.exists(userId)) return null; 2901 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2902 // writer 2903 synchronized (mPackages) { 2904 PackageParser.Package p = mPackages.get(packageName); 2905 if (DEBUG_PACKAGE_INFO) Log.v( 2906 TAG, "getApplicationInfo " + packageName 2907 + ": " + p); 2908 if (p != null) { 2909 PackageSetting ps = mSettings.mPackages.get(packageName); 2910 if (ps == null) return null; 2911 // Note: isEnabledLP() does not apply here - always return info 2912 return PackageParser.generateApplicationInfo( 2913 p, flags, ps.readUserState(userId), userId); 2914 } 2915 if ("android".equals(packageName)||"system".equals(packageName)) { 2916 return mAndroidApplication; 2917 } 2918 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2919 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2920 } 2921 } 2922 return null; 2923 } 2924 2925 @Override 2926 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2927 final IPackageDataObserver observer) { 2928 mContext.enforceCallingOrSelfPermission( 2929 android.Manifest.permission.CLEAR_APP_CACHE, null); 2930 // Queue up an async operation since clearing cache may take a little while. 2931 mHandler.post(new Runnable() { 2932 public void run() { 2933 mHandler.removeCallbacks(this); 2934 int retCode = -1; 2935 synchronized (mInstallLock) { 2936 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2937 if (retCode < 0) { 2938 Slog.w(TAG, "Couldn't clear application caches"); 2939 } 2940 } 2941 if (observer != null) { 2942 try { 2943 observer.onRemoveCompleted(null, (retCode >= 0)); 2944 } catch (RemoteException e) { 2945 Slog.w(TAG, "RemoveException when invoking call back"); 2946 } 2947 } 2948 } 2949 }); 2950 } 2951 2952 @Override 2953 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2954 final IntentSender pi) { 2955 mContext.enforceCallingOrSelfPermission( 2956 android.Manifest.permission.CLEAR_APP_CACHE, null); 2957 // Queue up an async operation since clearing cache may take a little while. 2958 mHandler.post(new Runnable() { 2959 public void run() { 2960 mHandler.removeCallbacks(this); 2961 int retCode = -1; 2962 synchronized (mInstallLock) { 2963 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2964 if (retCode < 0) { 2965 Slog.w(TAG, "Couldn't clear application caches"); 2966 } 2967 } 2968 if(pi != null) { 2969 try { 2970 // Callback via pending intent 2971 int code = (retCode >= 0) ? 1 : 0; 2972 pi.sendIntent(null, code, null, 2973 null, null); 2974 } catch (SendIntentException e1) { 2975 Slog.i(TAG, "Failed to send pending intent"); 2976 } 2977 } 2978 } 2979 }); 2980 } 2981 2982 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2983 synchronized (mInstallLock) { 2984 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2985 throw new IOException("Failed to free enough space"); 2986 } 2987 } 2988 } 2989 2990 @Override 2991 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2992 if (!sUserManager.exists(userId)) return null; 2993 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2994 synchronized (mPackages) { 2995 PackageParser.Activity a = mActivities.mActivities.get(component); 2996 2997 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2998 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2999 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3000 if (ps == null) return null; 3001 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3002 userId); 3003 } 3004 if (mResolveComponentName.equals(component)) { 3005 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3006 new PackageUserState(), userId); 3007 } 3008 } 3009 return null; 3010 } 3011 3012 @Override 3013 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3014 String resolvedType) { 3015 synchronized (mPackages) { 3016 if (component.equals(mResolveComponentName)) { 3017 // The resolver supports EVERYTHING! 3018 return true; 3019 } 3020 PackageParser.Activity a = mActivities.mActivities.get(component); 3021 if (a == null) { 3022 return false; 3023 } 3024 for (int i=0; i<a.intents.size(); i++) { 3025 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3026 intent.getData(), intent.getCategories(), TAG) >= 0) { 3027 return true; 3028 } 3029 } 3030 return false; 3031 } 3032 } 3033 3034 @Override 3035 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3036 if (!sUserManager.exists(userId)) return null; 3037 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3038 synchronized (mPackages) { 3039 PackageParser.Activity a = mReceivers.mActivities.get(component); 3040 if (DEBUG_PACKAGE_INFO) Log.v( 3041 TAG, "getReceiverInfo " + component + ": " + a); 3042 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3043 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3044 if (ps == null) return null; 3045 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3046 userId); 3047 } 3048 } 3049 return null; 3050 } 3051 3052 @Override 3053 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3054 if (!sUserManager.exists(userId)) return null; 3055 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3056 synchronized (mPackages) { 3057 PackageParser.Service s = mServices.mServices.get(component); 3058 if (DEBUG_PACKAGE_INFO) Log.v( 3059 TAG, "getServiceInfo " + component + ": " + s); 3060 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3061 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3062 if (ps == null) return null; 3063 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3064 userId); 3065 } 3066 } 3067 return null; 3068 } 3069 3070 @Override 3071 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3072 if (!sUserManager.exists(userId)) return null; 3073 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3074 synchronized (mPackages) { 3075 PackageParser.Provider p = mProviders.mProviders.get(component); 3076 if (DEBUG_PACKAGE_INFO) Log.v( 3077 TAG, "getProviderInfo " + component + ": " + p); 3078 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3079 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3080 if (ps == null) return null; 3081 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3082 userId); 3083 } 3084 } 3085 return null; 3086 } 3087 3088 @Override 3089 public String[] getSystemSharedLibraryNames() { 3090 Set<String> libSet; 3091 synchronized (mPackages) { 3092 libSet = mSharedLibraries.keySet(); 3093 int size = libSet.size(); 3094 if (size > 0) { 3095 String[] libs = new String[size]; 3096 libSet.toArray(libs); 3097 return libs; 3098 } 3099 } 3100 return null; 3101 } 3102 3103 /** 3104 * @hide 3105 */ 3106 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3107 synchronized (mPackages) { 3108 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3109 if (lib != null && lib.apk != null) { 3110 return mPackages.get(lib.apk); 3111 } 3112 } 3113 return null; 3114 } 3115 3116 @Override 3117 public FeatureInfo[] getSystemAvailableFeatures() { 3118 Collection<FeatureInfo> featSet; 3119 synchronized (mPackages) { 3120 featSet = mAvailableFeatures.values(); 3121 int size = featSet.size(); 3122 if (size > 0) { 3123 FeatureInfo[] features = new FeatureInfo[size+1]; 3124 featSet.toArray(features); 3125 FeatureInfo fi = new FeatureInfo(); 3126 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3127 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3128 features[size] = fi; 3129 return features; 3130 } 3131 } 3132 return null; 3133 } 3134 3135 @Override 3136 public boolean hasSystemFeature(String name) { 3137 synchronized (mPackages) { 3138 return mAvailableFeatures.containsKey(name); 3139 } 3140 } 3141 3142 private void checkValidCaller(int uid, int userId) { 3143 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3144 return; 3145 3146 throw new SecurityException("Caller uid=" + uid 3147 + " is not privileged to communicate with user=" + userId); 3148 } 3149 3150 @Override 3151 public int checkPermission(String permName, String pkgName, int userId) { 3152 if (!sUserManager.exists(userId)) { 3153 return PackageManager.PERMISSION_DENIED; 3154 } 3155 3156 synchronized (mPackages) { 3157 final PackageParser.Package p = mPackages.get(pkgName); 3158 if (p != null && p.mExtras != null) { 3159 final PackageSetting ps = (PackageSetting) p.mExtras; 3160 final PermissionsState permissionsState = ps.getPermissionsState(); 3161 if (permissionsState.hasPermission(permName, userId)) { 3162 return PackageManager.PERMISSION_GRANTED; 3163 } 3164 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3165 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3166 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3167 return PackageManager.PERMISSION_GRANTED; 3168 } 3169 } 3170 } 3171 3172 return PackageManager.PERMISSION_DENIED; 3173 } 3174 3175 @Override 3176 public int checkUidPermission(String permName, int uid) { 3177 final int userId = UserHandle.getUserId(uid); 3178 3179 if (!sUserManager.exists(userId)) { 3180 return PackageManager.PERMISSION_DENIED; 3181 } 3182 3183 synchronized (mPackages) { 3184 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3185 if (obj != null) { 3186 final SettingBase ps = (SettingBase) obj; 3187 final PermissionsState permissionsState = ps.getPermissionsState(); 3188 if (permissionsState.hasPermission(permName, userId)) { 3189 return PackageManager.PERMISSION_GRANTED; 3190 } 3191 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3192 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3193 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3194 return PackageManager.PERMISSION_GRANTED; 3195 } 3196 } else { 3197 ArraySet<String> perms = mSystemPermissions.get(uid); 3198 if (perms != null) { 3199 if (perms.contains(permName)) { 3200 return PackageManager.PERMISSION_GRANTED; 3201 } 3202 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3203 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3204 return PackageManager.PERMISSION_GRANTED; 3205 } 3206 } 3207 } 3208 } 3209 3210 return PackageManager.PERMISSION_DENIED; 3211 } 3212 3213 @Override 3214 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3215 if (UserHandle.getCallingUserId() != userId) { 3216 mContext.enforceCallingPermission( 3217 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3218 "isPermissionRevokedByPolicy for user " + userId); 3219 } 3220 3221 if (checkPermission(permission, packageName, userId) 3222 == PackageManager.PERMISSION_GRANTED) { 3223 return false; 3224 } 3225 3226 final long identity = Binder.clearCallingIdentity(); 3227 try { 3228 final int flags = getPermissionFlags(permission, packageName, userId); 3229 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3230 } finally { 3231 Binder.restoreCallingIdentity(identity); 3232 } 3233 } 3234 3235 @Override 3236 public String getPermissionControllerPackageName() { 3237 synchronized (mPackages) { 3238 return mRequiredInstallerPackage; 3239 } 3240 } 3241 3242 /** 3243 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3244 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3245 * @param checkShell TODO(yamasani): 3246 * @param message the message to log on security exception 3247 */ 3248 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3249 boolean checkShell, String message) { 3250 if (userId < 0) { 3251 throw new IllegalArgumentException("Invalid userId " + userId); 3252 } 3253 if (checkShell) { 3254 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3255 } 3256 if (userId == UserHandle.getUserId(callingUid)) return; 3257 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3258 if (requireFullPermission) { 3259 mContext.enforceCallingOrSelfPermission( 3260 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3261 } else { 3262 try { 3263 mContext.enforceCallingOrSelfPermission( 3264 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3265 } catch (SecurityException se) { 3266 mContext.enforceCallingOrSelfPermission( 3267 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3268 } 3269 } 3270 } 3271 } 3272 3273 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3274 if (callingUid == Process.SHELL_UID) { 3275 if (userHandle >= 0 3276 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3277 throw new SecurityException("Shell does not have permission to access user " 3278 + userHandle); 3279 } else if (userHandle < 0) { 3280 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3281 + Debug.getCallers(3)); 3282 } 3283 } 3284 } 3285 3286 private BasePermission findPermissionTreeLP(String permName) { 3287 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3288 if (permName.startsWith(bp.name) && 3289 permName.length() > bp.name.length() && 3290 permName.charAt(bp.name.length()) == '.') { 3291 return bp; 3292 } 3293 } 3294 return null; 3295 } 3296 3297 private BasePermission checkPermissionTreeLP(String permName) { 3298 if (permName != null) { 3299 BasePermission bp = findPermissionTreeLP(permName); 3300 if (bp != null) { 3301 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3302 return bp; 3303 } 3304 throw new SecurityException("Calling uid " 3305 + Binder.getCallingUid() 3306 + " is not allowed to add to permission tree " 3307 + bp.name + " owned by uid " + bp.uid); 3308 } 3309 } 3310 throw new SecurityException("No permission tree found for " + permName); 3311 } 3312 3313 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3314 if (s1 == null) { 3315 return s2 == null; 3316 } 3317 if (s2 == null) { 3318 return false; 3319 } 3320 if (s1.getClass() != s2.getClass()) { 3321 return false; 3322 } 3323 return s1.equals(s2); 3324 } 3325 3326 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3327 if (pi1.icon != pi2.icon) return false; 3328 if (pi1.logo != pi2.logo) return false; 3329 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3330 if (!compareStrings(pi1.name, pi2.name)) return false; 3331 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3332 // We'll take care of setting this one. 3333 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3334 // These are not currently stored in settings. 3335 //if (!compareStrings(pi1.group, pi2.group)) return false; 3336 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3337 //if (pi1.labelRes != pi2.labelRes) return false; 3338 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3339 return true; 3340 } 3341 3342 int permissionInfoFootprint(PermissionInfo info) { 3343 int size = info.name.length(); 3344 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3345 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3346 return size; 3347 } 3348 3349 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3350 int size = 0; 3351 for (BasePermission perm : mSettings.mPermissions.values()) { 3352 if (perm.uid == tree.uid) { 3353 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3354 } 3355 } 3356 return size; 3357 } 3358 3359 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3360 // We calculate the max size of permissions defined by this uid and throw 3361 // if that plus the size of 'info' would exceed our stated maximum. 3362 if (tree.uid != Process.SYSTEM_UID) { 3363 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3364 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3365 throw new SecurityException("Permission tree size cap exceeded"); 3366 } 3367 } 3368 } 3369 3370 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3371 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3372 throw new SecurityException("Label must be specified in permission"); 3373 } 3374 BasePermission tree = checkPermissionTreeLP(info.name); 3375 BasePermission bp = mSettings.mPermissions.get(info.name); 3376 boolean added = bp == null; 3377 boolean changed = true; 3378 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3379 if (added) { 3380 enforcePermissionCapLocked(info, tree); 3381 bp = new BasePermission(info.name, tree.sourcePackage, 3382 BasePermission.TYPE_DYNAMIC); 3383 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3384 throw new SecurityException( 3385 "Not allowed to modify non-dynamic permission " 3386 + info.name); 3387 } else { 3388 if (bp.protectionLevel == fixedLevel 3389 && bp.perm.owner.equals(tree.perm.owner) 3390 && bp.uid == tree.uid 3391 && comparePermissionInfos(bp.perm.info, info)) { 3392 changed = false; 3393 } 3394 } 3395 bp.protectionLevel = fixedLevel; 3396 info = new PermissionInfo(info); 3397 info.protectionLevel = fixedLevel; 3398 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3399 bp.perm.info.packageName = tree.perm.info.packageName; 3400 bp.uid = tree.uid; 3401 if (added) { 3402 mSettings.mPermissions.put(info.name, bp); 3403 } 3404 if (changed) { 3405 if (!async) { 3406 mSettings.writeLPr(); 3407 } else { 3408 scheduleWriteSettingsLocked(); 3409 } 3410 } 3411 return added; 3412 } 3413 3414 @Override 3415 public boolean addPermission(PermissionInfo info) { 3416 synchronized (mPackages) { 3417 return addPermissionLocked(info, false); 3418 } 3419 } 3420 3421 @Override 3422 public boolean addPermissionAsync(PermissionInfo info) { 3423 synchronized (mPackages) { 3424 return addPermissionLocked(info, true); 3425 } 3426 } 3427 3428 @Override 3429 public void removePermission(String name) { 3430 synchronized (mPackages) { 3431 checkPermissionTreeLP(name); 3432 BasePermission bp = mSettings.mPermissions.get(name); 3433 if (bp != null) { 3434 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3435 throw new SecurityException( 3436 "Not allowed to modify non-dynamic permission " 3437 + name); 3438 } 3439 mSettings.mPermissions.remove(name); 3440 mSettings.writeLPr(); 3441 } 3442 } 3443 } 3444 3445 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3446 BasePermission bp) { 3447 int index = pkg.requestedPermissions.indexOf(bp.name); 3448 if (index == -1) { 3449 throw new SecurityException("Package " + pkg.packageName 3450 + " has not requested permission " + bp.name); 3451 } 3452 if (!bp.isRuntime() && !bp.isDevelopment()) { 3453 throw new SecurityException("Permission " + bp.name 3454 + " is not a changeable permission type"); 3455 } 3456 } 3457 3458 @Override 3459 public void grantRuntimePermission(String packageName, String name, final int userId) { 3460 if (!sUserManager.exists(userId)) { 3461 Log.e(TAG, "No such user:" + userId); 3462 return; 3463 } 3464 3465 mContext.enforceCallingOrSelfPermission( 3466 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3467 "grantRuntimePermission"); 3468 3469 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3470 "grantRuntimePermission"); 3471 3472 final int uid; 3473 final SettingBase sb; 3474 3475 synchronized (mPackages) { 3476 final PackageParser.Package pkg = mPackages.get(packageName); 3477 if (pkg == null) { 3478 throw new IllegalArgumentException("Unknown package: " + packageName); 3479 } 3480 3481 final BasePermission bp = mSettings.mPermissions.get(name); 3482 if (bp == null) { 3483 throw new IllegalArgumentException("Unknown permission: " + name); 3484 } 3485 3486 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3487 3488 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3489 sb = (SettingBase) pkg.mExtras; 3490 if (sb == null) { 3491 throw new IllegalArgumentException("Unknown package: " + packageName); 3492 } 3493 3494 final PermissionsState permissionsState = sb.getPermissionsState(); 3495 3496 final int flags = permissionsState.getPermissionFlags(name, userId); 3497 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3498 throw new SecurityException("Cannot grant system fixed permission: " 3499 + name + " for package: " + packageName); 3500 } 3501 3502 if (bp.isDevelopment()) { 3503 // Development permissions must be handled specially, since they are not 3504 // normal runtime permissions. For now they apply to all users. 3505 if (permissionsState.grantInstallPermission(bp) != 3506 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3507 scheduleWriteSettingsLocked(); 3508 } 3509 return; 3510 } 3511 3512 final int result = permissionsState.grantRuntimePermission(bp, userId); 3513 switch (result) { 3514 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3515 return; 3516 } 3517 3518 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3519 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3520 mHandler.post(new Runnable() { 3521 @Override 3522 public void run() { 3523 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3524 } 3525 }); 3526 } 3527 break; 3528 } 3529 3530 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3531 3532 // Not critical if that is lost - app has to request again. 3533 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3534 } 3535 3536 // Only need to do this if user is initialized. Otherwise it's a new user 3537 // and there are no processes running as the user yet and there's no need 3538 // to make an expensive call to remount processes for the changed permissions. 3539 if (READ_EXTERNAL_STORAGE.equals(name) 3540 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3541 final long token = Binder.clearCallingIdentity(); 3542 try { 3543 if (sUserManager.isInitialized(userId)) { 3544 MountServiceInternal mountServiceInternal = LocalServices.getService( 3545 MountServiceInternal.class); 3546 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3547 } 3548 } finally { 3549 Binder.restoreCallingIdentity(token); 3550 } 3551 } 3552 } 3553 3554 @Override 3555 public void revokeRuntimePermission(String packageName, String name, int userId) { 3556 if (!sUserManager.exists(userId)) { 3557 Log.e(TAG, "No such user:" + userId); 3558 return; 3559 } 3560 3561 mContext.enforceCallingOrSelfPermission( 3562 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3563 "revokeRuntimePermission"); 3564 3565 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3566 "revokeRuntimePermission"); 3567 3568 final int appId; 3569 3570 synchronized (mPackages) { 3571 final PackageParser.Package pkg = mPackages.get(packageName); 3572 if (pkg == null) { 3573 throw new IllegalArgumentException("Unknown package: " + packageName); 3574 } 3575 3576 final BasePermission bp = mSettings.mPermissions.get(name); 3577 if (bp == null) { 3578 throw new IllegalArgumentException("Unknown permission: " + name); 3579 } 3580 3581 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3582 3583 SettingBase sb = (SettingBase) pkg.mExtras; 3584 if (sb == null) { 3585 throw new IllegalArgumentException("Unknown package: " + packageName); 3586 } 3587 3588 final PermissionsState permissionsState = sb.getPermissionsState(); 3589 3590 final int flags = permissionsState.getPermissionFlags(name, userId); 3591 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3592 throw new SecurityException("Cannot revoke system fixed permission: " 3593 + name + " for package: " + packageName); 3594 } 3595 3596 if (bp.isDevelopment()) { 3597 // Development permissions must be handled specially, since they are not 3598 // normal runtime permissions. For now they apply to all users. 3599 if (permissionsState.revokeInstallPermission(bp) != 3600 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3601 scheduleWriteSettingsLocked(); 3602 } 3603 return; 3604 } 3605 3606 if (permissionsState.revokeRuntimePermission(bp, userId) == 3607 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3608 return; 3609 } 3610 3611 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3612 3613 // Critical, after this call app should never have the permission. 3614 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3615 3616 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3617 } 3618 3619 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3620 } 3621 3622 @Override 3623 public void resetRuntimePermissions() { 3624 mContext.enforceCallingOrSelfPermission( 3625 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3626 "revokeRuntimePermission"); 3627 3628 int callingUid = Binder.getCallingUid(); 3629 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3630 mContext.enforceCallingOrSelfPermission( 3631 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3632 "resetRuntimePermissions"); 3633 } 3634 3635 synchronized (mPackages) { 3636 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3637 for (int userId : UserManagerService.getInstance().getUserIds()) { 3638 final int packageCount = mPackages.size(); 3639 for (int i = 0; i < packageCount; i++) { 3640 PackageParser.Package pkg = mPackages.valueAt(i); 3641 if (!(pkg.mExtras instanceof PackageSetting)) { 3642 continue; 3643 } 3644 PackageSetting ps = (PackageSetting) pkg.mExtras; 3645 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3646 } 3647 } 3648 } 3649 } 3650 3651 @Override 3652 public int getPermissionFlags(String name, String packageName, int userId) { 3653 if (!sUserManager.exists(userId)) { 3654 return 0; 3655 } 3656 3657 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3658 3659 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3660 "getPermissionFlags"); 3661 3662 synchronized (mPackages) { 3663 final PackageParser.Package pkg = mPackages.get(packageName); 3664 if (pkg == null) { 3665 throw new IllegalArgumentException("Unknown package: " + packageName); 3666 } 3667 3668 final BasePermission bp = mSettings.mPermissions.get(name); 3669 if (bp == null) { 3670 throw new IllegalArgumentException("Unknown permission: " + name); 3671 } 3672 3673 SettingBase sb = (SettingBase) pkg.mExtras; 3674 if (sb == null) { 3675 throw new IllegalArgumentException("Unknown package: " + packageName); 3676 } 3677 3678 PermissionsState permissionsState = sb.getPermissionsState(); 3679 return permissionsState.getPermissionFlags(name, userId); 3680 } 3681 } 3682 3683 @Override 3684 public void updatePermissionFlags(String name, String packageName, int flagMask, 3685 int flagValues, int userId) { 3686 if (!sUserManager.exists(userId)) { 3687 return; 3688 } 3689 3690 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3691 3692 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3693 "updatePermissionFlags"); 3694 3695 // Only the system can change these flags and nothing else. 3696 if (getCallingUid() != Process.SYSTEM_UID) { 3697 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3698 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3699 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3700 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3701 } 3702 3703 synchronized (mPackages) { 3704 final PackageParser.Package pkg = mPackages.get(packageName); 3705 if (pkg == null) { 3706 throw new IllegalArgumentException("Unknown package: " + packageName); 3707 } 3708 3709 final BasePermission bp = mSettings.mPermissions.get(name); 3710 if (bp == null) { 3711 throw new IllegalArgumentException("Unknown permission: " + name); 3712 } 3713 3714 SettingBase sb = (SettingBase) pkg.mExtras; 3715 if (sb == null) { 3716 throw new IllegalArgumentException("Unknown package: " + packageName); 3717 } 3718 3719 PermissionsState permissionsState = sb.getPermissionsState(); 3720 3721 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3722 3723 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3724 // Install and runtime permissions are stored in different places, 3725 // so figure out what permission changed and persist the change. 3726 if (permissionsState.getInstallPermissionState(name) != null) { 3727 scheduleWriteSettingsLocked(); 3728 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3729 || hadState) { 3730 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3731 } 3732 } 3733 } 3734 } 3735 3736 /** 3737 * Update the permission flags for all packages and runtime permissions of a user in order 3738 * to allow device or profile owner to remove POLICY_FIXED. 3739 */ 3740 @Override 3741 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3742 if (!sUserManager.exists(userId)) { 3743 return; 3744 } 3745 3746 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3747 3748 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3749 "updatePermissionFlagsForAllApps"); 3750 3751 // Only the system can change system fixed flags. 3752 if (getCallingUid() != Process.SYSTEM_UID) { 3753 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3754 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3755 } 3756 3757 synchronized (mPackages) { 3758 boolean changed = false; 3759 final int packageCount = mPackages.size(); 3760 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3761 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3762 SettingBase sb = (SettingBase) pkg.mExtras; 3763 if (sb == null) { 3764 continue; 3765 } 3766 PermissionsState permissionsState = sb.getPermissionsState(); 3767 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3768 userId, flagMask, flagValues); 3769 } 3770 if (changed) { 3771 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3772 } 3773 } 3774 } 3775 3776 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3777 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3778 != PackageManager.PERMISSION_GRANTED 3779 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3780 != PackageManager.PERMISSION_GRANTED) { 3781 throw new SecurityException(message + " requires " 3782 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3783 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3784 } 3785 } 3786 3787 @Override 3788 public boolean shouldShowRequestPermissionRationale(String permissionName, 3789 String packageName, int userId) { 3790 if (UserHandle.getCallingUserId() != userId) { 3791 mContext.enforceCallingPermission( 3792 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3793 "canShowRequestPermissionRationale for user " + userId); 3794 } 3795 3796 final int uid = getPackageUid(packageName, userId); 3797 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3798 return false; 3799 } 3800 3801 if (checkPermission(permissionName, packageName, userId) 3802 == PackageManager.PERMISSION_GRANTED) { 3803 return false; 3804 } 3805 3806 final int flags; 3807 3808 final long identity = Binder.clearCallingIdentity(); 3809 try { 3810 flags = getPermissionFlags(permissionName, 3811 packageName, userId); 3812 } finally { 3813 Binder.restoreCallingIdentity(identity); 3814 } 3815 3816 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3817 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3818 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3819 3820 if ((flags & fixedFlags) != 0) { 3821 return false; 3822 } 3823 3824 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3825 } 3826 3827 @Override 3828 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3829 mContext.enforceCallingOrSelfPermission( 3830 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3831 "addOnPermissionsChangeListener"); 3832 3833 synchronized (mPackages) { 3834 mOnPermissionChangeListeners.addListenerLocked(listener); 3835 } 3836 } 3837 3838 @Override 3839 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3840 synchronized (mPackages) { 3841 mOnPermissionChangeListeners.removeListenerLocked(listener); 3842 } 3843 } 3844 3845 @Override 3846 public boolean isProtectedBroadcast(String actionName) { 3847 synchronized (mPackages) { 3848 return mProtectedBroadcasts.contains(actionName); 3849 } 3850 } 3851 3852 @Override 3853 public int checkSignatures(String pkg1, String pkg2) { 3854 synchronized (mPackages) { 3855 final PackageParser.Package p1 = mPackages.get(pkg1); 3856 final PackageParser.Package p2 = mPackages.get(pkg2); 3857 if (p1 == null || p1.mExtras == null 3858 || p2 == null || p2.mExtras == null) { 3859 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3860 } 3861 return compareSignatures(p1.mSignatures, p2.mSignatures); 3862 } 3863 } 3864 3865 @Override 3866 public int checkUidSignatures(int uid1, int uid2) { 3867 // Map to base uids. 3868 uid1 = UserHandle.getAppId(uid1); 3869 uid2 = UserHandle.getAppId(uid2); 3870 // reader 3871 synchronized (mPackages) { 3872 Signature[] s1; 3873 Signature[] s2; 3874 Object obj = mSettings.getUserIdLPr(uid1); 3875 if (obj != null) { 3876 if (obj instanceof SharedUserSetting) { 3877 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3878 } else if (obj instanceof PackageSetting) { 3879 s1 = ((PackageSetting)obj).signatures.mSignatures; 3880 } else { 3881 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3882 } 3883 } else { 3884 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3885 } 3886 obj = mSettings.getUserIdLPr(uid2); 3887 if (obj != null) { 3888 if (obj instanceof SharedUserSetting) { 3889 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3890 } else if (obj instanceof PackageSetting) { 3891 s2 = ((PackageSetting)obj).signatures.mSignatures; 3892 } else { 3893 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3894 } 3895 } else { 3896 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3897 } 3898 return compareSignatures(s1, s2); 3899 } 3900 } 3901 3902 private void killUid(int appId, int userId, String reason) { 3903 final long identity = Binder.clearCallingIdentity(); 3904 try { 3905 IActivityManager am = ActivityManagerNative.getDefault(); 3906 if (am != null) { 3907 try { 3908 am.killUid(appId, userId, reason); 3909 } catch (RemoteException e) { 3910 /* ignore - same process */ 3911 } 3912 } 3913 } finally { 3914 Binder.restoreCallingIdentity(identity); 3915 } 3916 } 3917 3918 /** 3919 * Compares two sets of signatures. Returns: 3920 * <br /> 3921 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3922 * <br /> 3923 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3924 * <br /> 3925 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3926 * <br /> 3927 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3928 * <br /> 3929 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3930 */ 3931 static int compareSignatures(Signature[] s1, Signature[] s2) { 3932 if (s1 == null) { 3933 return s2 == null 3934 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3935 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3936 } 3937 3938 if (s2 == null) { 3939 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3940 } 3941 3942 if (s1.length != s2.length) { 3943 return PackageManager.SIGNATURE_NO_MATCH; 3944 } 3945 3946 // Since both signature sets are of size 1, we can compare without HashSets. 3947 if (s1.length == 1) { 3948 return s1[0].equals(s2[0]) ? 3949 PackageManager.SIGNATURE_MATCH : 3950 PackageManager.SIGNATURE_NO_MATCH; 3951 } 3952 3953 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3954 for (Signature sig : s1) { 3955 set1.add(sig); 3956 } 3957 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3958 for (Signature sig : s2) { 3959 set2.add(sig); 3960 } 3961 // Make sure s2 contains all signatures in s1. 3962 if (set1.equals(set2)) { 3963 return PackageManager.SIGNATURE_MATCH; 3964 } 3965 return PackageManager.SIGNATURE_NO_MATCH; 3966 } 3967 3968 /** 3969 * If the database version for this type of package (internal storage or 3970 * external storage) is less than the version where package signatures 3971 * were updated, return true. 3972 */ 3973 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3974 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3975 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3976 } 3977 3978 /** 3979 * Used for backward compatibility to make sure any packages with 3980 * certificate chains get upgraded to the new style. {@code existingSigs} 3981 * will be in the old format (since they were stored on disk from before the 3982 * system upgrade) and {@code scannedSigs} will be in the newer format. 3983 */ 3984 private int compareSignaturesCompat(PackageSignatures existingSigs, 3985 PackageParser.Package scannedPkg) { 3986 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3987 return PackageManager.SIGNATURE_NO_MATCH; 3988 } 3989 3990 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3991 for (Signature sig : existingSigs.mSignatures) { 3992 existingSet.add(sig); 3993 } 3994 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3995 for (Signature sig : scannedPkg.mSignatures) { 3996 try { 3997 Signature[] chainSignatures = sig.getChainSignatures(); 3998 for (Signature chainSig : chainSignatures) { 3999 scannedCompatSet.add(chainSig); 4000 } 4001 } catch (CertificateEncodingException e) { 4002 scannedCompatSet.add(sig); 4003 } 4004 } 4005 /* 4006 * Make sure the expanded scanned set contains all signatures in the 4007 * existing one. 4008 */ 4009 if (scannedCompatSet.equals(existingSet)) { 4010 // Migrate the old signatures to the new scheme. 4011 existingSigs.assignSignatures(scannedPkg.mSignatures); 4012 // The new KeySets will be re-added later in the scanning process. 4013 synchronized (mPackages) { 4014 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4015 } 4016 return PackageManager.SIGNATURE_MATCH; 4017 } 4018 return PackageManager.SIGNATURE_NO_MATCH; 4019 } 4020 4021 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4022 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4023 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4024 } 4025 4026 private int compareSignaturesRecover(PackageSignatures existingSigs, 4027 PackageParser.Package scannedPkg) { 4028 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4029 return PackageManager.SIGNATURE_NO_MATCH; 4030 } 4031 4032 String msg = null; 4033 try { 4034 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4035 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4036 + scannedPkg.packageName); 4037 return PackageManager.SIGNATURE_MATCH; 4038 } 4039 } catch (CertificateException e) { 4040 msg = e.getMessage(); 4041 } 4042 4043 logCriticalInfo(Log.INFO, 4044 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4045 return PackageManager.SIGNATURE_NO_MATCH; 4046 } 4047 4048 @Override 4049 public String[] getPackagesForUid(int uid) { 4050 uid = UserHandle.getAppId(uid); 4051 // reader 4052 synchronized (mPackages) { 4053 Object obj = mSettings.getUserIdLPr(uid); 4054 if (obj instanceof SharedUserSetting) { 4055 final SharedUserSetting sus = (SharedUserSetting) obj; 4056 final int N = sus.packages.size(); 4057 final String[] res = new String[N]; 4058 final Iterator<PackageSetting> it = sus.packages.iterator(); 4059 int i = 0; 4060 while (it.hasNext()) { 4061 res[i++] = it.next().name; 4062 } 4063 return res; 4064 } else if (obj instanceof PackageSetting) { 4065 final PackageSetting ps = (PackageSetting) obj; 4066 return new String[] { ps.name }; 4067 } 4068 } 4069 return null; 4070 } 4071 4072 @Override 4073 public String getNameForUid(int uid) { 4074 // reader 4075 synchronized (mPackages) { 4076 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4077 if (obj instanceof SharedUserSetting) { 4078 final SharedUserSetting sus = (SharedUserSetting) obj; 4079 return sus.name + ":" + sus.userId; 4080 } else if (obj instanceof PackageSetting) { 4081 final PackageSetting ps = (PackageSetting) obj; 4082 return ps.name; 4083 } 4084 } 4085 return null; 4086 } 4087 4088 @Override 4089 public int getUidForSharedUser(String sharedUserName) { 4090 if(sharedUserName == null) { 4091 return -1; 4092 } 4093 // reader 4094 synchronized (mPackages) { 4095 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4096 if (suid == null) { 4097 return -1; 4098 } 4099 return suid.userId; 4100 } 4101 } 4102 4103 @Override 4104 public int getFlagsForUid(int uid) { 4105 synchronized (mPackages) { 4106 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4107 if (obj instanceof SharedUserSetting) { 4108 final SharedUserSetting sus = (SharedUserSetting) obj; 4109 return sus.pkgFlags; 4110 } else if (obj instanceof PackageSetting) { 4111 final PackageSetting ps = (PackageSetting) obj; 4112 return ps.pkgFlags; 4113 } 4114 } 4115 return 0; 4116 } 4117 4118 @Override 4119 public int getPrivateFlagsForUid(int uid) { 4120 synchronized (mPackages) { 4121 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4122 if (obj instanceof SharedUserSetting) { 4123 final SharedUserSetting sus = (SharedUserSetting) obj; 4124 return sus.pkgPrivateFlags; 4125 } else if (obj instanceof PackageSetting) { 4126 final PackageSetting ps = (PackageSetting) obj; 4127 return ps.pkgPrivateFlags; 4128 } 4129 } 4130 return 0; 4131 } 4132 4133 @Override 4134 public boolean isUidPrivileged(int uid) { 4135 uid = UserHandle.getAppId(uid); 4136 // reader 4137 synchronized (mPackages) { 4138 Object obj = mSettings.getUserIdLPr(uid); 4139 if (obj instanceof SharedUserSetting) { 4140 final SharedUserSetting sus = (SharedUserSetting) obj; 4141 final Iterator<PackageSetting> it = sus.packages.iterator(); 4142 while (it.hasNext()) { 4143 if (it.next().isPrivileged()) { 4144 return true; 4145 } 4146 } 4147 } else if (obj instanceof PackageSetting) { 4148 final PackageSetting ps = (PackageSetting) obj; 4149 return ps.isPrivileged(); 4150 } 4151 } 4152 return false; 4153 } 4154 4155 @Override 4156 public String[] getAppOpPermissionPackages(String permissionName) { 4157 synchronized (mPackages) { 4158 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4159 if (pkgs == null) { 4160 return null; 4161 } 4162 return pkgs.toArray(new String[pkgs.size()]); 4163 } 4164 } 4165 4166 @Override 4167 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4168 int flags, int userId) { 4169 if (!sUserManager.exists(userId)) return null; 4170 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4171 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4172 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4173 } 4174 4175 @Override 4176 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4177 IntentFilter filter, int match, ComponentName activity) { 4178 final int userId = UserHandle.getCallingUserId(); 4179 if (DEBUG_PREFERRED) { 4180 Log.v(TAG, "setLastChosenActivity intent=" + intent 4181 + " resolvedType=" + resolvedType 4182 + " flags=" + flags 4183 + " filter=" + filter 4184 + " match=" + match 4185 + " activity=" + activity); 4186 filter.dump(new PrintStreamPrinter(System.out), " "); 4187 } 4188 intent.setComponent(null); 4189 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4190 // Find any earlier preferred or last chosen entries and nuke them 4191 findPreferredActivity(intent, resolvedType, 4192 flags, query, 0, false, true, false, userId); 4193 // Add the new activity as the last chosen for this filter 4194 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4195 "Setting last chosen"); 4196 } 4197 4198 @Override 4199 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4200 final int userId = UserHandle.getCallingUserId(); 4201 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4202 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4203 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4204 false, false, false, userId); 4205 } 4206 4207 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4208 int flags, List<ResolveInfo> query, int userId) { 4209 if (query != null) { 4210 final int N = query.size(); 4211 if (N == 1) { 4212 return query.get(0); 4213 } else if (N > 1) { 4214 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4215 // If there is more than one activity with the same priority, 4216 // then let the user decide between them. 4217 ResolveInfo r0 = query.get(0); 4218 ResolveInfo r1 = query.get(1); 4219 if (DEBUG_INTENT_MATCHING || debug) { 4220 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4221 + r1.activityInfo.name + "=" + r1.priority); 4222 } 4223 // If the first activity has a higher priority, or a different 4224 // default, then it is always desireable to pick it. 4225 if (r0.priority != r1.priority 4226 || r0.preferredOrder != r1.preferredOrder 4227 || r0.isDefault != r1.isDefault) { 4228 return query.get(0); 4229 } 4230 // If we have saved a preference for a preferred activity for 4231 // this Intent, use that. 4232 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4233 flags, query, r0.priority, true, false, debug, userId); 4234 if (ri != null) { 4235 return ri; 4236 } 4237 ri = new ResolveInfo(mResolveInfo); 4238 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4239 ri.activityInfo.applicationInfo = new ApplicationInfo( 4240 ri.activityInfo.applicationInfo); 4241 if (userId != 0) { 4242 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4243 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4244 } 4245 // Make sure that the resolver is displayable in car mode 4246 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4247 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4248 return ri; 4249 } 4250 } 4251 return null; 4252 } 4253 4254 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4255 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4256 final int N = query.size(); 4257 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4258 .get(userId); 4259 // Get the list of persistent preferred activities that handle the intent 4260 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4261 List<PersistentPreferredActivity> pprefs = ppir != null 4262 ? ppir.queryIntent(intent, resolvedType, 4263 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4264 : null; 4265 if (pprefs != null && pprefs.size() > 0) { 4266 final int M = pprefs.size(); 4267 for (int i=0; i<M; i++) { 4268 final PersistentPreferredActivity ppa = pprefs.get(i); 4269 if (DEBUG_PREFERRED || debug) { 4270 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4271 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4272 + "\n component=" + ppa.mComponent); 4273 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4274 } 4275 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4276 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4277 if (DEBUG_PREFERRED || debug) { 4278 Slog.v(TAG, "Found persistent preferred activity:"); 4279 if (ai != null) { 4280 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4281 } else { 4282 Slog.v(TAG, " null"); 4283 } 4284 } 4285 if (ai == null) { 4286 // This previously registered persistent preferred activity 4287 // component is no longer known. Ignore it and do NOT remove it. 4288 continue; 4289 } 4290 for (int j=0; j<N; j++) { 4291 final ResolveInfo ri = query.get(j); 4292 if (!ri.activityInfo.applicationInfo.packageName 4293 .equals(ai.applicationInfo.packageName)) { 4294 continue; 4295 } 4296 if (!ri.activityInfo.name.equals(ai.name)) { 4297 continue; 4298 } 4299 // Found a persistent preference that can handle the intent. 4300 if (DEBUG_PREFERRED || debug) { 4301 Slog.v(TAG, "Returning persistent preferred activity: " + 4302 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4303 } 4304 return ri; 4305 } 4306 } 4307 } 4308 return null; 4309 } 4310 4311 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4312 List<ResolveInfo> query, int priority, boolean always, 4313 boolean removeMatches, boolean debug, int userId) { 4314 if (!sUserManager.exists(userId)) return null; 4315 // writer 4316 synchronized (mPackages) { 4317 if (intent.getSelector() != null) { 4318 intent = intent.getSelector(); 4319 } 4320 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4321 4322 // Try to find a matching persistent preferred activity. 4323 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4324 debug, userId); 4325 4326 // If a persistent preferred activity matched, use it. 4327 if (pri != null) { 4328 return pri; 4329 } 4330 4331 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4332 // Get the list of preferred activities that handle the intent 4333 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4334 List<PreferredActivity> prefs = pir != null 4335 ? pir.queryIntent(intent, resolvedType, 4336 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4337 : null; 4338 if (prefs != null && prefs.size() > 0) { 4339 boolean changed = false; 4340 try { 4341 // First figure out how good the original match set is. 4342 // We will only allow preferred activities that came 4343 // from the same match quality. 4344 int match = 0; 4345 4346 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4347 4348 final int N = query.size(); 4349 for (int j=0; j<N; j++) { 4350 final ResolveInfo ri = query.get(j); 4351 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4352 + ": 0x" + Integer.toHexString(match)); 4353 if (ri.match > match) { 4354 match = ri.match; 4355 } 4356 } 4357 4358 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4359 + Integer.toHexString(match)); 4360 4361 match &= IntentFilter.MATCH_CATEGORY_MASK; 4362 final int M = prefs.size(); 4363 for (int i=0; i<M; i++) { 4364 final PreferredActivity pa = prefs.get(i); 4365 if (DEBUG_PREFERRED || debug) { 4366 Slog.v(TAG, "Checking PreferredActivity ds=" 4367 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4368 + "\n component=" + pa.mPref.mComponent); 4369 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4370 } 4371 if (pa.mPref.mMatch != match) { 4372 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4373 + Integer.toHexString(pa.mPref.mMatch)); 4374 continue; 4375 } 4376 // If it's not an "always" type preferred activity and that's what we're 4377 // looking for, skip it. 4378 if (always && !pa.mPref.mAlways) { 4379 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4380 continue; 4381 } 4382 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4383 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4384 if (DEBUG_PREFERRED || debug) { 4385 Slog.v(TAG, "Found preferred activity:"); 4386 if (ai != null) { 4387 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4388 } else { 4389 Slog.v(TAG, " null"); 4390 } 4391 } 4392 if (ai == null) { 4393 // This previously registered preferred activity 4394 // component is no longer known. Most likely an update 4395 // to the app was installed and in the new version this 4396 // component no longer exists. Clean it up by removing 4397 // it from the preferred activities list, and skip it. 4398 Slog.w(TAG, "Removing dangling preferred activity: " 4399 + pa.mPref.mComponent); 4400 pir.removeFilter(pa); 4401 changed = true; 4402 continue; 4403 } 4404 for (int j=0; j<N; j++) { 4405 final ResolveInfo ri = query.get(j); 4406 if (!ri.activityInfo.applicationInfo.packageName 4407 .equals(ai.applicationInfo.packageName)) { 4408 continue; 4409 } 4410 if (!ri.activityInfo.name.equals(ai.name)) { 4411 continue; 4412 } 4413 4414 if (removeMatches) { 4415 pir.removeFilter(pa); 4416 changed = true; 4417 if (DEBUG_PREFERRED) { 4418 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4419 } 4420 break; 4421 } 4422 4423 // Okay we found a previously set preferred or last chosen app. 4424 // If the result set is different from when this 4425 // was created, we need to clear it and re-ask the 4426 // user their preference, if we're looking for an "always" type entry. 4427 if (always && !pa.mPref.sameSet(query)) { 4428 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4429 + intent + " type " + resolvedType); 4430 if (DEBUG_PREFERRED) { 4431 Slog.v(TAG, "Removing preferred activity since set changed " 4432 + pa.mPref.mComponent); 4433 } 4434 pir.removeFilter(pa); 4435 // Re-add the filter as a "last chosen" entry (!always) 4436 PreferredActivity lastChosen = new PreferredActivity( 4437 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4438 pir.addFilter(lastChosen); 4439 changed = true; 4440 return null; 4441 } 4442 4443 // Yay! Either the set matched or we're looking for the last chosen 4444 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4445 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4446 return ri; 4447 } 4448 } 4449 } finally { 4450 if (changed) { 4451 if (DEBUG_PREFERRED) { 4452 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4453 } 4454 scheduleWritePackageRestrictionsLocked(userId); 4455 } 4456 } 4457 } 4458 } 4459 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4460 return null; 4461 } 4462 4463 /* 4464 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4465 */ 4466 @Override 4467 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4468 int targetUserId) { 4469 mContext.enforceCallingOrSelfPermission( 4470 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4471 List<CrossProfileIntentFilter> matches = 4472 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4473 if (matches != null) { 4474 int size = matches.size(); 4475 for (int i = 0; i < size; i++) { 4476 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4477 } 4478 } 4479 if (hasWebURI(intent)) { 4480 // cross-profile app linking works only towards the parent. 4481 final UserInfo parent = getProfileParent(sourceUserId); 4482 synchronized(mPackages) { 4483 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4484 intent, resolvedType, 0, sourceUserId, parent.id); 4485 return xpDomainInfo != null; 4486 } 4487 } 4488 return false; 4489 } 4490 4491 private UserInfo getProfileParent(int userId) { 4492 final long identity = Binder.clearCallingIdentity(); 4493 try { 4494 return sUserManager.getProfileParent(userId); 4495 } finally { 4496 Binder.restoreCallingIdentity(identity); 4497 } 4498 } 4499 4500 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4501 String resolvedType, int userId) { 4502 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4503 if (resolver != null) { 4504 return resolver.queryIntent(intent, resolvedType, false, userId); 4505 } 4506 return null; 4507 } 4508 4509 @Override 4510 public List<ResolveInfo> queryIntentActivities(Intent intent, 4511 String resolvedType, int flags, int userId) { 4512 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4513 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4514 ComponentName comp = intent.getComponent(); 4515 if (comp == null) { 4516 if (intent.getSelector() != null) { 4517 intent = intent.getSelector(); 4518 comp = intent.getComponent(); 4519 } 4520 } 4521 4522 if (comp != null) { 4523 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4524 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4525 if (ai != null) { 4526 final ResolveInfo ri = new ResolveInfo(); 4527 ri.activityInfo = ai; 4528 list.add(ri); 4529 } 4530 return list; 4531 } 4532 4533 // reader 4534 synchronized (mPackages) { 4535 final String pkgName = intent.getPackage(); 4536 if (pkgName == null) { 4537 List<CrossProfileIntentFilter> matchingFilters = 4538 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4539 // Check for results that need to skip the current profile. 4540 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4541 resolvedType, flags, userId); 4542 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4543 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4544 result.add(xpResolveInfo); 4545 return filterIfNotPrimaryUser(result, userId); 4546 } 4547 4548 // Check for results in the current profile. 4549 List<ResolveInfo> result = mActivities.queryIntent( 4550 intent, resolvedType, flags, userId); 4551 4552 // Check for cross profile results. 4553 xpResolveInfo = queryCrossProfileIntents( 4554 matchingFilters, intent, resolvedType, flags, userId); 4555 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4556 result.add(xpResolveInfo); 4557 Collections.sort(result, mResolvePrioritySorter); 4558 } 4559 result = filterIfNotPrimaryUser(result, userId); 4560 if (hasWebURI(intent)) { 4561 CrossProfileDomainInfo xpDomainInfo = null; 4562 final UserInfo parent = getProfileParent(userId); 4563 if (parent != null) { 4564 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4565 flags, userId, parent.id); 4566 } 4567 if (xpDomainInfo != null) { 4568 if (xpResolveInfo != null) { 4569 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4570 // in the result. 4571 result.remove(xpResolveInfo); 4572 } 4573 if (result.size() == 0) { 4574 result.add(xpDomainInfo.resolveInfo); 4575 return result; 4576 } 4577 } else if (result.size() <= 1) { 4578 return result; 4579 } 4580 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4581 xpDomainInfo, userId); 4582 Collections.sort(result, mResolvePrioritySorter); 4583 } 4584 return result; 4585 } 4586 final PackageParser.Package pkg = mPackages.get(pkgName); 4587 if (pkg != null) { 4588 return filterIfNotPrimaryUser( 4589 mActivities.queryIntentForPackage( 4590 intent, resolvedType, flags, pkg.activities, userId), 4591 userId); 4592 } 4593 return new ArrayList<ResolveInfo>(); 4594 } 4595 } 4596 4597 private static class CrossProfileDomainInfo { 4598 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4599 ResolveInfo resolveInfo; 4600 /* Best domain verification status of the activities found in the other profile */ 4601 int bestDomainVerificationStatus; 4602 } 4603 4604 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4605 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4606 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4607 sourceUserId)) { 4608 return null; 4609 } 4610 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4611 resolvedType, flags, parentUserId); 4612 4613 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4614 return null; 4615 } 4616 CrossProfileDomainInfo result = null; 4617 int size = resultTargetUser.size(); 4618 for (int i = 0; i < size; i++) { 4619 ResolveInfo riTargetUser = resultTargetUser.get(i); 4620 // Intent filter verification is only for filters that specify a host. So don't return 4621 // those that handle all web uris. 4622 if (riTargetUser.handleAllWebDataURI) { 4623 continue; 4624 } 4625 String packageName = riTargetUser.activityInfo.packageName; 4626 PackageSetting ps = mSettings.mPackages.get(packageName); 4627 if (ps == null) { 4628 continue; 4629 } 4630 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4631 int status = (int)(verificationState >> 32); 4632 if (result == null) { 4633 result = new CrossProfileDomainInfo(); 4634 result.resolveInfo = 4635 createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId); 4636 result.bestDomainVerificationStatus = status; 4637 } else { 4638 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4639 result.bestDomainVerificationStatus); 4640 } 4641 } 4642 // Don't consider matches with status NEVER across profiles. 4643 if (result != null && result.bestDomainVerificationStatus 4644 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4645 return null; 4646 } 4647 return result; 4648 } 4649 4650 /** 4651 * Verification statuses are ordered from the worse to the best, except for 4652 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4653 */ 4654 private int bestDomainVerificationStatus(int status1, int status2) { 4655 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4656 return status2; 4657 } 4658 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4659 return status1; 4660 } 4661 return (int) MathUtils.max(status1, status2); 4662 } 4663 4664 private boolean isUserEnabled(int userId) { 4665 long callingId = Binder.clearCallingIdentity(); 4666 try { 4667 UserInfo userInfo = sUserManager.getUserInfo(userId); 4668 return userInfo != null && userInfo.isEnabled(); 4669 } finally { 4670 Binder.restoreCallingIdentity(callingId); 4671 } 4672 } 4673 4674 /** 4675 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4676 * 4677 * @return filtered list 4678 */ 4679 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4680 if (userId == UserHandle.USER_OWNER) { 4681 return resolveInfos; 4682 } 4683 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4684 ResolveInfo info = resolveInfos.get(i); 4685 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4686 resolveInfos.remove(i); 4687 } 4688 } 4689 return resolveInfos; 4690 } 4691 4692 private static boolean hasWebURI(Intent intent) { 4693 if (intent.getData() == null) { 4694 return false; 4695 } 4696 final String scheme = intent.getScheme(); 4697 if (TextUtils.isEmpty(scheme)) { 4698 return false; 4699 } 4700 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4701 } 4702 4703 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4704 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4705 int userId) { 4706 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4707 4708 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4709 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4710 candidates.size()); 4711 } 4712 4713 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4714 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4715 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4716 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4717 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4718 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4719 4720 synchronized (mPackages) { 4721 final int count = candidates.size(); 4722 // First, try to use linked apps. Partition the candidates into four lists: 4723 // one for the final results, one for the "do not use ever", one for "undefined status" 4724 // and finally one for "browser app type". 4725 for (int n=0; n<count; n++) { 4726 ResolveInfo info = candidates.get(n); 4727 String packageName = info.activityInfo.packageName; 4728 PackageSetting ps = mSettings.mPackages.get(packageName); 4729 if (ps != null) { 4730 // Add to the special match all list (Browser use case) 4731 if (info.handleAllWebDataURI) { 4732 matchAllList.add(info); 4733 continue; 4734 } 4735 // Try to get the status from User settings first 4736 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4737 int status = (int)(packedStatus >> 32); 4738 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4739 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4740 if (DEBUG_DOMAIN_VERIFICATION) { 4741 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4742 + " : linkgen=" + linkGeneration); 4743 } 4744 // Use link-enabled generation as preferredOrder, i.e. 4745 // prefer newly-enabled over earlier-enabled. 4746 info.preferredOrder = linkGeneration; 4747 alwaysList.add(info); 4748 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4749 if (DEBUG_DOMAIN_VERIFICATION) { 4750 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4751 } 4752 neverList.add(info); 4753 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4754 if (DEBUG_DOMAIN_VERIFICATION) { 4755 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4756 } 4757 alwaysAskList.add(info); 4758 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4759 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4760 if (DEBUG_DOMAIN_VERIFICATION) { 4761 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4762 } 4763 undefinedList.add(info); 4764 } 4765 } 4766 } 4767 4768 // We'll want to include browser possibilities in a few cases 4769 boolean includeBrowser = false; 4770 4771 // First try to add the "always" resolution(s) for the current user, if any 4772 if (alwaysList.size() > 0) { 4773 result.addAll(alwaysList); 4774 } else { 4775 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4776 result.addAll(undefinedList); 4777 // Maybe add one for the other profile. 4778 if (xpDomainInfo != null && ( 4779 xpDomainInfo.bestDomainVerificationStatus 4780 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 4781 result.add(xpDomainInfo.resolveInfo); 4782 } 4783 includeBrowser = true; 4784 } 4785 4786 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4787 // If there were 'always' entries their preferred order has been set, so we also 4788 // back that off to make the alternatives equivalent 4789 if (alwaysAskList.size() > 0) { 4790 for (ResolveInfo i : result) { 4791 i.preferredOrder = 0; 4792 } 4793 result.addAll(alwaysAskList); 4794 includeBrowser = true; 4795 } 4796 4797 if (includeBrowser) { 4798 // Also add browsers (all of them or only the default one) 4799 if (DEBUG_DOMAIN_VERIFICATION) { 4800 Slog.v(TAG, " ...including browsers in candidate set"); 4801 } 4802 if ((matchFlags & MATCH_ALL) != 0) { 4803 result.addAll(matchAllList); 4804 } else { 4805 // Browser/generic handling case. If there's a default browser, go straight 4806 // to that (but only if there is no other higher-priority match). 4807 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4808 int maxMatchPrio = 0; 4809 ResolveInfo defaultBrowserMatch = null; 4810 final int numCandidates = matchAllList.size(); 4811 for (int n = 0; n < numCandidates; n++) { 4812 ResolveInfo info = matchAllList.get(n); 4813 // track the highest overall match priority... 4814 if (info.priority > maxMatchPrio) { 4815 maxMatchPrio = info.priority; 4816 } 4817 // ...and the highest-priority default browser match 4818 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4819 if (defaultBrowserMatch == null 4820 || (defaultBrowserMatch.priority < info.priority)) { 4821 if (debug) { 4822 Slog.v(TAG, "Considering default browser match " + info); 4823 } 4824 defaultBrowserMatch = info; 4825 } 4826 } 4827 } 4828 if (defaultBrowserMatch != null 4829 && defaultBrowserMatch.priority >= maxMatchPrio 4830 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4831 { 4832 if (debug) { 4833 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4834 } 4835 result.add(defaultBrowserMatch); 4836 } else { 4837 result.addAll(matchAllList); 4838 } 4839 } 4840 4841 // If there is nothing selected, add all candidates and remove the ones that the user 4842 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4843 if (result.size() == 0) { 4844 result.addAll(candidates); 4845 result.removeAll(neverList); 4846 } 4847 } 4848 } 4849 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4850 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4851 result.size()); 4852 for (ResolveInfo info : result) { 4853 Slog.v(TAG, " + " + info.activityInfo); 4854 } 4855 } 4856 return result; 4857 } 4858 4859 // Returns a packed value as a long: 4860 // 4861 // high 'int'-sized word: link status: undefined/ask/never/always. 4862 // low 'int'-sized word: relative priority among 'always' results. 4863 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4864 long result = ps.getDomainVerificationStatusForUser(userId); 4865 // if none available, get the master status 4866 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4867 if (ps.getIntentFilterVerificationInfo() != null) { 4868 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4869 } 4870 } 4871 return result; 4872 } 4873 4874 private ResolveInfo querySkipCurrentProfileIntents( 4875 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4876 int flags, int sourceUserId) { 4877 if (matchingFilters != null) { 4878 int size = matchingFilters.size(); 4879 for (int i = 0; i < size; i ++) { 4880 CrossProfileIntentFilter filter = matchingFilters.get(i); 4881 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4882 // Checking if there are activities in the target user that can handle the 4883 // intent. 4884 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4885 flags, sourceUserId); 4886 if (resolveInfo != null) { 4887 return resolveInfo; 4888 } 4889 } 4890 } 4891 } 4892 return null; 4893 } 4894 4895 // Return matching ResolveInfo if any for skip current profile intent filters. 4896 private ResolveInfo queryCrossProfileIntents( 4897 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4898 int flags, int sourceUserId) { 4899 if (matchingFilters != null) { 4900 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4901 // match the same intent. For performance reasons, it is better not to 4902 // run queryIntent twice for the same userId 4903 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4904 int size = matchingFilters.size(); 4905 for (int i = 0; i < size; i++) { 4906 CrossProfileIntentFilter filter = matchingFilters.get(i); 4907 int targetUserId = filter.getTargetUserId(); 4908 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4909 && !alreadyTriedUserIds.get(targetUserId)) { 4910 // Checking if there are activities in the target user that can handle the 4911 // intent. 4912 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4913 flags, sourceUserId); 4914 if (resolveInfo != null) return resolveInfo; 4915 alreadyTriedUserIds.put(targetUserId, true); 4916 } 4917 } 4918 } 4919 return null; 4920 } 4921 4922 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4923 String resolvedType, int flags, int sourceUserId) { 4924 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4925 resolvedType, flags, filter.getTargetUserId()); 4926 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4927 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4928 } 4929 return null; 4930 } 4931 4932 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4933 int sourceUserId, int targetUserId) { 4934 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4935 String className; 4936 if (targetUserId == UserHandle.USER_OWNER) { 4937 className = FORWARD_INTENT_TO_USER_OWNER; 4938 } else { 4939 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4940 } 4941 ComponentName forwardingActivityComponentName = new ComponentName( 4942 mAndroidApplication.packageName, className); 4943 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4944 sourceUserId); 4945 if (targetUserId == UserHandle.USER_OWNER) { 4946 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4947 forwardingResolveInfo.noResourceId = true; 4948 } 4949 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4950 forwardingResolveInfo.priority = 0; 4951 forwardingResolveInfo.preferredOrder = 0; 4952 forwardingResolveInfo.match = 0; 4953 forwardingResolveInfo.isDefault = true; 4954 forwardingResolveInfo.filter = filter; 4955 forwardingResolveInfo.targetUserId = targetUserId; 4956 return forwardingResolveInfo; 4957 } 4958 4959 @Override 4960 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4961 Intent[] specifics, String[] specificTypes, Intent intent, 4962 String resolvedType, int flags, int userId) { 4963 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4964 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4965 false, "query intent activity options"); 4966 final String resultsAction = intent.getAction(); 4967 4968 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4969 | PackageManager.GET_RESOLVED_FILTER, userId); 4970 4971 if (DEBUG_INTENT_MATCHING) { 4972 Log.v(TAG, "Query " + intent + ": " + results); 4973 } 4974 4975 int specificsPos = 0; 4976 int N; 4977 4978 // todo: note that the algorithm used here is O(N^2). This 4979 // isn't a problem in our current environment, but if we start running 4980 // into situations where we have more than 5 or 10 matches then this 4981 // should probably be changed to something smarter... 4982 4983 // First we go through and resolve each of the specific items 4984 // that were supplied, taking care of removing any corresponding 4985 // duplicate items in the generic resolve list. 4986 if (specifics != null) { 4987 for (int i=0; i<specifics.length; i++) { 4988 final Intent sintent = specifics[i]; 4989 if (sintent == null) { 4990 continue; 4991 } 4992 4993 if (DEBUG_INTENT_MATCHING) { 4994 Log.v(TAG, "Specific #" + i + ": " + sintent); 4995 } 4996 4997 String action = sintent.getAction(); 4998 if (resultsAction != null && resultsAction.equals(action)) { 4999 // If this action was explicitly requested, then don't 5000 // remove things that have it. 5001 action = null; 5002 } 5003 5004 ResolveInfo ri = null; 5005 ActivityInfo ai = null; 5006 5007 ComponentName comp = sintent.getComponent(); 5008 if (comp == null) { 5009 ri = resolveIntent( 5010 sintent, 5011 specificTypes != null ? specificTypes[i] : null, 5012 flags, userId); 5013 if (ri == null) { 5014 continue; 5015 } 5016 if (ri == mResolveInfo) { 5017 // ACK! Must do something better with this. 5018 } 5019 ai = ri.activityInfo; 5020 comp = new ComponentName(ai.applicationInfo.packageName, 5021 ai.name); 5022 } else { 5023 ai = getActivityInfo(comp, flags, userId); 5024 if (ai == null) { 5025 continue; 5026 } 5027 } 5028 5029 // Look for any generic query activities that are duplicates 5030 // of this specific one, and remove them from the results. 5031 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5032 N = results.size(); 5033 int j; 5034 for (j=specificsPos; j<N; j++) { 5035 ResolveInfo sri = results.get(j); 5036 if ((sri.activityInfo.name.equals(comp.getClassName()) 5037 && sri.activityInfo.applicationInfo.packageName.equals( 5038 comp.getPackageName())) 5039 || (action != null && sri.filter.matchAction(action))) { 5040 results.remove(j); 5041 if (DEBUG_INTENT_MATCHING) Log.v( 5042 TAG, "Removing duplicate item from " + j 5043 + " due to specific " + specificsPos); 5044 if (ri == null) { 5045 ri = sri; 5046 } 5047 j--; 5048 N--; 5049 } 5050 } 5051 5052 // Add this specific item to its proper place. 5053 if (ri == null) { 5054 ri = new ResolveInfo(); 5055 ri.activityInfo = ai; 5056 } 5057 results.add(specificsPos, ri); 5058 ri.specificIndex = i; 5059 specificsPos++; 5060 } 5061 } 5062 5063 // Now we go through the remaining generic results and remove any 5064 // duplicate actions that are found here. 5065 N = results.size(); 5066 for (int i=specificsPos; i<N-1; i++) { 5067 final ResolveInfo rii = results.get(i); 5068 if (rii.filter == null) { 5069 continue; 5070 } 5071 5072 // Iterate over all of the actions of this result's intent 5073 // filter... typically this should be just one. 5074 final Iterator<String> it = rii.filter.actionsIterator(); 5075 if (it == null) { 5076 continue; 5077 } 5078 while (it.hasNext()) { 5079 final String action = it.next(); 5080 if (resultsAction != null && resultsAction.equals(action)) { 5081 // If this action was explicitly requested, then don't 5082 // remove things that have it. 5083 continue; 5084 } 5085 for (int j=i+1; j<N; j++) { 5086 final ResolveInfo rij = results.get(j); 5087 if (rij.filter != null && rij.filter.hasAction(action)) { 5088 results.remove(j); 5089 if (DEBUG_INTENT_MATCHING) Log.v( 5090 TAG, "Removing duplicate item from " + j 5091 + " due to action " + action + " at " + i); 5092 j--; 5093 N--; 5094 } 5095 } 5096 } 5097 5098 // If the caller didn't request filter information, drop it now 5099 // so we don't have to marshall/unmarshall it. 5100 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5101 rii.filter = null; 5102 } 5103 } 5104 5105 // Filter out the caller activity if so requested. 5106 if (caller != null) { 5107 N = results.size(); 5108 for (int i=0; i<N; i++) { 5109 ActivityInfo ainfo = results.get(i).activityInfo; 5110 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5111 && caller.getClassName().equals(ainfo.name)) { 5112 results.remove(i); 5113 break; 5114 } 5115 } 5116 } 5117 5118 // If the caller didn't request filter information, 5119 // drop them now so we don't have to 5120 // marshall/unmarshall it. 5121 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5122 N = results.size(); 5123 for (int i=0; i<N; i++) { 5124 results.get(i).filter = null; 5125 } 5126 } 5127 5128 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5129 return results; 5130 } 5131 5132 @Override 5133 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5134 int userId) { 5135 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5136 ComponentName comp = intent.getComponent(); 5137 if (comp == null) { 5138 if (intent.getSelector() != null) { 5139 intent = intent.getSelector(); 5140 comp = intent.getComponent(); 5141 } 5142 } 5143 if (comp != null) { 5144 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5145 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5146 if (ai != null) { 5147 ResolveInfo ri = new ResolveInfo(); 5148 ri.activityInfo = ai; 5149 list.add(ri); 5150 } 5151 return list; 5152 } 5153 5154 // reader 5155 synchronized (mPackages) { 5156 String pkgName = intent.getPackage(); 5157 if (pkgName == null) { 5158 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5159 } 5160 final PackageParser.Package pkg = mPackages.get(pkgName); 5161 if (pkg != null) { 5162 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5163 userId); 5164 } 5165 return null; 5166 } 5167 } 5168 5169 @Override 5170 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5171 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5172 if (!sUserManager.exists(userId)) return null; 5173 if (query != null) { 5174 if (query.size() >= 1) { 5175 // If there is more than one service with the same priority, 5176 // just arbitrarily pick the first one. 5177 return query.get(0); 5178 } 5179 } 5180 return null; 5181 } 5182 5183 @Override 5184 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5185 int userId) { 5186 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5187 ComponentName comp = intent.getComponent(); 5188 if (comp == null) { 5189 if (intent.getSelector() != null) { 5190 intent = intent.getSelector(); 5191 comp = intent.getComponent(); 5192 } 5193 } 5194 if (comp != null) { 5195 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5196 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5197 if (si != null) { 5198 final ResolveInfo ri = new ResolveInfo(); 5199 ri.serviceInfo = si; 5200 list.add(ri); 5201 } 5202 return list; 5203 } 5204 5205 // reader 5206 synchronized (mPackages) { 5207 String pkgName = intent.getPackage(); 5208 if (pkgName == null) { 5209 return mServices.queryIntent(intent, resolvedType, flags, userId); 5210 } 5211 final PackageParser.Package pkg = mPackages.get(pkgName); 5212 if (pkg != null) { 5213 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5214 userId); 5215 } 5216 return null; 5217 } 5218 } 5219 5220 @Override 5221 public List<ResolveInfo> queryIntentContentProviders( 5222 Intent intent, String resolvedType, int flags, int userId) { 5223 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5224 ComponentName comp = intent.getComponent(); 5225 if (comp == null) { 5226 if (intent.getSelector() != null) { 5227 intent = intent.getSelector(); 5228 comp = intent.getComponent(); 5229 } 5230 } 5231 if (comp != null) { 5232 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5233 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5234 if (pi != null) { 5235 final ResolveInfo ri = new ResolveInfo(); 5236 ri.providerInfo = pi; 5237 list.add(ri); 5238 } 5239 return list; 5240 } 5241 5242 // reader 5243 synchronized (mPackages) { 5244 String pkgName = intent.getPackage(); 5245 if (pkgName == null) { 5246 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5247 } 5248 final PackageParser.Package pkg = mPackages.get(pkgName); 5249 if (pkg != null) { 5250 return mProviders.queryIntentForPackage( 5251 intent, resolvedType, flags, pkg.providers, userId); 5252 } 5253 return null; 5254 } 5255 } 5256 5257 @Override 5258 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5259 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5260 5261 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5262 5263 // writer 5264 synchronized (mPackages) { 5265 ArrayList<PackageInfo> list; 5266 if (listUninstalled) { 5267 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5268 for (PackageSetting ps : mSettings.mPackages.values()) { 5269 PackageInfo pi; 5270 if (ps.pkg != null) { 5271 pi = generatePackageInfo(ps.pkg, flags, userId); 5272 } else { 5273 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5274 } 5275 if (pi != null) { 5276 list.add(pi); 5277 } 5278 } 5279 } else { 5280 list = new ArrayList<PackageInfo>(mPackages.size()); 5281 for (PackageParser.Package p : mPackages.values()) { 5282 PackageInfo pi = generatePackageInfo(p, flags, userId); 5283 if (pi != null) { 5284 list.add(pi); 5285 } 5286 } 5287 } 5288 5289 return new ParceledListSlice<PackageInfo>(list); 5290 } 5291 } 5292 5293 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5294 String[] permissions, boolean[] tmp, int flags, int userId) { 5295 int numMatch = 0; 5296 final PermissionsState permissionsState = ps.getPermissionsState(); 5297 for (int i=0; i<permissions.length; i++) { 5298 final String permission = permissions[i]; 5299 if (permissionsState.hasPermission(permission, userId)) { 5300 tmp[i] = true; 5301 numMatch++; 5302 } else { 5303 tmp[i] = false; 5304 } 5305 } 5306 if (numMatch == 0) { 5307 return; 5308 } 5309 PackageInfo pi; 5310 if (ps.pkg != null) { 5311 pi = generatePackageInfo(ps.pkg, flags, userId); 5312 } else { 5313 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5314 } 5315 // The above might return null in cases of uninstalled apps or install-state 5316 // skew across users/profiles. 5317 if (pi != null) { 5318 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5319 if (numMatch == permissions.length) { 5320 pi.requestedPermissions = permissions; 5321 } else { 5322 pi.requestedPermissions = new String[numMatch]; 5323 numMatch = 0; 5324 for (int i=0; i<permissions.length; i++) { 5325 if (tmp[i]) { 5326 pi.requestedPermissions[numMatch] = permissions[i]; 5327 numMatch++; 5328 } 5329 } 5330 } 5331 } 5332 list.add(pi); 5333 } 5334 } 5335 5336 @Override 5337 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5338 String[] permissions, int flags, int userId) { 5339 if (!sUserManager.exists(userId)) return null; 5340 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5341 5342 // writer 5343 synchronized (mPackages) { 5344 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5345 boolean[] tmpBools = new boolean[permissions.length]; 5346 if (listUninstalled) { 5347 for (PackageSetting ps : mSettings.mPackages.values()) { 5348 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5349 } 5350 } else { 5351 for (PackageParser.Package pkg : mPackages.values()) { 5352 PackageSetting ps = (PackageSetting)pkg.mExtras; 5353 if (ps != null) { 5354 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5355 userId); 5356 } 5357 } 5358 } 5359 5360 return new ParceledListSlice<PackageInfo>(list); 5361 } 5362 } 5363 5364 @Override 5365 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5366 if (!sUserManager.exists(userId)) return null; 5367 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5368 5369 // writer 5370 synchronized (mPackages) { 5371 ArrayList<ApplicationInfo> list; 5372 if (listUninstalled) { 5373 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5374 for (PackageSetting ps : mSettings.mPackages.values()) { 5375 ApplicationInfo ai; 5376 if (ps.pkg != null) { 5377 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5378 ps.readUserState(userId), userId); 5379 } else { 5380 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5381 } 5382 if (ai != null) { 5383 list.add(ai); 5384 } 5385 } 5386 } else { 5387 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5388 for (PackageParser.Package p : mPackages.values()) { 5389 if (p.mExtras != null) { 5390 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5391 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5392 if (ai != null) { 5393 list.add(ai); 5394 } 5395 } 5396 } 5397 } 5398 5399 return new ParceledListSlice<ApplicationInfo>(list); 5400 } 5401 } 5402 5403 public List<ApplicationInfo> getPersistentApplications(int flags) { 5404 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5405 5406 // reader 5407 synchronized (mPackages) { 5408 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5409 final int userId = UserHandle.getCallingUserId(); 5410 while (i.hasNext()) { 5411 final PackageParser.Package p = i.next(); 5412 if (p.applicationInfo != null 5413 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5414 && (!mSafeMode || isSystemApp(p))) { 5415 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5416 if (ps != null) { 5417 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5418 ps.readUserState(userId), userId); 5419 if (ai != null) { 5420 finalList.add(ai); 5421 } 5422 } 5423 } 5424 } 5425 } 5426 5427 return finalList; 5428 } 5429 5430 @Override 5431 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5432 if (!sUserManager.exists(userId)) return null; 5433 // reader 5434 synchronized (mPackages) { 5435 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5436 PackageSetting ps = provider != null 5437 ? mSettings.mPackages.get(provider.owner.packageName) 5438 : null; 5439 return ps != null 5440 && mSettings.isEnabledLPr(provider.info, flags, userId) 5441 && (!mSafeMode || (provider.info.applicationInfo.flags 5442 &ApplicationInfo.FLAG_SYSTEM) != 0) 5443 ? PackageParser.generateProviderInfo(provider, flags, 5444 ps.readUserState(userId), userId) 5445 : null; 5446 } 5447 } 5448 5449 /** 5450 * @deprecated 5451 */ 5452 @Deprecated 5453 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5454 // reader 5455 synchronized (mPackages) { 5456 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5457 .entrySet().iterator(); 5458 final int userId = UserHandle.getCallingUserId(); 5459 while (i.hasNext()) { 5460 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5461 PackageParser.Provider p = entry.getValue(); 5462 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5463 5464 if (ps != null && p.syncable 5465 && (!mSafeMode || (p.info.applicationInfo.flags 5466 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5467 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5468 ps.readUserState(userId), userId); 5469 if (info != null) { 5470 outNames.add(entry.getKey()); 5471 outInfo.add(info); 5472 } 5473 } 5474 } 5475 } 5476 } 5477 5478 @Override 5479 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5480 int uid, int flags) { 5481 ArrayList<ProviderInfo> finalList = null; 5482 // reader 5483 synchronized (mPackages) { 5484 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5485 final int userId = processName != null ? 5486 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5487 while (i.hasNext()) { 5488 final PackageParser.Provider p = i.next(); 5489 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5490 if (ps != null && p.info.authority != null 5491 && (processName == null 5492 || (p.info.processName.equals(processName) 5493 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5494 && mSettings.isEnabledLPr(p.info, flags, userId) 5495 && (!mSafeMode 5496 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5497 if (finalList == null) { 5498 finalList = new ArrayList<ProviderInfo>(3); 5499 } 5500 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5501 ps.readUserState(userId), userId); 5502 if (info != null) { 5503 finalList.add(info); 5504 } 5505 } 5506 } 5507 } 5508 5509 if (finalList != null) { 5510 Collections.sort(finalList, mProviderInitOrderSorter); 5511 return new ParceledListSlice<ProviderInfo>(finalList); 5512 } 5513 5514 return null; 5515 } 5516 5517 @Override 5518 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5519 int flags) { 5520 // reader 5521 synchronized (mPackages) { 5522 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5523 return PackageParser.generateInstrumentationInfo(i, flags); 5524 } 5525 } 5526 5527 @Override 5528 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5529 int flags) { 5530 ArrayList<InstrumentationInfo> finalList = 5531 new ArrayList<InstrumentationInfo>(); 5532 5533 // reader 5534 synchronized (mPackages) { 5535 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5536 while (i.hasNext()) { 5537 final PackageParser.Instrumentation p = i.next(); 5538 if (targetPackage == null 5539 || targetPackage.equals(p.info.targetPackage)) { 5540 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5541 flags); 5542 if (ii != null) { 5543 finalList.add(ii); 5544 } 5545 } 5546 } 5547 } 5548 5549 return finalList; 5550 } 5551 5552 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5553 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5554 if (overlays == null) { 5555 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5556 return; 5557 } 5558 for (PackageParser.Package opkg : overlays.values()) { 5559 // Not much to do if idmap fails: we already logged the error 5560 // and we certainly don't want to abort installation of pkg simply 5561 // because an overlay didn't fit properly. For these reasons, 5562 // ignore the return value of createIdmapForPackagePairLI. 5563 createIdmapForPackagePairLI(pkg, opkg); 5564 } 5565 } 5566 5567 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5568 PackageParser.Package opkg) { 5569 if (!opkg.mTrustedOverlay) { 5570 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5571 opkg.baseCodePath + ": overlay not trusted"); 5572 return false; 5573 } 5574 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5575 if (overlaySet == null) { 5576 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5577 opkg.baseCodePath + " but target package has no known overlays"); 5578 return false; 5579 } 5580 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5581 // TODO: generate idmap for split APKs 5582 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5583 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5584 + opkg.baseCodePath); 5585 return false; 5586 } 5587 PackageParser.Package[] overlayArray = 5588 overlaySet.values().toArray(new PackageParser.Package[0]); 5589 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5590 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5591 return p1.mOverlayPriority - p2.mOverlayPriority; 5592 } 5593 }; 5594 Arrays.sort(overlayArray, cmp); 5595 5596 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5597 int i = 0; 5598 for (PackageParser.Package p : overlayArray) { 5599 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5600 } 5601 return true; 5602 } 5603 5604 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5605 final File[] files = dir.listFiles(); 5606 if (ArrayUtils.isEmpty(files)) { 5607 Log.d(TAG, "No files in app dir " + dir); 5608 return; 5609 } 5610 5611 if (DEBUG_PACKAGE_SCANNING) { 5612 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5613 + " flags=0x" + Integer.toHexString(parseFlags)); 5614 } 5615 5616 for (File file : files) { 5617 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5618 && !PackageInstallerService.isStageName(file.getName()); 5619 if (!isPackage) { 5620 // Ignore entries which are not packages 5621 continue; 5622 } 5623 try { 5624 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5625 scanFlags, currentTime, null); 5626 } catch (PackageManagerException e) { 5627 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5628 5629 // Delete invalid userdata apps 5630 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5631 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5632 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5633 if (file.isDirectory()) { 5634 mInstaller.rmPackageDir(file.getAbsolutePath()); 5635 } else { 5636 file.delete(); 5637 } 5638 } 5639 } 5640 } 5641 } 5642 5643 private static File getSettingsProblemFile() { 5644 File dataDir = Environment.getDataDirectory(); 5645 File systemDir = new File(dataDir, "system"); 5646 File fname = new File(systemDir, "uiderrors.txt"); 5647 return fname; 5648 } 5649 5650 static void reportSettingsProblem(int priority, String msg) { 5651 logCriticalInfo(priority, msg); 5652 } 5653 5654 static void logCriticalInfo(int priority, String msg) { 5655 Slog.println(priority, TAG, msg); 5656 EventLogTags.writePmCriticalInfo(msg); 5657 try { 5658 File fname = getSettingsProblemFile(); 5659 FileOutputStream out = new FileOutputStream(fname, true); 5660 PrintWriter pw = new FastPrintWriter(out); 5661 SimpleDateFormat formatter = new SimpleDateFormat(); 5662 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5663 pw.println(dateString + ": " + msg); 5664 pw.close(); 5665 FileUtils.setPermissions( 5666 fname.toString(), 5667 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5668 -1, -1); 5669 } catch (java.io.IOException e) { 5670 } 5671 } 5672 5673 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5674 PackageParser.Package pkg, File srcFile, int parseFlags) 5675 throws PackageManagerException { 5676 if (ps != null 5677 && ps.codePath.equals(srcFile) 5678 && ps.timeStamp == srcFile.lastModified() 5679 && !isCompatSignatureUpdateNeeded(pkg) 5680 && !isRecoverSignatureUpdateNeeded(pkg)) { 5681 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5682 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5683 ArraySet<PublicKey> signingKs; 5684 synchronized (mPackages) { 5685 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5686 } 5687 if (ps.signatures.mSignatures != null 5688 && ps.signatures.mSignatures.length != 0 5689 && signingKs != null) { 5690 // Optimization: reuse the existing cached certificates 5691 // if the package appears to be unchanged. 5692 pkg.mSignatures = ps.signatures.mSignatures; 5693 pkg.mSigningKeys = signingKs; 5694 return; 5695 } 5696 5697 Slog.w(TAG, "PackageSetting for " + ps.name 5698 + " is missing signatures. Collecting certs again to recover them."); 5699 } else { 5700 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5701 } 5702 5703 try { 5704 pp.collectCertificates(pkg, parseFlags); 5705 pp.collectManifestDigest(pkg); 5706 } catch (PackageParserException e) { 5707 throw PackageManagerException.from(e); 5708 } 5709 } 5710 5711 /* 5712 * Scan a package and return the newly parsed package. 5713 * Returns null in case of errors and the error code is stored in mLastScanError 5714 */ 5715 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5716 long currentTime, UserHandle user) throws PackageManagerException { 5717 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5718 parseFlags |= mDefParseFlags; 5719 PackageParser pp = new PackageParser(); 5720 pp.setSeparateProcesses(mSeparateProcesses); 5721 pp.setOnlyCoreApps(mOnlyCore); 5722 pp.setDisplayMetrics(mMetrics); 5723 5724 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5725 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5726 } 5727 5728 final PackageParser.Package pkg; 5729 try { 5730 pkg = pp.parsePackage(scanFile, parseFlags); 5731 } catch (PackageParserException e) { 5732 throw PackageManagerException.from(e); 5733 } 5734 5735 PackageSetting ps = null; 5736 PackageSetting updatedPkg; 5737 // reader 5738 synchronized (mPackages) { 5739 // Look to see if we already know about this package. 5740 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5741 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5742 // This package has been renamed to its original name. Let's 5743 // use that. 5744 ps = mSettings.peekPackageLPr(oldName); 5745 } 5746 // If there was no original package, see one for the real package name. 5747 if (ps == null) { 5748 ps = mSettings.peekPackageLPr(pkg.packageName); 5749 } 5750 // Check to see if this package could be hiding/updating a system 5751 // package. Must look for it either under the original or real 5752 // package name depending on our state. 5753 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5754 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5755 } 5756 boolean updatedPkgBetter = false; 5757 // First check if this is a system package that may involve an update 5758 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5759 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5760 // it needs to drop FLAG_PRIVILEGED. 5761 if (locationIsPrivileged(scanFile)) { 5762 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5763 } else { 5764 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5765 } 5766 5767 if (ps != null && !ps.codePath.equals(scanFile)) { 5768 // The path has changed from what was last scanned... check the 5769 // version of the new path against what we have stored to determine 5770 // what to do. 5771 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5772 if (pkg.mVersionCode <= ps.versionCode) { 5773 // The system package has been updated and the code path does not match 5774 // Ignore entry. Skip it. 5775 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5776 + " ignored: updated version " + ps.versionCode 5777 + " better than this " + pkg.mVersionCode); 5778 if (!updatedPkg.codePath.equals(scanFile)) { 5779 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5780 + ps.name + " changing from " + updatedPkg.codePathString 5781 + " to " + scanFile); 5782 updatedPkg.codePath = scanFile; 5783 updatedPkg.codePathString = scanFile.toString(); 5784 updatedPkg.resourcePath = scanFile; 5785 updatedPkg.resourcePathString = scanFile.toString(); 5786 } 5787 updatedPkg.pkg = pkg; 5788 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5789 "Package " + ps.name + " at " + scanFile 5790 + " ignored: updated version " + ps.versionCode 5791 + " better than this " + pkg.mVersionCode); 5792 } else { 5793 // The current app on the system partition is better than 5794 // what we have updated to on the data partition; switch 5795 // back to the system partition version. 5796 // At this point, its safely assumed that package installation for 5797 // apps in system partition will go through. If not there won't be a working 5798 // version of the app 5799 // writer 5800 synchronized (mPackages) { 5801 // Just remove the loaded entries from package lists. 5802 mPackages.remove(ps.name); 5803 } 5804 5805 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5806 + " reverting from " + ps.codePathString 5807 + ": new version " + pkg.mVersionCode 5808 + " better than installed " + ps.versionCode); 5809 5810 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5811 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5812 synchronized (mInstallLock) { 5813 args.cleanUpResourcesLI(); 5814 } 5815 synchronized (mPackages) { 5816 mSettings.enableSystemPackageLPw(ps.name); 5817 } 5818 updatedPkgBetter = true; 5819 } 5820 } 5821 } 5822 5823 if (updatedPkg != null) { 5824 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5825 // initially 5826 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5827 5828 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5829 // flag set initially 5830 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5831 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5832 } 5833 } 5834 5835 // Verify certificates against what was last scanned 5836 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5837 5838 /* 5839 * A new system app appeared, but we already had a non-system one of the 5840 * same name installed earlier. 5841 */ 5842 boolean shouldHideSystemApp = false; 5843 if (updatedPkg == null && ps != null 5844 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5845 /* 5846 * Check to make sure the signatures match first. If they don't, 5847 * wipe the installed application and its data. 5848 */ 5849 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5850 != PackageManager.SIGNATURE_MATCH) { 5851 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5852 + " signatures don't match existing userdata copy; removing"); 5853 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5854 ps = null; 5855 } else { 5856 /* 5857 * If the newly-added system app is an older version than the 5858 * already installed version, hide it. It will be scanned later 5859 * and re-added like an update. 5860 */ 5861 if (pkg.mVersionCode <= ps.versionCode) { 5862 shouldHideSystemApp = true; 5863 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5864 + " but new version " + pkg.mVersionCode + " better than installed " 5865 + ps.versionCode + "; hiding system"); 5866 } else { 5867 /* 5868 * The newly found system app is a newer version that the 5869 * one previously installed. Simply remove the 5870 * already-installed application and replace it with our own 5871 * while keeping the application data. 5872 */ 5873 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5874 + " reverting from " + ps.codePathString + ": new version " 5875 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5876 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5877 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5878 synchronized (mInstallLock) { 5879 args.cleanUpResourcesLI(); 5880 } 5881 } 5882 } 5883 } 5884 5885 // The apk is forward locked (not public) if its code and resources 5886 // are kept in different files. (except for app in either system or 5887 // vendor path). 5888 // TODO grab this value from PackageSettings 5889 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5890 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5891 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5892 } 5893 } 5894 5895 // TODO: extend to support forward-locked splits 5896 String resourcePath = null; 5897 String baseResourcePath = null; 5898 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5899 if (ps != null && ps.resourcePathString != null) { 5900 resourcePath = ps.resourcePathString; 5901 baseResourcePath = ps.resourcePathString; 5902 } else { 5903 // Should not happen at all. Just log an error. 5904 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5905 } 5906 } else { 5907 resourcePath = pkg.codePath; 5908 baseResourcePath = pkg.baseCodePath; 5909 } 5910 5911 // Set application objects path explicitly. 5912 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5913 pkg.applicationInfo.setCodePath(pkg.codePath); 5914 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5915 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5916 pkg.applicationInfo.setResourcePath(resourcePath); 5917 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5918 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5919 5920 // Note that we invoke the following method only if we are about to unpack an application 5921 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5922 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5923 5924 /* 5925 * If the system app should be overridden by a previously installed 5926 * data, hide the system app now and let the /data/app scan pick it up 5927 * again. 5928 */ 5929 if (shouldHideSystemApp) { 5930 synchronized (mPackages) { 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 // Filter out packages that aren't recently used. 6081 filterRecentlyUsedApps(pkgs); 6082 // Add all remaining apps. 6083 for (PackageParser.Package pkg : pkgs) { 6084 if (DEBUG_DEXOPT) { 6085 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6086 } 6087 sortedPkgs.add(pkg); 6088 } 6089 6090 // If we want to be lazy, filter everything that wasn't recently used. 6091 if (mLazyDexOpt) { 6092 filterRecentlyUsedApps(sortedPkgs); 6093 } 6094 6095 int i = 0; 6096 int total = sortedPkgs.size(); 6097 File dataDir = Environment.getDataDirectory(); 6098 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6099 if (lowThreshold == 0) { 6100 throw new IllegalStateException("Invalid low memory threshold"); 6101 } 6102 for (PackageParser.Package pkg : sortedPkgs) { 6103 long usableSpace = dataDir.getUsableSpace(); 6104 if (usableSpace < lowThreshold) { 6105 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6106 break; 6107 } 6108 performBootDexOpt(pkg, ++i, total); 6109 } 6110 } 6111 } 6112 6113 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6114 // Filter out packages that aren't recently used. 6115 // 6116 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6117 // should do a full dexopt. 6118 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6119 int total = pkgs.size(); 6120 int skipped = 0; 6121 long now = System.currentTimeMillis(); 6122 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6123 PackageParser.Package pkg = i.next(); 6124 long then = pkg.mLastPackageUsageTimeInMills; 6125 if (then + mDexOptLRUThresholdInMills < now) { 6126 if (DEBUG_DEXOPT) { 6127 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6128 ((then == 0) ? "never" : new Date(then))); 6129 } 6130 i.remove(); 6131 skipped++; 6132 } 6133 } 6134 if (DEBUG_DEXOPT) { 6135 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6136 } 6137 } 6138 } 6139 6140 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6141 List<ResolveInfo> ris = null; 6142 try { 6143 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6144 intent, null, 0, UserHandle.USER_OWNER); 6145 } catch (RemoteException e) { 6146 } 6147 ArraySet<String> pkgNames = new ArraySet<String>(); 6148 if (ris != null) { 6149 for (ResolveInfo ri : ris) { 6150 pkgNames.add(ri.activityInfo.packageName); 6151 } 6152 } 6153 return pkgNames; 6154 } 6155 6156 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6157 if (DEBUG_DEXOPT) { 6158 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6159 } 6160 if (!isFirstBoot()) { 6161 try { 6162 ActivityManagerNative.getDefault().showBootMessage( 6163 mContext.getResources().getString(R.string.android_upgrading_apk, 6164 curr, total), true); 6165 } catch (RemoteException e) { 6166 } 6167 } 6168 PackageParser.Package p = pkg; 6169 synchronized (mInstallLock) { 6170 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6171 false /* force dex */, false /* defer */, true /* include dependencies */, 6172 false /* boot complete */, false /*useJit*/); 6173 } 6174 } 6175 6176 @Override 6177 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6178 return performDexOpt(packageName, instructionSet, false); 6179 } 6180 6181 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6182 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6183 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6184 if (!dexopt && !updateUsage) { 6185 // We aren't going to dexopt or update usage, so bail early. 6186 return false; 6187 } 6188 PackageParser.Package p; 6189 final String targetInstructionSet; 6190 synchronized (mPackages) { 6191 p = mPackages.get(packageName); 6192 if (p == null) { 6193 return false; 6194 } 6195 if (updateUsage) { 6196 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6197 } 6198 mPackageUsage.write(false); 6199 if (!dexopt) { 6200 // We aren't going to dexopt, so bail early. 6201 return false; 6202 } 6203 6204 targetInstructionSet = instructionSet != null ? instructionSet : 6205 getPrimaryInstructionSet(p.applicationInfo); 6206 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6207 return false; 6208 } 6209 } 6210 long callingId = Binder.clearCallingIdentity(); 6211 try { 6212 synchronized (mInstallLock) { 6213 final String[] instructionSets = new String[] { targetInstructionSet }; 6214 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6215 false /* forceDex */, false /* defer */, true /* inclDependencies */, 6216 true /* boot complete */, false /*useJit*/); 6217 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6218 } 6219 } finally { 6220 Binder.restoreCallingIdentity(callingId); 6221 } 6222 } 6223 6224 public ArraySet<String> getPackagesThatNeedDexOpt() { 6225 ArraySet<String> pkgs = null; 6226 synchronized (mPackages) { 6227 for (PackageParser.Package p : mPackages.values()) { 6228 if (DEBUG_DEXOPT) { 6229 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6230 } 6231 if (!p.mDexOptPerformed.isEmpty()) { 6232 continue; 6233 } 6234 if (pkgs == null) { 6235 pkgs = new ArraySet<String>(); 6236 } 6237 pkgs.add(p.packageName); 6238 } 6239 } 6240 return pkgs; 6241 } 6242 6243 public void shutdown() { 6244 mPackageUsage.write(true); 6245 } 6246 6247 @Override 6248 public void forceDexOpt(String packageName) { 6249 enforceSystemOrRoot("forceDexOpt"); 6250 6251 PackageParser.Package pkg; 6252 synchronized (mPackages) { 6253 pkg = mPackages.get(packageName); 6254 if (pkg == null) { 6255 throw new IllegalArgumentException("Missing package: " + packageName); 6256 } 6257 } 6258 6259 synchronized (mInstallLock) { 6260 final String[] instructionSets = new String[] { 6261 getPrimaryInstructionSet(pkg.applicationInfo) }; 6262 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6263 true /*forceDex*/, false /* defer */, true /* inclDependencies */, 6264 true /* boot complete */, false /*useJit*/); 6265 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6266 throw new IllegalStateException("Failed to dexopt: " + res); 6267 } 6268 } 6269 } 6270 6271 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6272 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6273 Slog.w(TAG, "Unable to update from " + oldPkg.name 6274 + " to " + newPkg.packageName 6275 + ": old package not in system partition"); 6276 return false; 6277 } else if (mPackages.get(oldPkg.name) != null) { 6278 Slog.w(TAG, "Unable to update from " + oldPkg.name 6279 + " to " + newPkg.packageName 6280 + ": old package still exists"); 6281 return false; 6282 } 6283 return true; 6284 } 6285 6286 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6287 int[] users = sUserManager.getUserIds(); 6288 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6289 if (res < 0) { 6290 return res; 6291 } 6292 for (int user : users) { 6293 if (user != 0) { 6294 res = mInstaller.createUserData(volumeUuid, packageName, 6295 UserHandle.getUid(user, uid), user, seinfo); 6296 if (res < 0) { 6297 return res; 6298 } 6299 } 6300 } 6301 return res; 6302 } 6303 6304 private int removeDataDirsLI(String volumeUuid, String packageName) { 6305 int[] users = sUserManager.getUserIds(); 6306 int res = 0; 6307 for (int user : users) { 6308 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6309 if (resInner < 0) { 6310 res = resInner; 6311 } 6312 } 6313 6314 return res; 6315 } 6316 6317 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6318 int[] users = sUserManager.getUserIds(); 6319 int res = 0; 6320 for (int user : users) { 6321 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6322 if (resInner < 0) { 6323 res = resInner; 6324 } 6325 } 6326 return res; 6327 } 6328 6329 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6330 PackageParser.Package changingLib) { 6331 if (file.path != null) { 6332 usesLibraryFiles.add(file.path); 6333 return; 6334 } 6335 PackageParser.Package p = mPackages.get(file.apk); 6336 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6337 // If we are doing this while in the middle of updating a library apk, 6338 // then we need to make sure to use that new apk for determining the 6339 // dependencies here. (We haven't yet finished committing the new apk 6340 // to the package manager state.) 6341 if (p == null || p.packageName.equals(changingLib.packageName)) { 6342 p = changingLib; 6343 } 6344 } 6345 if (p != null) { 6346 usesLibraryFiles.addAll(p.getAllCodePaths()); 6347 } 6348 } 6349 6350 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6351 PackageParser.Package changingLib) throws PackageManagerException { 6352 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6353 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6354 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6355 for (int i=0; i<N; i++) { 6356 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6357 if (file == null) { 6358 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6359 "Package " + pkg.packageName + " requires unavailable shared library " 6360 + pkg.usesLibraries.get(i) + "; failing!"); 6361 } 6362 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6363 } 6364 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6365 for (int i=0; i<N; i++) { 6366 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6367 if (file == null) { 6368 Slog.w(TAG, "Package " + pkg.packageName 6369 + " desires unavailable shared library " 6370 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6371 } else { 6372 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6373 } 6374 } 6375 N = usesLibraryFiles.size(); 6376 if (N > 0) { 6377 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6378 } else { 6379 pkg.usesLibraryFiles = null; 6380 } 6381 } 6382 } 6383 6384 private static boolean hasString(List<String> list, List<String> which) { 6385 if (list == null) { 6386 return false; 6387 } 6388 for (int i=list.size()-1; i>=0; i--) { 6389 for (int j=which.size()-1; j>=0; j--) { 6390 if (which.get(j).equals(list.get(i))) { 6391 return true; 6392 } 6393 } 6394 } 6395 return false; 6396 } 6397 6398 private void updateAllSharedLibrariesLPw() { 6399 for (PackageParser.Package pkg : mPackages.values()) { 6400 try { 6401 updateSharedLibrariesLPw(pkg, null); 6402 } catch (PackageManagerException e) { 6403 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6404 } 6405 } 6406 } 6407 6408 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6409 PackageParser.Package changingPkg) { 6410 ArrayList<PackageParser.Package> res = null; 6411 for (PackageParser.Package pkg : mPackages.values()) { 6412 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6413 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6414 if (res == null) { 6415 res = new ArrayList<PackageParser.Package>(); 6416 } 6417 res.add(pkg); 6418 try { 6419 updateSharedLibrariesLPw(pkg, changingPkg); 6420 } catch (PackageManagerException e) { 6421 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6422 } 6423 } 6424 } 6425 return res; 6426 } 6427 6428 /** 6429 * Derive the value of the {@code cpuAbiOverride} based on the provided 6430 * value and an optional stored value from the package settings. 6431 */ 6432 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6433 String cpuAbiOverride = null; 6434 6435 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6436 cpuAbiOverride = null; 6437 } else if (abiOverride != null) { 6438 cpuAbiOverride = abiOverride; 6439 } else if (settings != null) { 6440 cpuAbiOverride = settings.cpuAbiOverrideString; 6441 } 6442 6443 return cpuAbiOverride; 6444 } 6445 6446 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6447 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6448 boolean success = false; 6449 try { 6450 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6451 currentTime, user); 6452 success = true; 6453 return res; 6454 } finally { 6455 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6456 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6457 } 6458 } 6459 } 6460 6461 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6462 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6463 final File scanFile = new File(pkg.codePath); 6464 if (pkg.applicationInfo.getCodePath() == null || 6465 pkg.applicationInfo.getResourcePath() == null) { 6466 // Bail out. The resource and code paths haven't been set. 6467 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6468 "Code and resource paths haven't been set correctly"); 6469 } 6470 6471 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6472 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6473 } else { 6474 // Only allow system apps to be flagged as core apps. 6475 pkg.coreApp = false; 6476 } 6477 6478 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6479 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6480 } 6481 6482 if (mCustomResolverComponentName != null && 6483 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6484 setUpCustomResolverActivity(pkg); 6485 } 6486 6487 if (pkg.packageName.equals("android")) { 6488 synchronized (mPackages) { 6489 if (mAndroidApplication != null) { 6490 Slog.w(TAG, "*************************************************"); 6491 Slog.w(TAG, "Core android package being redefined. Skipping."); 6492 Slog.w(TAG, " file=" + scanFile); 6493 Slog.w(TAG, "*************************************************"); 6494 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6495 "Core android package being redefined. Skipping."); 6496 } 6497 6498 // Set up information for our fall-back user intent resolution activity. 6499 mPlatformPackage = pkg; 6500 pkg.mVersionCode = mSdkVersion; 6501 mAndroidApplication = pkg.applicationInfo; 6502 6503 if (!mResolverReplaced) { 6504 mResolveActivity.applicationInfo = mAndroidApplication; 6505 mResolveActivity.name = ResolverActivity.class.getName(); 6506 mResolveActivity.packageName = mAndroidApplication.packageName; 6507 mResolveActivity.processName = "system:ui"; 6508 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6509 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6510 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6511 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6512 mResolveActivity.exported = true; 6513 mResolveActivity.enabled = true; 6514 mResolveInfo.activityInfo = mResolveActivity; 6515 mResolveInfo.priority = 0; 6516 mResolveInfo.preferredOrder = 0; 6517 mResolveInfo.match = 0; 6518 mResolveComponentName = new ComponentName( 6519 mAndroidApplication.packageName, mResolveActivity.name); 6520 } 6521 } 6522 } 6523 6524 if (DEBUG_PACKAGE_SCANNING) { 6525 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6526 Log.d(TAG, "Scanning package " + pkg.packageName); 6527 } 6528 6529 if (mPackages.containsKey(pkg.packageName) 6530 || mSharedLibraries.containsKey(pkg.packageName)) { 6531 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6532 "Application package " + pkg.packageName 6533 + " already installed. Skipping duplicate."); 6534 } 6535 6536 // If we're only installing presumed-existing packages, require that the 6537 // scanned APK is both already known and at the path previously established 6538 // for it. Previously unknown packages we pick up normally, but if we have an 6539 // a priori expectation about this package's install presence, enforce it. 6540 // With a singular exception for new system packages. When an OTA contains 6541 // a new system package, we allow the codepath to change from a system location 6542 // to the user-installed location. If we don't allow this change, any newer, 6543 // user-installed version of the application will be ignored. 6544 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6545 if (mExpectingBetter.containsKey(pkg.packageName)) { 6546 logCriticalInfo(Log.WARN, 6547 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6548 } else { 6549 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6550 if (known != null) { 6551 if (DEBUG_PACKAGE_SCANNING) { 6552 Log.d(TAG, "Examining " + pkg.codePath 6553 + " and requiring known paths " + known.codePathString 6554 + " & " + known.resourcePathString); 6555 } 6556 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6557 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6558 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6559 "Application package " + pkg.packageName 6560 + " found at " + pkg.applicationInfo.getCodePath() 6561 + " but expected at " + known.codePathString + "; ignoring."); 6562 } 6563 } 6564 } 6565 } 6566 6567 // Initialize package source and resource directories 6568 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6569 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6570 6571 SharedUserSetting suid = null; 6572 PackageSetting pkgSetting = null; 6573 6574 if (!isSystemApp(pkg)) { 6575 // Only system apps can use these features. 6576 pkg.mOriginalPackages = null; 6577 pkg.mRealPackage = null; 6578 pkg.mAdoptPermissions = null; 6579 } 6580 6581 // writer 6582 synchronized (mPackages) { 6583 if (pkg.mSharedUserId != null) { 6584 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6585 if (suid == null) { 6586 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6587 "Creating application package " + pkg.packageName 6588 + " for shared user failed"); 6589 } 6590 if (DEBUG_PACKAGE_SCANNING) { 6591 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6592 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6593 + "): packages=" + suid.packages); 6594 } 6595 } 6596 6597 // Check if we are renaming from an original package name. 6598 PackageSetting origPackage = null; 6599 String realName = null; 6600 if (pkg.mOriginalPackages != null) { 6601 // This package may need to be renamed to a previously 6602 // installed name. Let's check on that... 6603 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6604 if (pkg.mOriginalPackages.contains(renamed)) { 6605 // This package had originally been installed as the 6606 // original name, and we have already taken care of 6607 // transitioning to the new one. Just update the new 6608 // one to continue using the old name. 6609 realName = pkg.mRealPackage; 6610 if (!pkg.packageName.equals(renamed)) { 6611 // Callers into this function may have already taken 6612 // care of renaming the package; only do it here if 6613 // it is not already done. 6614 pkg.setPackageName(renamed); 6615 } 6616 6617 } else { 6618 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6619 if ((origPackage = mSettings.peekPackageLPr( 6620 pkg.mOriginalPackages.get(i))) != null) { 6621 // We do have the package already installed under its 6622 // original name... should we use it? 6623 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6624 // New package is not compatible with original. 6625 origPackage = null; 6626 continue; 6627 } else if (origPackage.sharedUser != null) { 6628 // Make sure uid is compatible between packages. 6629 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6630 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6631 + " to " + pkg.packageName + ": old uid " 6632 + origPackage.sharedUser.name 6633 + " differs from " + pkg.mSharedUserId); 6634 origPackage = null; 6635 continue; 6636 } 6637 } else { 6638 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6639 + pkg.packageName + " to old name " + origPackage.name); 6640 } 6641 break; 6642 } 6643 } 6644 } 6645 } 6646 6647 if (mTransferedPackages.contains(pkg.packageName)) { 6648 Slog.w(TAG, "Package " + pkg.packageName 6649 + " was transferred to another, but its .apk remains"); 6650 } 6651 6652 // Just create the setting, don't add it yet. For already existing packages 6653 // the PkgSetting exists already and doesn't have to be created. 6654 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6655 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6656 pkg.applicationInfo.primaryCpuAbi, 6657 pkg.applicationInfo.secondaryCpuAbi, 6658 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6659 user, false); 6660 if (pkgSetting == null) { 6661 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6662 "Creating application package " + pkg.packageName + " failed"); 6663 } 6664 6665 if (pkgSetting.origPackage != null) { 6666 // If we are first transitioning from an original package, 6667 // fix up the new package's name now. We need to do this after 6668 // looking up the package under its new name, so getPackageLP 6669 // can take care of fiddling things correctly. 6670 pkg.setPackageName(origPackage.name); 6671 6672 // File a report about this. 6673 String msg = "New package " + pkgSetting.realName 6674 + " renamed to replace old package " + pkgSetting.name; 6675 reportSettingsProblem(Log.WARN, msg); 6676 6677 // Make a note of it. 6678 mTransferedPackages.add(origPackage.name); 6679 6680 // No longer need to retain this. 6681 pkgSetting.origPackage = null; 6682 } 6683 6684 if (realName != null) { 6685 // Make a note of it. 6686 mTransferedPackages.add(pkg.packageName); 6687 } 6688 6689 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6690 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6691 } 6692 6693 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6694 // Check all shared libraries and map to their actual file path. 6695 // We only do this here for apps not on a system dir, because those 6696 // are the only ones that can fail an install due to this. We 6697 // will take care of the system apps by updating all of their 6698 // library paths after the scan is done. 6699 updateSharedLibrariesLPw(pkg, null); 6700 } 6701 6702 if (mFoundPolicyFile) { 6703 SELinuxMMAC.assignSeinfoValue(pkg); 6704 } 6705 6706 pkg.applicationInfo.uid = pkgSetting.appId; 6707 pkg.mExtras = pkgSetting; 6708 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6709 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6710 // We just determined the app is signed correctly, so bring 6711 // over the latest parsed certs. 6712 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6713 } else { 6714 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6715 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6716 "Package " + pkg.packageName + " upgrade keys do not match the " 6717 + "previously installed version"); 6718 } else { 6719 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6720 String msg = "System package " + pkg.packageName 6721 + " signature changed; retaining data."; 6722 reportSettingsProblem(Log.WARN, msg); 6723 } 6724 } 6725 } else { 6726 try { 6727 verifySignaturesLP(pkgSetting, pkg); 6728 // We just determined the app is signed correctly, so bring 6729 // over the latest parsed certs. 6730 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6731 } catch (PackageManagerException e) { 6732 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6733 throw e; 6734 } 6735 // The signature has changed, but this package is in the system 6736 // image... let's recover! 6737 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6738 // However... if this package is part of a shared user, but it 6739 // doesn't match the signature of the shared user, let's fail. 6740 // What this means is that you can't change the signatures 6741 // associated with an overall shared user, which doesn't seem all 6742 // that unreasonable. 6743 if (pkgSetting.sharedUser != null) { 6744 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6745 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6746 throw new PackageManagerException( 6747 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6748 "Signature mismatch for shared user : " 6749 + pkgSetting.sharedUser); 6750 } 6751 } 6752 // File a report about this. 6753 String msg = "System package " + pkg.packageName 6754 + " signature changed; retaining data."; 6755 reportSettingsProblem(Log.WARN, msg); 6756 } 6757 } 6758 // Verify that this new package doesn't have any content providers 6759 // that conflict with existing packages. Only do this if the 6760 // package isn't already installed, since we don't want to break 6761 // things that are installed. 6762 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6763 final int N = pkg.providers.size(); 6764 int i; 6765 for (i=0; i<N; i++) { 6766 PackageParser.Provider p = pkg.providers.get(i); 6767 if (p.info.authority != null) { 6768 String names[] = p.info.authority.split(";"); 6769 for (int j = 0; j < names.length; j++) { 6770 if (mProvidersByAuthority.containsKey(names[j])) { 6771 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6772 final String otherPackageName = 6773 ((other != null && other.getComponentName() != null) ? 6774 other.getComponentName().getPackageName() : "?"); 6775 throw new PackageManagerException( 6776 INSTALL_FAILED_CONFLICTING_PROVIDER, 6777 "Can't install because provider name " + names[j] 6778 + " (in package " + pkg.applicationInfo.packageName 6779 + ") is already used by " + otherPackageName); 6780 } 6781 } 6782 } 6783 } 6784 } 6785 6786 if (pkg.mAdoptPermissions != null) { 6787 // This package wants to adopt ownership of permissions from 6788 // another package. 6789 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6790 final String origName = pkg.mAdoptPermissions.get(i); 6791 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6792 if (orig != null) { 6793 if (verifyPackageUpdateLPr(orig, pkg)) { 6794 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6795 + pkg.packageName); 6796 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6797 } 6798 } 6799 } 6800 } 6801 } 6802 6803 final String pkgName = pkg.packageName; 6804 6805 final long scanFileTime = scanFile.lastModified(); 6806 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6807 pkg.applicationInfo.processName = fixProcessName( 6808 pkg.applicationInfo.packageName, 6809 pkg.applicationInfo.processName, 6810 pkg.applicationInfo.uid); 6811 6812 File dataPath; 6813 if (mPlatformPackage == pkg) { 6814 // The system package is special. 6815 dataPath = new File(Environment.getDataDirectory(), "system"); 6816 6817 pkg.applicationInfo.dataDir = dataPath.getPath(); 6818 6819 } else { 6820 // This is a normal package, need to make its data directory. 6821 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6822 UserHandle.USER_OWNER, pkg.packageName); 6823 6824 boolean uidError = false; 6825 if (dataPath.exists()) { 6826 int currentUid = 0; 6827 try { 6828 StructStat stat = Os.stat(dataPath.getPath()); 6829 currentUid = stat.st_uid; 6830 } catch (ErrnoException e) { 6831 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6832 } 6833 6834 // If we have mismatched owners for the data path, we have a problem. 6835 if (currentUid != pkg.applicationInfo.uid) { 6836 boolean recovered = false; 6837 if (currentUid == 0) { 6838 // The directory somehow became owned by root. Wow. 6839 // This is probably because the system was stopped while 6840 // installd was in the middle of messing with its libs 6841 // directory. Ask installd to fix that. 6842 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6843 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6844 if (ret >= 0) { 6845 recovered = true; 6846 String msg = "Package " + pkg.packageName 6847 + " unexpectedly changed to uid 0; recovered to " + 6848 + pkg.applicationInfo.uid; 6849 reportSettingsProblem(Log.WARN, msg); 6850 } 6851 } 6852 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6853 || (scanFlags&SCAN_BOOTING) != 0)) { 6854 // If this is a system app, we can at least delete its 6855 // current data so the application will still work. 6856 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6857 if (ret >= 0) { 6858 // TODO: Kill the processes first 6859 // Old data gone! 6860 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6861 ? "System package " : "Third party package "; 6862 String msg = prefix + pkg.packageName 6863 + " has changed from uid: " 6864 + currentUid + " to " 6865 + pkg.applicationInfo.uid + "; old data erased"; 6866 reportSettingsProblem(Log.WARN, msg); 6867 recovered = true; 6868 6869 // And now re-install the app. 6870 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6871 pkg.applicationInfo.seinfo); 6872 if (ret == -1) { 6873 // Ack should not happen! 6874 msg = prefix + pkg.packageName 6875 + " could not have data directory re-created after delete."; 6876 reportSettingsProblem(Log.WARN, msg); 6877 throw new PackageManagerException( 6878 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6879 } 6880 } 6881 if (!recovered) { 6882 mHasSystemUidErrors = true; 6883 } 6884 } else if (!recovered) { 6885 // If we allow this install to proceed, we will be broken. 6886 // Abort, abort! 6887 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6888 "scanPackageLI"); 6889 } 6890 if (!recovered) { 6891 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6892 + pkg.applicationInfo.uid + "/fs_" 6893 + currentUid; 6894 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6895 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6896 String msg = "Package " + pkg.packageName 6897 + " has mismatched uid: " 6898 + currentUid + " on disk, " 6899 + pkg.applicationInfo.uid + " in settings"; 6900 // writer 6901 synchronized (mPackages) { 6902 mSettings.mReadMessages.append(msg); 6903 mSettings.mReadMessages.append('\n'); 6904 uidError = true; 6905 if (!pkgSetting.uidError) { 6906 reportSettingsProblem(Log.ERROR, msg); 6907 } 6908 } 6909 } 6910 } 6911 pkg.applicationInfo.dataDir = dataPath.getPath(); 6912 if (mShouldRestoreconData) { 6913 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6914 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6915 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6916 } 6917 } else { 6918 if (DEBUG_PACKAGE_SCANNING) { 6919 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6920 Log.v(TAG, "Want this data dir: " + dataPath); 6921 } 6922 //invoke installer to do the actual installation 6923 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6924 pkg.applicationInfo.seinfo); 6925 if (ret < 0) { 6926 // Error from installer 6927 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6928 "Unable to create data dirs [errorCode=" + ret + "]"); 6929 } 6930 6931 if (dataPath.exists()) { 6932 pkg.applicationInfo.dataDir = dataPath.getPath(); 6933 } else { 6934 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6935 pkg.applicationInfo.dataDir = null; 6936 } 6937 } 6938 6939 pkgSetting.uidError = uidError; 6940 } 6941 6942 final String path = scanFile.getPath(); 6943 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6944 6945 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6946 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6947 6948 // Some system apps still use directory structure for native libraries 6949 // in which case we might end up not detecting abi solely based on apk 6950 // structure. Try to detect abi based on directory structure. 6951 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6952 pkg.applicationInfo.primaryCpuAbi == null) { 6953 setBundledAppAbisAndRoots(pkg, pkgSetting); 6954 setNativeLibraryPaths(pkg); 6955 } 6956 6957 } else { 6958 if ((scanFlags & SCAN_MOVE) != 0) { 6959 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6960 // but we already have this packages package info in the PackageSetting. We just 6961 // use that and derive the native library path based on the new codepath. 6962 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6963 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6964 } 6965 6966 // Set native library paths again. For moves, the path will be updated based on the 6967 // ABIs we've determined above. For non-moves, the path will be updated based on the 6968 // ABIs we determined during compilation, but the path will depend on the final 6969 // package path (after the rename away from the stage path). 6970 setNativeLibraryPaths(pkg); 6971 } 6972 6973 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6974 final int[] userIds = sUserManager.getUserIds(); 6975 synchronized (mInstallLock) { 6976 // Make sure all user data directories are ready to roll; we're okay 6977 // if they already exist 6978 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6979 for (int userId : userIds) { 6980 if (userId != 0) { 6981 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6982 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6983 pkg.applicationInfo.seinfo); 6984 } 6985 } 6986 } 6987 6988 // Create a native library symlink only if we have native libraries 6989 // and if the native libraries are 32 bit libraries. We do not provide 6990 // this symlink for 64 bit libraries. 6991 if (pkg.applicationInfo.primaryCpuAbi != null && 6992 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6993 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6994 for (int userId : userIds) { 6995 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6996 nativeLibPath, userId) < 0) { 6997 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6998 "Failed linking native library dir (user=" + userId + ")"); 6999 } 7000 } 7001 } 7002 } 7003 7004 // This is a special case for the "system" package, where the ABI is 7005 // dictated by the zygote configuration (and init.rc). We should keep track 7006 // of this ABI so that we can deal with "normal" applications that run under 7007 // the same UID correctly. 7008 if (mPlatformPackage == pkg) { 7009 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7010 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7011 } 7012 7013 // If there's a mismatch between the abi-override in the package setting 7014 // and the abiOverride specified for the install. Warn about this because we 7015 // would've already compiled the app without taking the package setting into 7016 // account. 7017 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7018 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7019 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7020 " for package: " + pkg.packageName); 7021 } 7022 } 7023 7024 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7025 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7026 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7027 7028 // Copy the derived override back to the parsed package, so that we can 7029 // update the package settings accordingly. 7030 pkg.cpuAbiOverride = cpuAbiOverride; 7031 7032 if (DEBUG_ABI_SELECTION) { 7033 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7034 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7035 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7036 } 7037 7038 // Push the derived path down into PackageSettings so we know what to 7039 // clean up at uninstall time. 7040 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7041 7042 if (DEBUG_ABI_SELECTION) { 7043 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7044 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7045 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7046 } 7047 7048 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7049 // We don't do this here during boot because we can do it all 7050 // at once after scanning all existing packages. 7051 // 7052 // We also do this *before* we perform dexopt on this package, so that 7053 // we can avoid redundant dexopts, and also to make sure we've got the 7054 // code and package path correct. 7055 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7056 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */); 7057 } 7058 7059 if ((scanFlags & SCAN_NO_DEX) == 0) { 7060 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7061 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */, 7062 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7063 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7064 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7065 } 7066 } 7067 if (mFactoryTest && pkg.requestedPermissions.contains( 7068 android.Manifest.permission.FACTORY_TEST)) { 7069 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7070 } 7071 7072 ArrayList<PackageParser.Package> clientLibPkgs = null; 7073 7074 // writer 7075 synchronized (mPackages) { 7076 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7077 // Only system apps can add new shared libraries. 7078 if (pkg.libraryNames != null) { 7079 for (int i=0; i<pkg.libraryNames.size(); i++) { 7080 String name = pkg.libraryNames.get(i); 7081 boolean allowed = false; 7082 if (pkg.isUpdatedSystemApp()) { 7083 // New library entries can only be added through the 7084 // system image. This is important to get rid of a lot 7085 // of nasty edge cases: for example if we allowed a non- 7086 // system update of the app to add a library, then uninstalling 7087 // the update would make the library go away, and assumptions 7088 // we made such as through app install filtering would now 7089 // have allowed apps on the device which aren't compatible 7090 // with it. Better to just have the restriction here, be 7091 // conservative, and create many fewer cases that can negatively 7092 // impact the user experience. 7093 final PackageSetting sysPs = mSettings 7094 .getDisabledSystemPkgLPr(pkg.packageName); 7095 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7096 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7097 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7098 allowed = true; 7099 allowed = true; 7100 break; 7101 } 7102 } 7103 } 7104 } else { 7105 allowed = true; 7106 } 7107 if (allowed) { 7108 if (!mSharedLibraries.containsKey(name)) { 7109 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7110 } else if (!name.equals(pkg.packageName)) { 7111 Slog.w(TAG, "Package " + pkg.packageName + " library " 7112 + name + " already exists; skipping"); 7113 } 7114 } else { 7115 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7116 + name + " that is not declared on system image; skipping"); 7117 } 7118 } 7119 if ((scanFlags&SCAN_BOOTING) == 0) { 7120 // If we are not booting, we need to update any applications 7121 // that are clients of our shared library. If we are booting, 7122 // this will all be done once the scan is complete. 7123 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7124 } 7125 } 7126 } 7127 } 7128 7129 // We also need to dexopt any apps that are dependent on this library. Note that 7130 // if these fail, we should abort the install since installing the library will 7131 // result in some apps being broken. 7132 if (clientLibPkgs != null) { 7133 if ((scanFlags & SCAN_NO_DEX) == 0) { 7134 for (int i = 0; i < clientLibPkgs.size(); i++) { 7135 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7136 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7137 null /* instruction sets */, forceDex, 7138 (scanFlags & SCAN_DEFER_DEX) != 0, false, 7139 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7140 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7141 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7142 "scanPackageLI failed to dexopt clientLibPkgs"); 7143 } 7144 } 7145 } 7146 } 7147 7148 // Request the ActivityManager to kill the process(only for existing packages) 7149 // so that we do not end up in a confused state while the user is still using the older 7150 // version of the application while the new one gets installed. 7151 if ((scanFlags & SCAN_REPLACING) != 0) { 7152 killApplication(pkg.applicationInfo.packageName, 7153 pkg.applicationInfo.uid, "replace pkg"); 7154 } 7155 7156 // Also need to kill any apps that are dependent on the library. 7157 if (clientLibPkgs != null) { 7158 for (int i=0; i<clientLibPkgs.size(); i++) { 7159 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7160 killApplication(clientPkg.applicationInfo.packageName, 7161 clientPkg.applicationInfo.uid, "update lib"); 7162 } 7163 } 7164 7165 // Make sure we're not adding any bogus keyset info 7166 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7167 ksms.assertScannedPackageValid(pkg); 7168 7169 // writer 7170 synchronized (mPackages) { 7171 // We don't expect installation to fail beyond this point 7172 7173 // Add the new setting to mSettings 7174 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7175 // Add the new setting to mPackages 7176 mPackages.put(pkg.applicationInfo.packageName, pkg); 7177 // Make sure we don't accidentally delete its data. 7178 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7179 while (iter.hasNext()) { 7180 PackageCleanItem item = iter.next(); 7181 if (pkgName.equals(item.packageName)) { 7182 iter.remove(); 7183 } 7184 } 7185 7186 // Take care of first install / last update times. 7187 if (currentTime != 0) { 7188 if (pkgSetting.firstInstallTime == 0) { 7189 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7190 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7191 pkgSetting.lastUpdateTime = currentTime; 7192 } 7193 } else if (pkgSetting.firstInstallTime == 0) { 7194 // We need *something*. Take time time stamp of the file. 7195 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7196 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7197 if (scanFileTime != pkgSetting.timeStamp) { 7198 // A package on the system image has changed; consider this 7199 // to be an update. 7200 pkgSetting.lastUpdateTime = scanFileTime; 7201 } 7202 } 7203 7204 // Add the package's KeySets to the global KeySetManagerService 7205 ksms.addScannedPackageLPw(pkg); 7206 7207 int N = pkg.providers.size(); 7208 StringBuilder r = null; 7209 int i; 7210 for (i=0; i<N; i++) { 7211 PackageParser.Provider p = pkg.providers.get(i); 7212 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7213 p.info.processName, pkg.applicationInfo.uid); 7214 mProviders.addProvider(p); 7215 p.syncable = p.info.isSyncable; 7216 if (p.info.authority != null) { 7217 String names[] = p.info.authority.split(";"); 7218 p.info.authority = null; 7219 for (int j = 0; j < names.length; j++) { 7220 if (j == 1 && p.syncable) { 7221 // We only want the first authority for a provider to possibly be 7222 // syncable, so if we already added this provider using a different 7223 // authority clear the syncable flag. We copy the provider before 7224 // changing it because the mProviders object contains a reference 7225 // to a provider that we don't want to change. 7226 // Only do this for the second authority since the resulting provider 7227 // object can be the same for all future authorities for this provider. 7228 p = new PackageParser.Provider(p); 7229 p.syncable = false; 7230 } 7231 if (!mProvidersByAuthority.containsKey(names[j])) { 7232 mProvidersByAuthority.put(names[j], p); 7233 if (p.info.authority == null) { 7234 p.info.authority = names[j]; 7235 } else { 7236 p.info.authority = p.info.authority + ";" + names[j]; 7237 } 7238 if (DEBUG_PACKAGE_SCANNING) { 7239 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7240 Log.d(TAG, "Registered content provider: " + names[j] 7241 + ", className = " + p.info.name + ", isSyncable = " 7242 + p.info.isSyncable); 7243 } 7244 } else { 7245 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7246 Slog.w(TAG, "Skipping provider name " + names[j] + 7247 " (in package " + pkg.applicationInfo.packageName + 7248 "): name already used by " 7249 + ((other != null && other.getComponentName() != null) 7250 ? other.getComponentName().getPackageName() : "?")); 7251 } 7252 } 7253 } 7254 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7255 if (r == null) { 7256 r = new StringBuilder(256); 7257 } else { 7258 r.append(' '); 7259 } 7260 r.append(p.info.name); 7261 } 7262 } 7263 if (r != null) { 7264 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7265 } 7266 7267 N = pkg.services.size(); 7268 r = null; 7269 for (i=0; i<N; i++) { 7270 PackageParser.Service s = pkg.services.get(i); 7271 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7272 s.info.processName, pkg.applicationInfo.uid); 7273 mServices.addService(s); 7274 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7275 if (r == null) { 7276 r = new StringBuilder(256); 7277 } else { 7278 r.append(' '); 7279 } 7280 r.append(s.info.name); 7281 } 7282 } 7283 if (r != null) { 7284 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7285 } 7286 7287 N = pkg.receivers.size(); 7288 r = null; 7289 for (i=0; i<N; i++) { 7290 PackageParser.Activity a = pkg.receivers.get(i); 7291 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7292 a.info.processName, pkg.applicationInfo.uid); 7293 mReceivers.addActivity(a, "receiver"); 7294 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7295 if (r == null) { 7296 r = new StringBuilder(256); 7297 } else { 7298 r.append(' '); 7299 } 7300 r.append(a.info.name); 7301 } 7302 } 7303 if (r != null) { 7304 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7305 } 7306 7307 N = pkg.activities.size(); 7308 r = null; 7309 for (i=0; i<N; i++) { 7310 PackageParser.Activity a = pkg.activities.get(i); 7311 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7312 a.info.processName, pkg.applicationInfo.uid); 7313 mActivities.addActivity(a, "activity"); 7314 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7315 if (r == null) { 7316 r = new StringBuilder(256); 7317 } else { 7318 r.append(' '); 7319 } 7320 r.append(a.info.name); 7321 } 7322 } 7323 if (r != null) { 7324 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7325 } 7326 7327 N = pkg.permissionGroups.size(); 7328 r = null; 7329 for (i=0; i<N; i++) { 7330 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7331 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7332 if (cur == null) { 7333 mPermissionGroups.put(pg.info.name, pg); 7334 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7335 if (r == null) { 7336 r = new StringBuilder(256); 7337 } else { 7338 r.append(' '); 7339 } 7340 r.append(pg.info.name); 7341 } 7342 } else { 7343 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7344 + pg.info.packageName + " ignored: original from " 7345 + cur.info.packageName); 7346 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7347 if (r == null) { 7348 r = new StringBuilder(256); 7349 } else { 7350 r.append(' '); 7351 } 7352 r.append("DUP:"); 7353 r.append(pg.info.name); 7354 } 7355 } 7356 } 7357 if (r != null) { 7358 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7359 } 7360 7361 N = pkg.permissions.size(); 7362 r = null; 7363 for (i=0; i<N; i++) { 7364 PackageParser.Permission p = pkg.permissions.get(i); 7365 7366 // Assume by default that we did not install this permission into the system. 7367 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7368 7369 // Now that permission groups have a special meaning, we ignore permission 7370 // groups for legacy apps to prevent unexpected behavior. In particular, 7371 // permissions for one app being granted to someone just becuase they happen 7372 // to be in a group defined by another app (before this had no implications). 7373 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7374 p.group = mPermissionGroups.get(p.info.group); 7375 // Warn for a permission in an unknown group. 7376 if (p.info.group != null && p.group == null) { 7377 Slog.w(TAG, "Permission " + p.info.name + " from package " 7378 + p.info.packageName + " in an unknown group " + p.info.group); 7379 } 7380 } 7381 7382 ArrayMap<String, BasePermission> permissionMap = 7383 p.tree ? mSettings.mPermissionTrees 7384 : mSettings.mPermissions; 7385 BasePermission bp = permissionMap.get(p.info.name); 7386 7387 // Allow system apps to redefine non-system permissions 7388 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7389 final boolean currentOwnerIsSystem = (bp.perm != null 7390 && isSystemApp(bp.perm.owner)); 7391 if (isSystemApp(p.owner)) { 7392 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7393 // It's a built-in permission and no owner, take ownership now 7394 bp.packageSetting = pkgSetting; 7395 bp.perm = p; 7396 bp.uid = pkg.applicationInfo.uid; 7397 bp.sourcePackage = p.info.packageName; 7398 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7399 } else if (!currentOwnerIsSystem) { 7400 String msg = "New decl " + p.owner + " of permission " 7401 + p.info.name + " is system; overriding " + bp.sourcePackage; 7402 reportSettingsProblem(Log.WARN, msg); 7403 bp = null; 7404 } 7405 } 7406 } 7407 7408 if (bp == null) { 7409 bp = new BasePermission(p.info.name, p.info.packageName, 7410 BasePermission.TYPE_NORMAL); 7411 permissionMap.put(p.info.name, bp); 7412 } 7413 7414 if (bp.perm == null) { 7415 if (bp.sourcePackage == null 7416 || bp.sourcePackage.equals(p.info.packageName)) { 7417 BasePermission tree = findPermissionTreeLP(p.info.name); 7418 if (tree == null 7419 || tree.sourcePackage.equals(p.info.packageName)) { 7420 bp.packageSetting = pkgSetting; 7421 bp.perm = p; 7422 bp.uid = pkg.applicationInfo.uid; 7423 bp.sourcePackage = p.info.packageName; 7424 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7425 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7426 if (r == null) { 7427 r = new StringBuilder(256); 7428 } else { 7429 r.append(' '); 7430 } 7431 r.append(p.info.name); 7432 } 7433 } else { 7434 Slog.w(TAG, "Permission " + p.info.name + " from package " 7435 + p.info.packageName + " ignored: base tree " 7436 + tree.name + " is from package " 7437 + tree.sourcePackage); 7438 } 7439 } else { 7440 Slog.w(TAG, "Permission " + p.info.name + " from package " 7441 + p.info.packageName + " ignored: original from " 7442 + bp.sourcePackage); 7443 } 7444 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7445 if (r == null) { 7446 r = new StringBuilder(256); 7447 } else { 7448 r.append(' '); 7449 } 7450 r.append("DUP:"); 7451 r.append(p.info.name); 7452 } 7453 if (bp.perm == p) { 7454 bp.protectionLevel = p.info.protectionLevel; 7455 } 7456 } 7457 7458 if (r != null) { 7459 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7460 } 7461 7462 N = pkg.instrumentation.size(); 7463 r = null; 7464 for (i=0; i<N; i++) { 7465 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7466 a.info.packageName = pkg.applicationInfo.packageName; 7467 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7468 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7469 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7470 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7471 a.info.dataDir = pkg.applicationInfo.dataDir; 7472 7473 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7474 // need other information about the application, like the ABI and what not ? 7475 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7476 mInstrumentation.put(a.getComponentName(), a); 7477 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7478 if (r == null) { 7479 r = new StringBuilder(256); 7480 } else { 7481 r.append(' '); 7482 } 7483 r.append(a.info.name); 7484 } 7485 } 7486 if (r != null) { 7487 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7488 } 7489 7490 if (pkg.protectedBroadcasts != null) { 7491 N = pkg.protectedBroadcasts.size(); 7492 for (i=0; i<N; i++) { 7493 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7494 } 7495 } 7496 7497 pkgSetting.setTimeStamp(scanFileTime); 7498 7499 // Create idmap files for pairs of (packages, overlay packages). 7500 // Note: "android", ie framework-res.apk, is handled by native layers. 7501 if (pkg.mOverlayTarget != null) { 7502 // This is an overlay package. 7503 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7504 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7505 mOverlays.put(pkg.mOverlayTarget, 7506 new ArrayMap<String, PackageParser.Package>()); 7507 } 7508 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7509 map.put(pkg.packageName, pkg); 7510 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7511 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7512 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7513 "scanPackageLI failed to createIdmap"); 7514 } 7515 } 7516 } else if (mOverlays.containsKey(pkg.packageName) && 7517 !pkg.packageName.equals("android")) { 7518 // This is a regular package, with one or more known overlay packages. 7519 createIdmapsForPackageLI(pkg); 7520 } 7521 } 7522 7523 return pkg; 7524 } 7525 7526 /** 7527 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7528 * is derived purely on the basis of the contents of {@code scanFile} and 7529 * {@code cpuAbiOverride}. 7530 * 7531 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7532 */ 7533 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7534 String cpuAbiOverride, boolean extractLibs) 7535 throws PackageManagerException { 7536 // TODO: We can probably be smarter about this stuff. For installed apps, 7537 // we can calculate this information at install time once and for all. For 7538 // system apps, we can probably assume that this information doesn't change 7539 // after the first boot scan. As things stand, we do lots of unnecessary work. 7540 7541 // Give ourselves some initial paths; we'll come back for another 7542 // pass once we've determined ABI below. 7543 setNativeLibraryPaths(pkg); 7544 7545 // We would never need to extract libs for forward-locked and external packages, 7546 // since the container service will do it for us. We shouldn't attempt to 7547 // extract libs from system app when it was not updated. 7548 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7549 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7550 extractLibs = false; 7551 } 7552 7553 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7554 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7555 7556 NativeLibraryHelper.Handle handle = null; 7557 try { 7558 handle = NativeLibraryHelper.Handle.create(scanFile); 7559 // TODO(multiArch): This can be null for apps that didn't go through the 7560 // usual installation process. We can calculate it again, like we 7561 // do during install time. 7562 // 7563 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7564 // unnecessary. 7565 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7566 7567 // Null out the abis so that they can be recalculated. 7568 pkg.applicationInfo.primaryCpuAbi = null; 7569 pkg.applicationInfo.secondaryCpuAbi = null; 7570 if (isMultiArch(pkg.applicationInfo)) { 7571 // Warn if we've set an abiOverride for multi-lib packages.. 7572 // By definition, we need to copy both 32 and 64 bit libraries for 7573 // such packages. 7574 if (pkg.cpuAbiOverride != null 7575 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7576 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7577 } 7578 7579 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7580 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7581 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7582 if (extractLibs) { 7583 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7584 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7585 useIsaSpecificSubdirs); 7586 } else { 7587 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7588 } 7589 } 7590 7591 maybeThrowExceptionForMultiArchCopy( 7592 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7593 7594 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7595 if (extractLibs) { 7596 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7597 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7598 useIsaSpecificSubdirs); 7599 } else { 7600 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7601 } 7602 } 7603 7604 maybeThrowExceptionForMultiArchCopy( 7605 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7606 7607 if (abi64 >= 0) { 7608 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7609 } 7610 7611 if (abi32 >= 0) { 7612 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7613 if (abi64 >= 0) { 7614 pkg.applicationInfo.secondaryCpuAbi = abi; 7615 } else { 7616 pkg.applicationInfo.primaryCpuAbi = abi; 7617 } 7618 } 7619 } else { 7620 String[] abiList = (cpuAbiOverride != null) ? 7621 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7622 7623 // Enable gross and lame hacks for apps that are built with old 7624 // SDK tools. We must scan their APKs for renderscript bitcode and 7625 // not launch them if it's present. Don't bother checking on devices 7626 // that don't have 64 bit support. 7627 boolean needsRenderScriptOverride = false; 7628 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7629 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7630 abiList = Build.SUPPORTED_32_BIT_ABIS; 7631 needsRenderScriptOverride = true; 7632 } 7633 7634 final int copyRet; 7635 if (extractLibs) { 7636 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7637 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7638 } else { 7639 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7640 } 7641 7642 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7643 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7644 "Error unpackaging native libs for app, errorCode=" + copyRet); 7645 } 7646 7647 if (copyRet >= 0) { 7648 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7649 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7650 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7651 } else if (needsRenderScriptOverride) { 7652 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7653 } 7654 } 7655 } catch (IOException ioe) { 7656 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7657 } finally { 7658 IoUtils.closeQuietly(handle); 7659 } 7660 7661 // Now that we've calculated the ABIs and determined if it's an internal app, 7662 // we will go ahead and populate the nativeLibraryPath. 7663 setNativeLibraryPaths(pkg); 7664 } 7665 7666 /** 7667 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7668 * i.e, so that all packages can be run inside a single process if required. 7669 * 7670 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7671 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7672 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7673 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7674 * updating a package that belongs to a shared user. 7675 * 7676 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7677 * adds unnecessary complexity. 7678 */ 7679 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7680 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt, 7681 boolean bootComplete) { 7682 String requiredInstructionSet = null; 7683 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7684 requiredInstructionSet = VMRuntime.getInstructionSet( 7685 scannedPackage.applicationInfo.primaryCpuAbi); 7686 } 7687 7688 PackageSetting requirer = null; 7689 for (PackageSetting ps : packagesForUser) { 7690 // If packagesForUser contains scannedPackage, we skip it. This will happen 7691 // when scannedPackage is an update of an existing package. Without this check, 7692 // we will never be able to change the ABI of any package belonging to a shared 7693 // user, even if it's compatible with other packages. 7694 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7695 if (ps.primaryCpuAbiString == null) { 7696 continue; 7697 } 7698 7699 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7700 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7701 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7702 // this but there's not much we can do. 7703 String errorMessage = "Instruction set mismatch, " 7704 + ((requirer == null) ? "[caller]" : requirer) 7705 + " requires " + requiredInstructionSet + " whereas " + ps 7706 + " requires " + instructionSet; 7707 Slog.w(TAG, errorMessage); 7708 } 7709 7710 if (requiredInstructionSet == null) { 7711 requiredInstructionSet = instructionSet; 7712 requirer = ps; 7713 } 7714 } 7715 } 7716 7717 if (requiredInstructionSet != null) { 7718 String adjustedAbi; 7719 if (requirer != null) { 7720 // requirer != null implies that either scannedPackage was null or that scannedPackage 7721 // did not require an ABI, in which case we have to adjust scannedPackage to match 7722 // the ABI of the set (which is the same as requirer's ABI) 7723 adjustedAbi = requirer.primaryCpuAbiString; 7724 if (scannedPackage != null) { 7725 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7726 } 7727 } else { 7728 // requirer == null implies that we're updating all ABIs in the set to 7729 // match scannedPackage. 7730 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7731 } 7732 7733 for (PackageSetting ps : packagesForUser) { 7734 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7735 if (ps.primaryCpuAbiString != null) { 7736 continue; 7737 } 7738 7739 ps.primaryCpuAbiString = adjustedAbi; 7740 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7741 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7742 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7743 7744 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7745 null /* instruction sets */, forceDexOpt, deferDexOpt, true, 7746 bootComplete, false /*useJit*/); 7747 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7748 ps.primaryCpuAbiString = null; 7749 ps.pkg.applicationInfo.primaryCpuAbi = null; 7750 return; 7751 } else { 7752 mInstaller.rmdex(ps.codePathString, 7753 getDexCodeInstructionSet(getPreferredInstructionSet())); 7754 } 7755 } 7756 } 7757 } 7758 } 7759 } 7760 7761 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7762 synchronized (mPackages) { 7763 mResolverReplaced = true; 7764 // Set up information for custom user intent resolution activity. 7765 mResolveActivity.applicationInfo = pkg.applicationInfo; 7766 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7767 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7768 mResolveActivity.processName = pkg.applicationInfo.packageName; 7769 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7770 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7771 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7772 mResolveActivity.theme = 0; 7773 mResolveActivity.exported = true; 7774 mResolveActivity.enabled = true; 7775 mResolveInfo.activityInfo = mResolveActivity; 7776 mResolveInfo.priority = 0; 7777 mResolveInfo.preferredOrder = 0; 7778 mResolveInfo.match = 0; 7779 mResolveComponentName = mCustomResolverComponentName; 7780 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7781 mResolveComponentName); 7782 } 7783 } 7784 7785 private static String calculateBundledApkRoot(final String codePathString) { 7786 final File codePath = new File(codePathString); 7787 final File codeRoot; 7788 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7789 codeRoot = Environment.getRootDirectory(); 7790 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7791 codeRoot = Environment.getOemDirectory(); 7792 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7793 codeRoot = Environment.getVendorDirectory(); 7794 } else { 7795 // Unrecognized code path; take its top real segment as the apk root: 7796 // e.g. /something/app/blah.apk => /something 7797 try { 7798 File f = codePath.getCanonicalFile(); 7799 File parent = f.getParentFile(); // non-null because codePath is a file 7800 File tmp; 7801 while ((tmp = parent.getParentFile()) != null) { 7802 f = parent; 7803 parent = tmp; 7804 } 7805 codeRoot = f; 7806 Slog.w(TAG, "Unrecognized code path " 7807 + codePath + " - using " + codeRoot); 7808 } catch (IOException e) { 7809 // Can't canonicalize the code path -- shenanigans? 7810 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7811 return Environment.getRootDirectory().getPath(); 7812 } 7813 } 7814 return codeRoot.getPath(); 7815 } 7816 7817 /** 7818 * Derive and set the location of native libraries for the given package, 7819 * which varies depending on where and how the package was installed. 7820 */ 7821 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7822 final ApplicationInfo info = pkg.applicationInfo; 7823 final String codePath = pkg.codePath; 7824 final File codeFile = new File(codePath); 7825 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7826 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 7827 7828 info.nativeLibraryRootDir = null; 7829 info.nativeLibraryRootRequiresIsa = false; 7830 info.nativeLibraryDir = null; 7831 info.secondaryNativeLibraryDir = null; 7832 7833 if (isApkFile(codeFile)) { 7834 // Monolithic install 7835 if (bundledApp) { 7836 // If "/system/lib64/apkname" exists, assume that is the per-package 7837 // native library directory to use; otherwise use "/system/lib/apkname". 7838 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7839 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7840 getPrimaryInstructionSet(info)); 7841 7842 // This is a bundled system app so choose the path based on the ABI. 7843 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7844 // is just the default path. 7845 final String apkName = deriveCodePathName(codePath); 7846 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7847 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7848 apkName).getAbsolutePath(); 7849 7850 if (info.secondaryCpuAbi != null) { 7851 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7852 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7853 secondaryLibDir, apkName).getAbsolutePath(); 7854 } 7855 } else if (asecApp) { 7856 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7857 .getAbsolutePath(); 7858 } else { 7859 final String apkName = deriveCodePathName(codePath); 7860 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7861 .getAbsolutePath(); 7862 } 7863 7864 info.nativeLibraryRootRequiresIsa = false; 7865 info.nativeLibraryDir = info.nativeLibraryRootDir; 7866 } else { 7867 // Cluster install 7868 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7869 info.nativeLibraryRootRequiresIsa = true; 7870 7871 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7872 getPrimaryInstructionSet(info)).getAbsolutePath(); 7873 7874 if (info.secondaryCpuAbi != null) { 7875 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7876 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7877 } 7878 } 7879 } 7880 7881 /** 7882 * Calculate the abis and roots for a bundled app. These can uniquely 7883 * be determined from the contents of the system partition, i.e whether 7884 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7885 * of this information, and instead assume that the system was built 7886 * sensibly. 7887 */ 7888 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7889 PackageSetting pkgSetting) { 7890 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7891 7892 // If "/system/lib64/apkname" exists, assume that is the per-package 7893 // native library directory to use; otherwise use "/system/lib/apkname". 7894 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7895 setBundledAppAbi(pkg, apkRoot, apkName); 7896 // pkgSetting might be null during rescan following uninstall of updates 7897 // to a bundled app, so accommodate that possibility. The settings in 7898 // that case will be established later from the parsed package. 7899 // 7900 // If the settings aren't null, sync them up with what we've just derived. 7901 // note that apkRoot isn't stored in the package settings. 7902 if (pkgSetting != null) { 7903 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7904 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7905 } 7906 } 7907 7908 /** 7909 * Deduces the ABI of a bundled app and sets the relevant fields on the 7910 * parsed pkg object. 7911 * 7912 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7913 * under which system libraries are installed. 7914 * @param apkName the name of the installed package. 7915 */ 7916 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7917 final File codeFile = new File(pkg.codePath); 7918 7919 final boolean has64BitLibs; 7920 final boolean has32BitLibs; 7921 if (isApkFile(codeFile)) { 7922 // Monolithic install 7923 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7924 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7925 } else { 7926 // Cluster install 7927 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7928 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7929 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7930 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7931 has64BitLibs = (new File(rootDir, isa)).exists(); 7932 } else { 7933 has64BitLibs = false; 7934 } 7935 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7936 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7937 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7938 has32BitLibs = (new File(rootDir, isa)).exists(); 7939 } else { 7940 has32BitLibs = false; 7941 } 7942 } 7943 7944 if (has64BitLibs && !has32BitLibs) { 7945 // The package has 64 bit libs, but not 32 bit libs. Its primary 7946 // ABI should be 64 bit. We can safely assume here that the bundled 7947 // native libraries correspond to the most preferred ABI in the list. 7948 7949 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7950 pkg.applicationInfo.secondaryCpuAbi = null; 7951 } else if (has32BitLibs && !has64BitLibs) { 7952 // The package has 32 bit libs but not 64 bit libs. Its primary 7953 // ABI should be 32 bit. 7954 7955 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7956 pkg.applicationInfo.secondaryCpuAbi = null; 7957 } else if (has32BitLibs && has64BitLibs) { 7958 // The application has both 64 and 32 bit bundled libraries. We check 7959 // here that the app declares multiArch support, and warn if it doesn't. 7960 // 7961 // We will be lenient here and record both ABIs. The primary will be the 7962 // ABI that's higher on the list, i.e, a device that's configured to prefer 7963 // 64 bit apps will see a 64 bit primary ABI, 7964 7965 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7966 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7967 } 7968 7969 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7970 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7971 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7972 } else { 7973 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7974 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7975 } 7976 } else { 7977 pkg.applicationInfo.primaryCpuAbi = null; 7978 pkg.applicationInfo.secondaryCpuAbi = null; 7979 } 7980 } 7981 7982 private void killApplication(String pkgName, int appId, String reason) { 7983 // Request the ActivityManager to kill the process(only for existing packages) 7984 // so that we do not end up in a confused state while the user is still using the older 7985 // version of the application while the new one gets installed. 7986 IActivityManager am = ActivityManagerNative.getDefault(); 7987 if (am != null) { 7988 try { 7989 am.killApplicationWithAppId(pkgName, appId, reason); 7990 } catch (RemoteException e) { 7991 } 7992 } 7993 } 7994 7995 void removePackageLI(PackageSetting ps, boolean chatty) { 7996 if (DEBUG_INSTALL) { 7997 if (chatty) 7998 Log.d(TAG, "Removing package " + ps.name); 7999 } 8000 8001 // writer 8002 synchronized (mPackages) { 8003 mPackages.remove(ps.name); 8004 final PackageParser.Package pkg = ps.pkg; 8005 if (pkg != null) { 8006 cleanPackageDataStructuresLILPw(pkg, chatty); 8007 } 8008 } 8009 } 8010 8011 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8012 if (DEBUG_INSTALL) { 8013 if (chatty) 8014 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8015 } 8016 8017 // writer 8018 synchronized (mPackages) { 8019 mPackages.remove(pkg.applicationInfo.packageName); 8020 cleanPackageDataStructuresLILPw(pkg, chatty); 8021 } 8022 } 8023 8024 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8025 int N = pkg.providers.size(); 8026 StringBuilder r = null; 8027 int i; 8028 for (i=0; i<N; i++) { 8029 PackageParser.Provider p = pkg.providers.get(i); 8030 mProviders.removeProvider(p); 8031 if (p.info.authority == null) { 8032 8033 /* There was another ContentProvider with this authority when 8034 * this app was installed so this authority is null, 8035 * Ignore it as we don't have to unregister the provider. 8036 */ 8037 continue; 8038 } 8039 String names[] = p.info.authority.split(";"); 8040 for (int j = 0; j < names.length; j++) { 8041 if (mProvidersByAuthority.get(names[j]) == p) { 8042 mProvidersByAuthority.remove(names[j]); 8043 if (DEBUG_REMOVE) { 8044 if (chatty) 8045 Log.d(TAG, "Unregistered content provider: " + names[j] 8046 + ", className = " + p.info.name + ", isSyncable = " 8047 + p.info.isSyncable); 8048 } 8049 } 8050 } 8051 if (DEBUG_REMOVE && chatty) { 8052 if (r == null) { 8053 r = new StringBuilder(256); 8054 } else { 8055 r.append(' '); 8056 } 8057 r.append(p.info.name); 8058 } 8059 } 8060 if (r != null) { 8061 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8062 } 8063 8064 N = pkg.services.size(); 8065 r = null; 8066 for (i=0; i<N; i++) { 8067 PackageParser.Service s = pkg.services.get(i); 8068 mServices.removeService(s); 8069 if (chatty) { 8070 if (r == null) { 8071 r = new StringBuilder(256); 8072 } else { 8073 r.append(' '); 8074 } 8075 r.append(s.info.name); 8076 } 8077 } 8078 if (r != null) { 8079 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8080 } 8081 8082 N = pkg.receivers.size(); 8083 r = null; 8084 for (i=0; i<N; i++) { 8085 PackageParser.Activity a = pkg.receivers.get(i); 8086 mReceivers.removeActivity(a, "receiver"); 8087 if (DEBUG_REMOVE && chatty) { 8088 if (r == null) { 8089 r = new StringBuilder(256); 8090 } else { 8091 r.append(' '); 8092 } 8093 r.append(a.info.name); 8094 } 8095 } 8096 if (r != null) { 8097 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8098 } 8099 8100 N = pkg.activities.size(); 8101 r = null; 8102 for (i=0; i<N; i++) { 8103 PackageParser.Activity a = pkg.activities.get(i); 8104 mActivities.removeActivity(a, "activity"); 8105 if (DEBUG_REMOVE && chatty) { 8106 if (r == null) { 8107 r = new StringBuilder(256); 8108 } else { 8109 r.append(' '); 8110 } 8111 r.append(a.info.name); 8112 } 8113 } 8114 if (r != null) { 8115 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8116 } 8117 8118 N = pkg.permissions.size(); 8119 r = null; 8120 for (i=0; i<N; i++) { 8121 PackageParser.Permission p = pkg.permissions.get(i); 8122 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8123 if (bp == null) { 8124 bp = mSettings.mPermissionTrees.get(p.info.name); 8125 } 8126 if (bp != null && bp.perm == p) { 8127 bp.perm = null; 8128 if (DEBUG_REMOVE && chatty) { 8129 if (r == null) { 8130 r = new StringBuilder(256); 8131 } else { 8132 r.append(' '); 8133 } 8134 r.append(p.info.name); 8135 } 8136 } 8137 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8138 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8139 if (appOpPkgs != null) { 8140 appOpPkgs.remove(pkg.packageName); 8141 } 8142 } 8143 } 8144 if (r != null) { 8145 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8146 } 8147 8148 N = pkg.requestedPermissions.size(); 8149 r = null; 8150 for (i=0; i<N; i++) { 8151 String perm = pkg.requestedPermissions.get(i); 8152 BasePermission bp = mSettings.mPermissions.get(perm); 8153 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8154 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8155 if (appOpPkgs != null) { 8156 appOpPkgs.remove(pkg.packageName); 8157 if (appOpPkgs.isEmpty()) { 8158 mAppOpPermissionPackages.remove(perm); 8159 } 8160 } 8161 } 8162 } 8163 if (r != null) { 8164 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8165 } 8166 8167 N = pkg.instrumentation.size(); 8168 r = null; 8169 for (i=0; i<N; i++) { 8170 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8171 mInstrumentation.remove(a.getComponentName()); 8172 if (DEBUG_REMOVE && chatty) { 8173 if (r == null) { 8174 r = new StringBuilder(256); 8175 } else { 8176 r.append(' '); 8177 } 8178 r.append(a.info.name); 8179 } 8180 } 8181 if (r != null) { 8182 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8183 } 8184 8185 r = null; 8186 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8187 // Only system apps can hold shared libraries. 8188 if (pkg.libraryNames != null) { 8189 for (i=0; i<pkg.libraryNames.size(); i++) { 8190 String name = pkg.libraryNames.get(i); 8191 SharedLibraryEntry cur = mSharedLibraries.get(name); 8192 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8193 mSharedLibraries.remove(name); 8194 if (DEBUG_REMOVE && chatty) { 8195 if (r == null) { 8196 r = new StringBuilder(256); 8197 } else { 8198 r.append(' '); 8199 } 8200 r.append(name); 8201 } 8202 } 8203 } 8204 } 8205 } 8206 if (r != null) { 8207 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8208 } 8209 } 8210 8211 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8212 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8213 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8214 return true; 8215 } 8216 } 8217 return false; 8218 } 8219 8220 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8221 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8222 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8223 8224 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8225 int flags) { 8226 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8227 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8228 } 8229 8230 private void updatePermissionsLPw(String changingPkg, 8231 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8232 // Make sure there are no dangling permission trees. 8233 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8234 while (it.hasNext()) { 8235 final BasePermission bp = it.next(); 8236 if (bp.packageSetting == null) { 8237 // We may not yet have parsed the package, so just see if 8238 // we still know about its settings. 8239 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8240 } 8241 if (bp.packageSetting == null) { 8242 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8243 + " from package " + bp.sourcePackage); 8244 it.remove(); 8245 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8246 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8247 Slog.i(TAG, "Removing old permission tree: " + bp.name 8248 + " from package " + bp.sourcePackage); 8249 flags |= UPDATE_PERMISSIONS_ALL; 8250 it.remove(); 8251 } 8252 } 8253 } 8254 8255 // Make sure all dynamic permissions have been assigned to a package, 8256 // and make sure there are no dangling permissions. 8257 it = mSettings.mPermissions.values().iterator(); 8258 while (it.hasNext()) { 8259 final BasePermission bp = it.next(); 8260 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8261 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8262 + bp.name + " pkg=" + bp.sourcePackage 8263 + " info=" + bp.pendingInfo); 8264 if (bp.packageSetting == null && bp.pendingInfo != null) { 8265 final BasePermission tree = findPermissionTreeLP(bp.name); 8266 if (tree != null && tree.perm != null) { 8267 bp.packageSetting = tree.packageSetting; 8268 bp.perm = new PackageParser.Permission(tree.perm.owner, 8269 new PermissionInfo(bp.pendingInfo)); 8270 bp.perm.info.packageName = tree.perm.info.packageName; 8271 bp.perm.info.name = bp.name; 8272 bp.uid = tree.uid; 8273 } 8274 } 8275 } 8276 if (bp.packageSetting == null) { 8277 // We may not yet have parsed the package, so just see if 8278 // we still know about its settings. 8279 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8280 } 8281 if (bp.packageSetting == null) { 8282 Slog.w(TAG, "Removing dangling permission: " + bp.name 8283 + " from package " + bp.sourcePackage); 8284 it.remove(); 8285 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8286 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8287 Slog.i(TAG, "Removing old permission: " + bp.name 8288 + " from package " + bp.sourcePackage); 8289 flags |= UPDATE_PERMISSIONS_ALL; 8290 it.remove(); 8291 } 8292 } 8293 } 8294 8295 // Now update the permissions for all packages, in particular 8296 // replace the granted permissions of the system packages. 8297 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8298 for (PackageParser.Package pkg : mPackages.values()) { 8299 if (pkg != pkgInfo) { 8300 // Only replace for packages on requested volume 8301 final String volumeUuid = getVolumeUuidForPackage(pkg); 8302 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8303 && Objects.equals(replaceVolumeUuid, volumeUuid); 8304 grantPermissionsLPw(pkg, replace, changingPkg); 8305 } 8306 } 8307 } 8308 8309 if (pkgInfo != null) { 8310 // Only replace for packages on requested volume 8311 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8312 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8313 && Objects.equals(replaceVolumeUuid, volumeUuid); 8314 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8315 } 8316 } 8317 8318 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8319 String packageOfInterest) { 8320 // IMPORTANT: There are two types of permissions: install and runtime. 8321 // Install time permissions are granted when the app is installed to 8322 // all device users and users added in the future. Runtime permissions 8323 // are granted at runtime explicitly to specific users. Normal and signature 8324 // protected permissions are install time permissions. Dangerous permissions 8325 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8326 // otherwise they are runtime permissions. This function does not manage 8327 // runtime permissions except for the case an app targeting Lollipop MR1 8328 // being upgraded to target a newer SDK, in which case dangerous permissions 8329 // are transformed from install time to runtime ones. 8330 8331 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8332 if (ps == null) { 8333 return; 8334 } 8335 8336 PermissionsState permissionsState = ps.getPermissionsState(); 8337 PermissionsState origPermissions = permissionsState; 8338 8339 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8340 8341 boolean runtimePermissionsRevoked = false; 8342 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8343 8344 boolean changedInstallPermission = false; 8345 8346 if (replace) { 8347 ps.installPermissionsFixed = false; 8348 if (!ps.isSharedUser()) { 8349 origPermissions = new PermissionsState(permissionsState); 8350 permissionsState.reset(); 8351 } else { 8352 // We need to know only about runtime permission changes since the 8353 // calling code always writes the install permissions state but 8354 // the runtime ones are written only if changed. The only cases of 8355 // changed runtime permissions here are promotion of an install to 8356 // runtime and revocation of a runtime from a shared user. 8357 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8358 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8359 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8360 runtimePermissionsRevoked = true; 8361 } 8362 } 8363 } 8364 8365 permissionsState.setGlobalGids(mGlobalGids); 8366 8367 final int N = pkg.requestedPermissions.size(); 8368 for (int i=0; i<N; i++) { 8369 final String name = pkg.requestedPermissions.get(i); 8370 final BasePermission bp = mSettings.mPermissions.get(name); 8371 8372 if (DEBUG_INSTALL) { 8373 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8374 } 8375 8376 if (bp == null || bp.packageSetting == null) { 8377 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8378 Slog.w(TAG, "Unknown permission " + name 8379 + " in package " + pkg.packageName); 8380 } 8381 continue; 8382 } 8383 8384 final String perm = bp.name; 8385 boolean allowedSig = false; 8386 int grant = GRANT_DENIED; 8387 8388 // Keep track of app op permissions. 8389 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8390 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8391 if (pkgs == null) { 8392 pkgs = new ArraySet<>(); 8393 mAppOpPermissionPackages.put(bp.name, pkgs); 8394 } 8395 pkgs.add(pkg.packageName); 8396 } 8397 8398 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8399 switch (level) { 8400 case PermissionInfo.PROTECTION_NORMAL: { 8401 // For all apps normal permissions are install time ones. 8402 grant = GRANT_INSTALL; 8403 } break; 8404 8405 case PermissionInfo.PROTECTION_DANGEROUS: { 8406 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8407 // For legacy apps dangerous permissions are install time ones. 8408 grant = GRANT_INSTALL_LEGACY; 8409 } else if (origPermissions.hasInstallPermission(bp.name)) { 8410 // For legacy apps that became modern, install becomes runtime. 8411 grant = GRANT_UPGRADE; 8412 } else if (mPromoteSystemApps 8413 && isSystemApp(ps) 8414 && mExistingSystemPackages.contains(ps.name)) { 8415 // For legacy system apps, install becomes runtime. 8416 // We cannot check hasInstallPermission() for system apps since those 8417 // permissions were granted implicitly and not persisted pre-M. 8418 grant = GRANT_UPGRADE; 8419 } else { 8420 // For modern apps keep runtime permissions unchanged. 8421 grant = GRANT_RUNTIME; 8422 } 8423 } break; 8424 8425 case PermissionInfo.PROTECTION_SIGNATURE: { 8426 // For all apps signature permissions are install time ones. 8427 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8428 if (allowedSig) { 8429 grant = GRANT_INSTALL; 8430 } 8431 } break; 8432 } 8433 8434 if (DEBUG_INSTALL) { 8435 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8436 } 8437 8438 if (grant != GRANT_DENIED) { 8439 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8440 // If this is an existing, non-system package, then 8441 // we can't add any new permissions to it. 8442 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8443 // Except... if this is a permission that was added 8444 // to the platform (note: need to only do this when 8445 // updating the platform). 8446 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8447 grant = GRANT_DENIED; 8448 } 8449 } 8450 } 8451 8452 switch (grant) { 8453 case GRANT_INSTALL: { 8454 // Revoke this as runtime permission to handle the case of 8455 // a runtime permission being downgraded to an install one. 8456 for (int userId : UserManagerService.getInstance().getUserIds()) { 8457 if (origPermissions.getRuntimePermissionState( 8458 bp.name, userId) != null) { 8459 // Revoke the runtime permission and clear the flags. 8460 origPermissions.revokeRuntimePermission(bp, userId); 8461 origPermissions.updatePermissionFlags(bp, userId, 8462 PackageManager.MASK_PERMISSION_FLAGS, 0); 8463 // If we revoked a permission permission, we have to write. 8464 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8465 changedRuntimePermissionUserIds, userId); 8466 } 8467 } 8468 // Grant an install permission. 8469 if (permissionsState.grantInstallPermission(bp) != 8470 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8471 changedInstallPermission = true; 8472 } 8473 } break; 8474 8475 case GRANT_INSTALL_LEGACY: { 8476 // Grant an install permission. 8477 if (permissionsState.grantInstallPermission(bp) != 8478 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8479 changedInstallPermission = true; 8480 } 8481 } break; 8482 8483 case GRANT_RUNTIME: { 8484 // Grant previously granted runtime permissions. 8485 for (int userId : UserManagerService.getInstance().getUserIds()) { 8486 PermissionState permissionState = origPermissions 8487 .getRuntimePermissionState(bp.name, userId); 8488 final int flags = permissionState != null 8489 ? permissionState.getFlags() : 0; 8490 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8491 if (permissionsState.grantRuntimePermission(bp, userId) == 8492 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8493 // If we cannot put the permission as it was, we have to write. 8494 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8495 changedRuntimePermissionUserIds, userId); 8496 } 8497 } 8498 // Propagate the permission flags. 8499 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8500 } 8501 } break; 8502 8503 case GRANT_UPGRADE: { 8504 // Grant runtime permissions for a previously held install permission. 8505 PermissionState permissionState = origPermissions 8506 .getInstallPermissionState(bp.name); 8507 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8508 8509 if (origPermissions.revokeInstallPermission(bp) 8510 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8511 // We will be transferring the permission flags, so clear them. 8512 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8513 PackageManager.MASK_PERMISSION_FLAGS, 0); 8514 changedInstallPermission = true; 8515 } 8516 8517 // If the permission is not to be promoted to runtime we ignore it and 8518 // also its other flags as they are not applicable to install permissions. 8519 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8520 for (int userId : currentUserIds) { 8521 if (permissionsState.grantRuntimePermission(bp, userId) != 8522 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8523 // Transfer the permission flags. 8524 permissionsState.updatePermissionFlags(bp, userId, 8525 flags, flags); 8526 // If we granted the permission, we have to write. 8527 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8528 changedRuntimePermissionUserIds, userId); 8529 } 8530 } 8531 } 8532 } break; 8533 8534 default: { 8535 if (packageOfInterest == null 8536 || packageOfInterest.equals(pkg.packageName)) { 8537 Slog.w(TAG, "Not granting permission " + perm 8538 + " to package " + pkg.packageName 8539 + " because it was previously installed without"); 8540 } 8541 } break; 8542 } 8543 } else { 8544 if (permissionsState.revokeInstallPermission(bp) != 8545 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8546 // Also drop the permission flags. 8547 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8548 PackageManager.MASK_PERMISSION_FLAGS, 0); 8549 changedInstallPermission = true; 8550 Slog.i(TAG, "Un-granting permission " + perm 8551 + " from package " + pkg.packageName 8552 + " (protectionLevel=" + bp.protectionLevel 8553 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8554 + ")"); 8555 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8556 // Don't print warning for app op permissions, since it is fine for them 8557 // not to be granted, there is a UI for the user to decide. 8558 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8559 Slog.w(TAG, "Not granting permission " + perm 8560 + " to package " + pkg.packageName 8561 + " (protectionLevel=" + bp.protectionLevel 8562 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8563 + ")"); 8564 } 8565 } 8566 } 8567 } 8568 8569 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8570 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8571 // This is the first that we have heard about this package, so the 8572 // permissions we have now selected are fixed until explicitly 8573 // changed. 8574 ps.installPermissionsFixed = true; 8575 } 8576 8577 // Persist the runtime permissions state for users with changes. If permissions 8578 // were revoked because no app in the shared user declares them we have to 8579 // write synchronously to avoid losing runtime permissions state. 8580 for (int userId : changedRuntimePermissionUserIds) { 8581 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8582 } 8583 } 8584 8585 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8586 boolean allowed = false; 8587 final int NP = PackageParser.NEW_PERMISSIONS.length; 8588 for (int ip=0; ip<NP; ip++) { 8589 final PackageParser.NewPermissionInfo npi 8590 = PackageParser.NEW_PERMISSIONS[ip]; 8591 if (npi.name.equals(perm) 8592 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8593 allowed = true; 8594 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8595 + pkg.packageName); 8596 break; 8597 } 8598 } 8599 return allowed; 8600 } 8601 8602 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8603 BasePermission bp, PermissionsState origPermissions) { 8604 boolean allowed; 8605 allowed = (compareSignatures( 8606 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8607 == PackageManager.SIGNATURE_MATCH) 8608 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8609 == PackageManager.SIGNATURE_MATCH); 8610 if (!allowed && (bp.protectionLevel 8611 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8612 if (isSystemApp(pkg)) { 8613 // For updated system applications, a system permission 8614 // is granted only if it had been defined by the original application. 8615 if (pkg.isUpdatedSystemApp()) { 8616 final PackageSetting sysPs = mSettings 8617 .getDisabledSystemPkgLPr(pkg.packageName); 8618 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8619 // If the original was granted this permission, we take 8620 // that grant decision as read and propagate it to the 8621 // update. 8622 if (sysPs.isPrivileged()) { 8623 allowed = true; 8624 } 8625 } else { 8626 // The system apk may have been updated with an older 8627 // version of the one on the data partition, but which 8628 // granted a new system permission that it didn't have 8629 // before. In this case we do want to allow the app to 8630 // now get the new permission if the ancestral apk is 8631 // privileged to get it. 8632 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8633 for (int j=0; 8634 j<sysPs.pkg.requestedPermissions.size(); j++) { 8635 if (perm.equals( 8636 sysPs.pkg.requestedPermissions.get(j))) { 8637 allowed = true; 8638 break; 8639 } 8640 } 8641 } 8642 } 8643 } else { 8644 allowed = isPrivilegedApp(pkg); 8645 } 8646 } 8647 } 8648 if (!allowed) { 8649 if (!allowed && (bp.protectionLevel 8650 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8651 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8652 // If this was a previously normal/dangerous permission that got moved 8653 // to a system permission as part of the runtime permission redesign, then 8654 // we still want to blindly grant it to old apps. 8655 allowed = true; 8656 } 8657 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8658 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8659 // If this permission is to be granted to the system installer and 8660 // this app is an installer, then it gets the permission. 8661 allowed = true; 8662 } 8663 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8664 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8665 // If this permission is to be granted to the system verifier and 8666 // this app is a verifier, then it gets the permission. 8667 allowed = true; 8668 } 8669 if (!allowed && (bp.protectionLevel 8670 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8671 && isSystemApp(pkg)) { 8672 // Any pre-installed system app is allowed to get this permission. 8673 allowed = true; 8674 } 8675 if (!allowed && (bp.protectionLevel 8676 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8677 // For development permissions, a development permission 8678 // is granted only if it was already granted. 8679 allowed = origPermissions.hasInstallPermission(perm); 8680 } 8681 } 8682 return allowed; 8683 } 8684 8685 final class ActivityIntentResolver 8686 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8687 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8688 boolean defaultOnly, int userId) { 8689 if (!sUserManager.exists(userId)) return null; 8690 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8691 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8692 } 8693 8694 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8695 int userId) { 8696 if (!sUserManager.exists(userId)) return null; 8697 mFlags = flags; 8698 return super.queryIntent(intent, resolvedType, 8699 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8700 } 8701 8702 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8703 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8704 if (!sUserManager.exists(userId)) return null; 8705 if (packageActivities == null) { 8706 return null; 8707 } 8708 mFlags = flags; 8709 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8710 final int N = packageActivities.size(); 8711 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8712 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8713 8714 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8715 for (int i = 0; i < N; ++i) { 8716 intentFilters = packageActivities.get(i).intents; 8717 if (intentFilters != null && intentFilters.size() > 0) { 8718 PackageParser.ActivityIntentInfo[] array = 8719 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8720 intentFilters.toArray(array); 8721 listCut.add(array); 8722 } 8723 } 8724 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8725 } 8726 8727 public final void addActivity(PackageParser.Activity a, String type) { 8728 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8729 mActivities.put(a.getComponentName(), a); 8730 if (DEBUG_SHOW_INFO) 8731 Log.v( 8732 TAG, " " + type + " " + 8733 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8734 if (DEBUG_SHOW_INFO) 8735 Log.v(TAG, " Class=" + a.info.name); 8736 final int NI = a.intents.size(); 8737 for (int j=0; j<NI; j++) { 8738 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8739 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8740 intent.setPriority(0); 8741 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8742 + a.className + " with priority > 0, forcing to 0"); 8743 } 8744 if (DEBUG_SHOW_INFO) { 8745 Log.v(TAG, " IntentFilter:"); 8746 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8747 } 8748 if (!intent.debugCheck()) { 8749 Log.w(TAG, "==> For Activity " + a.info.name); 8750 } 8751 addFilter(intent); 8752 } 8753 } 8754 8755 public final void removeActivity(PackageParser.Activity a, String type) { 8756 mActivities.remove(a.getComponentName()); 8757 if (DEBUG_SHOW_INFO) { 8758 Log.v(TAG, " " + type + " " 8759 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8760 : a.info.name) + ":"); 8761 Log.v(TAG, " Class=" + a.info.name); 8762 } 8763 final int NI = a.intents.size(); 8764 for (int j=0; j<NI; j++) { 8765 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8766 if (DEBUG_SHOW_INFO) { 8767 Log.v(TAG, " IntentFilter:"); 8768 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8769 } 8770 removeFilter(intent); 8771 } 8772 } 8773 8774 @Override 8775 protected boolean allowFilterResult( 8776 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8777 ActivityInfo filterAi = filter.activity.info; 8778 for (int i=dest.size()-1; i>=0; i--) { 8779 ActivityInfo destAi = dest.get(i).activityInfo; 8780 if (destAi.name == filterAi.name 8781 && destAi.packageName == filterAi.packageName) { 8782 return false; 8783 } 8784 } 8785 return true; 8786 } 8787 8788 @Override 8789 protected ActivityIntentInfo[] newArray(int size) { 8790 return new ActivityIntentInfo[size]; 8791 } 8792 8793 @Override 8794 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8795 if (!sUserManager.exists(userId)) return true; 8796 PackageParser.Package p = filter.activity.owner; 8797 if (p != null) { 8798 PackageSetting ps = (PackageSetting)p.mExtras; 8799 if (ps != null) { 8800 // System apps are never considered stopped for purposes of 8801 // filtering, because there may be no way for the user to 8802 // actually re-launch them. 8803 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8804 && ps.getStopped(userId); 8805 } 8806 } 8807 return false; 8808 } 8809 8810 @Override 8811 protected boolean isPackageForFilter(String packageName, 8812 PackageParser.ActivityIntentInfo info) { 8813 return packageName.equals(info.activity.owner.packageName); 8814 } 8815 8816 @Override 8817 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8818 int match, int userId) { 8819 if (!sUserManager.exists(userId)) return null; 8820 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8821 return null; 8822 } 8823 final PackageParser.Activity activity = info.activity; 8824 if (mSafeMode && (activity.info.applicationInfo.flags 8825 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8826 return null; 8827 } 8828 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8829 if (ps == null) { 8830 return null; 8831 } 8832 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8833 ps.readUserState(userId), userId); 8834 if (ai == null) { 8835 return null; 8836 } 8837 final ResolveInfo res = new ResolveInfo(); 8838 res.activityInfo = ai; 8839 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8840 res.filter = info; 8841 } 8842 if (info != null) { 8843 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8844 } 8845 res.priority = info.getPriority(); 8846 res.preferredOrder = activity.owner.mPreferredOrder; 8847 //System.out.println("Result: " + res.activityInfo.className + 8848 // " = " + res.priority); 8849 res.match = match; 8850 res.isDefault = info.hasDefault; 8851 res.labelRes = info.labelRes; 8852 res.nonLocalizedLabel = info.nonLocalizedLabel; 8853 if (userNeedsBadging(userId)) { 8854 res.noResourceId = true; 8855 } else { 8856 res.icon = info.icon; 8857 } 8858 res.iconResourceId = info.icon; 8859 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8860 return res; 8861 } 8862 8863 @Override 8864 protected void sortResults(List<ResolveInfo> results) { 8865 Collections.sort(results, mResolvePrioritySorter); 8866 } 8867 8868 @Override 8869 protected void dumpFilter(PrintWriter out, String prefix, 8870 PackageParser.ActivityIntentInfo filter) { 8871 out.print(prefix); out.print( 8872 Integer.toHexString(System.identityHashCode(filter.activity))); 8873 out.print(' '); 8874 filter.activity.printComponentShortName(out); 8875 out.print(" filter "); 8876 out.println(Integer.toHexString(System.identityHashCode(filter))); 8877 } 8878 8879 @Override 8880 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8881 return filter.activity; 8882 } 8883 8884 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8885 PackageParser.Activity activity = (PackageParser.Activity)label; 8886 out.print(prefix); out.print( 8887 Integer.toHexString(System.identityHashCode(activity))); 8888 out.print(' '); 8889 activity.printComponentShortName(out); 8890 if (count > 1) { 8891 out.print(" ("); out.print(count); out.print(" filters)"); 8892 } 8893 out.println(); 8894 } 8895 8896// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8897// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8898// final List<ResolveInfo> retList = Lists.newArrayList(); 8899// while (i.hasNext()) { 8900// final ResolveInfo resolveInfo = i.next(); 8901// if (isEnabledLP(resolveInfo.activityInfo)) { 8902// retList.add(resolveInfo); 8903// } 8904// } 8905// return retList; 8906// } 8907 8908 // Keys are String (activity class name), values are Activity. 8909 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8910 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8911 private int mFlags; 8912 } 8913 8914 private final class ServiceIntentResolver 8915 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8916 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8917 boolean defaultOnly, int userId) { 8918 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8919 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8920 } 8921 8922 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8923 int userId) { 8924 if (!sUserManager.exists(userId)) return null; 8925 mFlags = flags; 8926 return super.queryIntent(intent, resolvedType, 8927 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8928 } 8929 8930 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8931 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8932 if (!sUserManager.exists(userId)) return null; 8933 if (packageServices == null) { 8934 return null; 8935 } 8936 mFlags = flags; 8937 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8938 final int N = packageServices.size(); 8939 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8940 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8941 8942 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8943 for (int i = 0; i < N; ++i) { 8944 intentFilters = packageServices.get(i).intents; 8945 if (intentFilters != null && intentFilters.size() > 0) { 8946 PackageParser.ServiceIntentInfo[] array = 8947 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8948 intentFilters.toArray(array); 8949 listCut.add(array); 8950 } 8951 } 8952 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8953 } 8954 8955 public final void addService(PackageParser.Service s) { 8956 mServices.put(s.getComponentName(), s); 8957 if (DEBUG_SHOW_INFO) { 8958 Log.v(TAG, " " 8959 + (s.info.nonLocalizedLabel != null 8960 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8961 Log.v(TAG, " Class=" + s.info.name); 8962 } 8963 final int NI = s.intents.size(); 8964 int j; 8965 for (j=0; j<NI; j++) { 8966 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8967 if (DEBUG_SHOW_INFO) { 8968 Log.v(TAG, " IntentFilter:"); 8969 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8970 } 8971 if (!intent.debugCheck()) { 8972 Log.w(TAG, "==> For Service " + s.info.name); 8973 } 8974 addFilter(intent); 8975 } 8976 } 8977 8978 public final void removeService(PackageParser.Service s) { 8979 mServices.remove(s.getComponentName()); 8980 if (DEBUG_SHOW_INFO) { 8981 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8982 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8983 Log.v(TAG, " Class=" + s.info.name); 8984 } 8985 final int NI = s.intents.size(); 8986 int j; 8987 for (j=0; j<NI; j++) { 8988 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8989 if (DEBUG_SHOW_INFO) { 8990 Log.v(TAG, " IntentFilter:"); 8991 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8992 } 8993 removeFilter(intent); 8994 } 8995 } 8996 8997 @Override 8998 protected boolean allowFilterResult( 8999 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9000 ServiceInfo filterSi = filter.service.info; 9001 for (int i=dest.size()-1; i>=0; i--) { 9002 ServiceInfo destAi = dest.get(i).serviceInfo; 9003 if (destAi.name == filterSi.name 9004 && destAi.packageName == filterSi.packageName) { 9005 return false; 9006 } 9007 } 9008 return true; 9009 } 9010 9011 @Override 9012 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9013 return new PackageParser.ServiceIntentInfo[size]; 9014 } 9015 9016 @Override 9017 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9018 if (!sUserManager.exists(userId)) return true; 9019 PackageParser.Package p = filter.service.owner; 9020 if (p != null) { 9021 PackageSetting ps = (PackageSetting)p.mExtras; 9022 if (ps != null) { 9023 // System apps are never considered stopped for purposes of 9024 // filtering, because there may be no way for the user to 9025 // actually re-launch them. 9026 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9027 && ps.getStopped(userId); 9028 } 9029 } 9030 return false; 9031 } 9032 9033 @Override 9034 protected boolean isPackageForFilter(String packageName, 9035 PackageParser.ServiceIntentInfo info) { 9036 return packageName.equals(info.service.owner.packageName); 9037 } 9038 9039 @Override 9040 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9041 int match, int userId) { 9042 if (!sUserManager.exists(userId)) return null; 9043 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9044 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9045 return null; 9046 } 9047 final PackageParser.Service service = info.service; 9048 if (mSafeMode && (service.info.applicationInfo.flags 9049 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9050 return null; 9051 } 9052 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9053 if (ps == null) { 9054 return null; 9055 } 9056 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9057 ps.readUserState(userId), userId); 9058 if (si == null) { 9059 return null; 9060 } 9061 final ResolveInfo res = new ResolveInfo(); 9062 res.serviceInfo = si; 9063 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9064 res.filter = filter; 9065 } 9066 res.priority = info.getPriority(); 9067 res.preferredOrder = service.owner.mPreferredOrder; 9068 res.match = match; 9069 res.isDefault = info.hasDefault; 9070 res.labelRes = info.labelRes; 9071 res.nonLocalizedLabel = info.nonLocalizedLabel; 9072 res.icon = info.icon; 9073 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9074 return res; 9075 } 9076 9077 @Override 9078 protected void sortResults(List<ResolveInfo> results) { 9079 Collections.sort(results, mResolvePrioritySorter); 9080 } 9081 9082 @Override 9083 protected void dumpFilter(PrintWriter out, String prefix, 9084 PackageParser.ServiceIntentInfo filter) { 9085 out.print(prefix); out.print( 9086 Integer.toHexString(System.identityHashCode(filter.service))); 9087 out.print(' '); 9088 filter.service.printComponentShortName(out); 9089 out.print(" filter "); 9090 out.println(Integer.toHexString(System.identityHashCode(filter))); 9091 } 9092 9093 @Override 9094 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9095 return filter.service; 9096 } 9097 9098 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9099 PackageParser.Service service = (PackageParser.Service)label; 9100 out.print(prefix); out.print( 9101 Integer.toHexString(System.identityHashCode(service))); 9102 out.print(' '); 9103 service.printComponentShortName(out); 9104 if (count > 1) { 9105 out.print(" ("); out.print(count); out.print(" filters)"); 9106 } 9107 out.println(); 9108 } 9109 9110// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9111// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9112// final List<ResolveInfo> retList = Lists.newArrayList(); 9113// while (i.hasNext()) { 9114// final ResolveInfo resolveInfo = (ResolveInfo) i; 9115// if (isEnabledLP(resolveInfo.serviceInfo)) { 9116// retList.add(resolveInfo); 9117// } 9118// } 9119// return retList; 9120// } 9121 9122 // Keys are String (activity class name), values are Activity. 9123 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9124 = new ArrayMap<ComponentName, PackageParser.Service>(); 9125 private int mFlags; 9126 }; 9127 9128 private final class ProviderIntentResolver 9129 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9130 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9131 boolean defaultOnly, int userId) { 9132 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9133 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9134 } 9135 9136 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9137 int userId) { 9138 if (!sUserManager.exists(userId)) 9139 return null; 9140 mFlags = flags; 9141 return super.queryIntent(intent, resolvedType, 9142 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9143 } 9144 9145 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9146 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9147 if (!sUserManager.exists(userId)) 9148 return null; 9149 if (packageProviders == null) { 9150 return null; 9151 } 9152 mFlags = flags; 9153 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9154 final int N = packageProviders.size(); 9155 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9156 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9157 9158 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9159 for (int i = 0; i < N; ++i) { 9160 intentFilters = packageProviders.get(i).intents; 9161 if (intentFilters != null && intentFilters.size() > 0) { 9162 PackageParser.ProviderIntentInfo[] array = 9163 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9164 intentFilters.toArray(array); 9165 listCut.add(array); 9166 } 9167 } 9168 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9169 } 9170 9171 public final void addProvider(PackageParser.Provider p) { 9172 if (mProviders.containsKey(p.getComponentName())) { 9173 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9174 return; 9175 } 9176 9177 mProviders.put(p.getComponentName(), p); 9178 if (DEBUG_SHOW_INFO) { 9179 Log.v(TAG, " " 9180 + (p.info.nonLocalizedLabel != null 9181 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9182 Log.v(TAG, " Class=" + p.info.name); 9183 } 9184 final int NI = p.intents.size(); 9185 int j; 9186 for (j = 0; j < NI; j++) { 9187 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9188 if (DEBUG_SHOW_INFO) { 9189 Log.v(TAG, " IntentFilter:"); 9190 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9191 } 9192 if (!intent.debugCheck()) { 9193 Log.w(TAG, "==> For Provider " + p.info.name); 9194 } 9195 addFilter(intent); 9196 } 9197 } 9198 9199 public final void removeProvider(PackageParser.Provider p) { 9200 mProviders.remove(p.getComponentName()); 9201 if (DEBUG_SHOW_INFO) { 9202 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9203 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9204 Log.v(TAG, " Class=" + p.info.name); 9205 } 9206 final int NI = p.intents.size(); 9207 int j; 9208 for (j = 0; j < NI; j++) { 9209 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9210 if (DEBUG_SHOW_INFO) { 9211 Log.v(TAG, " IntentFilter:"); 9212 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9213 } 9214 removeFilter(intent); 9215 } 9216 } 9217 9218 @Override 9219 protected boolean allowFilterResult( 9220 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9221 ProviderInfo filterPi = filter.provider.info; 9222 for (int i = dest.size() - 1; i >= 0; i--) { 9223 ProviderInfo destPi = dest.get(i).providerInfo; 9224 if (destPi.name == filterPi.name 9225 && destPi.packageName == filterPi.packageName) { 9226 return false; 9227 } 9228 } 9229 return true; 9230 } 9231 9232 @Override 9233 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9234 return new PackageParser.ProviderIntentInfo[size]; 9235 } 9236 9237 @Override 9238 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9239 if (!sUserManager.exists(userId)) 9240 return true; 9241 PackageParser.Package p = filter.provider.owner; 9242 if (p != null) { 9243 PackageSetting ps = (PackageSetting) p.mExtras; 9244 if (ps != null) { 9245 // System apps are never considered stopped for purposes of 9246 // filtering, because there may be no way for the user to 9247 // actually re-launch them. 9248 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9249 && ps.getStopped(userId); 9250 } 9251 } 9252 return false; 9253 } 9254 9255 @Override 9256 protected boolean isPackageForFilter(String packageName, 9257 PackageParser.ProviderIntentInfo info) { 9258 return packageName.equals(info.provider.owner.packageName); 9259 } 9260 9261 @Override 9262 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9263 int match, int userId) { 9264 if (!sUserManager.exists(userId)) 9265 return null; 9266 final PackageParser.ProviderIntentInfo info = filter; 9267 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9268 return null; 9269 } 9270 final PackageParser.Provider provider = info.provider; 9271 if (mSafeMode && (provider.info.applicationInfo.flags 9272 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9273 return null; 9274 } 9275 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9276 if (ps == null) { 9277 return null; 9278 } 9279 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9280 ps.readUserState(userId), userId); 9281 if (pi == null) { 9282 return null; 9283 } 9284 final ResolveInfo res = new ResolveInfo(); 9285 res.providerInfo = pi; 9286 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9287 res.filter = filter; 9288 } 9289 res.priority = info.getPriority(); 9290 res.preferredOrder = provider.owner.mPreferredOrder; 9291 res.match = match; 9292 res.isDefault = info.hasDefault; 9293 res.labelRes = info.labelRes; 9294 res.nonLocalizedLabel = info.nonLocalizedLabel; 9295 res.icon = info.icon; 9296 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9297 return res; 9298 } 9299 9300 @Override 9301 protected void sortResults(List<ResolveInfo> results) { 9302 Collections.sort(results, mResolvePrioritySorter); 9303 } 9304 9305 @Override 9306 protected void dumpFilter(PrintWriter out, String prefix, 9307 PackageParser.ProviderIntentInfo filter) { 9308 out.print(prefix); 9309 out.print( 9310 Integer.toHexString(System.identityHashCode(filter.provider))); 9311 out.print(' '); 9312 filter.provider.printComponentShortName(out); 9313 out.print(" filter "); 9314 out.println(Integer.toHexString(System.identityHashCode(filter))); 9315 } 9316 9317 @Override 9318 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9319 return filter.provider; 9320 } 9321 9322 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9323 PackageParser.Provider provider = (PackageParser.Provider)label; 9324 out.print(prefix); out.print( 9325 Integer.toHexString(System.identityHashCode(provider))); 9326 out.print(' '); 9327 provider.printComponentShortName(out); 9328 if (count > 1) { 9329 out.print(" ("); out.print(count); out.print(" filters)"); 9330 } 9331 out.println(); 9332 } 9333 9334 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9335 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9336 private int mFlags; 9337 }; 9338 9339 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9340 new Comparator<ResolveInfo>() { 9341 public int compare(ResolveInfo r1, ResolveInfo r2) { 9342 int v1 = r1.priority; 9343 int v2 = r2.priority; 9344 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9345 if (v1 != v2) { 9346 return (v1 > v2) ? -1 : 1; 9347 } 9348 v1 = r1.preferredOrder; 9349 v2 = r2.preferredOrder; 9350 if (v1 != v2) { 9351 return (v1 > v2) ? -1 : 1; 9352 } 9353 if (r1.isDefault != r2.isDefault) { 9354 return r1.isDefault ? -1 : 1; 9355 } 9356 v1 = r1.match; 9357 v2 = r2.match; 9358 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9359 if (v1 != v2) { 9360 return (v1 > v2) ? -1 : 1; 9361 } 9362 if (r1.system != r2.system) { 9363 return r1.system ? -1 : 1; 9364 } 9365 return 0; 9366 } 9367 }; 9368 9369 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9370 new Comparator<ProviderInfo>() { 9371 public int compare(ProviderInfo p1, ProviderInfo p2) { 9372 final int v1 = p1.initOrder; 9373 final int v2 = p2.initOrder; 9374 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9375 } 9376 }; 9377 9378 final void sendPackageBroadcast(final String action, final String pkg, 9379 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9380 final int[] userIds) { 9381 mHandler.post(new Runnable() { 9382 @Override 9383 public void run() { 9384 try { 9385 final IActivityManager am = ActivityManagerNative.getDefault(); 9386 if (am == null) return; 9387 final int[] resolvedUserIds; 9388 if (userIds == null) { 9389 resolvedUserIds = am.getRunningUserIds(); 9390 } else { 9391 resolvedUserIds = userIds; 9392 } 9393 for (int id : resolvedUserIds) { 9394 final Intent intent = new Intent(action, 9395 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9396 if (extras != null) { 9397 intent.putExtras(extras); 9398 } 9399 if (targetPkg != null) { 9400 intent.setPackage(targetPkg); 9401 } 9402 // Modify the UID when posting to other users 9403 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9404 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9405 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9406 intent.putExtra(Intent.EXTRA_UID, uid); 9407 } 9408 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9409 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9410 if (DEBUG_BROADCASTS) { 9411 RuntimeException here = new RuntimeException("here"); 9412 here.fillInStackTrace(); 9413 Slog.d(TAG, "Sending to user " + id + ": " 9414 + intent.toShortString(false, true, false, false) 9415 + " " + intent.getExtras(), here); 9416 } 9417 am.broadcastIntent(null, intent, null, finishedReceiver, 9418 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9419 null, finishedReceiver != null, false, id); 9420 } 9421 } catch (RemoteException ex) { 9422 } 9423 } 9424 }); 9425 } 9426 9427 /** 9428 * Check if the external storage media is available. This is true if there 9429 * is a mounted external storage medium or if the external storage is 9430 * emulated. 9431 */ 9432 private boolean isExternalMediaAvailable() { 9433 return mMediaMounted || Environment.isExternalStorageEmulated(); 9434 } 9435 9436 @Override 9437 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9438 // writer 9439 synchronized (mPackages) { 9440 if (!isExternalMediaAvailable()) { 9441 // If the external storage is no longer mounted at this point, 9442 // the caller may not have been able to delete all of this 9443 // packages files and can not delete any more. Bail. 9444 return null; 9445 } 9446 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9447 if (lastPackage != null) { 9448 pkgs.remove(lastPackage); 9449 } 9450 if (pkgs.size() > 0) { 9451 return pkgs.get(0); 9452 } 9453 } 9454 return null; 9455 } 9456 9457 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9458 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9459 userId, andCode ? 1 : 0, packageName); 9460 if (mSystemReady) { 9461 msg.sendToTarget(); 9462 } else { 9463 if (mPostSystemReadyMessages == null) { 9464 mPostSystemReadyMessages = new ArrayList<>(); 9465 } 9466 mPostSystemReadyMessages.add(msg); 9467 } 9468 } 9469 9470 void startCleaningPackages() { 9471 // reader 9472 synchronized (mPackages) { 9473 if (!isExternalMediaAvailable()) { 9474 return; 9475 } 9476 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9477 return; 9478 } 9479 } 9480 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9481 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9482 IActivityManager am = ActivityManagerNative.getDefault(); 9483 if (am != null) { 9484 try { 9485 am.startService(null, intent, null, mContext.getOpPackageName(), 9486 UserHandle.USER_OWNER); 9487 } catch (RemoteException e) { 9488 } 9489 } 9490 } 9491 9492 @Override 9493 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9494 int installFlags, String installerPackageName, VerificationParams verificationParams, 9495 String packageAbiOverride) { 9496 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9497 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9498 } 9499 9500 @Override 9501 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9502 int installFlags, String installerPackageName, VerificationParams verificationParams, 9503 String packageAbiOverride, int userId) { 9504 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9505 9506 final int callingUid = Binder.getCallingUid(); 9507 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9508 9509 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9510 try { 9511 if (observer != null) { 9512 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9513 } 9514 } catch (RemoteException re) { 9515 } 9516 return; 9517 } 9518 9519 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9520 installFlags |= PackageManager.INSTALL_FROM_ADB; 9521 9522 } else { 9523 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9524 // about installerPackageName. 9525 9526 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9527 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9528 } 9529 9530 UserHandle user; 9531 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9532 user = UserHandle.ALL; 9533 } else { 9534 user = new UserHandle(userId); 9535 } 9536 9537 // Only system components can circumvent runtime permissions when installing. 9538 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9539 && mContext.checkCallingOrSelfPermission(Manifest.permission 9540 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9541 throw new SecurityException("You need the " 9542 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9543 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9544 } 9545 9546 verificationParams.setInstallerUid(callingUid); 9547 9548 final File originFile = new File(originPath); 9549 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9550 9551 final Message msg = mHandler.obtainMessage(INIT_COPY); 9552 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9553 null, verificationParams, user, packageAbiOverride, null); 9554 mHandler.sendMessage(msg); 9555 } 9556 9557 void installStage(String packageName, File stagedDir, String stagedCid, 9558 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9559 String installerPackageName, int installerUid, UserHandle user) { 9560 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9561 params.referrerUri, installerUid, null); 9562 verifParams.setInstallerUid(installerUid); 9563 9564 final OriginInfo origin; 9565 if (stagedDir != null) { 9566 origin = OriginInfo.fromStagedFile(stagedDir); 9567 } else { 9568 origin = OriginInfo.fromStagedContainer(stagedCid); 9569 } 9570 9571 final Message msg = mHandler.obtainMessage(INIT_COPY); 9572 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9573 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9574 params.grantedRuntimePermissions); 9575 mHandler.sendMessage(msg); 9576 } 9577 9578 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9579 Bundle extras = new Bundle(1); 9580 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9581 9582 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9583 packageName, extras, null, null, new int[] {userId}); 9584 try { 9585 IActivityManager am = ActivityManagerNative.getDefault(); 9586 final boolean isSystem = 9587 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9588 if (isSystem && am.isUserRunning(userId, false)) { 9589 // The just-installed/enabled app is bundled on the system, so presumed 9590 // to be able to run automatically without needing an explicit launch. 9591 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9592 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9593 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9594 .setPackage(packageName); 9595 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9596 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9597 } 9598 } catch (RemoteException e) { 9599 // shouldn't happen 9600 Slog.w(TAG, "Unable to bootstrap installed package", e); 9601 } 9602 } 9603 9604 @Override 9605 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9606 int userId) { 9607 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9608 PackageSetting pkgSetting; 9609 final int uid = Binder.getCallingUid(); 9610 enforceCrossUserPermission(uid, userId, true, true, 9611 "setApplicationHiddenSetting for user " + userId); 9612 9613 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9614 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9615 return false; 9616 } 9617 9618 long callingId = Binder.clearCallingIdentity(); 9619 try { 9620 boolean sendAdded = false; 9621 boolean sendRemoved = false; 9622 // writer 9623 synchronized (mPackages) { 9624 pkgSetting = mSettings.mPackages.get(packageName); 9625 if (pkgSetting == null) { 9626 return false; 9627 } 9628 if (pkgSetting.getHidden(userId) != hidden) { 9629 pkgSetting.setHidden(hidden, userId); 9630 mSettings.writePackageRestrictionsLPr(userId); 9631 if (hidden) { 9632 sendRemoved = true; 9633 } else { 9634 sendAdded = true; 9635 } 9636 } 9637 } 9638 if (sendAdded) { 9639 sendPackageAddedForUser(packageName, pkgSetting, userId); 9640 return true; 9641 } 9642 if (sendRemoved) { 9643 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9644 "hiding pkg"); 9645 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9646 return true; 9647 } 9648 } finally { 9649 Binder.restoreCallingIdentity(callingId); 9650 } 9651 return false; 9652 } 9653 9654 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9655 int userId) { 9656 final PackageRemovedInfo info = new PackageRemovedInfo(); 9657 info.removedPackage = packageName; 9658 info.removedUsers = new int[] {userId}; 9659 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9660 info.sendBroadcast(false, false, false); 9661 } 9662 9663 /** 9664 * Returns true if application is not found or there was an error. Otherwise it returns 9665 * the hidden state of the package for the given user. 9666 */ 9667 @Override 9668 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9669 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9670 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9671 false, "getApplicationHidden for user " + userId); 9672 PackageSetting pkgSetting; 9673 long callingId = Binder.clearCallingIdentity(); 9674 try { 9675 // writer 9676 synchronized (mPackages) { 9677 pkgSetting = mSettings.mPackages.get(packageName); 9678 if (pkgSetting == null) { 9679 return true; 9680 } 9681 return pkgSetting.getHidden(userId); 9682 } 9683 } finally { 9684 Binder.restoreCallingIdentity(callingId); 9685 } 9686 } 9687 9688 /** 9689 * @hide 9690 */ 9691 @Override 9692 public int installExistingPackageAsUser(String packageName, int userId) { 9693 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9694 null); 9695 PackageSetting pkgSetting; 9696 final int uid = Binder.getCallingUid(); 9697 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9698 + userId); 9699 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9700 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9701 } 9702 9703 long callingId = Binder.clearCallingIdentity(); 9704 try { 9705 boolean sendAdded = false; 9706 9707 // writer 9708 synchronized (mPackages) { 9709 pkgSetting = mSettings.mPackages.get(packageName); 9710 if (pkgSetting == null) { 9711 return PackageManager.INSTALL_FAILED_INVALID_URI; 9712 } 9713 if (!pkgSetting.getInstalled(userId)) { 9714 pkgSetting.setInstalled(true, userId); 9715 pkgSetting.setHidden(false, userId); 9716 mSettings.writePackageRestrictionsLPr(userId); 9717 sendAdded = true; 9718 } 9719 } 9720 9721 if (sendAdded) { 9722 sendPackageAddedForUser(packageName, pkgSetting, userId); 9723 } 9724 } finally { 9725 Binder.restoreCallingIdentity(callingId); 9726 } 9727 9728 return PackageManager.INSTALL_SUCCEEDED; 9729 } 9730 9731 boolean isUserRestricted(int userId, String restrictionKey) { 9732 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9733 if (restrictions.getBoolean(restrictionKey, false)) { 9734 Log.w(TAG, "User is restricted: " + restrictionKey); 9735 return true; 9736 } 9737 return false; 9738 } 9739 9740 @Override 9741 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9742 mContext.enforceCallingOrSelfPermission( 9743 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9744 "Only package verification agents can verify applications"); 9745 9746 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9747 final PackageVerificationResponse response = new PackageVerificationResponse( 9748 verificationCode, Binder.getCallingUid()); 9749 msg.arg1 = id; 9750 msg.obj = response; 9751 mHandler.sendMessage(msg); 9752 } 9753 9754 @Override 9755 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9756 long millisecondsToDelay) { 9757 mContext.enforceCallingOrSelfPermission( 9758 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9759 "Only package verification agents can extend verification timeouts"); 9760 9761 final PackageVerificationState state = mPendingVerification.get(id); 9762 final PackageVerificationResponse response = new PackageVerificationResponse( 9763 verificationCodeAtTimeout, Binder.getCallingUid()); 9764 9765 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9766 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9767 } 9768 if (millisecondsToDelay < 0) { 9769 millisecondsToDelay = 0; 9770 } 9771 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9772 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9773 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9774 } 9775 9776 if ((state != null) && !state.timeoutExtended()) { 9777 state.extendTimeout(); 9778 9779 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9780 msg.arg1 = id; 9781 msg.obj = response; 9782 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9783 } 9784 } 9785 9786 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9787 int verificationCode, UserHandle user) { 9788 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9789 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9790 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9791 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9792 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9793 9794 mContext.sendBroadcastAsUser(intent, user, 9795 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9796 } 9797 9798 private ComponentName matchComponentForVerifier(String packageName, 9799 List<ResolveInfo> receivers) { 9800 ActivityInfo targetReceiver = null; 9801 9802 final int NR = receivers.size(); 9803 for (int i = 0; i < NR; i++) { 9804 final ResolveInfo info = receivers.get(i); 9805 if (info.activityInfo == null) { 9806 continue; 9807 } 9808 9809 if (packageName.equals(info.activityInfo.packageName)) { 9810 targetReceiver = info.activityInfo; 9811 break; 9812 } 9813 } 9814 9815 if (targetReceiver == null) { 9816 return null; 9817 } 9818 9819 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9820 } 9821 9822 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9823 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9824 if (pkgInfo.verifiers.length == 0) { 9825 return null; 9826 } 9827 9828 final int N = pkgInfo.verifiers.length; 9829 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9830 for (int i = 0; i < N; i++) { 9831 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9832 9833 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9834 receivers); 9835 if (comp == null) { 9836 continue; 9837 } 9838 9839 final int verifierUid = getUidForVerifier(verifierInfo); 9840 if (verifierUid == -1) { 9841 continue; 9842 } 9843 9844 if (DEBUG_VERIFY) { 9845 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9846 + " with the correct signature"); 9847 } 9848 sufficientVerifiers.add(comp); 9849 verificationState.addSufficientVerifier(verifierUid); 9850 } 9851 9852 return sufficientVerifiers; 9853 } 9854 9855 private int getUidForVerifier(VerifierInfo verifierInfo) { 9856 synchronized (mPackages) { 9857 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9858 if (pkg == null) { 9859 return -1; 9860 } else if (pkg.mSignatures.length != 1) { 9861 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9862 + " has more than one signature; ignoring"); 9863 return -1; 9864 } 9865 9866 /* 9867 * If the public key of the package's signature does not match 9868 * our expected public key, then this is a different package and 9869 * we should skip. 9870 */ 9871 9872 final byte[] expectedPublicKey; 9873 try { 9874 final Signature verifierSig = pkg.mSignatures[0]; 9875 final PublicKey publicKey = verifierSig.getPublicKey(); 9876 expectedPublicKey = publicKey.getEncoded(); 9877 } catch (CertificateException e) { 9878 return -1; 9879 } 9880 9881 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9882 9883 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9884 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9885 + " does not have the expected public key; ignoring"); 9886 return -1; 9887 } 9888 9889 return pkg.applicationInfo.uid; 9890 } 9891 } 9892 9893 @Override 9894 public void finishPackageInstall(int token) { 9895 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9896 9897 if (DEBUG_INSTALL) { 9898 Slog.v(TAG, "BM finishing package install for " + token); 9899 } 9900 9901 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9902 mHandler.sendMessage(msg); 9903 } 9904 9905 /** 9906 * Get the verification agent timeout. 9907 * 9908 * @return verification timeout in milliseconds 9909 */ 9910 private long getVerificationTimeout() { 9911 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9912 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9913 DEFAULT_VERIFICATION_TIMEOUT); 9914 } 9915 9916 /** 9917 * Get the default verification agent response code. 9918 * 9919 * @return default verification response code 9920 */ 9921 private int getDefaultVerificationResponse() { 9922 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9923 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9924 DEFAULT_VERIFICATION_RESPONSE); 9925 } 9926 9927 /** 9928 * Check whether or not package verification has been enabled. 9929 * 9930 * @return true if verification should be performed 9931 */ 9932 private boolean isVerificationEnabled(int userId, int installFlags) { 9933 if (!DEFAULT_VERIFY_ENABLE) { 9934 return false; 9935 } 9936 9937 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9938 9939 // Check if installing from ADB 9940 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9941 // Do not run verification in a test harness environment 9942 if (ActivityManager.isRunningInTestHarness()) { 9943 return false; 9944 } 9945 if (ensureVerifyAppsEnabled) { 9946 return true; 9947 } 9948 // Check if the developer does not want package verification for ADB installs 9949 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9950 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9951 return false; 9952 } 9953 } 9954 9955 if (ensureVerifyAppsEnabled) { 9956 return true; 9957 } 9958 9959 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9960 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9961 } 9962 9963 @Override 9964 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9965 throws RemoteException { 9966 mContext.enforceCallingOrSelfPermission( 9967 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9968 "Only intentfilter verification agents can verify applications"); 9969 9970 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9971 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9972 Binder.getCallingUid(), verificationCode, failedDomains); 9973 msg.arg1 = id; 9974 msg.obj = response; 9975 mHandler.sendMessage(msg); 9976 } 9977 9978 @Override 9979 public int getIntentVerificationStatus(String packageName, int userId) { 9980 synchronized (mPackages) { 9981 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9982 } 9983 } 9984 9985 @Override 9986 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9987 mContext.enforceCallingOrSelfPermission( 9988 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9989 9990 boolean result = false; 9991 synchronized (mPackages) { 9992 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9993 } 9994 if (result) { 9995 scheduleWritePackageRestrictionsLocked(userId); 9996 } 9997 return result; 9998 } 9999 10000 @Override 10001 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10002 synchronized (mPackages) { 10003 return mSettings.getIntentFilterVerificationsLPr(packageName); 10004 } 10005 } 10006 10007 @Override 10008 public List<IntentFilter> getAllIntentFilters(String packageName) { 10009 if (TextUtils.isEmpty(packageName)) { 10010 return Collections.<IntentFilter>emptyList(); 10011 } 10012 synchronized (mPackages) { 10013 PackageParser.Package pkg = mPackages.get(packageName); 10014 if (pkg == null || pkg.activities == null) { 10015 return Collections.<IntentFilter>emptyList(); 10016 } 10017 final int count = pkg.activities.size(); 10018 ArrayList<IntentFilter> result = new ArrayList<>(); 10019 for (int n=0; n<count; n++) { 10020 PackageParser.Activity activity = pkg.activities.get(n); 10021 if (activity.intents != null || activity.intents.size() > 0) { 10022 result.addAll(activity.intents); 10023 } 10024 } 10025 return result; 10026 } 10027 } 10028 10029 @Override 10030 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10031 mContext.enforceCallingOrSelfPermission( 10032 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10033 10034 synchronized (mPackages) { 10035 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10036 if (packageName != null) { 10037 result |= updateIntentVerificationStatus(packageName, 10038 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10039 userId); 10040 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10041 packageName, userId); 10042 } 10043 return result; 10044 } 10045 } 10046 10047 @Override 10048 public String getDefaultBrowserPackageName(int userId) { 10049 synchronized (mPackages) { 10050 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10051 } 10052 } 10053 10054 /** 10055 * Get the "allow unknown sources" setting. 10056 * 10057 * @return the current "allow unknown sources" setting 10058 */ 10059 private int getUnknownSourcesSettings() { 10060 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10061 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10062 -1); 10063 } 10064 10065 @Override 10066 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10067 final int uid = Binder.getCallingUid(); 10068 // writer 10069 synchronized (mPackages) { 10070 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10071 if (targetPackageSetting == null) { 10072 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10073 } 10074 10075 PackageSetting installerPackageSetting; 10076 if (installerPackageName != null) { 10077 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10078 if (installerPackageSetting == null) { 10079 throw new IllegalArgumentException("Unknown installer package: " 10080 + installerPackageName); 10081 } 10082 } else { 10083 installerPackageSetting = null; 10084 } 10085 10086 Signature[] callerSignature; 10087 Object obj = mSettings.getUserIdLPr(uid); 10088 if (obj != null) { 10089 if (obj instanceof SharedUserSetting) { 10090 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10091 } else if (obj instanceof PackageSetting) { 10092 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10093 } else { 10094 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10095 } 10096 } else { 10097 throw new SecurityException("Unknown calling uid " + uid); 10098 } 10099 10100 // Verify: can't set installerPackageName to a package that is 10101 // not signed with the same cert as the caller. 10102 if (installerPackageSetting != null) { 10103 if (compareSignatures(callerSignature, 10104 installerPackageSetting.signatures.mSignatures) 10105 != PackageManager.SIGNATURE_MATCH) { 10106 throw new SecurityException( 10107 "Caller does not have same cert as new installer package " 10108 + installerPackageName); 10109 } 10110 } 10111 10112 // Verify: if target already has an installer package, it must 10113 // be signed with the same cert as the caller. 10114 if (targetPackageSetting.installerPackageName != null) { 10115 PackageSetting setting = mSettings.mPackages.get( 10116 targetPackageSetting.installerPackageName); 10117 // If the currently set package isn't valid, then it's always 10118 // okay to change it. 10119 if (setting != null) { 10120 if (compareSignatures(callerSignature, 10121 setting.signatures.mSignatures) 10122 != PackageManager.SIGNATURE_MATCH) { 10123 throw new SecurityException( 10124 "Caller does not have same cert as old installer package " 10125 + targetPackageSetting.installerPackageName); 10126 } 10127 } 10128 } 10129 10130 // Okay! 10131 targetPackageSetting.installerPackageName = installerPackageName; 10132 scheduleWriteSettingsLocked(); 10133 } 10134 } 10135 10136 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10137 // Queue up an async operation since the package installation may take a little while. 10138 mHandler.post(new Runnable() { 10139 public void run() { 10140 mHandler.removeCallbacks(this); 10141 // Result object to be returned 10142 PackageInstalledInfo res = new PackageInstalledInfo(); 10143 res.returnCode = currentStatus; 10144 res.uid = -1; 10145 res.pkg = null; 10146 res.removedInfo = new PackageRemovedInfo(); 10147 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10148 args.doPreInstall(res.returnCode); 10149 synchronized (mInstallLock) { 10150 installPackageLI(args, res); 10151 } 10152 args.doPostInstall(res.returnCode, res.uid); 10153 } 10154 10155 // A restore should be performed at this point if (a) the install 10156 // succeeded, (b) the operation is not an update, and (c) the new 10157 // package has not opted out of backup participation. 10158 final boolean update = res.removedInfo.removedPackage != null; 10159 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10160 boolean doRestore = !update 10161 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10162 10163 // Set up the post-install work request bookkeeping. This will be used 10164 // and cleaned up by the post-install event handling regardless of whether 10165 // there's a restore pass performed. Token values are >= 1. 10166 int token; 10167 if (mNextInstallToken < 0) mNextInstallToken = 1; 10168 token = mNextInstallToken++; 10169 10170 PostInstallData data = new PostInstallData(args, res); 10171 mRunningInstalls.put(token, data); 10172 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10173 10174 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10175 // Pass responsibility to the Backup Manager. It will perform a 10176 // restore if appropriate, then pass responsibility back to the 10177 // Package Manager to run the post-install observer callbacks 10178 // and broadcasts. 10179 IBackupManager bm = IBackupManager.Stub.asInterface( 10180 ServiceManager.getService(Context.BACKUP_SERVICE)); 10181 if (bm != null) { 10182 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10183 + " to BM for possible restore"); 10184 try { 10185 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10186 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10187 } else { 10188 doRestore = false; 10189 } 10190 } catch (RemoteException e) { 10191 // can't happen; the backup manager is local 10192 } catch (Exception e) { 10193 Slog.e(TAG, "Exception trying to enqueue restore", e); 10194 doRestore = false; 10195 } 10196 } else { 10197 Slog.e(TAG, "Backup Manager not found!"); 10198 doRestore = false; 10199 } 10200 } 10201 10202 if (!doRestore) { 10203 // No restore possible, or the Backup Manager was mysteriously not 10204 // available -- just fire the post-install work request directly. 10205 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10206 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10207 mHandler.sendMessage(msg); 10208 } 10209 } 10210 }); 10211 } 10212 10213 private abstract class HandlerParams { 10214 private static final int MAX_RETRIES = 4; 10215 10216 /** 10217 * Number of times startCopy() has been attempted and had a non-fatal 10218 * error. 10219 */ 10220 private int mRetries = 0; 10221 10222 /** User handle for the user requesting the information or installation. */ 10223 private final UserHandle mUser; 10224 10225 HandlerParams(UserHandle user) { 10226 mUser = user; 10227 } 10228 10229 UserHandle getUser() { 10230 return mUser; 10231 } 10232 10233 final boolean startCopy() { 10234 boolean res; 10235 try { 10236 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10237 10238 if (++mRetries > MAX_RETRIES) { 10239 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10240 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10241 handleServiceError(); 10242 return false; 10243 } else { 10244 handleStartCopy(); 10245 res = true; 10246 } 10247 } catch (RemoteException e) { 10248 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10249 mHandler.sendEmptyMessage(MCS_RECONNECT); 10250 res = false; 10251 } 10252 handleReturnCode(); 10253 return res; 10254 } 10255 10256 final void serviceError() { 10257 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10258 handleServiceError(); 10259 handleReturnCode(); 10260 } 10261 10262 abstract void handleStartCopy() throws RemoteException; 10263 abstract void handleServiceError(); 10264 abstract void handleReturnCode(); 10265 } 10266 10267 class MeasureParams extends HandlerParams { 10268 private final PackageStats mStats; 10269 private boolean mSuccess; 10270 10271 private final IPackageStatsObserver mObserver; 10272 10273 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10274 super(new UserHandle(stats.userHandle)); 10275 mObserver = observer; 10276 mStats = stats; 10277 } 10278 10279 @Override 10280 public String toString() { 10281 return "MeasureParams{" 10282 + Integer.toHexString(System.identityHashCode(this)) 10283 + " " + mStats.packageName + "}"; 10284 } 10285 10286 @Override 10287 void handleStartCopy() throws RemoteException { 10288 synchronized (mInstallLock) { 10289 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10290 } 10291 10292 if (mSuccess) { 10293 final boolean mounted; 10294 if (Environment.isExternalStorageEmulated()) { 10295 mounted = true; 10296 } else { 10297 final String status = Environment.getExternalStorageState(); 10298 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10299 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10300 } 10301 10302 if (mounted) { 10303 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10304 10305 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10306 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10307 10308 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10309 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10310 10311 // Always subtract cache size, since it's a subdirectory 10312 mStats.externalDataSize -= mStats.externalCacheSize; 10313 10314 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10315 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10316 10317 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10318 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10319 } 10320 } 10321 } 10322 10323 @Override 10324 void handleReturnCode() { 10325 if (mObserver != null) { 10326 try { 10327 mObserver.onGetStatsCompleted(mStats, mSuccess); 10328 } catch (RemoteException e) { 10329 Slog.i(TAG, "Observer no longer exists."); 10330 } 10331 } 10332 } 10333 10334 @Override 10335 void handleServiceError() { 10336 Slog.e(TAG, "Could not measure application " + mStats.packageName 10337 + " external storage"); 10338 } 10339 } 10340 10341 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10342 throws RemoteException { 10343 long result = 0; 10344 for (File path : paths) { 10345 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10346 } 10347 return result; 10348 } 10349 10350 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10351 for (File path : paths) { 10352 try { 10353 mcs.clearDirectory(path.getAbsolutePath()); 10354 } catch (RemoteException e) { 10355 } 10356 } 10357 } 10358 10359 static class OriginInfo { 10360 /** 10361 * Location where install is coming from, before it has been 10362 * copied/renamed into place. This could be a single monolithic APK 10363 * file, or a cluster directory. This location may be untrusted. 10364 */ 10365 final File file; 10366 final String cid; 10367 10368 /** 10369 * Flag indicating that {@link #file} or {@link #cid} has already been 10370 * staged, meaning downstream users don't need to defensively copy the 10371 * contents. 10372 */ 10373 final boolean staged; 10374 10375 /** 10376 * Flag indicating that {@link #file} or {@link #cid} is an already 10377 * installed app that is being moved. 10378 */ 10379 final boolean existing; 10380 10381 final String resolvedPath; 10382 final File resolvedFile; 10383 10384 static OriginInfo fromNothing() { 10385 return new OriginInfo(null, null, false, false); 10386 } 10387 10388 static OriginInfo fromUntrustedFile(File file) { 10389 return new OriginInfo(file, null, false, false); 10390 } 10391 10392 static OriginInfo fromExistingFile(File file) { 10393 return new OriginInfo(file, null, false, true); 10394 } 10395 10396 static OriginInfo fromStagedFile(File file) { 10397 return new OriginInfo(file, null, true, false); 10398 } 10399 10400 static OriginInfo fromStagedContainer(String cid) { 10401 return new OriginInfo(null, cid, true, false); 10402 } 10403 10404 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10405 this.file = file; 10406 this.cid = cid; 10407 this.staged = staged; 10408 this.existing = existing; 10409 10410 if (cid != null) { 10411 resolvedPath = PackageHelper.getSdDir(cid); 10412 resolvedFile = new File(resolvedPath); 10413 } else if (file != null) { 10414 resolvedPath = file.getAbsolutePath(); 10415 resolvedFile = file; 10416 } else { 10417 resolvedPath = null; 10418 resolvedFile = null; 10419 } 10420 } 10421 } 10422 10423 class MoveInfo { 10424 final int moveId; 10425 final String fromUuid; 10426 final String toUuid; 10427 final String packageName; 10428 final String dataAppName; 10429 final int appId; 10430 final String seinfo; 10431 10432 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10433 String dataAppName, int appId, String seinfo) { 10434 this.moveId = moveId; 10435 this.fromUuid = fromUuid; 10436 this.toUuid = toUuid; 10437 this.packageName = packageName; 10438 this.dataAppName = dataAppName; 10439 this.appId = appId; 10440 this.seinfo = seinfo; 10441 } 10442 } 10443 10444 class InstallParams extends HandlerParams { 10445 final OriginInfo origin; 10446 final MoveInfo move; 10447 final IPackageInstallObserver2 observer; 10448 int installFlags; 10449 final String installerPackageName; 10450 final String volumeUuid; 10451 final VerificationParams verificationParams; 10452 private InstallArgs mArgs; 10453 private int mRet; 10454 final String packageAbiOverride; 10455 final String[] grantedRuntimePermissions; 10456 10457 10458 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10459 int installFlags, String installerPackageName, String volumeUuid, 10460 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10461 String[] grantedPermissions) { 10462 super(user); 10463 this.origin = origin; 10464 this.move = move; 10465 this.observer = observer; 10466 this.installFlags = installFlags; 10467 this.installerPackageName = installerPackageName; 10468 this.volumeUuid = volumeUuid; 10469 this.verificationParams = verificationParams; 10470 this.packageAbiOverride = packageAbiOverride; 10471 this.grantedRuntimePermissions = grantedPermissions; 10472 } 10473 10474 @Override 10475 public String toString() { 10476 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10477 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10478 } 10479 10480 public ManifestDigest getManifestDigest() { 10481 if (verificationParams == null) { 10482 return null; 10483 } 10484 return verificationParams.getManifestDigest(); 10485 } 10486 10487 private int installLocationPolicy(PackageInfoLite pkgLite) { 10488 String packageName = pkgLite.packageName; 10489 int installLocation = pkgLite.installLocation; 10490 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10491 // reader 10492 synchronized (mPackages) { 10493 PackageParser.Package pkg = mPackages.get(packageName); 10494 if (pkg != null) { 10495 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10496 // Check for downgrading. 10497 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10498 try { 10499 checkDowngrade(pkg, pkgLite); 10500 } catch (PackageManagerException e) { 10501 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10502 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10503 } 10504 } 10505 // Check for updated system application. 10506 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10507 if (onSd) { 10508 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10509 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10510 } 10511 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10512 } else { 10513 if (onSd) { 10514 // Install flag overrides everything. 10515 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10516 } 10517 // If current upgrade specifies particular preference 10518 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10519 // Application explicitly specified internal. 10520 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10521 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10522 // App explictly prefers external. Let policy decide 10523 } else { 10524 // Prefer previous location 10525 if (isExternal(pkg)) { 10526 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10527 } 10528 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10529 } 10530 } 10531 } else { 10532 // Invalid install. Return error code 10533 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10534 } 10535 } 10536 } 10537 // All the special cases have been taken care of. 10538 // Return result based on recommended install location. 10539 if (onSd) { 10540 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10541 } 10542 return pkgLite.recommendedInstallLocation; 10543 } 10544 10545 /* 10546 * Invoke remote method to get package information and install 10547 * location values. Override install location based on default 10548 * policy if needed and then create install arguments based 10549 * on the install location. 10550 */ 10551 public void handleStartCopy() throws RemoteException { 10552 int ret = PackageManager.INSTALL_SUCCEEDED; 10553 10554 // If we're already staged, we've firmly committed to an install location 10555 if (origin.staged) { 10556 if (origin.file != null) { 10557 installFlags |= PackageManager.INSTALL_INTERNAL; 10558 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10559 } else if (origin.cid != null) { 10560 installFlags |= PackageManager.INSTALL_EXTERNAL; 10561 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10562 } else { 10563 throw new IllegalStateException("Invalid stage location"); 10564 } 10565 } 10566 10567 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10568 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10569 10570 PackageInfoLite pkgLite = null; 10571 10572 if (onInt && onSd) { 10573 // Check if both bits are set. 10574 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10575 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10576 } else { 10577 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10578 packageAbiOverride); 10579 10580 /* 10581 * If we have too little free space, try to free cache 10582 * before giving up. 10583 */ 10584 if (!origin.staged && pkgLite.recommendedInstallLocation 10585 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10586 // TODO: focus freeing disk space on the target device 10587 final StorageManager storage = StorageManager.from(mContext); 10588 final long lowThreshold = storage.getStorageLowBytes( 10589 Environment.getDataDirectory()); 10590 10591 final long sizeBytes = mContainerService.calculateInstalledSize( 10592 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10593 10594 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10595 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10596 installFlags, packageAbiOverride); 10597 } 10598 10599 /* 10600 * The cache free must have deleted the file we 10601 * downloaded to install. 10602 * 10603 * TODO: fix the "freeCache" call to not delete 10604 * the file we care about. 10605 */ 10606 if (pkgLite.recommendedInstallLocation 10607 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10608 pkgLite.recommendedInstallLocation 10609 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10610 } 10611 } 10612 } 10613 10614 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10615 int loc = pkgLite.recommendedInstallLocation; 10616 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10617 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10618 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10619 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10620 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10621 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10622 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10623 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10624 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10625 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10626 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10627 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10628 } else { 10629 // Override with defaults if needed. 10630 loc = installLocationPolicy(pkgLite); 10631 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10632 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10633 } else if (!onSd && !onInt) { 10634 // Override install location with flags 10635 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10636 // Set the flag to install on external media. 10637 installFlags |= PackageManager.INSTALL_EXTERNAL; 10638 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10639 } else { 10640 // Make sure the flag for installing on external 10641 // media is unset 10642 installFlags |= PackageManager.INSTALL_INTERNAL; 10643 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10644 } 10645 } 10646 } 10647 } 10648 10649 final InstallArgs args = createInstallArgs(this); 10650 mArgs = args; 10651 10652 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10653 /* 10654 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10655 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10656 */ 10657 int userIdentifier = getUser().getIdentifier(); 10658 if (userIdentifier == UserHandle.USER_ALL 10659 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10660 userIdentifier = UserHandle.USER_OWNER; 10661 } 10662 10663 /* 10664 * Determine if we have any installed package verifiers. If we 10665 * do, then we'll defer to them to verify the packages. 10666 */ 10667 final int requiredUid = mRequiredVerifierPackage == null ? -1 10668 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10669 if (!origin.existing && requiredUid != -1 10670 && isVerificationEnabled(userIdentifier, installFlags)) { 10671 final Intent verification = new Intent( 10672 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10673 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10674 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10675 PACKAGE_MIME_TYPE); 10676 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10677 10678 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10679 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10680 0 /* TODO: Which userId? */); 10681 10682 if (DEBUG_VERIFY) { 10683 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10684 + verification.toString() + " with " + pkgLite.verifiers.length 10685 + " optional verifiers"); 10686 } 10687 10688 final int verificationId = mPendingVerificationToken++; 10689 10690 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10691 10692 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10693 installerPackageName); 10694 10695 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10696 installFlags); 10697 10698 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10699 pkgLite.packageName); 10700 10701 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10702 pkgLite.versionCode); 10703 10704 if (verificationParams != null) { 10705 if (verificationParams.getVerificationURI() != null) { 10706 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10707 verificationParams.getVerificationURI()); 10708 } 10709 if (verificationParams.getOriginatingURI() != null) { 10710 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10711 verificationParams.getOriginatingURI()); 10712 } 10713 if (verificationParams.getReferrer() != null) { 10714 verification.putExtra(Intent.EXTRA_REFERRER, 10715 verificationParams.getReferrer()); 10716 } 10717 if (verificationParams.getOriginatingUid() >= 0) { 10718 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10719 verificationParams.getOriginatingUid()); 10720 } 10721 if (verificationParams.getInstallerUid() >= 0) { 10722 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10723 verificationParams.getInstallerUid()); 10724 } 10725 } 10726 10727 final PackageVerificationState verificationState = new PackageVerificationState( 10728 requiredUid, args); 10729 10730 mPendingVerification.append(verificationId, verificationState); 10731 10732 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10733 receivers, verificationState); 10734 10735 // Apps installed for "all" users use the device owner to verify the app 10736 UserHandle verifierUser = getUser(); 10737 if (verifierUser == UserHandle.ALL) { 10738 verifierUser = UserHandle.OWNER; 10739 } 10740 10741 /* 10742 * If any sufficient verifiers were listed in the package 10743 * manifest, attempt to ask them. 10744 */ 10745 if (sufficientVerifiers != null) { 10746 final int N = sufficientVerifiers.size(); 10747 if (N == 0) { 10748 Slog.i(TAG, "Additional verifiers required, but none installed."); 10749 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10750 } else { 10751 for (int i = 0; i < N; i++) { 10752 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10753 10754 final Intent sufficientIntent = new Intent(verification); 10755 sufficientIntent.setComponent(verifierComponent); 10756 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10757 } 10758 } 10759 } 10760 10761 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10762 mRequiredVerifierPackage, receivers); 10763 if (ret == PackageManager.INSTALL_SUCCEEDED 10764 && mRequiredVerifierPackage != null) { 10765 /* 10766 * Send the intent to the required verification agent, 10767 * but only start the verification timeout after the 10768 * target BroadcastReceivers have run. 10769 */ 10770 verification.setComponent(requiredVerifierComponent); 10771 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10772 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10773 new BroadcastReceiver() { 10774 @Override 10775 public void onReceive(Context context, Intent intent) { 10776 final Message msg = mHandler 10777 .obtainMessage(CHECK_PENDING_VERIFICATION); 10778 msg.arg1 = verificationId; 10779 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10780 } 10781 }, null, 0, null, null); 10782 10783 /* 10784 * We don't want the copy to proceed until verification 10785 * succeeds, so null out this field. 10786 */ 10787 mArgs = null; 10788 } 10789 } else { 10790 /* 10791 * No package verification is enabled, so immediately start 10792 * the remote call to initiate copy using temporary file. 10793 */ 10794 ret = args.copyApk(mContainerService, true); 10795 } 10796 } 10797 10798 mRet = ret; 10799 } 10800 10801 @Override 10802 void handleReturnCode() { 10803 // If mArgs is null, then MCS couldn't be reached. When it 10804 // reconnects, it will try again to install. At that point, this 10805 // will succeed. 10806 if (mArgs != null) { 10807 processPendingInstall(mArgs, mRet); 10808 } 10809 } 10810 10811 @Override 10812 void handleServiceError() { 10813 mArgs = createInstallArgs(this); 10814 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10815 } 10816 10817 public boolean isForwardLocked() { 10818 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10819 } 10820 } 10821 10822 /** 10823 * Used during creation of InstallArgs 10824 * 10825 * @param installFlags package installation flags 10826 * @return true if should be installed on external storage 10827 */ 10828 private static boolean installOnExternalAsec(int installFlags) { 10829 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10830 return false; 10831 } 10832 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10833 return true; 10834 } 10835 return false; 10836 } 10837 10838 /** 10839 * Used during creation of InstallArgs 10840 * 10841 * @param installFlags package installation flags 10842 * @return true if should be installed as forward locked 10843 */ 10844 private static boolean installForwardLocked(int installFlags) { 10845 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10846 } 10847 10848 private InstallArgs createInstallArgs(InstallParams params) { 10849 if (params.move != null) { 10850 return new MoveInstallArgs(params); 10851 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10852 return new AsecInstallArgs(params); 10853 } else { 10854 return new FileInstallArgs(params); 10855 } 10856 } 10857 10858 /** 10859 * Create args that describe an existing installed package. Typically used 10860 * when cleaning up old installs, or used as a move source. 10861 */ 10862 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10863 String resourcePath, String[] instructionSets) { 10864 final boolean isInAsec; 10865 if (installOnExternalAsec(installFlags)) { 10866 /* Apps on SD card are always in ASEC containers. */ 10867 isInAsec = true; 10868 } else if (installForwardLocked(installFlags) 10869 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10870 /* 10871 * Forward-locked apps are only in ASEC containers if they're the 10872 * new style 10873 */ 10874 isInAsec = true; 10875 } else { 10876 isInAsec = false; 10877 } 10878 10879 if (isInAsec) { 10880 return new AsecInstallArgs(codePath, instructionSets, 10881 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10882 } else { 10883 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10884 } 10885 } 10886 10887 static abstract class InstallArgs { 10888 /** @see InstallParams#origin */ 10889 final OriginInfo origin; 10890 /** @see InstallParams#move */ 10891 final MoveInfo move; 10892 10893 final IPackageInstallObserver2 observer; 10894 // Always refers to PackageManager flags only 10895 final int installFlags; 10896 final String installerPackageName; 10897 final String volumeUuid; 10898 final ManifestDigest manifestDigest; 10899 final UserHandle user; 10900 final String abiOverride; 10901 final String[] installGrantPermissions; 10902 10903 // The list of instruction sets supported by this app. This is currently 10904 // only used during the rmdex() phase to clean up resources. We can get rid of this 10905 // if we move dex files under the common app path. 10906 /* nullable */ String[] instructionSets; 10907 10908 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10909 int installFlags, String installerPackageName, String volumeUuid, 10910 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10911 String abiOverride, String[] installGrantPermissions) { 10912 this.origin = origin; 10913 this.move = move; 10914 this.installFlags = installFlags; 10915 this.observer = observer; 10916 this.installerPackageName = installerPackageName; 10917 this.volumeUuid = volumeUuid; 10918 this.manifestDigest = manifestDigest; 10919 this.user = user; 10920 this.instructionSets = instructionSets; 10921 this.abiOverride = abiOverride; 10922 this.installGrantPermissions = installGrantPermissions; 10923 } 10924 10925 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10926 abstract int doPreInstall(int status); 10927 10928 /** 10929 * Rename package into final resting place. All paths on the given 10930 * scanned package should be updated to reflect the rename. 10931 */ 10932 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10933 abstract int doPostInstall(int status, int uid); 10934 10935 /** @see PackageSettingBase#codePathString */ 10936 abstract String getCodePath(); 10937 /** @see PackageSettingBase#resourcePathString */ 10938 abstract String getResourcePath(); 10939 10940 // Need installer lock especially for dex file removal. 10941 abstract void cleanUpResourcesLI(); 10942 abstract boolean doPostDeleteLI(boolean delete); 10943 10944 /** 10945 * Called before the source arguments are copied. This is used mostly 10946 * for MoveParams when it needs to read the source file to put it in the 10947 * destination. 10948 */ 10949 int doPreCopy() { 10950 return PackageManager.INSTALL_SUCCEEDED; 10951 } 10952 10953 /** 10954 * Called after the source arguments are copied. This is used mostly for 10955 * MoveParams when it needs to read the source file to put it in the 10956 * destination. 10957 * 10958 * @return 10959 */ 10960 int doPostCopy(int uid) { 10961 return PackageManager.INSTALL_SUCCEEDED; 10962 } 10963 10964 protected boolean isFwdLocked() { 10965 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10966 } 10967 10968 protected boolean isExternalAsec() { 10969 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10970 } 10971 10972 UserHandle getUser() { 10973 return user; 10974 } 10975 } 10976 10977 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10978 if (!allCodePaths.isEmpty()) { 10979 if (instructionSets == null) { 10980 throw new IllegalStateException("instructionSet == null"); 10981 } 10982 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10983 for (String codePath : allCodePaths) { 10984 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10985 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10986 if (retCode < 0) { 10987 Slog.w(TAG, "Couldn't remove dex file for package: " 10988 + " at location " + codePath + ", retcode=" + retCode); 10989 // we don't consider this to be a failure of the core package deletion 10990 } 10991 } 10992 } 10993 } 10994 } 10995 10996 /** 10997 * Logic to handle installation of non-ASEC applications, including copying 10998 * and renaming logic. 10999 */ 11000 class FileInstallArgs extends InstallArgs { 11001 private File codeFile; 11002 private File resourceFile; 11003 11004 // Example topology: 11005 // /data/app/com.example/base.apk 11006 // /data/app/com.example/split_foo.apk 11007 // /data/app/com.example/lib/arm/libfoo.so 11008 // /data/app/com.example/lib/arm64/libfoo.so 11009 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11010 11011 /** New install */ 11012 FileInstallArgs(InstallParams params) { 11013 super(params.origin, params.move, params.observer, params.installFlags, 11014 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11015 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11016 params.grantedRuntimePermissions); 11017 if (isFwdLocked()) { 11018 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11019 } 11020 } 11021 11022 /** Existing install */ 11023 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11024 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11025 null, null); 11026 this.codeFile = (codePath != null) ? new File(codePath) : null; 11027 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11028 } 11029 11030 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11031 if (origin.staged) { 11032 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11033 codeFile = origin.file; 11034 resourceFile = origin.file; 11035 return PackageManager.INSTALL_SUCCEEDED; 11036 } 11037 11038 try { 11039 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11040 codeFile = tempDir; 11041 resourceFile = tempDir; 11042 } catch (IOException e) { 11043 Slog.w(TAG, "Failed to create copy file: " + e); 11044 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11045 } 11046 11047 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11048 @Override 11049 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11050 if (!FileUtils.isValidExtFilename(name)) { 11051 throw new IllegalArgumentException("Invalid filename: " + name); 11052 } 11053 try { 11054 final File file = new File(codeFile, name); 11055 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11056 O_RDWR | O_CREAT, 0644); 11057 Os.chmod(file.getAbsolutePath(), 0644); 11058 return new ParcelFileDescriptor(fd); 11059 } catch (ErrnoException e) { 11060 throw new RemoteException("Failed to open: " + e.getMessage()); 11061 } 11062 } 11063 }; 11064 11065 int ret = PackageManager.INSTALL_SUCCEEDED; 11066 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11067 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11068 Slog.e(TAG, "Failed to copy package"); 11069 return ret; 11070 } 11071 11072 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11073 NativeLibraryHelper.Handle handle = null; 11074 try { 11075 handle = NativeLibraryHelper.Handle.create(codeFile); 11076 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11077 abiOverride); 11078 } catch (IOException e) { 11079 Slog.e(TAG, "Copying native libraries failed", e); 11080 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11081 } finally { 11082 IoUtils.closeQuietly(handle); 11083 } 11084 11085 return ret; 11086 } 11087 11088 int doPreInstall(int status) { 11089 if (status != PackageManager.INSTALL_SUCCEEDED) { 11090 cleanUp(); 11091 } 11092 return status; 11093 } 11094 11095 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11096 if (status != PackageManager.INSTALL_SUCCEEDED) { 11097 cleanUp(); 11098 return false; 11099 } 11100 11101 final File targetDir = codeFile.getParentFile(); 11102 final File beforeCodeFile = codeFile; 11103 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11104 11105 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11106 try { 11107 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11108 } catch (ErrnoException e) { 11109 Slog.w(TAG, "Failed to rename", e); 11110 return false; 11111 } 11112 11113 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11114 Slog.w(TAG, "Failed to restorecon"); 11115 return false; 11116 } 11117 11118 // Reflect the rename internally 11119 codeFile = afterCodeFile; 11120 resourceFile = afterCodeFile; 11121 11122 // Reflect the rename in scanned details 11123 pkg.codePath = afterCodeFile.getAbsolutePath(); 11124 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11125 pkg.baseCodePath); 11126 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11127 pkg.splitCodePaths); 11128 11129 // Reflect the rename in app info 11130 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11131 pkg.applicationInfo.setCodePath(pkg.codePath); 11132 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11133 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11134 pkg.applicationInfo.setResourcePath(pkg.codePath); 11135 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11136 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11137 11138 return true; 11139 } 11140 11141 int doPostInstall(int status, int uid) { 11142 if (status != PackageManager.INSTALL_SUCCEEDED) { 11143 cleanUp(); 11144 } 11145 return status; 11146 } 11147 11148 @Override 11149 String getCodePath() { 11150 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11151 } 11152 11153 @Override 11154 String getResourcePath() { 11155 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11156 } 11157 11158 private boolean cleanUp() { 11159 if (codeFile == null || !codeFile.exists()) { 11160 return false; 11161 } 11162 11163 if (codeFile.isDirectory()) { 11164 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11165 } else { 11166 codeFile.delete(); 11167 } 11168 11169 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11170 resourceFile.delete(); 11171 } 11172 11173 return true; 11174 } 11175 11176 void cleanUpResourcesLI() { 11177 // Try enumerating all code paths before deleting 11178 List<String> allCodePaths = Collections.EMPTY_LIST; 11179 if (codeFile != null && codeFile.exists()) { 11180 try { 11181 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11182 allCodePaths = pkg.getAllCodePaths(); 11183 } catch (PackageParserException e) { 11184 // Ignored; we tried our best 11185 } 11186 } 11187 11188 cleanUp(); 11189 removeDexFiles(allCodePaths, instructionSets); 11190 } 11191 11192 boolean doPostDeleteLI(boolean delete) { 11193 // XXX err, shouldn't we respect the delete flag? 11194 cleanUpResourcesLI(); 11195 return true; 11196 } 11197 } 11198 11199 private boolean isAsecExternal(String cid) { 11200 final String asecPath = PackageHelper.getSdFilesystem(cid); 11201 return !asecPath.startsWith(mAsecInternalPath); 11202 } 11203 11204 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11205 PackageManagerException { 11206 if (copyRet < 0) { 11207 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11208 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11209 throw new PackageManagerException(copyRet, message); 11210 } 11211 } 11212 } 11213 11214 /** 11215 * Extract the MountService "container ID" from the full code path of an 11216 * .apk. 11217 */ 11218 static String cidFromCodePath(String fullCodePath) { 11219 int eidx = fullCodePath.lastIndexOf("/"); 11220 String subStr1 = fullCodePath.substring(0, eidx); 11221 int sidx = subStr1.lastIndexOf("/"); 11222 return subStr1.substring(sidx+1, eidx); 11223 } 11224 11225 /** 11226 * Logic to handle installation of ASEC applications, including copying and 11227 * renaming logic. 11228 */ 11229 class AsecInstallArgs extends InstallArgs { 11230 static final String RES_FILE_NAME = "pkg.apk"; 11231 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11232 11233 String cid; 11234 String packagePath; 11235 String resourcePath; 11236 11237 /** New install */ 11238 AsecInstallArgs(InstallParams params) { 11239 super(params.origin, params.move, params.observer, params.installFlags, 11240 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11241 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11242 params.grantedRuntimePermissions); 11243 } 11244 11245 /** Existing install */ 11246 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11247 boolean isExternal, boolean isForwardLocked) { 11248 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11249 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11250 instructionSets, null, null); 11251 // Hackily pretend we're still looking at a full code path 11252 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11253 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11254 } 11255 11256 // Extract cid from fullCodePath 11257 int eidx = fullCodePath.lastIndexOf("/"); 11258 String subStr1 = fullCodePath.substring(0, eidx); 11259 int sidx = subStr1.lastIndexOf("/"); 11260 cid = subStr1.substring(sidx+1, eidx); 11261 setMountPath(subStr1); 11262 } 11263 11264 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11265 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11266 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11267 instructionSets, null, null); 11268 this.cid = cid; 11269 setMountPath(PackageHelper.getSdDir(cid)); 11270 } 11271 11272 void createCopyFile() { 11273 cid = mInstallerService.allocateExternalStageCidLegacy(); 11274 } 11275 11276 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11277 if (origin.staged) { 11278 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11279 cid = origin.cid; 11280 setMountPath(PackageHelper.getSdDir(cid)); 11281 return PackageManager.INSTALL_SUCCEEDED; 11282 } 11283 11284 if (temp) { 11285 createCopyFile(); 11286 } else { 11287 /* 11288 * Pre-emptively destroy the container since it's destroyed if 11289 * copying fails due to it existing anyway. 11290 */ 11291 PackageHelper.destroySdDir(cid); 11292 } 11293 11294 final String newMountPath = imcs.copyPackageToContainer( 11295 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11296 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11297 11298 if (newMountPath != null) { 11299 setMountPath(newMountPath); 11300 return PackageManager.INSTALL_SUCCEEDED; 11301 } else { 11302 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11303 } 11304 } 11305 11306 @Override 11307 String getCodePath() { 11308 return packagePath; 11309 } 11310 11311 @Override 11312 String getResourcePath() { 11313 return resourcePath; 11314 } 11315 11316 int doPreInstall(int status) { 11317 if (status != PackageManager.INSTALL_SUCCEEDED) { 11318 // Destroy container 11319 PackageHelper.destroySdDir(cid); 11320 } else { 11321 boolean mounted = PackageHelper.isContainerMounted(cid); 11322 if (!mounted) { 11323 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11324 Process.SYSTEM_UID); 11325 if (newMountPath != null) { 11326 setMountPath(newMountPath); 11327 } else { 11328 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11329 } 11330 } 11331 } 11332 return status; 11333 } 11334 11335 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11336 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11337 String newMountPath = null; 11338 if (PackageHelper.isContainerMounted(cid)) { 11339 // Unmount the container 11340 if (!PackageHelper.unMountSdDir(cid)) { 11341 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11342 return false; 11343 } 11344 } 11345 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11346 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11347 " which might be stale. Will try to clean up."); 11348 // Clean up the stale container and proceed to recreate. 11349 if (!PackageHelper.destroySdDir(newCacheId)) { 11350 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11351 return false; 11352 } 11353 // Successfully cleaned up stale container. Try to rename again. 11354 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11355 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11356 + " inspite of cleaning it up."); 11357 return false; 11358 } 11359 } 11360 if (!PackageHelper.isContainerMounted(newCacheId)) { 11361 Slog.w(TAG, "Mounting container " + newCacheId); 11362 newMountPath = PackageHelper.mountSdDir(newCacheId, 11363 getEncryptKey(), Process.SYSTEM_UID); 11364 } else { 11365 newMountPath = PackageHelper.getSdDir(newCacheId); 11366 } 11367 if (newMountPath == null) { 11368 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11369 return false; 11370 } 11371 Log.i(TAG, "Succesfully renamed " + cid + 11372 " to " + newCacheId + 11373 " at new path: " + newMountPath); 11374 cid = newCacheId; 11375 11376 final File beforeCodeFile = new File(packagePath); 11377 setMountPath(newMountPath); 11378 final File afterCodeFile = new File(packagePath); 11379 11380 // Reflect the rename in scanned details 11381 pkg.codePath = afterCodeFile.getAbsolutePath(); 11382 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11383 pkg.baseCodePath); 11384 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11385 pkg.splitCodePaths); 11386 11387 // Reflect the rename in app info 11388 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11389 pkg.applicationInfo.setCodePath(pkg.codePath); 11390 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11391 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11392 pkg.applicationInfo.setResourcePath(pkg.codePath); 11393 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11394 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11395 11396 return true; 11397 } 11398 11399 private void setMountPath(String mountPath) { 11400 final File mountFile = new File(mountPath); 11401 11402 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11403 if (monolithicFile.exists()) { 11404 packagePath = monolithicFile.getAbsolutePath(); 11405 if (isFwdLocked()) { 11406 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11407 } else { 11408 resourcePath = packagePath; 11409 } 11410 } else { 11411 packagePath = mountFile.getAbsolutePath(); 11412 resourcePath = packagePath; 11413 } 11414 } 11415 11416 int doPostInstall(int status, int uid) { 11417 if (status != PackageManager.INSTALL_SUCCEEDED) { 11418 cleanUp(); 11419 } else { 11420 final int groupOwner; 11421 final String protectedFile; 11422 if (isFwdLocked()) { 11423 groupOwner = UserHandle.getSharedAppGid(uid); 11424 protectedFile = RES_FILE_NAME; 11425 } else { 11426 groupOwner = -1; 11427 protectedFile = null; 11428 } 11429 11430 if (uid < Process.FIRST_APPLICATION_UID 11431 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11432 Slog.e(TAG, "Failed to finalize " + cid); 11433 PackageHelper.destroySdDir(cid); 11434 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11435 } 11436 11437 boolean mounted = PackageHelper.isContainerMounted(cid); 11438 if (!mounted) { 11439 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11440 } 11441 } 11442 return status; 11443 } 11444 11445 private void cleanUp() { 11446 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11447 11448 // Destroy secure container 11449 PackageHelper.destroySdDir(cid); 11450 } 11451 11452 private List<String> getAllCodePaths() { 11453 final File codeFile = new File(getCodePath()); 11454 if (codeFile != null && codeFile.exists()) { 11455 try { 11456 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11457 return pkg.getAllCodePaths(); 11458 } catch (PackageParserException e) { 11459 // Ignored; we tried our best 11460 } 11461 } 11462 return Collections.EMPTY_LIST; 11463 } 11464 11465 void cleanUpResourcesLI() { 11466 // Enumerate all code paths before deleting 11467 cleanUpResourcesLI(getAllCodePaths()); 11468 } 11469 11470 private void cleanUpResourcesLI(List<String> allCodePaths) { 11471 cleanUp(); 11472 removeDexFiles(allCodePaths, instructionSets); 11473 } 11474 11475 String getPackageName() { 11476 return getAsecPackageName(cid); 11477 } 11478 11479 boolean doPostDeleteLI(boolean delete) { 11480 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11481 final List<String> allCodePaths = getAllCodePaths(); 11482 boolean mounted = PackageHelper.isContainerMounted(cid); 11483 if (mounted) { 11484 // Unmount first 11485 if (PackageHelper.unMountSdDir(cid)) { 11486 mounted = false; 11487 } 11488 } 11489 if (!mounted && delete) { 11490 cleanUpResourcesLI(allCodePaths); 11491 } 11492 return !mounted; 11493 } 11494 11495 @Override 11496 int doPreCopy() { 11497 if (isFwdLocked()) { 11498 if (!PackageHelper.fixSdPermissions(cid, 11499 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11500 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11501 } 11502 } 11503 11504 return PackageManager.INSTALL_SUCCEEDED; 11505 } 11506 11507 @Override 11508 int doPostCopy(int uid) { 11509 if (isFwdLocked()) { 11510 if (uid < Process.FIRST_APPLICATION_UID 11511 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11512 RES_FILE_NAME)) { 11513 Slog.e(TAG, "Failed to finalize " + cid); 11514 PackageHelper.destroySdDir(cid); 11515 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11516 } 11517 } 11518 11519 return PackageManager.INSTALL_SUCCEEDED; 11520 } 11521 } 11522 11523 /** 11524 * Logic to handle movement of existing installed applications. 11525 */ 11526 class MoveInstallArgs extends InstallArgs { 11527 private File codeFile; 11528 private File resourceFile; 11529 11530 /** New install */ 11531 MoveInstallArgs(InstallParams params) { 11532 super(params.origin, params.move, params.observer, params.installFlags, 11533 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11534 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11535 params.grantedRuntimePermissions); 11536 } 11537 11538 int copyApk(IMediaContainerService imcs, boolean temp) { 11539 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11540 + move.fromUuid + " to " + move.toUuid); 11541 synchronized (mInstaller) { 11542 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11543 move.dataAppName, move.appId, move.seinfo) != 0) { 11544 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11545 } 11546 } 11547 11548 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11549 resourceFile = codeFile; 11550 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11551 11552 return PackageManager.INSTALL_SUCCEEDED; 11553 } 11554 11555 int doPreInstall(int status) { 11556 if (status != PackageManager.INSTALL_SUCCEEDED) { 11557 cleanUp(move.toUuid); 11558 } 11559 return status; 11560 } 11561 11562 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11563 if (status != PackageManager.INSTALL_SUCCEEDED) { 11564 cleanUp(move.toUuid); 11565 return false; 11566 } 11567 11568 // Reflect the move in app info 11569 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11570 pkg.applicationInfo.setCodePath(pkg.codePath); 11571 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11572 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11573 pkg.applicationInfo.setResourcePath(pkg.codePath); 11574 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11575 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11576 11577 return true; 11578 } 11579 11580 int doPostInstall(int status, int uid) { 11581 if (status == PackageManager.INSTALL_SUCCEEDED) { 11582 cleanUp(move.fromUuid); 11583 } else { 11584 cleanUp(move.toUuid); 11585 } 11586 return status; 11587 } 11588 11589 @Override 11590 String getCodePath() { 11591 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11592 } 11593 11594 @Override 11595 String getResourcePath() { 11596 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11597 } 11598 11599 private boolean cleanUp(String volumeUuid) { 11600 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11601 move.dataAppName); 11602 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11603 synchronized (mInstallLock) { 11604 // Clean up both app data and code 11605 removeDataDirsLI(volumeUuid, move.packageName); 11606 if (codeFile.isDirectory()) { 11607 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11608 } else { 11609 codeFile.delete(); 11610 } 11611 } 11612 return true; 11613 } 11614 11615 void cleanUpResourcesLI() { 11616 throw new UnsupportedOperationException(); 11617 } 11618 11619 boolean doPostDeleteLI(boolean delete) { 11620 throw new UnsupportedOperationException(); 11621 } 11622 } 11623 11624 static String getAsecPackageName(String packageCid) { 11625 int idx = packageCid.lastIndexOf("-"); 11626 if (idx == -1) { 11627 return packageCid; 11628 } 11629 return packageCid.substring(0, idx); 11630 } 11631 11632 // Utility method used to create code paths based on package name and available index. 11633 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11634 String idxStr = ""; 11635 int idx = 1; 11636 // Fall back to default value of idx=1 if prefix is not 11637 // part of oldCodePath 11638 if (oldCodePath != null) { 11639 String subStr = oldCodePath; 11640 // Drop the suffix right away 11641 if (suffix != null && subStr.endsWith(suffix)) { 11642 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11643 } 11644 // If oldCodePath already contains prefix find out the 11645 // ending index to either increment or decrement. 11646 int sidx = subStr.lastIndexOf(prefix); 11647 if (sidx != -1) { 11648 subStr = subStr.substring(sidx + prefix.length()); 11649 if (subStr != null) { 11650 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11651 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11652 } 11653 try { 11654 idx = Integer.parseInt(subStr); 11655 if (idx <= 1) { 11656 idx++; 11657 } else { 11658 idx--; 11659 } 11660 } catch(NumberFormatException e) { 11661 } 11662 } 11663 } 11664 } 11665 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11666 return prefix + idxStr; 11667 } 11668 11669 private File getNextCodePath(File targetDir, String packageName) { 11670 int suffix = 1; 11671 File result; 11672 do { 11673 result = new File(targetDir, packageName + "-" + suffix); 11674 suffix++; 11675 } while (result.exists()); 11676 return result; 11677 } 11678 11679 // Utility method that returns the relative package path with respect 11680 // to the installation directory. Like say for /data/data/com.test-1.apk 11681 // string com.test-1 is returned. 11682 static String deriveCodePathName(String codePath) { 11683 if (codePath == null) { 11684 return null; 11685 } 11686 final File codeFile = new File(codePath); 11687 final String name = codeFile.getName(); 11688 if (codeFile.isDirectory()) { 11689 return name; 11690 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11691 final int lastDot = name.lastIndexOf('.'); 11692 return name.substring(0, lastDot); 11693 } else { 11694 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11695 return null; 11696 } 11697 } 11698 11699 class PackageInstalledInfo { 11700 String name; 11701 int uid; 11702 // The set of users that originally had this package installed. 11703 int[] origUsers; 11704 // The set of users that now have this package installed. 11705 int[] newUsers; 11706 PackageParser.Package pkg; 11707 int returnCode; 11708 String returnMsg; 11709 PackageRemovedInfo removedInfo; 11710 11711 public void setError(int code, String msg) { 11712 returnCode = code; 11713 returnMsg = msg; 11714 Slog.w(TAG, msg); 11715 } 11716 11717 public void setError(String msg, PackageParserException e) { 11718 returnCode = e.error; 11719 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11720 Slog.w(TAG, msg, e); 11721 } 11722 11723 public void setError(String msg, PackageManagerException e) { 11724 returnCode = e.error; 11725 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11726 Slog.w(TAG, msg, e); 11727 } 11728 11729 // In some error cases we want to convey more info back to the observer 11730 String origPackage; 11731 String origPermission; 11732 } 11733 11734 /* 11735 * Install a non-existing package. 11736 */ 11737 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11738 UserHandle user, String installerPackageName, String volumeUuid, 11739 PackageInstalledInfo res) { 11740 // Remember this for later, in case we need to rollback this install 11741 String pkgName = pkg.packageName; 11742 11743 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11744 final boolean dataDirExists = Environment 11745 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11746 synchronized(mPackages) { 11747 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11748 // A package with the same name is already installed, though 11749 // it has been renamed to an older name. The package we 11750 // are trying to install should be installed as an update to 11751 // the existing one, but that has not been requested, so bail. 11752 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11753 + " without first uninstalling package running as " 11754 + mSettings.mRenamedPackages.get(pkgName)); 11755 return; 11756 } 11757 if (mPackages.containsKey(pkgName)) { 11758 // Don't allow installation over an existing package with the same name. 11759 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11760 + " without first uninstalling."); 11761 return; 11762 } 11763 } 11764 11765 try { 11766 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11767 System.currentTimeMillis(), user); 11768 11769 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11770 // delete the partially installed application. the data directory will have to be 11771 // restored if it was already existing 11772 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11773 // remove package from internal structures. Note that we want deletePackageX to 11774 // delete the package data and cache directories that it created in 11775 // scanPackageLocked, unless those directories existed before we even tried to 11776 // install. 11777 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11778 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11779 res.removedInfo, true); 11780 } 11781 11782 } catch (PackageManagerException e) { 11783 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11784 } 11785 } 11786 11787 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11788 // Can't rotate keys during boot or if sharedUser. 11789 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11790 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11791 return false; 11792 } 11793 // app is using upgradeKeySets; make sure all are valid 11794 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11795 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11796 for (int i = 0; i < upgradeKeySets.length; i++) { 11797 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11798 Slog.wtf(TAG, "Package " 11799 + (oldPs.name != null ? oldPs.name : "<null>") 11800 + " contains upgrade-key-set reference to unknown key-set: " 11801 + upgradeKeySets[i] 11802 + " reverting to signatures check."); 11803 return false; 11804 } 11805 } 11806 return true; 11807 } 11808 11809 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11810 // Upgrade keysets are being used. Determine if new package has a superset of the 11811 // required keys. 11812 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11813 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11814 for (int i = 0; i < upgradeKeySets.length; i++) { 11815 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11816 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11817 return true; 11818 } 11819 } 11820 return false; 11821 } 11822 11823 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11824 UserHandle user, String installerPackageName, String volumeUuid, 11825 PackageInstalledInfo res) { 11826 final PackageParser.Package oldPackage; 11827 final String pkgName = pkg.packageName; 11828 final int[] allUsers; 11829 final boolean[] perUserInstalled; 11830 11831 // First find the old package info and check signatures 11832 synchronized(mPackages) { 11833 oldPackage = mPackages.get(pkgName); 11834 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11835 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11836 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11837 if(!checkUpgradeKeySetLP(ps, pkg)) { 11838 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11839 "New package not signed by keys specified by upgrade-keysets: " 11840 + pkgName); 11841 return; 11842 } 11843 } else { 11844 // default to original signature matching 11845 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11846 != PackageManager.SIGNATURE_MATCH) { 11847 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11848 "New package has a different signature: " + pkgName); 11849 return; 11850 } 11851 } 11852 11853 // In case of rollback, remember per-user/profile install state 11854 allUsers = sUserManager.getUserIds(); 11855 perUserInstalled = new boolean[allUsers.length]; 11856 for (int i = 0; i < allUsers.length; i++) { 11857 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11858 } 11859 } 11860 11861 boolean sysPkg = (isSystemApp(oldPackage)); 11862 if (sysPkg) { 11863 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11864 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11865 } else { 11866 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11867 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11868 } 11869 } 11870 11871 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11872 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11873 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11874 String volumeUuid, PackageInstalledInfo res) { 11875 String pkgName = deletedPackage.packageName; 11876 boolean deletedPkg = true; 11877 boolean updatedSettings = false; 11878 11879 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11880 + deletedPackage); 11881 long origUpdateTime; 11882 if (pkg.mExtras != null) { 11883 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11884 } else { 11885 origUpdateTime = 0; 11886 } 11887 11888 // First delete the existing package while retaining the data directory 11889 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11890 res.removedInfo, true)) { 11891 // If the existing package wasn't successfully deleted 11892 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11893 deletedPkg = false; 11894 } else { 11895 // Successfully deleted the old package; proceed with replace. 11896 11897 // If deleted package lived in a container, give users a chance to 11898 // relinquish resources before killing. 11899 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11900 if (DEBUG_INSTALL) { 11901 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11902 } 11903 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11904 final ArrayList<String> pkgList = new ArrayList<String>(1); 11905 pkgList.add(deletedPackage.applicationInfo.packageName); 11906 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11907 } 11908 11909 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11910 try { 11911 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11912 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11913 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11914 perUserInstalled, res, user); 11915 updatedSettings = true; 11916 } catch (PackageManagerException e) { 11917 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11918 } 11919 } 11920 11921 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11922 // remove package from internal structures. Note that we want deletePackageX to 11923 // delete the package data and cache directories that it created in 11924 // scanPackageLocked, unless those directories existed before we even tried to 11925 // install. 11926 if(updatedSettings) { 11927 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11928 deletePackageLI( 11929 pkgName, null, true, allUsers, perUserInstalled, 11930 PackageManager.DELETE_KEEP_DATA, 11931 res.removedInfo, true); 11932 } 11933 // Since we failed to install the new package we need to restore the old 11934 // package that we deleted. 11935 if (deletedPkg) { 11936 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11937 File restoreFile = new File(deletedPackage.codePath); 11938 // Parse old package 11939 boolean oldExternal = isExternal(deletedPackage); 11940 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11941 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11942 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11943 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11944 try { 11945 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11946 } catch (PackageManagerException e) { 11947 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11948 + e.getMessage()); 11949 return; 11950 } 11951 // Restore of old package succeeded. Update permissions. 11952 // writer 11953 synchronized (mPackages) { 11954 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11955 UPDATE_PERMISSIONS_ALL); 11956 // can downgrade to reader 11957 mSettings.writeLPr(); 11958 } 11959 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11960 } 11961 } 11962 } 11963 11964 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11965 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11966 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11967 String volumeUuid, PackageInstalledInfo res) { 11968 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11969 + ", old=" + deletedPackage); 11970 boolean disabledSystem = false; 11971 boolean updatedSettings = false; 11972 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11973 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11974 != 0) { 11975 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11976 } 11977 String packageName = deletedPackage.packageName; 11978 if (packageName == null) { 11979 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11980 "Attempt to delete null packageName."); 11981 return; 11982 } 11983 PackageParser.Package oldPkg; 11984 PackageSetting oldPkgSetting; 11985 // reader 11986 synchronized (mPackages) { 11987 oldPkg = mPackages.get(packageName); 11988 oldPkgSetting = mSettings.mPackages.get(packageName); 11989 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11990 (oldPkgSetting == null)) { 11991 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11992 "Couldn't find package:" + packageName + " information"); 11993 return; 11994 } 11995 } 11996 11997 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 11998 11999 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12000 res.removedInfo.removedPackage = packageName; 12001 // Remove existing system package 12002 removePackageLI(oldPkgSetting, true); 12003 // writer 12004 synchronized (mPackages) { 12005 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12006 if (!disabledSystem && deletedPackage != null) { 12007 // We didn't need to disable the .apk as a current system package, 12008 // which means we are replacing another update that is already 12009 // installed. We need to make sure to delete the older one's .apk. 12010 res.removedInfo.args = createInstallArgsForExisting(0, 12011 deletedPackage.applicationInfo.getCodePath(), 12012 deletedPackage.applicationInfo.getResourcePath(), 12013 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12014 } else { 12015 res.removedInfo.args = null; 12016 } 12017 } 12018 12019 // Successfully disabled the old package. Now proceed with re-installation 12020 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12021 12022 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12023 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12024 12025 PackageParser.Package newPackage = null; 12026 try { 12027 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 12028 if (newPackage.mExtras != null) { 12029 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12030 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12031 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12032 12033 // is the update attempting to change shared user? that isn't going to work... 12034 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12035 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12036 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12037 + " to " + newPkgSetting.sharedUser); 12038 updatedSettings = true; 12039 } 12040 } 12041 12042 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12043 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12044 perUserInstalled, res, user); 12045 updatedSettings = true; 12046 } 12047 12048 } catch (PackageManagerException e) { 12049 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12050 } 12051 12052 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12053 // Re installation failed. Restore old information 12054 // Remove new pkg information 12055 if (newPackage != null) { 12056 removeInstalledPackageLI(newPackage, true); 12057 } 12058 // Add back the old system package 12059 try { 12060 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12061 } catch (PackageManagerException e) { 12062 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12063 } 12064 // Restore the old system information in Settings 12065 synchronized (mPackages) { 12066 if (disabledSystem) { 12067 mSettings.enableSystemPackageLPw(packageName); 12068 } 12069 if (updatedSettings) { 12070 mSettings.setInstallerPackageName(packageName, 12071 oldPkgSetting.installerPackageName); 12072 } 12073 mSettings.writeLPr(); 12074 } 12075 } 12076 } 12077 12078 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12079 // Collect all used permissions in the UID 12080 ArraySet<String> usedPermissions = new ArraySet<>(); 12081 final int packageCount = su.packages.size(); 12082 for (int i = 0; i < packageCount; i++) { 12083 PackageSetting ps = su.packages.valueAt(i); 12084 if (ps.pkg == null) { 12085 continue; 12086 } 12087 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12088 for (int j = 0; j < requestedPermCount; j++) { 12089 String permission = ps.pkg.requestedPermissions.get(j); 12090 BasePermission bp = mSettings.mPermissions.get(permission); 12091 if (bp != null) { 12092 usedPermissions.add(permission); 12093 } 12094 } 12095 } 12096 12097 PermissionsState permissionsState = su.getPermissionsState(); 12098 // Prune install permissions 12099 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12100 final int installPermCount = installPermStates.size(); 12101 for (int i = installPermCount - 1; i >= 0; i--) { 12102 PermissionState permissionState = installPermStates.get(i); 12103 if (!usedPermissions.contains(permissionState.getName())) { 12104 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12105 if (bp != null) { 12106 permissionsState.revokeInstallPermission(bp); 12107 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12108 PackageManager.MASK_PERMISSION_FLAGS, 0); 12109 } 12110 } 12111 } 12112 12113 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12114 12115 // Prune runtime permissions 12116 for (int userId : allUserIds) { 12117 List<PermissionState> runtimePermStates = permissionsState 12118 .getRuntimePermissionStates(userId); 12119 final int runtimePermCount = runtimePermStates.size(); 12120 for (int i = runtimePermCount - 1; i >= 0; i--) { 12121 PermissionState permissionState = runtimePermStates.get(i); 12122 if (!usedPermissions.contains(permissionState.getName())) { 12123 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12124 if (bp != null) { 12125 permissionsState.revokeRuntimePermission(bp, userId); 12126 permissionsState.updatePermissionFlags(bp, userId, 12127 PackageManager.MASK_PERMISSION_FLAGS, 0); 12128 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12129 runtimePermissionChangedUserIds, userId); 12130 } 12131 } 12132 } 12133 } 12134 12135 return runtimePermissionChangedUserIds; 12136 } 12137 12138 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12139 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12140 UserHandle user) { 12141 String pkgName = newPackage.packageName; 12142 synchronized (mPackages) { 12143 //write settings. the installStatus will be incomplete at this stage. 12144 //note that the new package setting would have already been 12145 //added to mPackages. It hasn't been persisted yet. 12146 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12147 mSettings.writeLPr(); 12148 } 12149 12150 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12151 12152 synchronized (mPackages) { 12153 updatePermissionsLPw(newPackage.packageName, newPackage, 12154 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12155 ? UPDATE_PERMISSIONS_ALL : 0)); 12156 // For system-bundled packages, we assume that installing an upgraded version 12157 // of the package implies that the user actually wants to run that new code, 12158 // so we enable the package. 12159 PackageSetting ps = mSettings.mPackages.get(pkgName); 12160 if (ps != null) { 12161 if (isSystemApp(newPackage)) { 12162 // NB: implicit assumption that system package upgrades apply to all users 12163 if (DEBUG_INSTALL) { 12164 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12165 } 12166 if (res.origUsers != null) { 12167 for (int userHandle : res.origUsers) { 12168 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12169 userHandle, installerPackageName); 12170 } 12171 } 12172 // Also convey the prior install/uninstall state 12173 if (allUsers != null && perUserInstalled != null) { 12174 for (int i = 0; i < allUsers.length; i++) { 12175 if (DEBUG_INSTALL) { 12176 Slog.d(TAG, " user " + allUsers[i] 12177 + " => " + perUserInstalled[i]); 12178 } 12179 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12180 } 12181 // these install state changes will be persisted in the 12182 // upcoming call to mSettings.writeLPr(). 12183 } 12184 } 12185 // It's implied that when a user requests installation, they want the app to be 12186 // installed and enabled. 12187 int userId = user.getIdentifier(); 12188 if (userId != UserHandle.USER_ALL) { 12189 ps.setInstalled(true, userId); 12190 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12191 } 12192 } 12193 res.name = pkgName; 12194 res.uid = newPackage.applicationInfo.uid; 12195 res.pkg = newPackage; 12196 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12197 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12198 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12199 //to update install status 12200 mSettings.writeLPr(); 12201 } 12202 } 12203 12204 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12205 final int installFlags = args.installFlags; 12206 final String installerPackageName = args.installerPackageName; 12207 final String volumeUuid = args.volumeUuid; 12208 final File tmpPackageFile = new File(args.getCodePath()); 12209 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12210 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12211 || (args.volumeUuid != null)); 12212 boolean replace = false; 12213 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12214 if (args.move != null) { 12215 // moving a complete application; perfom an initial scan on the new install location 12216 scanFlags |= SCAN_INITIAL; 12217 } 12218 // Result object to be returned 12219 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12220 12221 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12222 // Retrieve PackageSettings and parse package 12223 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12224 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12225 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12226 PackageParser pp = new PackageParser(); 12227 pp.setSeparateProcesses(mSeparateProcesses); 12228 pp.setDisplayMetrics(mMetrics); 12229 12230 final PackageParser.Package pkg; 12231 try { 12232 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12233 } catch (PackageParserException e) { 12234 res.setError("Failed parse during installPackageLI", e); 12235 return; 12236 } 12237 12238 // Mark that we have an install time CPU ABI override. 12239 pkg.cpuAbiOverride = args.abiOverride; 12240 12241 String pkgName = res.name = pkg.packageName; 12242 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12243 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12244 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12245 return; 12246 } 12247 } 12248 12249 try { 12250 pp.collectCertificates(pkg, parseFlags); 12251 pp.collectManifestDigest(pkg); 12252 } catch (PackageParserException e) { 12253 res.setError("Failed collect during installPackageLI", e); 12254 return; 12255 } 12256 12257 /* If the installer passed in a manifest digest, compare it now. */ 12258 if (args.manifestDigest != null) { 12259 if (DEBUG_INSTALL) { 12260 final String parsedManifest = pkg.manifestDigest == null ? "null" 12261 : pkg.manifestDigest.toString(); 12262 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12263 + parsedManifest); 12264 } 12265 12266 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12267 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12268 return; 12269 } 12270 } else if (DEBUG_INSTALL) { 12271 final String parsedManifest = pkg.manifestDigest == null 12272 ? "null" : pkg.manifestDigest.toString(); 12273 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12274 } 12275 12276 // Get rid of all references to package scan path via parser. 12277 pp = null; 12278 String oldCodePath = null; 12279 boolean systemApp = false; 12280 synchronized (mPackages) { 12281 // Check if installing already existing package 12282 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12283 String oldName = mSettings.mRenamedPackages.get(pkgName); 12284 if (pkg.mOriginalPackages != null 12285 && pkg.mOriginalPackages.contains(oldName) 12286 && mPackages.containsKey(oldName)) { 12287 // This package is derived from an original package, 12288 // and this device has been updating from that original 12289 // name. We must continue using the original name, so 12290 // rename the new package here. 12291 pkg.setPackageName(oldName); 12292 pkgName = pkg.packageName; 12293 replace = true; 12294 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12295 + oldName + " pkgName=" + pkgName); 12296 } else if (mPackages.containsKey(pkgName)) { 12297 // This package, under its official name, already exists 12298 // on the device; we should replace it. 12299 replace = true; 12300 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12301 } 12302 12303 // Prevent apps opting out from runtime permissions 12304 if (replace) { 12305 PackageParser.Package oldPackage = mPackages.get(pkgName); 12306 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12307 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12308 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12309 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12310 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12311 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12312 + " doesn't support runtime permissions but the old" 12313 + " target SDK " + oldTargetSdk + " does."); 12314 return; 12315 } 12316 } 12317 } 12318 12319 PackageSetting ps = mSettings.mPackages.get(pkgName); 12320 if (ps != null) { 12321 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12322 12323 // Quick sanity check that we're signed correctly if updating; 12324 // we'll check this again later when scanning, but we want to 12325 // bail early here before tripping over redefined permissions. 12326 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12327 if (!checkUpgradeKeySetLP(ps, pkg)) { 12328 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12329 + pkg.packageName + " upgrade keys do not match the " 12330 + "previously installed version"); 12331 return; 12332 } 12333 } else { 12334 try { 12335 verifySignaturesLP(ps, pkg); 12336 } catch (PackageManagerException e) { 12337 res.setError(e.error, e.getMessage()); 12338 return; 12339 } 12340 } 12341 12342 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12343 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12344 systemApp = (ps.pkg.applicationInfo.flags & 12345 ApplicationInfo.FLAG_SYSTEM) != 0; 12346 } 12347 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12348 } 12349 12350 // Check whether the newly-scanned package wants to define an already-defined perm 12351 int N = pkg.permissions.size(); 12352 for (int i = N-1; i >= 0; i--) { 12353 PackageParser.Permission perm = pkg.permissions.get(i); 12354 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12355 if (bp != null) { 12356 // If the defining package is signed with our cert, it's okay. This 12357 // also includes the "updating the same package" case, of course. 12358 // "updating same package" could also involve key-rotation. 12359 final boolean sigsOk; 12360 if (bp.sourcePackage.equals(pkg.packageName) 12361 && (bp.packageSetting instanceof PackageSetting) 12362 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12363 scanFlags))) { 12364 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12365 } else { 12366 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12367 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12368 } 12369 if (!sigsOk) { 12370 // If the owning package is the system itself, we log but allow 12371 // install to proceed; we fail the install on all other permission 12372 // redefinitions. 12373 if (!bp.sourcePackage.equals("android")) { 12374 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12375 + pkg.packageName + " attempting to redeclare permission " 12376 + perm.info.name + " already owned by " + bp.sourcePackage); 12377 res.origPermission = perm.info.name; 12378 res.origPackage = bp.sourcePackage; 12379 return; 12380 } else { 12381 Slog.w(TAG, "Package " + pkg.packageName 12382 + " attempting to redeclare system permission " 12383 + perm.info.name + "; ignoring new declaration"); 12384 pkg.permissions.remove(i); 12385 } 12386 } 12387 } 12388 } 12389 12390 } 12391 12392 if (systemApp && onExternal) { 12393 // Disable updates to system apps on sdcard 12394 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12395 "Cannot install updates to system apps on sdcard"); 12396 return; 12397 } 12398 12399 if (args.move != null) { 12400 // We did an in-place move, so dex is ready to roll 12401 scanFlags |= SCAN_NO_DEX; 12402 scanFlags |= SCAN_MOVE; 12403 12404 synchronized (mPackages) { 12405 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12406 if (ps == null) { 12407 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12408 "Missing settings for moved package " + pkgName); 12409 } 12410 12411 // We moved the entire application as-is, so bring over the 12412 // previously derived ABI information. 12413 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12414 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12415 } 12416 12417 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12418 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12419 scanFlags |= SCAN_NO_DEX; 12420 12421 try { 12422 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12423 true /* extract libs */); 12424 } catch (PackageManagerException pme) { 12425 Slog.e(TAG, "Error deriving application ABI", pme); 12426 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12427 return; 12428 } 12429 12430 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12431 int result = mPackageDexOptimizer 12432 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12433 false /* defer */, false /* inclDependencies */, 12434 true /*bootComplete*/, false /*useJit*/); 12435 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12436 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12437 return; 12438 } 12439 } 12440 12441 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12442 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12443 return; 12444 } 12445 12446 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12447 12448 if (replace) { 12449 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12450 installerPackageName, volumeUuid, res); 12451 } else { 12452 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12453 args.user, installerPackageName, volumeUuid, res); 12454 } 12455 synchronized (mPackages) { 12456 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12457 if (ps != null) { 12458 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12459 } 12460 } 12461 } 12462 12463 private void startIntentFilterVerifications(int userId, boolean replacing, 12464 PackageParser.Package pkg) { 12465 if (mIntentFilterVerifierComponent == null) { 12466 Slog.w(TAG, "No IntentFilter verification will not be done as " 12467 + "there is no IntentFilterVerifier available!"); 12468 return; 12469 } 12470 12471 final int verifierUid = getPackageUid( 12472 mIntentFilterVerifierComponent.getPackageName(), 12473 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12474 12475 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12476 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12477 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12478 mHandler.sendMessage(msg); 12479 } 12480 12481 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12482 PackageParser.Package pkg) { 12483 int size = pkg.activities.size(); 12484 if (size == 0) { 12485 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12486 "No activity, so no need to verify any IntentFilter!"); 12487 return; 12488 } 12489 12490 final boolean hasDomainURLs = hasDomainURLs(pkg); 12491 if (!hasDomainURLs) { 12492 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12493 "No domain URLs, so no need to verify any IntentFilter!"); 12494 return; 12495 } 12496 12497 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12498 + " if any IntentFilter from the " + size 12499 + " Activities needs verification ..."); 12500 12501 int count = 0; 12502 final String packageName = pkg.packageName; 12503 12504 synchronized (mPackages) { 12505 // If this is a new install and we see that we've already run verification for this 12506 // package, we have nothing to do: it means the state was restored from backup. 12507 if (!replacing) { 12508 IntentFilterVerificationInfo ivi = 12509 mSettings.getIntentFilterVerificationLPr(packageName); 12510 if (ivi != null) { 12511 if (DEBUG_DOMAIN_VERIFICATION) { 12512 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12513 + ivi.getStatusString()); 12514 } 12515 return; 12516 } 12517 } 12518 12519 // If any filters need to be verified, then all need to be. 12520 boolean needToVerify = false; 12521 for (PackageParser.Activity a : pkg.activities) { 12522 for (ActivityIntentInfo filter : a.intents) { 12523 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12524 if (DEBUG_DOMAIN_VERIFICATION) { 12525 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12526 } 12527 needToVerify = true; 12528 break; 12529 } 12530 } 12531 } 12532 12533 if (needToVerify) { 12534 final int verificationId = mIntentFilterVerificationToken++; 12535 for (PackageParser.Activity a : pkg.activities) { 12536 for (ActivityIntentInfo filter : a.intents) { 12537 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12538 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12539 "Verification needed for IntentFilter:" + filter.toString()); 12540 mIntentFilterVerifier.addOneIntentFilterVerification( 12541 verifierUid, userId, verificationId, filter, packageName); 12542 count++; 12543 } 12544 } 12545 } 12546 } 12547 } 12548 12549 if (count > 0) { 12550 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12551 + " IntentFilter verification" + (count > 1 ? "s" : "") 12552 + " for userId:" + userId); 12553 mIntentFilterVerifier.startVerifications(userId); 12554 } else { 12555 if (DEBUG_DOMAIN_VERIFICATION) { 12556 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12557 } 12558 } 12559 } 12560 12561 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12562 final ComponentName cn = filter.activity.getComponentName(); 12563 final String packageName = cn.getPackageName(); 12564 12565 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12566 packageName); 12567 if (ivi == null) { 12568 return true; 12569 } 12570 int status = ivi.getStatus(); 12571 switch (status) { 12572 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12573 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12574 return true; 12575 12576 default: 12577 // Nothing to do 12578 return false; 12579 } 12580 } 12581 12582 private static boolean isMultiArch(PackageSetting ps) { 12583 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12584 } 12585 12586 private static boolean isMultiArch(ApplicationInfo info) { 12587 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12588 } 12589 12590 private static boolean isExternal(PackageParser.Package pkg) { 12591 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12592 } 12593 12594 private static boolean isExternal(PackageSetting ps) { 12595 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12596 } 12597 12598 private static boolean isExternal(ApplicationInfo info) { 12599 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12600 } 12601 12602 private static boolean isSystemApp(PackageParser.Package pkg) { 12603 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12604 } 12605 12606 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12607 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12608 } 12609 12610 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12611 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12612 } 12613 12614 private static boolean isSystemApp(PackageSetting ps) { 12615 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12616 } 12617 12618 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12619 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12620 } 12621 12622 private int packageFlagsToInstallFlags(PackageSetting ps) { 12623 int installFlags = 0; 12624 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12625 // This existing package was an external ASEC install when we have 12626 // the external flag without a UUID 12627 installFlags |= PackageManager.INSTALL_EXTERNAL; 12628 } 12629 if (ps.isForwardLocked()) { 12630 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12631 } 12632 return installFlags; 12633 } 12634 12635 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 12636 if (isExternal(pkg)) { 12637 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12638 return StorageManager.UUID_PRIMARY_PHYSICAL; 12639 } else { 12640 return pkg.volumeUuid; 12641 } 12642 } else { 12643 return StorageManager.UUID_PRIVATE_INTERNAL; 12644 } 12645 } 12646 12647 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12648 if (isExternal(pkg)) { 12649 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12650 return mSettings.getExternalVersion(); 12651 } else { 12652 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12653 } 12654 } else { 12655 return mSettings.getInternalVersion(); 12656 } 12657 } 12658 12659 private void deleteTempPackageFiles() { 12660 final FilenameFilter filter = new FilenameFilter() { 12661 public boolean accept(File dir, String name) { 12662 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12663 } 12664 }; 12665 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12666 file.delete(); 12667 } 12668 } 12669 12670 @Override 12671 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12672 int flags) { 12673 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12674 flags); 12675 } 12676 12677 @Override 12678 public void deletePackage(final String packageName, 12679 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12680 mContext.enforceCallingOrSelfPermission( 12681 android.Manifest.permission.DELETE_PACKAGES, null); 12682 Preconditions.checkNotNull(packageName); 12683 Preconditions.checkNotNull(observer); 12684 final int uid = Binder.getCallingUid(); 12685 if (UserHandle.getUserId(uid) != userId) { 12686 mContext.enforceCallingPermission( 12687 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12688 "deletePackage for user " + userId); 12689 } 12690 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12691 try { 12692 observer.onPackageDeleted(packageName, 12693 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12694 } catch (RemoteException re) { 12695 } 12696 return; 12697 } 12698 12699 boolean uninstallBlocked = false; 12700 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12701 int[] users = sUserManager.getUserIds(); 12702 for (int i = 0; i < users.length; ++i) { 12703 if (getBlockUninstallForUser(packageName, users[i])) { 12704 uninstallBlocked = true; 12705 break; 12706 } 12707 } 12708 } else { 12709 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12710 } 12711 if (uninstallBlocked) { 12712 try { 12713 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12714 null); 12715 } catch (RemoteException re) { 12716 } 12717 return; 12718 } 12719 12720 if (DEBUG_REMOVE) { 12721 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12722 } 12723 // Queue up an async operation since the package deletion may take a little while. 12724 mHandler.post(new Runnable() { 12725 public void run() { 12726 mHandler.removeCallbacks(this); 12727 final int returnCode = deletePackageX(packageName, userId, flags); 12728 if (observer != null) { 12729 try { 12730 observer.onPackageDeleted(packageName, returnCode, null); 12731 } catch (RemoteException e) { 12732 Log.i(TAG, "Observer no longer exists."); 12733 } //end catch 12734 } //end if 12735 } //end run 12736 }); 12737 } 12738 12739 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12740 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12741 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12742 try { 12743 if (dpm != null) { 12744 if (dpm.isDeviceOwner(packageName)) { 12745 return true; 12746 } 12747 int[] users; 12748 if (userId == UserHandle.USER_ALL) { 12749 users = sUserManager.getUserIds(); 12750 } else { 12751 users = new int[]{userId}; 12752 } 12753 for (int i = 0; i < users.length; ++i) { 12754 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12755 return true; 12756 } 12757 } 12758 } 12759 } catch (RemoteException e) { 12760 } 12761 return false; 12762 } 12763 12764 /** 12765 * This method is an internal method that could be get invoked either 12766 * to delete an installed package or to clean up a failed installation. 12767 * After deleting an installed package, a broadcast is sent to notify any 12768 * listeners that the package has been installed. For cleaning up a failed 12769 * installation, the broadcast is not necessary since the package's 12770 * installation wouldn't have sent the initial broadcast either 12771 * The key steps in deleting a package are 12772 * deleting the package information in internal structures like mPackages, 12773 * deleting the packages base directories through installd 12774 * updating mSettings to reflect current status 12775 * persisting settings for later use 12776 * sending a broadcast if necessary 12777 */ 12778 private int deletePackageX(String packageName, int userId, int flags) { 12779 final PackageRemovedInfo info = new PackageRemovedInfo(); 12780 final boolean res; 12781 12782 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12783 ? UserHandle.ALL : new UserHandle(userId); 12784 12785 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12786 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12787 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12788 } 12789 12790 boolean removedForAllUsers = false; 12791 boolean systemUpdate = false; 12792 12793 // for the uninstall-updates case and restricted profiles, remember the per- 12794 // userhandle installed state 12795 int[] allUsers; 12796 boolean[] perUserInstalled; 12797 synchronized (mPackages) { 12798 PackageSetting ps = mSettings.mPackages.get(packageName); 12799 allUsers = sUserManager.getUserIds(); 12800 perUserInstalled = new boolean[allUsers.length]; 12801 for (int i = 0; i < allUsers.length; i++) { 12802 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12803 } 12804 } 12805 12806 synchronized (mInstallLock) { 12807 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12808 res = deletePackageLI(packageName, removeForUser, 12809 true, allUsers, perUserInstalled, 12810 flags | REMOVE_CHATTY, info, true); 12811 systemUpdate = info.isRemovedPackageSystemUpdate; 12812 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12813 removedForAllUsers = true; 12814 } 12815 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12816 + " removedForAllUsers=" + removedForAllUsers); 12817 } 12818 12819 if (res) { 12820 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12821 12822 // If the removed package was a system update, the old system package 12823 // was re-enabled; we need to broadcast this information 12824 if (systemUpdate) { 12825 Bundle extras = new Bundle(1); 12826 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12827 ? info.removedAppId : info.uid); 12828 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12829 12830 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12831 extras, null, null, null); 12832 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12833 extras, null, null, null); 12834 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12835 null, packageName, null, null); 12836 } 12837 } 12838 // Force a gc here. 12839 Runtime.getRuntime().gc(); 12840 // Delete the resources here after sending the broadcast to let 12841 // other processes clean up before deleting resources. 12842 if (info.args != null) { 12843 synchronized (mInstallLock) { 12844 info.args.doPostDeleteLI(true); 12845 } 12846 } 12847 12848 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12849 } 12850 12851 class PackageRemovedInfo { 12852 String removedPackage; 12853 int uid = -1; 12854 int removedAppId = -1; 12855 int[] removedUsers = null; 12856 boolean isRemovedPackageSystemUpdate = false; 12857 // Clean up resources deleted packages. 12858 InstallArgs args = null; 12859 12860 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12861 Bundle extras = new Bundle(1); 12862 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12863 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12864 if (replacing) { 12865 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12866 } 12867 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12868 if (removedPackage != null) { 12869 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12870 extras, null, null, removedUsers); 12871 if (fullRemove && !replacing) { 12872 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12873 extras, null, null, removedUsers); 12874 } 12875 } 12876 if (removedAppId >= 0) { 12877 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12878 removedUsers); 12879 } 12880 } 12881 } 12882 12883 /* 12884 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12885 * flag is not set, the data directory is removed as well. 12886 * make sure this flag is set for partially installed apps. If not its meaningless to 12887 * delete a partially installed application. 12888 */ 12889 private void removePackageDataLI(PackageSetting ps, 12890 int[] allUserHandles, boolean[] perUserInstalled, 12891 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12892 String packageName = ps.name; 12893 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12894 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12895 // Retrieve object to delete permissions for shared user later on 12896 final PackageSetting deletedPs; 12897 // reader 12898 synchronized (mPackages) { 12899 deletedPs = mSettings.mPackages.get(packageName); 12900 if (outInfo != null) { 12901 outInfo.removedPackage = packageName; 12902 outInfo.removedUsers = deletedPs != null 12903 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12904 : null; 12905 } 12906 } 12907 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12908 removeDataDirsLI(ps.volumeUuid, packageName); 12909 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12910 } 12911 // writer 12912 synchronized (mPackages) { 12913 if (deletedPs != null) { 12914 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12915 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12916 clearDefaultBrowserIfNeeded(packageName); 12917 if (outInfo != null) { 12918 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12919 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12920 } 12921 updatePermissionsLPw(deletedPs.name, null, 0); 12922 if (deletedPs.sharedUser != null) { 12923 // Remove permissions associated with package. Since runtime 12924 // permissions are per user we have to kill the removed package 12925 // or packages running under the shared user of the removed 12926 // package if revoking the permissions requested only by the removed 12927 // package is successful and this causes a change in gids. 12928 for (int userId : UserManagerService.getInstance().getUserIds()) { 12929 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12930 userId); 12931 if (userIdToKill == UserHandle.USER_ALL 12932 || userIdToKill >= UserHandle.USER_OWNER) { 12933 // If gids changed for this user, kill all affected packages. 12934 mHandler.post(new Runnable() { 12935 @Override 12936 public void run() { 12937 // This has to happen with no lock held. 12938 killApplication(deletedPs.name, deletedPs.appId, 12939 KILL_APP_REASON_GIDS_CHANGED); 12940 } 12941 }); 12942 break; 12943 } 12944 } 12945 } 12946 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12947 } 12948 // make sure to preserve per-user disabled state if this removal was just 12949 // a downgrade of a system app to the factory package 12950 if (allUserHandles != null && perUserInstalled != null) { 12951 if (DEBUG_REMOVE) { 12952 Slog.d(TAG, "Propagating install state across downgrade"); 12953 } 12954 for (int i = 0; i < allUserHandles.length; i++) { 12955 if (DEBUG_REMOVE) { 12956 Slog.d(TAG, " user " + allUserHandles[i] 12957 + " => " + perUserInstalled[i]); 12958 } 12959 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12960 } 12961 } 12962 } 12963 // can downgrade to reader 12964 if (writeSettings) { 12965 // Save settings now 12966 mSettings.writeLPr(); 12967 } 12968 } 12969 if (outInfo != null) { 12970 // A user ID was deleted here. Go through all users and remove it 12971 // from KeyStore. 12972 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12973 } 12974 } 12975 12976 static boolean locationIsPrivileged(File path) { 12977 try { 12978 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12979 .getCanonicalPath(); 12980 return path.getCanonicalPath().startsWith(privilegedAppDir); 12981 } catch (IOException e) { 12982 Slog.e(TAG, "Unable to access code path " + path); 12983 } 12984 return false; 12985 } 12986 12987 /* 12988 * Tries to delete system package. 12989 */ 12990 private boolean deleteSystemPackageLI(PackageSetting newPs, 12991 int[] allUserHandles, boolean[] perUserInstalled, 12992 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12993 final boolean applyUserRestrictions 12994 = (allUserHandles != null) && (perUserInstalled != null); 12995 PackageSetting disabledPs = null; 12996 // Confirm if the system package has been updated 12997 // An updated system app can be deleted. This will also have to restore 12998 // the system pkg from system partition 12999 // reader 13000 synchronized (mPackages) { 13001 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13002 } 13003 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13004 + " disabledPs=" + disabledPs); 13005 if (disabledPs == null) { 13006 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13007 return false; 13008 } else if (DEBUG_REMOVE) { 13009 Slog.d(TAG, "Deleting system pkg from data partition"); 13010 } 13011 if (DEBUG_REMOVE) { 13012 if (applyUserRestrictions) { 13013 Slog.d(TAG, "Remembering install states:"); 13014 for (int i = 0; i < allUserHandles.length; i++) { 13015 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13016 } 13017 } 13018 } 13019 // Delete the updated package 13020 outInfo.isRemovedPackageSystemUpdate = true; 13021 if (disabledPs.versionCode < newPs.versionCode) { 13022 // Delete data for downgrades 13023 flags &= ~PackageManager.DELETE_KEEP_DATA; 13024 } else { 13025 // Preserve data by setting flag 13026 flags |= PackageManager.DELETE_KEEP_DATA; 13027 } 13028 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13029 allUserHandles, perUserInstalled, outInfo, writeSettings); 13030 if (!ret) { 13031 return false; 13032 } 13033 // writer 13034 synchronized (mPackages) { 13035 // Reinstate the old system package 13036 mSettings.enableSystemPackageLPw(newPs.name); 13037 // Remove any native libraries from the upgraded package. 13038 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13039 } 13040 // Install the system package 13041 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13042 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13043 if (locationIsPrivileged(disabledPs.codePath)) { 13044 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13045 } 13046 13047 final PackageParser.Package newPkg; 13048 try { 13049 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13050 } catch (PackageManagerException e) { 13051 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13052 return false; 13053 } 13054 13055 // writer 13056 synchronized (mPackages) { 13057 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13058 13059 // Propagate the permissions state as we do not want to drop on the floor 13060 // runtime permissions. The update permissions method below will take 13061 // care of removing obsolete permissions and grant install permissions. 13062 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13063 updatePermissionsLPw(newPkg.packageName, newPkg, 13064 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13065 13066 if (applyUserRestrictions) { 13067 if (DEBUG_REMOVE) { 13068 Slog.d(TAG, "Propagating install state across reinstall"); 13069 } 13070 for (int i = 0; i < allUserHandles.length; i++) { 13071 if (DEBUG_REMOVE) { 13072 Slog.d(TAG, " user " + allUserHandles[i] 13073 + " => " + perUserInstalled[i]); 13074 } 13075 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13076 13077 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13078 } 13079 // Regardless of writeSettings we need to ensure that this restriction 13080 // state propagation is persisted 13081 mSettings.writeAllUsersPackageRestrictionsLPr(); 13082 } 13083 // can downgrade to reader here 13084 if (writeSettings) { 13085 mSettings.writeLPr(); 13086 } 13087 } 13088 return true; 13089 } 13090 13091 private boolean deleteInstalledPackageLI(PackageSetting ps, 13092 boolean deleteCodeAndResources, int flags, 13093 int[] allUserHandles, boolean[] perUserInstalled, 13094 PackageRemovedInfo outInfo, boolean writeSettings) { 13095 if (outInfo != null) { 13096 outInfo.uid = ps.appId; 13097 } 13098 13099 // Delete package data from internal structures and also remove data if flag is set 13100 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13101 13102 // Delete application code and resources 13103 if (deleteCodeAndResources && (outInfo != null)) { 13104 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13105 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13106 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13107 } 13108 return true; 13109 } 13110 13111 @Override 13112 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13113 int userId) { 13114 mContext.enforceCallingOrSelfPermission( 13115 android.Manifest.permission.DELETE_PACKAGES, null); 13116 synchronized (mPackages) { 13117 PackageSetting ps = mSettings.mPackages.get(packageName); 13118 if (ps == null) { 13119 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13120 return false; 13121 } 13122 if (!ps.getInstalled(userId)) { 13123 // Can't block uninstall for an app that is not installed or enabled. 13124 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13125 return false; 13126 } 13127 ps.setBlockUninstall(blockUninstall, userId); 13128 mSettings.writePackageRestrictionsLPr(userId); 13129 } 13130 return true; 13131 } 13132 13133 @Override 13134 public boolean getBlockUninstallForUser(String packageName, int userId) { 13135 synchronized (mPackages) { 13136 PackageSetting ps = mSettings.mPackages.get(packageName); 13137 if (ps == null) { 13138 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13139 return false; 13140 } 13141 return ps.getBlockUninstall(userId); 13142 } 13143 } 13144 13145 /* 13146 * This method handles package deletion in general 13147 */ 13148 private boolean deletePackageLI(String packageName, UserHandle user, 13149 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13150 int flags, PackageRemovedInfo outInfo, 13151 boolean writeSettings) { 13152 if (packageName == null) { 13153 Slog.w(TAG, "Attempt to delete null packageName."); 13154 return false; 13155 } 13156 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13157 PackageSetting ps; 13158 boolean dataOnly = false; 13159 int removeUser = -1; 13160 int appId = -1; 13161 synchronized (mPackages) { 13162 ps = mSettings.mPackages.get(packageName); 13163 if (ps == null) { 13164 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13165 return false; 13166 } 13167 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13168 && user.getIdentifier() != UserHandle.USER_ALL) { 13169 // The caller is asking that the package only be deleted for a single 13170 // user. To do this, we just mark its uninstalled state and delete 13171 // its data. If this is a system app, we only allow this to happen if 13172 // they have set the special DELETE_SYSTEM_APP which requests different 13173 // semantics than normal for uninstalling system apps. 13174 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13175 final int userId = user.getIdentifier(); 13176 ps.setUserState(userId, 13177 COMPONENT_ENABLED_STATE_DEFAULT, 13178 false, //installed 13179 true, //stopped 13180 true, //notLaunched 13181 false, //hidden 13182 null, null, null, 13183 false, // blockUninstall 13184 ps.readUserState(userId).domainVerificationStatus, 0); 13185 if (!isSystemApp(ps)) { 13186 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13187 // Other user still have this package installed, so all 13188 // we need to do is clear this user's data and save that 13189 // it is uninstalled. 13190 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13191 removeUser = user.getIdentifier(); 13192 appId = ps.appId; 13193 scheduleWritePackageRestrictionsLocked(removeUser); 13194 } else { 13195 // We need to set it back to 'installed' so the uninstall 13196 // broadcasts will be sent correctly. 13197 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13198 ps.setInstalled(true, user.getIdentifier()); 13199 } 13200 } else { 13201 // This is a system app, so we assume that the 13202 // other users still have this package installed, so all 13203 // we need to do is clear this user's data and save that 13204 // it is uninstalled. 13205 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13206 removeUser = user.getIdentifier(); 13207 appId = ps.appId; 13208 scheduleWritePackageRestrictionsLocked(removeUser); 13209 } 13210 } 13211 } 13212 13213 if (removeUser >= 0) { 13214 // From above, we determined that we are deleting this only 13215 // for a single user. Continue the work here. 13216 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13217 if (outInfo != null) { 13218 outInfo.removedPackage = packageName; 13219 outInfo.removedAppId = appId; 13220 outInfo.removedUsers = new int[] {removeUser}; 13221 } 13222 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13223 removeKeystoreDataIfNeeded(removeUser, appId); 13224 schedulePackageCleaning(packageName, removeUser, false); 13225 synchronized (mPackages) { 13226 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13227 scheduleWritePackageRestrictionsLocked(removeUser); 13228 } 13229 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13230 } 13231 return true; 13232 } 13233 13234 if (dataOnly) { 13235 // Delete application data first 13236 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13237 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13238 return true; 13239 } 13240 13241 boolean ret = false; 13242 if (isSystemApp(ps)) { 13243 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13244 // When an updated system application is deleted we delete the existing resources as well and 13245 // fall back to existing code in system partition 13246 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13247 flags, outInfo, writeSettings); 13248 } else { 13249 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13250 // Kill application pre-emptively especially for apps on sd. 13251 killApplication(packageName, ps.appId, "uninstall pkg"); 13252 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13253 allUserHandles, perUserInstalled, 13254 outInfo, writeSettings); 13255 } 13256 13257 return ret; 13258 } 13259 13260 private final class ClearStorageConnection implements ServiceConnection { 13261 IMediaContainerService mContainerService; 13262 13263 @Override 13264 public void onServiceConnected(ComponentName name, IBinder service) { 13265 synchronized (this) { 13266 mContainerService = IMediaContainerService.Stub.asInterface(service); 13267 notifyAll(); 13268 } 13269 } 13270 13271 @Override 13272 public void onServiceDisconnected(ComponentName name) { 13273 } 13274 } 13275 13276 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13277 final boolean mounted; 13278 if (Environment.isExternalStorageEmulated()) { 13279 mounted = true; 13280 } else { 13281 final String status = Environment.getExternalStorageState(); 13282 13283 mounted = status.equals(Environment.MEDIA_MOUNTED) 13284 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13285 } 13286 13287 if (!mounted) { 13288 return; 13289 } 13290 13291 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13292 int[] users; 13293 if (userId == UserHandle.USER_ALL) { 13294 users = sUserManager.getUserIds(); 13295 } else { 13296 users = new int[] { userId }; 13297 } 13298 final ClearStorageConnection conn = new ClearStorageConnection(); 13299 if (mContext.bindServiceAsUser( 13300 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13301 try { 13302 for (int curUser : users) { 13303 long timeout = SystemClock.uptimeMillis() + 5000; 13304 synchronized (conn) { 13305 long now = SystemClock.uptimeMillis(); 13306 while (conn.mContainerService == null && now < timeout) { 13307 try { 13308 conn.wait(timeout - now); 13309 } catch (InterruptedException e) { 13310 } 13311 } 13312 } 13313 if (conn.mContainerService == null) { 13314 return; 13315 } 13316 13317 final UserEnvironment userEnv = new UserEnvironment(curUser); 13318 clearDirectory(conn.mContainerService, 13319 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13320 if (allData) { 13321 clearDirectory(conn.mContainerService, 13322 userEnv.buildExternalStorageAppDataDirs(packageName)); 13323 clearDirectory(conn.mContainerService, 13324 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13325 } 13326 } 13327 } finally { 13328 mContext.unbindService(conn); 13329 } 13330 } 13331 } 13332 13333 @Override 13334 public void clearApplicationUserData(final String packageName, 13335 final IPackageDataObserver observer, final int userId) { 13336 mContext.enforceCallingOrSelfPermission( 13337 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13338 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13339 // Queue up an async operation since the package deletion may take a little while. 13340 mHandler.post(new Runnable() { 13341 public void run() { 13342 mHandler.removeCallbacks(this); 13343 final boolean succeeded; 13344 synchronized (mInstallLock) { 13345 succeeded = clearApplicationUserDataLI(packageName, userId); 13346 } 13347 clearExternalStorageDataSync(packageName, userId, true); 13348 if (succeeded) { 13349 // invoke DeviceStorageMonitor's update method to clear any notifications 13350 DeviceStorageMonitorInternal 13351 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13352 if (dsm != null) { 13353 dsm.checkMemory(); 13354 } 13355 } 13356 if(observer != null) { 13357 try { 13358 observer.onRemoveCompleted(packageName, succeeded); 13359 } catch (RemoteException e) { 13360 Log.i(TAG, "Observer no longer exists."); 13361 } 13362 } //end if observer 13363 } //end run 13364 }); 13365 } 13366 13367 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13368 if (packageName == null) { 13369 Slog.w(TAG, "Attempt to delete null packageName."); 13370 return false; 13371 } 13372 13373 // Try finding details about the requested package 13374 PackageParser.Package pkg; 13375 synchronized (mPackages) { 13376 pkg = mPackages.get(packageName); 13377 if (pkg == null) { 13378 final PackageSetting ps = mSettings.mPackages.get(packageName); 13379 if (ps != null) { 13380 pkg = ps.pkg; 13381 } 13382 } 13383 13384 if (pkg == null) { 13385 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13386 return false; 13387 } 13388 13389 PackageSetting ps = (PackageSetting) pkg.mExtras; 13390 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13391 } 13392 13393 // Always delete data directories for package, even if we found no other 13394 // record of app. This helps users recover from UID mismatches without 13395 // resorting to a full data wipe. 13396 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13397 if (retCode < 0) { 13398 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13399 return false; 13400 } 13401 13402 final int appId = pkg.applicationInfo.uid; 13403 removeKeystoreDataIfNeeded(userId, appId); 13404 13405 // Create a native library symlink only if we have native libraries 13406 // and if the native libraries are 32 bit libraries. We do not provide 13407 // this symlink for 64 bit libraries. 13408 if (pkg.applicationInfo.primaryCpuAbi != null && 13409 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13410 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13411 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13412 nativeLibPath, userId) < 0) { 13413 Slog.w(TAG, "Failed linking native library dir"); 13414 return false; 13415 } 13416 } 13417 13418 return true; 13419 } 13420 13421 /** 13422 * Reverts user permission state changes (permissions and flags) in 13423 * all packages for a given user. 13424 * 13425 * @param userId The device user for which to do a reset. 13426 */ 13427 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13428 final int packageCount = mPackages.size(); 13429 for (int i = 0; i < packageCount; i++) { 13430 PackageParser.Package pkg = mPackages.valueAt(i); 13431 PackageSetting ps = (PackageSetting) pkg.mExtras; 13432 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13433 } 13434 } 13435 13436 /** 13437 * Reverts user permission state changes (permissions and flags). 13438 * 13439 * @param ps The package for which to reset. 13440 * @param userId The device user for which to do a reset. 13441 */ 13442 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13443 final PackageSetting ps, final int userId) { 13444 if (ps.pkg == null) { 13445 return; 13446 } 13447 13448 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13449 | FLAG_PERMISSION_USER_FIXED 13450 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13451 13452 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13453 | FLAG_PERMISSION_POLICY_FIXED; 13454 13455 boolean writeInstallPermissions = false; 13456 boolean writeRuntimePermissions = false; 13457 13458 final int permissionCount = ps.pkg.requestedPermissions.size(); 13459 for (int i = 0; i < permissionCount; i++) { 13460 String permission = ps.pkg.requestedPermissions.get(i); 13461 13462 BasePermission bp = mSettings.mPermissions.get(permission); 13463 if (bp == null) { 13464 continue; 13465 } 13466 13467 // If shared user we just reset the state to which only this app contributed. 13468 if (ps.sharedUser != null) { 13469 boolean used = false; 13470 final int packageCount = ps.sharedUser.packages.size(); 13471 for (int j = 0; j < packageCount; j++) { 13472 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13473 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13474 && pkg.pkg.requestedPermissions.contains(permission)) { 13475 used = true; 13476 break; 13477 } 13478 } 13479 if (used) { 13480 continue; 13481 } 13482 } 13483 13484 PermissionsState permissionsState = ps.getPermissionsState(); 13485 13486 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13487 13488 // Always clear the user settable flags. 13489 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13490 bp.name) != null; 13491 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13492 if (hasInstallState) { 13493 writeInstallPermissions = true; 13494 } else { 13495 writeRuntimePermissions = true; 13496 } 13497 } 13498 13499 // Below is only runtime permission handling. 13500 if (!bp.isRuntime()) { 13501 continue; 13502 } 13503 13504 // Never clobber system or policy. 13505 if ((oldFlags & policyOrSystemFlags) != 0) { 13506 continue; 13507 } 13508 13509 // If this permission was granted by default, make sure it is. 13510 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13511 if (permissionsState.grantRuntimePermission(bp, userId) 13512 != PERMISSION_OPERATION_FAILURE) { 13513 writeRuntimePermissions = true; 13514 } 13515 } else { 13516 // Otherwise, reset the permission. 13517 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13518 switch (revokeResult) { 13519 case PERMISSION_OPERATION_SUCCESS: { 13520 writeRuntimePermissions = true; 13521 } break; 13522 13523 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13524 writeRuntimePermissions = true; 13525 final int appId = ps.appId; 13526 mHandler.post(new Runnable() { 13527 @Override 13528 public void run() { 13529 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13530 } 13531 }); 13532 } break; 13533 } 13534 } 13535 } 13536 13537 // Synchronously write as we are taking permissions away. 13538 if (writeRuntimePermissions) { 13539 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13540 } 13541 13542 // Synchronously write as we are taking permissions away. 13543 if (writeInstallPermissions) { 13544 mSettings.writeLPr(); 13545 } 13546 } 13547 13548 /** 13549 * Remove entries from the keystore daemon. Will only remove it if the 13550 * {@code appId} is valid. 13551 */ 13552 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13553 if (appId < 0) { 13554 return; 13555 } 13556 13557 final KeyStore keyStore = KeyStore.getInstance(); 13558 if (keyStore != null) { 13559 if (userId == UserHandle.USER_ALL) { 13560 for (final int individual : sUserManager.getUserIds()) { 13561 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13562 } 13563 } else { 13564 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13565 } 13566 } else { 13567 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13568 } 13569 } 13570 13571 @Override 13572 public void deleteApplicationCacheFiles(final String packageName, 13573 final IPackageDataObserver observer) { 13574 mContext.enforceCallingOrSelfPermission( 13575 android.Manifest.permission.DELETE_CACHE_FILES, null); 13576 // Queue up an async operation since the package deletion may take a little while. 13577 final int userId = UserHandle.getCallingUserId(); 13578 mHandler.post(new Runnable() { 13579 public void run() { 13580 mHandler.removeCallbacks(this); 13581 final boolean succeded; 13582 synchronized (mInstallLock) { 13583 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13584 } 13585 clearExternalStorageDataSync(packageName, userId, false); 13586 if (observer != null) { 13587 try { 13588 observer.onRemoveCompleted(packageName, succeded); 13589 } catch (RemoteException e) { 13590 Log.i(TAG, "Observer no longer exists."); 13591 } 13592 } //end if observer 13593 } //end run 13594 }); 13595 } 13596 13597 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13598 if (packageName == null) { 13599 Slog.w(TAG, "Attempt to delete null packageName."); 13600 return false; 13601 } 13602 PackageParser.Package p; 13603 synchronized (mPackages) { 13604 p = mPackages.get(packageName); 13605 } 13606 if (p == null) { 13607 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13608 return false; 13609 } 13610 final ApplicationInfo applicationInfo = p.applicationInfo; 13611 if (applicationInfo == null) { 13612 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13613 return false; 13614 } 13615 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13616 if (retCode < 0) { 13617 Slog.w(TAG, "Couldn't remove cache files for package: " 13618 + packageName + " u" + userId); 13619 return false; 13620 } 13621 return true; 13622 } 13623 13624 @Override 13625 public void getPackageSizeInfo(final String packageName, int userHandle, 13626 final IPackageStatsObserver observer) { 13627 mContext.enforceCallingOrSelfPermission( 13628 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13629 if (packageName == null) { 13630 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13631 } 13632 13633 PackageStats stats = new PackageStats(packageName, userHandle); 13634 13635 /* 13636 * Queue up an async operation since the package measurement may take a 13637 * little while. 13638 */ 13639 Message msg = mHandler.obtainMessage(INIT_COPY); 13640 msg.obj = new MeasureParams(stats, observer); 13641 mHandler.sendMessage(msg); 13642 } 13643 13644 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13645 PackageStats pStats) { 13646 if (packageName == null) { 13647 Slog.w(TAG, "Attempt to get size of null packageName."); 13648 return false; 13649 } 13650 PackageParser.Package p; 13651 boolean dataOnly = false; 13652 String libDirRoot = null; 13653 String asecPath = null; 13654 PackageSetting ps = null; 13655 synchronized (mPackages) { 13656 p = mPackages.get(packageName); 13657 ps = mSettings.mPackages.get(packageName); 13658 if(p == null) { 13659 dataOnly = true; 13660 if((ps == null) || (ps.pkg == null)) { 13661 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13662 return false; 13663 } 13664 p = ps.pkg; 13665 } 13666 if (ps != null) { 13667 libDirRoot = ps.legacyNativeLibraryPathString; 13668 } 13669 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 13670 final long token = Binder.clearCallingIdentity(); 13671 try { 13672 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13673 if (secureContainerId != null) { 13674 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13675 } 13676 } finally { 13677 Binder.restoreCallingIdentity(token); 13678 } 13679 } 13680 } 13681 String publicSrcDir = null; 13682 if(!dataOnly) { 13683 final ApplicationInfo applicationInfo = p.applicationInfo; 13684 if (applicationInfo == null) { 13685 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13686 return false; 13687 } 13688 if (p.isForwardLocked()) { 13689 publicSrcDir = applicationInfo.getBaseResourcePath(); 13690 } 13691 } 13692 // TODO: extend to measure size of split APKs 13693 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13694 // not just the first level. 13695 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13696 // just the primary. 13697 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13698 13699 String apkPath; 13700 File packageDir = new File(p.codePath); 13701 13702 if (packageDir.isDirectory() && p.canHaveOatDir()) { 13703 apkPath = packageDir.getAbsolutePath(); 13704 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 13705 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 13706 libDirRoot = null; 13707 } 13708 } else { 13709 apkPath = p.baseCodePath; 13710 } 13711 13712 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 13713 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13714 if (res < 0) { 13715 return false; 13716 } 13717 13718 // Fix-up for forward-locked applications in ASEC containers. 13719 if (!isExternal(p)) { 13720 pStats.codeSize += pStats.externalCodeSize; 13721 pStats.externalCodeSize = 0L; 13722 } 13723 13724 return true; 13725 } 13726 13727 13728 @Override 13729 public void addPackageToPreferred(String packageName) { 13730 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13731 } 13732 13733 @Override 13734 public void removePackageFromPreferred(String packageName) { 13735 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13736 } 13737 13738 @Override 13739 public List<PackageInfo> getPreferredPackages(int flags) { 13740 return new ArrayList<PackageInfo>(); 13741 } 13742 13743 private int getUidTargetSdkVersionLockedLPr(int uid) { 13744 Object obj = mSettings.getUserIdLPr(uid); 13745 if (obj instanceof SharedUserSetting) { 13746 final SharedUserSetting sus = (SharedUserSetting) obj; 13747 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13748 final Iterator<PackageSetting> it = sus.packages.iterator(); 13749 while (it.hasNext()) { 13750 final PackageSetting ps = it.next(); 13751 if (ps.pkg != null) { 13752 int v = ps.pkg.applicationInfo.targetSdkVersion; 13753 if (v < vers) vers = v; 13754 } 13755 } 13756 return vers; 13757 } else if (obj instanceof PackageSetting) { 13758 final PackageSetting ps = (PackageSetting) obj; 13759 if (ps.pkg != null) { 13760 return ps.pkg.applicationInfo.targetSdkVersion; 13761 } 13762 } 13763 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13764 } 13765 13766 @Override 13767 public void addPreferredActivity(IntentFilter filter, int match, 13768 ComponentName[] set, ComponentName activity, int userId) { 13769 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13770 "Adding preferred"); 13771 } 13772 13773 private void addPreferredActivityInternal(IntentFilter filter, int match, 13774 ComponentName[] set, ComponentName activity, boolean always, int userId, 13775 String opname) { 13776 // writer 13777 int callingUid = Binder.getCallingUid(); 13778 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13779 if (filter.countActions() == 0) { 13780 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13781 return; 13782 } 13783 synchronized (mPackages) { 13784 if (mContext.checkCallingOrSelfPermission( 13785 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13786 != PackageManager.PERMISSION_GRANTED) { 13787 if (getUidTargetSdkVersionLockedLPr(callingUid) 13788 < Build.VERSION_CODES.FROYO) { 13789 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13790 + callingUid); 13791 return; 13792 } 13793 mContext.enforceCallingOrSelfPermission( 13794 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13795 } 13796 13797 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13798 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13799 + userId + ":"); 13800 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13801 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13802 scheduleWritePackageRestrictionsLocked(userId); 13803 } 13804 } 13805 13806 @Override 13807 public void replacePreferredActivity(IntentFilter filter, int match, 13808 ComponentName[] set, ComponentName activity, int userId) { 13809 if (filter.countActions() != 1) { 13810 throw new IllegalArgumentException( 13811 "replacePreferredActivity expects filter to have only 1 action."); 13812 } 13813 if (filter.countDataAuthorities() != 0 13814 || filter.countDataPaths() != 0 13815 || filter.countDataSchemes() > 1 13816 || filter.countDataTypes() != 0) { 13817 throw new IllegalArgumentException( 13818 "replacePreferredActivity expects filter to have no data authorities, " + 13819 "paths, or types; and at most one scheme."); 13820 } 13821 13822 final int callingUid = Binder.getCallingUid(); 13823 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13824 synchronized (mPackages) { 13825 if (mContext.checkCallingOrSelfPermission( 13826 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13827 != PackageManager.PERMISSION_GRANTED) { 13828 if (getUidTargetSdkVersionLockedLPr(callingUid) 13829 < Build.VERSION_CODES.FROYO) { 13830 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13831 + Binder.getCallingUid()); 13832 return; 13833 } 13834 mContext.enforceCallingOrSelfPermission( 13835 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13836 } 13837 13838 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13839 if (pir != null) { 13840 // Get all of the existing entries that exactly match this filter. 13841 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13842 if (existing != null && existing.size() == 1) { 13843 PreferredActivity cur = existing.get(0); 13844 if (DEBUG_PREFERRED) { 13845 Slog.i(TAG, "Checking replace of preferred:"); 13846 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13847 if (!cur.mPref.mAlways) { 13848 Slog.i(TAG, " -- CUR; not mAlways!"); 13849 } else { 13850 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13851 Slog.i(TAG, " -- CUR: mSet=" 13852 + Arrays.toString(cur.mPref.mSetComponents)); 13853 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13854 Slog.i(TAG, " -- NEW: mMatch=" 13855 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13856 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13857 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13858 } 13859 } 13860 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13861 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13862 && cur.mPref.sameSet(set)) { 13863 // Setting the preferred activity to what it happens to be already 13864 if (DEBUG_PREFERRED) { 13865 Slog.i(TAG, "Replacing with same preferred activity " 13866 + cur.mPref.mShortComponent + " for user " 13867 + userId + ":"); 13868 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13869 } 13870 return; 13871 } 13872 } 13873 13874 if (existing != null) { 13875 if (DEBUG_PREFERRED) { 13876 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13877 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13878 } 13879 for (int i = 0; i < existing.size(); i++) { 13880 PreferredActivity pa = existing.get(i); 13881 if (DEBUG_PREFERRED) { 13882 Slog.i(TAG, "Removing existing preferred activity " 13883 + pa.mPref.mComponent + ":"); 13884 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13885 } 13886 pir.removeFilter(pa); 13887 } 13888 } 13889 } 13890 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13891 "Replacing preferred"); 13892 } 13893 } 13894 13895 @Override 13896 public void clearPackagePreferredActivities(String packageName) { 13897 final int uid = Binder.getCallingUid(); 13898 // writer 13899 synchronized (mPackages) { 13900 PackageParser.Package pkg = mPackages.get(packageName); 13901 if (pkg == null || pkg.applicationInfo.uid != uid) { 13902 if (mContext.checkCallingOrSelfPermission( 13903 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13904 != PackageManager.PERMISSION_GRANTED) { 13905 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13906 < Build.VERSION_CODES.FROYO) { 13907 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13908 + Binder.getCallingUid()); 13909 return; 13910 } 13911 mContext.enforceCallingOrSelfPermission( 13912 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13913 } 13914 } 13915 13916 int user = UserHandle.getCallingUserId(); 13917 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13918 scheduleWritePackageRestrictionsLocked(user); 13919 } 13920 } 13921 } 13922 13923 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13924 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13925 ArrayList<PreferredActivity> removed = null; 13926 boolean changed = false; 13927 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13928 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13929 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13930 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13931 continue; 13932 } 13933 Iterator<PreferredActivity> it = pir.filterIterator(); 13934 while (it.hasNext()) { 13935 PreferredActivity pa = it.next(); 13936 // Mark entry for removal only if it matches the package name 13937 // and the entry is of type "always". 13938 if (packageName == null || 13939 (pa.mPref.mComponent.getPackageName().equals(packageName) 13940 && pa.mPref.mAlways)) { 13941 if (removed == null) { 13942 removed = new ArrayList<PreferredActivity>(); 13943 } 13944 removed.add(pa); 13945 } 13946 } 13947 if (removed != null) { 13948 for (int j=0; j<removed.size(); j++) { 13949 PreferredActivity pa = removed.get(j); 13950 pir.removeFilter(pa); 13951 } 13952 changed = true; 13953 } 13954 } 13955 return changed; 13956 } 13957 13958 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13959 private void clearIntentFilterVerificationsLPw(int userId) { 13960 final int packageCount = mPackages.size(); 13961 for (int i = 0; i < packageCount; i++) { 13962 PackageParser.Package pkg = mPackages.valueAt(i); 13963 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13964 } 13965 } 13966 13967 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13968 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13969 if (userId == UserHandle.USER_ALL) { 13970 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13971 sUserManager.getUserIds())) { 13972 for (int oneUserId : sUserManager.getUserIds()) { 13973 scheduleWritePackageRestrictionsLocked(oneUserId); 13974 } 13975 } 13976 } else { 13977 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13978 scheduleWritePackageRestrictionsLocked(userId); 13979 } 13980 } 13981 } 13982 13983 void clearDefaultBrowserIfNeeded(String packageName) { 13984 for (int oneUserId : sUserManager.getUserIds()) { 13985 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13986 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13987 if (packageName.equals(defaultBrowserPackageName)) { 13988 setDefaultBrowserPackageName(null, oneUserId); 13989 } 13990 } 13991 } 13992 13993 @Override 13994 public void resetApplicationPreferences(int userId) { 13995 mContext.enforceCallingOrSelfPermission( 13996 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13997 // writer 13998 synchronized (mPackages) { 13999 final long identity = Binder.clearCallingIdentity(); 14000 try { 14001 clearPackagePreferredActivitiesLPw(null, userId); 14002 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14003 // TODO: We have to reset the default SMS and Phone. This requires 14004 // significant refactoring to keep all default apps in the package 14005 // manager (cleaner but more work) or have the services provide 14006 // callbacks to the package manager to request a default app reset. 14007 applyFactoryDefaultBrowserLPw(userId); 14008 clearIntentFilterVerificationsLPw(userId); 14009 primeDomainVerificationsLPw(userId); 14010 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14011 scheduleWritePackageRestrictionsLocked(userId); 14012 } finally { 14013 Binder.restoreCallingIdentity(identity); 14014 } 14015 } 14016 } 14017 14018 @Override 14019 public int getPreferredActivities(List<IntentFilter> outFilters, 14020 List<ComponentName> outActivities, String packageName) { 14021 14022 int num = 0; 14023 final int userId = UserHandle.getCallingUserId(); 14024 // reader 14025 synchronized (mPackages) { 14026 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14027 if (pir != null) { 14028 final Iterator<PreferredActivity> it = pir.filterIterator(); 14029 while (it.hasNext()) { 14030 final PreferredActivity pa = it.next(); 14031 if (packageName == null 14032 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14033 && pa.mPref.mAlways)) { 14034 if (outFilters != null) { 14035 outFilters.add(new IntentFilter(pa)); 14036 } 14037 if (outActivities != null) { 14038 outActivities.add(pa.mPref.mComponent); 14039 } 14040 } 14041 } 14042 } 14043 } 14044 14045 return num; 14046 } 14047 14048 @Override 14049 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14050 int userId) { 14051 int callingUid = Binder.getCallingUid(); 14052 if (callingUid != Process.SYSTEM_UID) { 14053 throw new SecurityException( 14054 "addPersistentPreferredActivity can only be run by the system"); 14055 } 14056 if (filter.countActions() == 0) { 14057 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14058 return; 14059 } 14060 synchronized (mPackages) { 14061 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14062 " :"); 14063 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14064 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14065 new PersistentPreferredActivity(filter, activity)); 14066 scheduleWritePackageRestrictionsLocked(userId); 14067 } 14068 } 14069 14070 @Override 14071 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14072 int callingUid = Binder.getCallingUid(); 14073 if (callingUid != Process.SYSTEM_UID) { 14074 throw new SecurityException( 14075 "clearPackagePersistentPreferredActivities can only be run by the system"); 14076 } 14077 ArrayList<PersistentPreferredActivity> removed = null; 14078 boolean changed = false; 14079 synchronized (mPackages) { 14080 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14081 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14082 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14083 .valueAt(i); 14084 if (userId != thisUserId) { 14085 continue; 14086 } 14087 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14088 while (it.hasNext()) { 14089 PersistentPreferredActivity ppa = it.next(); 14090 // Mark entry for removal only if it matches the package name. 14091 if (ppa.mComponent.getPackageName().equals(packageName)) { 14092 if (removed == null) { 14093 removed = new ArrayList<PersistentPreferredActivity>(); 14094 } 14095 removed.add(ppa); 14096 } 14097 } 14098 if (removed != null) { 14099 for (int j=0; j<removed.size(); j++) { 14100 PersistentPreferredActivity ppa = removed.get(j); 14101 ppir.removeFilter(ppa); 14102 } 14103 changed = true; 14104 } 14105 } 14106 14107 if (changed) { 14108 scheduleWritePackageRestrictionsLocked(userId); 14109 } 14110 } 14111 } 14112 14113 /** 14114 * Common machinery for picking apart a restored XML blob and passing 14115 * it to a caller-supplied functor to be applied to the running system. 14116 */ 14117 private void restoreFromXml(XmlPullParser parser, int userId, 14118 String expectedStartTag, BlobXmlRestorer functor) 14119 throws IOException, XmlPullParserException { 14120 int type; 14121 while ((type = parser.next()) != XmlPullParser.START_TAG 14122 && type != XmlPullParser.END_DOCUMENT) { 14123 } 14124 if (type != XmlPullParser.START_TAG) { 14125 // oops didn't find a start tag?! 14126 if (DEBUG_BACKUP) { 14127 Slog.e(TAG, "Didn't find start tag during restore"); 14128 } 14129 return; 14130 } 14131 14132 // this is supposed to be TAG_PREFERRED_BACKUP 14133 if (!expectedStartTag.equals(parser.getName())) { 14134 if (DEBUG_BACKUP) { 14135 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14136 } 14137 return; 14138 } 14139 14140 // skip interfering stuff, then we're aligned with the backing implementation 14141 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14142 functor.apply(parser, userId); 14143 } 14144 14145 private interface BlobXmlRestorer { 14146 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14147 } 14148 14149 /** 14150 * Non-Binder method, support for the backup/restore mechanism: write the 14151 * full set of preferred activities in its canonical XML format. Returns the 14152 * XML output as a byte array, or null if there is none. 14153 */ 14154 @Override 14155 public byte[] getPreferredActivityBackup(int userId) { 14156 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14157 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14158 } 14159 14160 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14161 try { 14162 final XmlSerializer serializer = new FastXmlSerializer(); 14163 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14164 serializer.startDocument(null, true); 14165 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14166 14167 synchronized (mPackages) { 14168 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14169 } 14170 14171 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14172 serializer.endDocument(); 14173 serializer.flush(); 14174 } catch (Exception e) { 14175 if (DEBUG_BACKUP) { 14176 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14177 } 14178 return null; 14179 } 14180 14181 return dataStream.toByteArray(); 14182 } 14183 14184 @Override 14185 public void restorePreferredActivities(byte[] backup, int userId) { 14186 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14187 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14188 } 14189 14190 try { 14191 final XmlPullParser parser = Xml.newPullParser(); 14192 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14193 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14194 new BlobXmlRestorer() { 14195 @Override 14196 public void apply(XmlPullParser parser, int userId) 14197 throws XmlPullParserException, IOException { 14198 synchronized (mPackages) { 14199 mSettings.readPreferredActivitiesLPw(parser, userId); 14200 } 14201 } 14202 } ); 14203 } catch (Exception e) { 14204 if (DEBUG_BACKUP) { 14205 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14206 } 14207 } 14208 } 14209 14210 /** 14211 * Non-Binder method, support for the backup/restore mechanism: write the 14212 * default browser (etc) settings in its canonical XML format. Returns the default 14213 * browser XML representation as a byte array, or null if there is none. 14214 */ 14215 @Override 14216 public byte[] getDefaultAppsBackup(int userId) { 14217 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14218 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14219 } 14220 14221 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14222 try { 14223 final XmlSerializer serializer = new FastXmlSerializer(); 14224 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14225 serializer.startDocument(null, true); 14226 serializer.startTag(null, TAG_DEFAULT_APPS); 14227 14228 synchronized (mPackages) { 14229 mSettings.writeDefaultAppsLPr(serializer, userId); 14230 } 14231 14232 serializer.endTag(null, TAG_DEFAULT_APPS); 14233 serializer.endDocument(); 14234 serializer.flush(); 14235 } catch (Exception e) { 14236 if (DEBUG_BACKUP) { 14237 Slog.e(TAG, "Unable to write default apps for backup", e); 14238 } 14239 return null; 14240 } 14241 14242 return dataStream.toByteArray(); 14243 } 14244 14245 @Override 14246 public void restoreDefaultApps(byte[] backup, int userId) { 14247 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14248 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14249 } 14250 14251 try { 14252 final XmlPullParser parser = Xml.newPullParser(); 14253 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14254 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14255 new BlobXmlRestorer() { 14256 @Override 14257 public void apply(XmlPullParser parser, int userId) 14258 throws XmlPullParserException, IOException { 14259 synchronized (mPackages) { 14260 mSettings.readDefaultAppsLPw(parser, userId); 14261 } 14262 } 14263 } ); 14264 } catch (Exception e) { 14265 if (DEBUG_BACKUP) { 14266 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14267 } 14268 } 14269 } 14270 14271 @Override 14272 public byte[] getIntentFilterVerificationBackup(int userId) { 14273 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14274 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14275 } 14276 14277 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14278 try { 14279 final XmlSerializer serializer = new FastXmlSerializer(); 14280 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14281 serializer.startDocument(null, true); 14282 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14283 14284 synchronized (mPackages) { 14285 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14286 } 14287 14288 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14289 serializer.endDocument(); 14290 serializer.flush(); 14291 } catch (Exception e) { 14292 if (DEBUG_BACKUP) { 14293 Slog.e(TAG, "Unable to write default apps for backup", e); 14294 } 14295 return null; 14296 } 14297 14298 return dataStream.toByteArray(); 14299 } 14300 14301 @Override 14302 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14303 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14304 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14305 } 14306 14307 try { 14308 final XmlPullParser parser = Xml.newPullParser(); 14309 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14310 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14311 new BlobXmlRestorer() { 14312 @Override 14313 public void apply(XmlPullParser parser, int userId) 14314 throws XmlPullParserException, IOException { 14315 synchronized (mPackages) { 14316 mSettings.readAllDomainVerificationsLPr(parser, userId); 14317 mSettings.writeLPr(); 14318 } 14319 } 14320 } ); 14321 } catch (Exception e) { 14322 if (DEBUG_BACKUP) { 14323 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14324 } 14325 } 14326 } 14327 14328 @Override 14329 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14330 int sourceUserId, int targetUserId, int flags) { 14331 mContext.enforceCallingOrSelfPermission( 14332 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14333 int callingUid = Binder.getCallingUid(); 14334 enforceOwnerRights(ownerPackage, callingUid); 14335 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14336 if (intentFilter.countActions() == 0) { 14337 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14338 return; 14339 } 14340 synchronized (mPackages) { 14341 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14342 ownerPackage, targetUserId, flags); 14343 CrossProfileIntentResolver resolver = 14344 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14345 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14346 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14347 if (existing != null) { 14348 int size = existing.size(); 14349 for (int i = 0; i < size; i++) { 14350 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14351 return; 14352 } 14353 } 14354 } 14355 resolver.addFilter(newFilter); 14356 scheduleWritePackageRestrictionsLocked(sourceUserId); 14357 } 14358 } 14359 14360 @Override 14361 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14362 mContext.enforceCallingOrSelfPermission( 14363 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14364 int callingUid = Binder.getCallingUid(); 14365 enforceOwnerRights(ownerPackage, callingUid); 14366 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14367 synchronized (mPackages) { 14368 CrossProfileIntentResolver resolver = 14369 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14370 ArraySet<CrossProfileIntentFilter> set = 14371 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14372 for (CrossProfileIntentFilter filter : set) { 14373 if (filter.getOwnerPackage().equals(ownerPackage)) { 14374 resolver.removeFilter(filter); 14375 } 14376 } 14377 scheduleWritePackageRestrictionsLocked(sourceUserId); 14378 } 14379 } 14380 14381 // Enforcing that callingUid is owning pkg on userId 14382 private void enforceOwnerRights(String pkg, int callingUid) { 14383 // The system owns everything. 14384 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14385 return; 14386 } 14387 int callingUserId = UserHandle.getUserId(callingUid); 14388 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14389 if (pi == null) { 14390 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14391 + callingUserId); 14392 } 14393 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14394 throw new SecurityException("Calling uid " + callingUid 14395 + " does not own package " + pkg); 14396 } 14397 } 14398 14399 @Override 14400 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14401 Intent intent = new Intent(Intent.ACTION_MAIN); 14402 intent.addCategory(Intent.CATEGORY_HOME); 14403 14404 final int callingUserId = UserHandle.getCallingUserId(); 14405 List<ResolveInfo> list = queryIntentActivities(intent, null, 14406 PackageManager.GET_META_DATA, callingUserId); 14407 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14408 true, false, false, callingUserId); 14409 14410 allHomeCandidates.clear(); 14411 if (list != null) { 14412 for (ResolveInfo ri : list) { 14413 allHomeCandidates.add(ri); 14414 } 14415 } 14416 return (preferred == null || preferred.activityInfo == null) 14417 ? null 14418 : new ComponentName(preferred.activityInfo.packageName, 14419 preferred.activityInfo.name); 14420 } 14421 14422 @Override 14423 public void setApplicationEnabledSetting(String appPackageName, 14424 int newState, int flags, int userId, String callingPackage) { 14425 if (!sUserManager.exists(userId)) return; 14426 if (callingPackage == null) { 14427 callingPackage = Integer.toString(Binder.getCallingUid()); 14428 } 14429 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14430 } 14431 14432 @Override 14433 public void setComponentEnabledSetting(ComponentName componentName, 14434 int newState, int flags, int userId) { 14435 if (!sUserManager.exists(userId)) return; 14436 setEnabledSetting(componentName.getPackageName(), 14437 componentName.getClassName(), newState, flags, userId, null); 14438 } 14439 14440 private void setEnabledSetting(final String packageName, String className, int newState, 14441 final int flags, int userId, String callingPackage) { 14442 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14443 || newState == COMPONENT_ENABLED_STATE_ENABLED 14444 || newState == COMPONENT_ENABLED_STATE_DISABLED 14445 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14446 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14447 throw new IllegalArgumentException("Invalid new component state: " 14448 + newState); 14449 } 14450 PackageSetting pkgSetting; 14451 final int uid = Binder.getCallingUid(); 14452 final int permission = mContext.checkCallingOrSelfPermission( 14453 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14454 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14455 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14456 boolean sendNow = false; 14457 boolean isApp = (className == null); 14458 String componentName = isApp ? packageName : className; 14459 int packageUid = -1; 14460 ArrayList<String> components; 14461 14462 // writer 14463 synchronized (mPackages) { 14464 pkgSetting = mSettings.mPackages.get(packageName); 14465 if (pkgSetting == null) { 14466 if (className == null) { 14467 throw new IllegalArgumentException( 14468 "Unknown package: " + packageName); 14469 } 14470 throw new IllegalArgumentException( 14471 "Unknown component: " + packageName 14472 + "/" + className); 14473 } 14474 // Allow root and verify that userId is not being specified by a different user 14475 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14476 throw new SecurityException( 14477 "Permission Denial: attempt to change component state from pid=" 14478 + Binder.getCallingPid() 14479 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14480 } 14481 if (className == null) { 14482 // We're dealing with an application/package level state change 14483 if (pkgSetting.getEnabled(userId) == newState) { 14484 // Nothing to do 14485 return; 14486 } 14487 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14488 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14489 // Don't care about who enables an app. 14490 callingPackage = null; 14491 } 14492 pkgSetting.setEnabled(newState, userId, callingPackage); 14493 // pkgSetting.pkg.mSetEnabled = newState; 14494 } else { 14495 // We're dealing with a component level state change 14496 // First, verify that this is a valid class name. 14497 PackageParser.Package pkg = pkgSetting.pkg; 14498 if (pkg == null || !pkg.hasComponentClassName(className)) { 14499 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14500 throw new IllegalArgumentException("Component class " + className 14501 + " does not exist in " + packageName); 14502 } else { 14503 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14504 + className + " does not exist in " + packageName); 14505 } 14506 } 14507 switch (newState) { 14508 case COMPONENT_ENABLED_STATE_ENABLED: 14509 if (!pkgSetting.enableComponentLPw(className, userId)) { 14510 return; 14511 } 14512 break; 14513 case COMPONENT_ENABLED_STATE_DISABLED: 14514 if (!pkgSetting.disableComponentLPw(className, userId)) { 14515 return; 14516 } 14517 break; 14518 case COMPONENT_ENABLED_STATE_DEFAULT: 14519 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14520 return; 14521 } 14522 break; 14523 default: 14524 Slog.e(TAG, "Invalid new component state: " + newState); 14525 return; 14526 } 14527 } 14528 scheduleWritePackageRestrictionsLocked(userId); 14529 components = mPendingBroadcasts.get(userId, packageName); 14530 final boolean newPackage = components == null; 14531 if (newPackage) { 14532 components = new ArrayList<String>(); 14533 } 14534 if (!components.contains(componentName)) { 14535 components.add(componentName); 14536 } 14537 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14538 sendNow = true; 14539 // Purge entry from pending broadcast list if another one exists already 14540 // since we are sending one right away. 14541 mPendingBroadcasts.remove(userId, packageName); 14542 } else { 14543 if (newPackage) { 14544 mPendingBroadcasts.put(userId, packageName, components); 14545 } 14546 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14547 // Schedule a message 14548 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14549 } 14550 } 14551 } 14552 14553 long callingId = Binder.clearCallingIdentity(); 14554 try { 14555 if (sendNow) { 14556 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14557 sendPackageChangedBroadcast(packageName, 14558 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14559 } 14560 } finally { 14561 Binder.restoreCallingIdentity(callingId); 14562 } 14563 } 14564 14565 private void sendPackageChangedBroadcast(String packageName, 14566 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14567 if (DEBUG_INSTALL) 14568 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14569 + componentNames); 14570 Bundle extras = new Bundle(4); 14571 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14572 String nameList[] = new String[componentNames.size()]; 14573 componentNames.toArray(nameList); 14574 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14575 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14576 extras.putInt(Intent.EXTRA_UID, packageUid); 14577 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14578 new int[] {UserHandle.getUserId(packageUid)}); 14579 } 14580 14581 @Override 14582 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14583 if (!sUserManager.exists(userId)) return; 14584 final int uid = Binder.getCallingUid(); 14585 final int permission = mContext.checkCallingOrSelfPermission( 14586 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14587 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14588 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14589 // writer 14590 synchronized (mPackages) { 14591 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14592 allowedByPermission, uid, userId)) { 14593 scheduleWritePackageRestrictionsLocked(userId); 14594 } 14595 } 14596 } 14597 14598 @Override 14599 public String getInstallerPackageName(String packageName) { 14600 // reader 14601 synchronized (mPackages) { 14602 return mSettings.getInstallerPackageNameLPr(packageName); 14603 } 14604 } 14605 14606 @Override 14607 public int getApplicationEnabledSetting(String packageName, int userId) { 14608 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14609 int uid = Binder.getCallingUid(); 14610 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14611 // reader 14612 synchronized (mPackages) { 14613 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14614 } 14615 } 14616 14617 @Override 14618 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14619 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14620 int uid = Binder.getCallingUid(); 14621 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14622 // reader 14623 synchronized (mPackages) { 14624 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14625 } 14626 } 14627 14628 @Override 14629 public void enterSafeMode() { 14630 enforceSystemOrRoot("Only the system can request entering safe mode"); 14631 14632 if (!mSystemReady) { 14633 mSafeMode = true; 14634 } 14635 } 14636 14637 @Override 14638 public void systemReady() { 14639 mSystemReady = true; 14640 14641 // Read the compatibilty setting when the system is ready. 14642 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14643 mContext.getContentResolver(), 14644 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14645 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14646 if (DEBUG_SETTINGS) { 14647 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14648 } 14649 14650 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14651 14652 synchronized (mPackages) { 14653 // Verify that all of the preferred activity components actually 14654 // exist. It is possible for applications to be updated and at 14655 // that point remove a previously declared activity component that 14656 // had been set as a preferred activity. We try to clean this up 14657 // the next time we encounter that preferred activity, but it is 14658 // possible for the user flow to never be able to return to that 14659 // situation so here we do a sanity check to make sure we haven't 14660 // left any junk around. 14661 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14662 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14663 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14664 removed.clear(); 14665 for (PreferredActivity pa : pir.filterSet()) { 14666 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14667 removed.add(pa); 14668 } 14669 } 14670 if (removed.size() > 0) { 14671 for (int r=0; r<removed.size(); r++) { 14672 PreferredActivity pa = removed.get(r); 14673 Slog.w(TAG, "Removing dangling preferred activity: " 14674 + pa.mPref.mComponent); 14675 pir.removeFilter(pa); 14676 } 14677 mSettings.writePackageRestrictionsLPr( 14678 mSettings.mPreferredActivities.keyAt(i)); 14679 } 14680 } 14681 14682 for (int userId : UserManagerService.getInstance().getUserIds()) { 14683 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14684 grantPermissionsUserIds = ArrayUtils.appendInt( 14685 grantPermissionsUserIds, userId); 14686 } 14687 } 14688 } 14689 sUserManager.systemReady(); 14690 14691 // If we upgraded grant all default permissions before kicking off. 14692 for (int userId : grantPermissionsUserIds) { 14693 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14694 } 14695 14696 // Kick off any messages waiting for system ready 14697 if (mPostSystemReadyMessages != null) { 14698 for (Message msg : mPostSystemReadyMessages) { 14699 msg.sendToTarget(); 14700 } 14701 mPostSystemReadyMessages = null; 14702 } 14703 14704 // Watch for external volumes that come and go over time 14705 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14706 storage.registerListener(mStorageListener); 14707 14708 mInstallerService.systemReady(); 14709 mPackageDexOptimizer.systemReady(); 14710 14711 MountServiceInternal mountServiceInternal = LocalServices.getService( 14712 MountServiceInternal.class); 14713 mountServiceInternal.addExternalStoragePolicy( 14714 new MountServiceInternal.ExternalStorageMountPolicy() { 14715 @Override 14716 public int getMountMode(int uid, String packageName) { 14717 if (Process.isIsolated(uid)) { 14718 return Zygote.MOUNT_EXTERNAL_NONE; 14719 } 14720 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14721 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14722 } 14723 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14724 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14725 } 14726 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14727 return Zygote.MOUNT_EXTERNAL_READ; 14728 } 14729 return Zygote.MOUNT_EXTERNAL_WRITE; 14730 } 14731 14732 @Override 14733 public boolean hasExternalStorage(int uid, String packageName) { 14734 return true; 14735 } 14736 }); 14737 } 14738 14739 @Override 14740 public boolean isSafeMode() { 14741 return mSafeMode; 14742 } 14743 14744 @Override 14745 public boolean hasSystemUidErrors() { 14746 return mHasSystemUidErrors; 14747 } 14748 14749 static String arrayToString(int[] array) { 14750 StringBuffer buf = new StringBuffer(128); 14751 buf.append('['); 14752 if (array != null) { 14753 for (int i=0; i<array.length; i++) { 14754 if (i > 0) buf.append(", "); 14755 buf.append(array[i]); 14756 } 14757 } 14758 buf.append(']'); 14759 return buf.toString(); 14760 } 14761 14762 static class DumpState { 14763 public static final int DUMP_LIBS = 1 << 0; 14764 public static final int DUMP_FEATURES = 1 << 1; 14765 public static final int DUMP_RESOLVERS = 1 << 2; 14766 public static final int DUMP_PERMISSIONS = 1 << 3; 14767 public static final int DUMP_PACKAGES = 1 << 4; 14768 public static final int DUMP_SHARED_USERS = 1 << 5; 14769 public static final int DUMP_MESSAGES = 1 << 6; 14770 public static final int DUMP_PROVIDERS = 1 << 7; 14771 public static final int DUMP_VERIFIERS = 1 << 8; 14772 public static final int DUMP_PREFERRED = 1 << 9; 14773 public static final int DUMP_PREFERRED_XML = 1 << 10; 14774 public static final int DUMP_KEYSETS = 1 << 11; 14775 public static final int DUMP_VERSION = 1 << 12; 14776 public static final int DUMP_INSTALLS = 1 << 13; 14777 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14778 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14779 14780 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14781 14782 private int mTypes; 14783 14784 private int mOptions; 14785 14786 private boolean mTitlePrinted; 14787 14788 private SharedUserSetting mSharedUser; 14789 14790 public boolean isDumping(int type) { 14791 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14792 return true; 14793 } 14794 14795 return (mTypes & type) != 0; 14796 } 14797 14798 public void setDump(int type) { 14799 mTypes |= type; 14800 } 14801 14802 public boolean isOptionEnabled(int option) { 14803 return (mOptions & option) != 0; 14804 } 14805 14806 public void setOptionEnabled(int option) { 14807 mOptions |= option; 14808 } 14809 14810 public boolean onTitlePrinted() { 14811 final boolean printed = mTitlePrinted; 14812 mTitlePrinted = true; 14813 return printed; 14814 } 14815 14816 public boolean getTitlePrinted() { 14817 return mTitlePrinted; 14818 } 14819 14820 public void setTitlePrinted(boolean enabled) { 14821 mTitlePrinted = enabled; 14822 } 14823 14824 public SharedUserSetting getSharedUser() { 14825 return mSharedUser; 14826 } 14827 14828 public void setSharedUser(SharedUserSetting user) { 14829 mSharedUser = user; 14830 } 14831 } 14832 14833 @Override 14834 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14835 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14836 != PackageManager.PERMISSION_GRANTED) { 14837 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14838 + Binder.getCallingPid() 14839 + ", uid=" + Binder.getCallingUid() 14840 + " without permission " 14841 + android.Manifest.permission.DUMP); 14842 return; 14843 } 14844 14845 DumpState dumpState = new DumpState(); 14846 boolean fullPreferred = false; 14847 boolean checkin = false; 14848 14849 String packageName = null; 14850 ArraySet<String> permissionNames = null; 14851 14852 int opti = 0; 14853 while (opti < args.length) { 14854 String opt = args[opti]; 14855 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14856 break; 14857 } 14858 opti++; 14859 14860 if ("-a".equals(opt)) { 14861 // Right now we only know how to print all. 14862 } else if ("-h".equals(opt)) { 14863 pw.println("Package manager dump options:"); 14864 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14865 pw.println(" --checkin: dump for a checkin"); 14866 pw.println(" -f: print details of intent filters"); 14867 pw.println(" -h: print this help"); 14868 pw.println(" cmd may be one of:"); 14869 pw.println(" l[ibraries]: list known shared libraries"); 14870 pw.println(" f[ibraries]: list device features"); 14871 pw.println(" k[eysets]: print known keysets"); 14872 pw.println(" r[esolvers]: dump intent resolvers"); 14873 pw.println(" perm[issions]: dump permissions"); 14874 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14875 pw.println(" pref[erred]: print preferred package settings"); 14876 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14877 pw.println(" prov[iders]: dump content providers"); 14878 pw.println(" p[ackages]: dump installed packages"); 14879 pw.println(" s[hared-users]: dump shared user IDs"); 14880 pw.println(" m[essages]: print collected runtime messages"); 14881 pw.println(" v[erifiers]: print package verifier info"); 14882 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14883 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14884 pw.println(" version: print database version info"); 14885 pw.println(" write: write current settings now"); 14886 pw.println(" installs: details about install sessions"); 14887 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 14888 pw.println(" <package.name>: info about given package"); 14889 return; 14890 } else if ("--checkin".equals(opt)) { 14891 checkin = true; 14892 } else if ("-f".equals(opt)) { 14893 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14894 } else { 14895 pw.println("Unknown argument: " + opt + "; use -h for help"); 14896 } 14897 } 14898 14899 // Is the caller requesting to dump a particular piece of data? 14900 if (opti < args.length) { 14901 String cmd = args[opti]; 14902 opti++; 14903 // Is this a package name? 14904 if ("android".equals(cmd) || cmd.contains(".")) { 14905 packageName = cmd; 14906 // When dumping a single package, we always dump all of its 14907 // filter information since the amount of data will be reasonable. 14908 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14909 } else if ("check-permission".equals(cmd)) { 14910 if (opti >= args.length) { 14911 pw.println("Error: check-permission missing permission argument"); 14912 return; 14913 } 14914 String perm = args[opti]; 14915 opti++; 14916 if (opti >= args.length) { 14917 pw.println("Error: check-permission missing package argument"); 14918 return; 14919 } 14920 String pkg = args[opti]; 14921 opti++; 14922 int user = UserHandle.getUserId(Binder.getCallingUid()); 14923 if (opti < args.length) { 14924 try { 14925 user = Integer.parseInt(args[opti]); 14926 } catch (NumberFormatException e) { 14927 pw.println("Error: check-permission user argument is not a number: " 14928 + args[opti]); 14929 return; 14930 } 14931 } 14932 pw.println(checkPermission(perm, pkg, user)); 14933 return; 14934 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14935 dumpState.setDump(DumpState.DUMP_LIBS); 14936 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14937 dumpState.setDump(DumpState.DUMP_FEATURES); 14938 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14939 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14940 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14941 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14942 } else if ("permission".equals(cmd)) { 14943 if (opti >= args.length) { 14944 pw.println("Error: permission requires permission name"); 14945 return; 14946 } 14947 permissionNames = new ArraySet<>(); 14948 while (opti < args.length) { 14949 permissionNames.add(args[opti]); 14950 opti++; 14951 } 14952 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14953 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14954 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14955 dumpState.setDump(DumpState.DUMP_PREFERRED); 14956 } else if ("preferred-xml".equals(cmd)) { 14957 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14958 if (opti < args.length && "--full".equals(args[opti])) { 14959 fullPreferred = true; 14960 opti++; 14961 } 14962 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14963 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14964 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14965 dumpState.setDump(DumpState.DUMP_PACKAGES); 14966 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14967 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14968 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14969 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14970 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14971 dumpState.setDump(DumpState.DUMP_MESSAGES); 14972 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14973 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14974 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14975 || "intent-filter-verifiers".equals(cmd)) { 14976 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14977 } else if ("version".equals(cmd)) { 14978 dumpState.setDump(DumpState.DUMP_VERSION); 14979 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14980 dumpState.setDump(DumpState.DUMP_KEYSETS); 14981 } else if ("installs".equals(cmd)) { 14982 dumpState.setDump(DumpState.DUMP_INSTALLS); 14983 } else if ("write".equals(cmd)) { 14984 synchronized (mPackages) { 14985 mSettings.writeLPr(); 14986 pw.println("Settings written."); 14987 return; 14988 } 14989 } 14990 } 14991 14992 if (checkin) { 14993 pw.println("vers,1"); 14994 } 14995 14996 // reader 14997 synchronized (mPackages) { 14998 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14999 if (!checkin) { 15000 if (dumpState.onTitlePrinted()) 15001 pw.println(); 15002 pw.println("Database versions:"); 15003 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15004 } 15005 } 15006 15007 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15008 if (!checkin) { 15009 if (dumpState.onTitlePrinted()) 15010 pw.println(); 15011 pw.println("Verifiers:"); 15012 pw.print(" Required: "); 15013 pw.print(mRequiredVerifierPackage); 15014 pw.print(" (uid="); 15015 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15016 pw.println(")"); 15017 } else if (mRequiredVerifierPackage != null) { 15018 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15019 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15020 } 15021 } 15022 15023 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15024 packageName == null) { 15025 if (mIntentFilterVerifierComponent != null) { 15026 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15027 if (!checkin) { 15028 if (dumpState.onTitlePrinted()) 15029 pw.println(); 15030 pw.println("Intent Filter Verifier:"); 15031 pw.print(" Using: "); 15032 pw.print(verifierPackageName); 15033 pw.print(" (uid="); 15034 pw.print(getPackageUid(verifierPackageName, 0)); 15035 pw.println(")"); 15036 } else if (verifierPackageName != null) { 15037 pw.print("ifv,"); pw.print(verifierPackageName); 15038 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15039 } 15040 } else { 15041 pw.println(); 15042 pw.println("No Intent Filter Verifier available!"); 15043 } 15044 } 15045 15046 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15047 boolean printedHeader = false; 15048 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15049 while (it.hasNext()) { 15050 String name = it.next(); 15051 SharedLibraryEntry ent = mSharedLibraries.get(name); 15052 if (!checkin) { 15053 if (!printedHeader) { 15054 if (dumpState.onTitlePrinted()) 15055 pw.println(); 15056 pw.println("Libraries:"); 15057 printedHeader = true; 15058 } 15059 pw.print(" "); 15060 } else { 15061 pw.print("lib,"); 15062 } 15063 pw.print(name); 15064 if (!checkin) { 15065 pw.print(" -> "); 15066 } 15067 if (ent.path != null) { 15068 if (!checkin) { 15069 pw.print("(jar) "); 15070 pw.print(ent.path); 15071 } else { 15072 pw.print(",jar,"); 15073 pw.print(ent.path); 15074 } 15075 } else { 15076 if (!checkin) { 15077 pw.print("(apk) "); 15078 pw.print(ent.apk); 15079 } else { 15080 pw.print(",apk,"); 15081 pw.print(ent.apk); 15082 } 15083 } 15084 pw.println(); 15085 } 15086 } 15087 15088 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15089 if (dumpState.onTitlePrinted()) 15090 pw.println(); 15091 if (!checkin) { 15092 pw.println("Features:"); 15093 } 15094 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15095 while (it.hasNext()) { 15096 String name = it.next(); 15097 if (!checkin) { 15098 pw.print(" "); 15099 } else { 15100 pw.print("feat,"); 15101 } 15102 pw.println(name); 15103 } 15104 } 15105 15106 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15107 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15108 : "Activity Resolver Table:", " ", packageName, 15109 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15110 dumpState.setTitlePrinted(true); 15111 } 15112 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15113 : "Receiver Resolver Table:", " ", packageName, 15114 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15115 dumpState.setTitlePrinted(true); 15116 } 15117 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15118 : "Service Resolver Table:", " ", packageName, 15119 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15120 dumpState.setTitlePrinted(true); 15121 } 15122 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15123 : "Provider Resolver Table:", " ", packageName, 15124 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15125 dumpState.setTitlePrinted(true); 15126 } 15127 } 15128 15129 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15130 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15131 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15132 int user = mSettings.mPreferredActivities.keyAt(i); 15133 if (pir.dump(pw, 15134 dumpState.getTitlePrinted() 15135 ? "\nPreferred Activities User " + user + ":" 15136 : "Preferred Activities User " + user + ":", " ", 15137 packageName, true, false)) { 15138 dumpState.setTitlePrinted(true); 15139 } 15140 } 15141 } 15142 15143 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15144 pw.flush(); 15145 FileOutputStream fout = new FileOutputStream(fd); 15146 BufferedOutputStream str = new BufferedOutputStream(fout); 15147 XmlSerializer serializer = new FastXmlSerializer(); 15148 try { 15149 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15150 serializer.startDocument(null, true); 15151 serializer.setFeature( 15152 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15153 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15154 serializer.endDocument(); 15155 serializer.flush(); 15156 } catch (IllegalArgumentException e) { 15157 pw.println("Failed writing: " + e); 15158 } catch (IllegalStateException e) { 15159 pw.println("Failed writing: " + e); 15160 } catch (IOException e) { 15161 pw.println("Failed writing: " + e); 15162 } 15163 } 15164 15165 if (!checkin 15166 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15167 && packageName == null) { 15168 pw.println(); 15169 int count = mSettings.mPackages.size(); 15170 if (count == 0) { 15171 pw.println("No applications!"); 15172 pw.println(); 15173 } else { 15174 final String prefix = " "; 15175 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15176 if (allPackageSettings.size() == 0) { 15177 pw.println("No domain preferred apps!"); 15178 pw.println(); 15179 } else { 15180 pw.println("App verification status:"); 15181 pw.println(); 15182 count = 0; 15183 for (PackageSetting ps : allPackageSettings) { 15184 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15185 if (ivi == null || ivi.getPackageName() == null) continue; 15186 pw.println(prefix + "Package: " + ivi.getPackageName()); 15187 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15188 pw.println(prefix + "Status: " + ivi.getStatusString()); 15189 pw.println(); 15190 count++; 15191 } 15192 if (count == 0) { 15193 pw.println(prefix + "No app verification established."); 15194 pw.println(); 15195 } 15196 for (int userId : sUserManager.getUserIds()) { 15197 pw.println("App linkages for user " + userId + ":"); 15198 pw.println(); 15199 count = 0; 15200 for (PackageSetting ps : allPackageSettings) { 15201 final long status = ps.getDomainVerificationStatusForUser(userId); 15202 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15203 continue; 15204 } 15205 pw.println(prefix + "Package: " + ps.name); 15206 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15207 String statusStr = IntentFilterVerificationInfo. 15208 getStatusStringFromValue(status); 15209 pw.println(prefix + "Status: " + statusStr); 15210 pw.println(); 15211 count++; 15212 } 15213 if (count == 0) { 15214 pw.println(prefix + "No configured app linkages."); 15215 pw.println(); 15216 } 15217 } 15218 } 15219 } 15220 } 15221 15222 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15223 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15224 if (packageName == null && permissionNames == null) { 15225 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15226 if (iperm == 0) { 15227 if (dumpState.onTitlePrinted()) 15228 pw.println(); 15229 pw.println("AppOp Permissions:"); 15230 } 15231 pw.print(" AppOp Permission "); 15232 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15233 pw.println(":"); 15234 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15235 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15236 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15237 } 15238 } 15239 } 15240 } 15241 15242 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15243 boolean printedSomething = false; 15244 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15245 if (packageName != null && !packageName.equals(p.info.packageName)) { 15246 continue; 15247 } 15248 if (!printedSomething) { 15249 if (dumpState.onTitlePrinted()) 15250 pw.println(); 15251 pw.println("Registered ContentProviders:"); 15252 printedSomething = true; 15253 } 15254 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15255 pw.print(" "); pw.println(p.toString()); 15256 } 15257 printedSomething = false; 15258 for (Map.Entry<String, PackageParser.Provider> entry : 15259 mProvidersByAuthority.entrySet()) { 15260 PackageParser.Provider p = entry.getValue(); 15261 if (packageName != null && !packageName.equals(p.info.packageName)) { 15262 continue; 15263 } 15264 if (!printedSomething) { 15265 if (dumpState.onTitlePrinted()) 15266 pw.println(); 15267 pw.println("ContentProvider Authorities:"); 15268 printedSomething = true; 15269 } 15270 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15271 pw.print(" "); pw.println(p.toString()); 15272 if (p.info != null && p.info.applicationInfo != null) { 15273 final String appInfo = p.info.applicationInfo.toString(); 15274 pw.print(" applicationInfo="); pw.println(appInfo); 15275 } 15276 } 15277 } 15278 15279 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15280 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15281 } 15282 15283 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15284 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15285 } 15286 15287 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15288 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15289 } 15290 15291 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15292 // XXX should handle packageName != null by dumping only install data that 15293 // the given package is involved with. 15294 if (dumpState.onTitlePrinted()) pw.println(); 15295 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15296 } 15297 15298 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15299 if (dumpState.onTitlePrinted()) pw.println(); 15300 mSettings.dumpReadMessagesLPr(pw, dumpState); 15301 15302 pw.println(); 15303 pw.println("Package warning messages:"); 15304 BufferedReader in = null; 15305 String line = null; 15306 try { 15307 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15308 while ((line = in.readLine()) != null) { 15309 if (line.contains("ignored: updated version")) continue; 15310 pw.println(line); 15311 } 15312 } catch (IOException ignored) { 15313 } finally { 15314 IoUtils.closeQuietly(in); 15315 } 15316 } 15317 15318 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15319 BufferedReader in = null; 15320 String line = null; 15321 try { 15322 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15323 while ((line = in.readLine()) != null) { 15324 if (line.contains("ignored: updated version")) continue; 15325 pw.print("msg,"); 15326 pw.println(line); 15327 } 15328 } catch (IOException ignored) { 15329 } finally { 15330 IoUtils.closeQuietly(in); 15331 } 15332 } 15333 } 15334 } 15335 15336 private String dumpDomainString(String packageName) { 15337 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15338 List<IntentFilter> filters = getAllIntentFilters(packageName); 15339 15340 ArraySet<String> result = new ArraySet<>(); 15341 if (iviList.size() > 0) { 15342 for (IntentFilterVerificationInfo ivi : iviList) { 15343 for (String host : ivi.getDomains()) { 15344 result.add(host); 15345 } 15346 } 15347 } 15348 if (filters != null && filters.size() > 0) { 15349 for (IntentFilter filter : filters) { 15350 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15351 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15352 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15353 result.addAll(filter.getHostsList()); 15354 } 15355 } 15356 } 15357 15358 StringBuilder sb = new StringBuilder(result.size() * 16); 15359 for (String domain : result) { 15360 if (sb.length() > 0) sb.append(" "); 15361 sb.append(domain); 15362 } 15363 return sb.toString(); 15364 } 15365 15366 // ------- apps on sdcard specific code ------- 15367 static final boolean DEBUG_SD_INSTALL = false; 15368 15369 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15370 15371 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15372 15373 private boolean mMediaMounted = false; 15374 15375 static String getEncryptKey() { 15376 try { 15377 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15378 SD_ENCRYPTION_KEYSTORE_NAME); 15379 if (sdEncKey == null) { 15380 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15381 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15382 if (sdEncKey == null) { 15383 Slog.e(TAG, "Failed to create encryption keys"); 15384 return null; 15385 } 15386 } 15387 return sdEncKey; 15388 } catch (NoSuchAlgorithmException nsae) { 15389 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15390 return null; 15391 } catch (IOException ioe) { 15392 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15393 return null; 15394 } 15395 } 15396 15397 /* 15398 * Update media status on PackageManager. 15399 */ 15400 @Override 15401 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15402 int callingUid = Binder.getCallingUid(); 15403 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15404 throw new SecurityException("Media status can only be updated by the system"); 15405 } 15406 // reader; this apparently protects mMediaMounted, but should probably 15407 // be a different lock in that case. 15408 synchronized (mPackages) { 15409 Log.i(TAG, "Updating external media status from " 15410 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15411 + (mediaStatus ? "mounted" : "unmounted")); 15412 if (DEBUG_SD_INSTALL) 15413 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15414 + ", mMediaMounted=" + mMediaMounted); 15415 if (mediaStatus == mMediaMounted) { 15416 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15417 : 0, -1); 15418 mHandler.sendMessage(msg); 15419 return; 15420 } 15421 mMediaMounted = mediaStatus; 15422 } 15423 // Queue up an async operation since the package installation may take a 15424 // little while. 15425 mHandler.post(new Runnable() { 15426 public void run() { 15427 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15428 } 15429 }); 15430 } 15431 15432 /** 15433 * Called by MountService when the initial ASECs to scan are available. 15434 * Should block until all the ASEC containers are finished being scanned. 15435 */ 15436 public void scanAvailableAsecs() { 15437 updateExternalMediaStatusInner(true, false, false); 15438 if (mShouldRestoreconData) { 15439 SELinuxMMAC.setRestoreconDone(); 15440 mShouldRestoreconData = false; 15441 } 15442 } 15443 15444 /* 15445 * Collect information of applications on external media, map them against 15446 * existing containers and update information based on current mount status. 15447 * Please note that we always have to report status if reportStatus has been 15448 * set to true especially when unloading packages. 15449 */ 15450 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15451 boolean externalStorage) { 15452 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15453 int[] uidArr = EmptyArray.INT; 15454 15455 final String[] list = PackageHelper.getSecureContainerList(); 15456 if (ArrayUtils.isEmpty(list)) { 15457 Log.i(TAG, "No secure containers found"); 15458 } else { 15459 // Process list of secure containers and categorize them 15460 // as active or stale based on their package internal state. 15461 15462 // reader 15463 synchronized (mPackages) { 15464 for (String cid : list) { 15465 // Leave stages untouched for now; installer service owns them 15466 if (PackageInstallerService.isStageName(cid)) continue; 15467 15468 if (DEBUG_SD_INSTALL) 15469 Log.i(TAG, "Processing container " + cid); 15470 String pkgName = getAsecPackageName(cid); 15471 if (pkgName == null) { 15472 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15473 continue; 15474 } 15475 if (DEBUG_SD_INSTALL) 15476 Log.i(TAG, "Looking for pkg : " + pkgName); 15477 15478 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15479 if (ps == null) { 15480 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15481 continue; 15482 } 15483 15484 /* 15485 * Skip packages that are not external if we're unmounting 15486 * external storage. 15487 */ 15488 if (externalStorage && !isMounted && !isExternal(ps)) { 15489 continue; 15490 } 15491 15492 final AsecInstallArgs args = new AsecInstallArgs(cid, 15493 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15494 // The package status is changed only if the code path 15495 // matches between settings and the container id. 15496 if (ps.codePathString != null 15497 && ps.codePathString.startsWith(args.getCodePath())) { 15498 if (DEBUG_SD_INSTALL) { 15499 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15500 + " at code path: " + ps.codePathString); 15501 } 15502 15503 // We do have a valid package installed on sdcard 15504 processCids.put(args, ps.codePathString); 15505 final int uid = ps.appId; 15506 if (uid != -1) { 15507 uidArr = ArrayUtils.appendInt(uidArr, uid); 15508 } 15509 } else { 15510 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15511 + ps.codePathString); 15512 } 15513 } 15514 } 15515 15516 Arrays.sort(uidArr); 15517 } 15518 15519 // Process packages with valid entries. 15520 if (isMounted) { 15521 if (DEBUG_SD_INSTALL) 15522 Log.i(TAG, "Loading packages"); 15523 loadMediaPackages(processCids, uidArr, externalStorage); 15524 startCleaningPackages(); 15525 mInstallerService.onSecureContainersAvailable(); 15526 } else { 15527 if (DEBUG_SD_INSTALL) 15528 Log.i(TAG, "Unloading packages"); 15529 unloadMediaPackages(processCids, uidArr, reportStatus); 15530 } 15531 } 15532 15533 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15534 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15535 final int size = infos.size(); 15536 final String[] packageNames = new String[size]; 15537 final int[] packageUids = new int[size]; 15538 for (int i = 0; i < size; i++) { 15539 final ApplicationInfo info = infos.get(i); 15540 packageNames[i] = info.packageName; 15541 packageUids[i] = info.uid; 15542 } 15543 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15544 finishedReceiver); 15545 } 15546 15547 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15548 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15549 sendResourcesChangedBroadcast(mediaStatus, replacing, 15550 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15551 } 15552 15553 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15554 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15555 int size = pkgList.length; 15556 if (size > 0) { 15557 // Send broadcasts here 15558 Bundle extras = new Bundle(); 15559 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15560 if (uidArr != null) { 15561 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15562 } 15563 if (replacing) { 15564 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15565 } 15566 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15567 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15568 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15569 } 15570 } 15571 15572 /* 15573 * Look at potentially valid container ids from processCids If package 15574 * information doesn't match the one on record or package scanning fails, 15575 * the cid is added to list of removeCids. We currently don't delete stale 15576 * containers. 15577 */ 15578 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 15579 boolean externalStorage) { 15580 ArrayList<String> pkgList = new ArrayList<String>(); 15581 Set<AsecInstallArgs> keys = processCids.keySet(); 15582 15583 for (AsecInstallArgs args : keys) { 15584 String codePath = processCids.get(args); 15585 if (DEBUG_SD_INSTALL) 15586 Log.i(TAG, "Loading container : " + args.cid); 15587 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15588 try { 15589 // Make sure there are no container errors first. 15590 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15591 Slog.e(TAG, "Failed to mount cid : " + args.cid 15592 + " when installing from sdcard"); 15593 continue; 15594 } 15595 // Check code path here. 15596 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15597 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15598 + " does not match one in settings " + codePath); 15599 continue; 15600 } 15601 // Parse package 15602 int parseFlags = mDefParseFlags; 15603 if (args.isExternalAsec()) { 15604 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15605 } 15606 if (args.isFwdLocked()) { 15607 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15608 } 15609 15610 synchronized (mInstallLock) { 15611 PackageParser.Package pkg = null; 15612 try { 15613 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15614 } catch (PackageManagerException e) { 15615 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15616 } 15617 // Scan the package 15618 if (pkg != null) { 15619 /* 15620 * TODO why is the lock being held? doPostInstall is 15621 * called in other places without the lock. This needs 15622 * to be straightened out. 15623 */ 15624 // writer 15625 synchronized (mPackages) { 15626 retCode = PackageManager.INSTALL_SUCCEEDED; 15627 pkgList.add(pkg.packageName); 15628 // Post process args 15629 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15630 pkg.applicationInfo.uid); 15631 } 15632 } else { 15633 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15634 } 15635 } 15636 15637 } finally { 15638 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15639 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15640 } 15641 } 15642 } 15643 // writer 15644 synchronized (mPackages) { 15645 // If the platform SDK has changed since the last time we booted, 15646 // we need to re-grant app permission to catch any new ones that 15647 // appear. This is really a hack, and means that apps can in some 15648 // cases get permissions that the user didn't initially explicitly 15649 // allow... it would be nice to have some better way to handle 15650 // this situation. 15651 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 15652 : mSettings.getInternalVersion(); 15653 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 15654 : StorageManager.UUID_PRIVATE_INTERNAL; 15655 15656 int updateFlags = UPDATE_PERMISSIONS_ALL; 15657 if (ver.sdkVersion != mSdkVersion) { 15658 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15659 + mSdkVersion + "; regranting permissions for external"); 15660 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15661 } 15662 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 15663 15664 // Yay, everything is now upgraded 15665 ver.forceCurrent(); 15666 15667 // can downgrade to reader 15668 // Persist settings 15669 mSettings.writeLPr(); 15670 } 15671 // Send a broadcast to let everyone know we are done processing 15672 if (pkgList.size() > 0) { 15673 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15674 } 15675 } 15676 15677 /* 15678 * Utility method to unload a list of specified containers 15679 */ 15680 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15681 // Just unmount all valid containers. 15682 for (AsecInstallArgs arg : cidArgs) { 15683 synchronized (mInstallLock) { 15684 arg.doPostDeleteLI(false); 15685 } 15686 } 15687 } 15688 15689 /* 15690 * Unload packages mounted on external media. This involves deleting package 15691 * data from internal structures, sending broadcasts about diabled packages, 15692 * gc'ing to free up references, unmounting all secure containers 15693 * corresponding to packages on external media, and posting a 15694 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15695 * that we always have to post this message if status has been requested no 15696 * matter what. 15697 */ 15698 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15699 final boolean reportStatus) { 15700 if (DEBUG_SD_INSTALL) 15701 Log.i(TAG, "unloading media packages"); 15702 ArrayList<String> pkgList = new ArrayList<String>(); 15703 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15704 final Set<AsecInstallArgs> keys = processCids.keySet(); 15705 for (AsecInstallArgs args : keys) { 15706 String pkgName = args.getPackageName(); 15707 if (DEBUG_SD_INSTALL) 15708 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15709 // Delete package internally 15710 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15711 synchronized (mInstallLock) { 15712 boolean res = deletePackageLI(pkgName, null, false, null, null, 15713 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15714 if (res) { 15715 pkgList.add(pkgName); 15716 } else { 15717 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15718 failedList.add(args); 15719 } 15720 } 15721 } 15722 15723 // reader 15724 synchronized (mPackages) { 15725 // We didn't update the settings after removing each package; 15726 // write them now for all packages. 15727 mSettings.writeLPr(); 15728 } 15729 15730 // We have to absolutely send UPDATED_MEDIA_STATUS only 15731 // after confirming that all the receivers processed the ordered 15732 // broadcast when packages get disabled, force a gc to clean things up. 15733 // and unload all the containers. 15734 if (pkgList.size() > 0) { 15735 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15736 new IIntentReceiver.Stub() { 15737 public void performReceive(Intent intent, int resultCode, String data, 15738 Bundle extras, boolean ordered, boolean sticky, 15739 int sendingUser) throws RemoteException { 15740 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15741 reportStatus ? 1 : 0, 1, keys); 15742 mHandler.sendMessage(msg); 15743 } 15744 }); 15745 } else { 15746 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15747 keys); 15748 mHandler.sendMessage(msg); 15749 } 15750 } 15751 15752 private void loadPrivatePackages(final VolumeInfo vol) { 15753 mHandler.post(new Runnable() { 15754 @Override 15755 public void run() { 15756 loadPrivatePackagesInner(vol); 15757 } 15758 }); 15759 } 15760 15761 private void loadPrivatePackagesInner(VolumeInfo vol) { 15762 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15763 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15764 15765 final VersionInfo ver; 15766 final List<PackageSetting> packages; 15767 synchronized (mPackages) { 15768 ver = mSettings.findOrCreateVersion(vol.fsUuid); 15769 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15770 } 15771 15772 for (PackageSetting ps : packages) { 15773 synchronized (mInstallLock) { 15774 final PackageParser.Package pkg; 15775 try { 15776 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15777 loaded.add(pkg.applicationInfo); 15778 } catch (PackageManagerException e) { 15779 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15780 } 15781 15782 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15783 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15784 } 15785 } 15786 } 15787 15788 synchronized (mPackages) { 15789 int updateFlags = UPDATE_PERMISSIONS_ALL; 15790 if (ver.sdkVersion != mSdkVersion) { 15791 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15792 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15793 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15794 } 15795 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 15796 15797 // Yay, everything is now upgraded 15798 ver.forceCurrent(); 15799 15800 mSettings.writeLPr(); 15801 } 15802 15803 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15804 sendResourcesChangedBroadcast(true, false, loaded, null); 15805 } 15806 15807 private void unloadPrivatePackages(final VolumeInfo vol) { 15808 mHandler.post(new Runnable() { 15809 @Override 15810 public void run() { 15811 unloadPrivatePackagesInner(vol); 15812 } 15813 }); 15814 } 15815 15816 private void unloadPrivatePackagesInner(VolumeInfo vol) { 15817 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15818 synchronized (mInstallLock) { 15819 synchronized (mPackages) { 15820 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15821 for (PackageSetting ps : packages) { 15822 if (ps.pkg == null) continue; 15823 15824 final ApplicationInfo info = ps.pkg.applicationInfo; 15825 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15826 if (deletePackageLI(ps.name, null, false, null, null, 15827 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15828 unloaded.add(info); 15829 } else { 15830 Slog.w(TAG, "Failed to unload " + ps.codePath); 15831 } 15832 } 15833 15834 mSettings.writeLPr(); 15835 } 15836 } 15837 15838 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15839 sendResourcesChangedBroadcast(false, false, unloaded, null); 15840 } 15841 15842 /** 15843 * Examine all users present on given mounted volume, and destroy data 15844 * belonging to users that are no longer valid, or whose user ID has been 15845 * recycled. 15846 */ 15847 private void reconcileUsers(String volumeUuid) { 15848 final File[] files = FileUtils 15849 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15850 for (File file : files) { 15851 if (!file.isDirectory()) continue; 15852 15853 final int userId; 15854 final UserInfo info; 15855 try { 15856 userId = Integer.parseInt(file.getName()); 15857 info = sUserManager.getUserInfo(userId); 15858 } catch (NumberFormatException e) { 15859 Slog.w(TAG, "Invalid user directory " + file); 15860 continue; 15861 } 15862 15863 boolean destroyUser = false; 15864 if (info == null) { 15865 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15866 + " because no matching user was found"); 15867 destroyUser = true; 15868 } else { 15869 try { 15870 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15871 } catch (IOException e) { 15872 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15873 + " because we failed to enforce serial number: " + e); 15874 destroyUser = true; 15875 } 15876 } 15877 15878 if (destroyUser) { 15879 synchronized (mInstallLock) { 15880 mInstaller.removeUserDataDirs(volumeUuid, userId); 15881 } 15882 } 15883 } 15884 15885 final UserManager um = mContext.getSystemService(UserManager.class); 15886 for (UserInfo user : um.getUsers()) { 15887 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15888 if (userDir.exists()) continue; 15889 15890 try { 15891 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15892 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15893 } catch (IOException e) { 15894 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15895 } 15896 } 15897 } 15898 15899 /** 15900 * Examine all apps present on given mounted volume, and destroy apps that 15901 * aren't expected, either due to uninstallation or reinstallation on 15902 * another volume. 15903 */ 15904 private void reconcileApps(String volumeUuid) { 15905 final File[] files = FileUtils 15906 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15907 for (File file : files) { 15908 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15909 && !PackageInstallerService.isStageName(file.getName()); 15910 if (!isPackage) { 15911 // Ignore entries which are not packages 15912 continue; 15913 } 15914 15915 boolean destroyApp = false; 15916 String packageName = null; 15917 try { 15918 final PackageLite pkg = PackageParser.parsePackageLite(file, 15919 PackageParser.PARSE_MUST_BE_APK); 15920 packageName = pkg.packageName; 15921 15922 synchronized (mPackages) { 15923 final PackageSetting ps = mSettings.mPackages.get(packageName); 15924 if (ps == null) { 15925 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15926 + volumeUuid + " because we found no install record"); 15927 destroyApp = true; 15928 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15929 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15930 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15931 destroyApp = true; 15932 } 15933 } 15934 15935 } catch (PackageParserException e) { 15936 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15937 destroyApp = true; 15938 } 15939 15940 if (destroyApp) { 15941 synchronized (mInstallLock) { 15942 if (packageName != null) { 15943 removeDataDirsLI(volumeUuid, packageName); 15944 } 15945 if (file.isDirectory()) { 15946 mInstaller.rmPackageDir(file.getAbsolutePath()); 15947 } else { 15948 file.delete(); 15949 } 15950 } 15951 } 15952 } 15953 } 15954 15955 private void unfreezePackage(String packageName) { 15956 synchronized (mPackages) { 15957 final PackageSetting ps = mSettings.mPackages.get(packageName); 15958 if (ps != null) { 15959 ps.frozen = false; 15960 } 15961 } 15962 } 15963 15964 @Override 15965 public int movePackage(final String packageName, final String volumeUuid) { 15966 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15967 15968 final int moveId = mNextMoveId.getAndIncrement(); 15969 try { 15970 movePackageInternal(packageName, volumeUuid, moveId); 15971 } catch (PackageManagerException e) { 15972 Slog.w(TAG, "Failed to move " + packageName, e); 15973 mMoveCallbacks.notifyStatusChanged(moveId, 15974 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15975 } 15976 return moveId; 15977 } 15978 15979 private void movePackageInternal(final String packageName, final String volumeUuid, 15980 final int moveId) throws PackageManagerException { 15981 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15982 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15983 final PackageManager pm = mContext.getPackageManager(); 15984 15985 final boolean currentAsec; 15986 final String currentVolumeUuid; 15987 final File codeFile; 15988 final String installerPackageName; 15989 final String packageAbiOverride; 15990 final int appId; 15991 final String seinfo; 15992 final String label; 15993 15994 // reader 15995 synchronized (mPackages) { 15996 final PackageParser.Package pkg = mPackages.get(packageName); 15997 final PackageSetting ps = mSettings.mPackages.get(packageName); 15998 if (pkg == null || ps == null) { 15999 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16000 } 16001 16002 if (pkg.applicationInfo.isSystemApp()) { 16003 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16004 "Cannot move system application"); 16005 } 16006 16007 if (pkg.applicationInfo.isExternalAsec()) { 16008 currentAsec = true; 16009 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16010 } else if (pkg.applicationInfo.isForwardLocked()) { 16011 currentAsec = true; 16012 currentVolumeUuid = "forward_locked"; 16013 } else { 16014 currentAsec = false; 16015 currentVolumeUuid = ps.volumeUuid; 16016 16017 final File probe = new File(pkg.codePath); 16018 final File probeOat = new File(probe, "oat"); 16019 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16020 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16021 "Move only supported for modern cluster style installs"); 16022 } 16023 } 16024 16025 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16026 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16027 "Package already moved to " + volumeUuid); 16028 } 16029 16030 if (ps.frozen) { 16031 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16032 "Failed to move already frozen package"); 16033 } 16034 ps.frozen = true; 16035 16036 codeFile = new File(pkg.codePath); 16037 installerPackageName = ps.installerPackageName; 16038 packageAbiOverride = ps.cpuAbiOverrideString; 16039 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16040 seinfo = pkg.applicationInfo.seinfo; 16041 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16042 } 16043 16044 // Now that we're guarded by frozen state, kill app during move 16045 final long token = Binder.clearCallingIdentity(); 16046 try { 16047 killApplication(packageName, appId, "move pkg"); 16048 } finally { 16049 Binder.restoreCallingIdentity(token); 16050 } 16051 16052 final Bundle extras = new Bundle(); 16053 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16054 extras.putString(Intent.EXTRA_TITLE, label); 16055 mMoveCallbacks.notifyCreated(moveId, extras); 16056 16057 int installFlags; 16058 final boolean moveCompleteApp; 16059 final File measurePath; 16060 16061 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16062 installFlags = INSTALL_INTERNAL; 16063 moveCompleteApp = !currentAsec; 16064 measurePath = Environment.getDataAppDirectory(volumeUuid); 16065 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16066 installFlags = INSTALL_EXTERNAL; 16067 moveCompleteApp = false; 16068 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16069 } else { 16070 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16071 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16072 || !volume.isMountedWritable()) { 16073 unfreezePackage(packageName); 16074 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16075 "Move location not mounted private volume"); 16076 } 16077 16078 Preconditions.checkState(!currentAsec); 16079 16080 installFlags = INSTALL_INTERNAL; 16081 moveCompleteApp = true; 16082 measurePath = Environment.getDataAppDirectory(volumeUuid); 16083 } 16084 16085 final PackageStats stats = new PackageStats(null, -1); 16086 synchronized (mInstaller) { 16087 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16088 unfreezePackage(packageName); 16089 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16090 "Failed to measure package size"); 16091 } 16092 } 16093 16094 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16095 + stats.dataSize); 16096 16097 final long startFreeBytes = measurePath.getFreeSpace(); 16098 final long sizeBytes; 16099 if (moveCompleteApp) { 16100 sizeBytes = stats.codeSize + stats.dataSize; 16101 } else { 16102 sizeBytes = stats.codeSize; 16103 } 16104 16105 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16106 unfreezePackage(packageName); 16107 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16108 "Not enough free space to move"); 16109 } 16110 16111 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16112 16113 final CountDownLatch installedLatch = new CountDownLatch(1); 16114 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16115 @Override 16116 public void onUserActionRequired(Intent intent) throws RemoteException { 16117 throw new IllegalStateException(); 16118 } 16119 16120 @Override 16121 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16122 Bundle extras) throws RemoteException { 16123 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16124 + PackageManager.installStatusToString(returnCode, msg)); 16125 16126 installedLatch.countDown(); 16127 16128 // Regardless of success or failure of the move operation, 16129 // always unfreeze the package 16130 unfreezePackage(packageName); 16131 16132 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16133 switch (status) { 16134 case PackageInstaller.STATUS_SUCCESS: 16135 mMoveCallbacks.notifyStatusChanged(moveId, 16136 PackageManager.MOVE_SUCCEEDED); 16137 break; 16138 case PackageInstaller.STATUS_FAILURE_STORAGE: 16139 mMoveCallbacks.notifyStatusChanged(moveId, 16140 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16141 break; 16142 default: 16143 mMoveCallbacks.notifyStatusChanged(moveId, 16144 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16145 break; 16146 } 16147 } 16148 }; 16149 16150 final MoveInfo move; 16151 if (moveCompleteApp) { 16152 // Kick off a thread to report progress estimates 16153 new Thread() { 16154 @Override 16155 public void run() { 16156 while (true) { 16157 try { 16158 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16159 break; 16160 } 16161 } catch (InterruptedException ignored) { 16162 } 16163 16164 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16165 final int progress = 10 + (int) MathUtils.constrain( 16166 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16167 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16168 } 16169 } 16170 }.start(); 16171 16172 final String dataAppName = codeFile.getName(); 16173 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16174 dataAppName, appId, seinfo); 16175 } else { 16176 move = null; 16177 } 16178 16179 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16180 16181 final Message msg = mHandler.obtainMessage(INIT_COPY); 16182 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16183 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 16184 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16185 mHandler.sendMessage(msg); 16186 } 16187 16188 @Override 16189 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16190 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16191 16192 final int realMoveId = mNextMoveId.getAndIncrement(); 16193 final Bundle extras = new Bundle(); 16194 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16195 mMoveCallbacks.notifyCreated(realMoveId, extras); 16196 16197 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16198 @Override 16199 public void onCreated(int moveId, Bundle extras) { 16200 // Ignored 16201 } 16202 16203 @Override 16204 public void onStatusChanged(int moveId, int status, long estMillis) { 16205 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16206 } 16207 }; 16208 16209 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16210 storage.setPrimaryStorageUuid(volumeUuid, callback); 16211 return realMoveId; 16212 } 16213 16214 @Override 16215 public int getMoveStatus(int moveId) { 16216 mContext.enforceCallingOrSelfPermission( 16217 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16218 return mMoveCallbacks.mLastStatus.get(moveId); 16219 } 16220 16221 @Override 16222 public void registerMoveCallback(IPackageMoveObserver callback) { 16223 mContext.enforceCallingOrSelfPermission( 16224 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16225 mMoveCallbacks.register(callback); 16226 } 16227 16228 @Override 16229 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16230 mContext.enforceCallingOrSelfPermission( 16231 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16232 mMoveCallbacks.unregister(callback); 16233 } 16234 16235 @Override 16236 public boolean setInstallLocation(int loc) { 16237 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16238 null); 16239 if (getInstallLocation() == loc) { 16240 return true; 16241 } 16242 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16243 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16244 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16245 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16246 return true; 16247 } 16248 return false; 16249 } 16250 16251 @Override 16252 public int getInstallLocation() { 16253 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16254 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16255 PackageHelper.APP_INSTALL_AUTO); 16256 } 16257 16258 /** Called by UserManagerService */ 16259 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16260 mDirtyUsers.remove(userHandle); 16261 mSettings.removeUserLPw(userHandle); 16262 mPendingBroadcasts.remove(userHandle); 16263 if (mInstaller != null) { 16264 // Technically, we shouldn't be doing this with the package lock 16265 // held. However, this is very rare, and there is already so much 16266 // other disk I/O going on, that we'll let it slide for now. 16267 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16268 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16269 final String volumeUuid = vol.getFsUuid(); 16270 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16271 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16272 } 16273 } 16274 mUserNeedsBadging.delete(userHandle); 16275 removeUnusedPackagesLILPw(userManager, userHandle); 16276 } 16277 16278 /** 16279 * We're removing userHandle and would like to remove any downloaded packages 16280 * that are no longer in use by any other user. 16281 * @param userHandle the user being removed 16282 */ 16283 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16284 final boolean DEBUG_CLEAN_APKS = false; 16285 int [] users = userManager.getUserIdsLPr(); 16286 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16287 while (psit.hasNext()) { 16288 PackageSetting ps = psit.next(); 16289 if (ps.pkg == null) { 16290 continue; 16291 } 16292 final String packageName = ps.pkg.packageName; 16293 // Skip over if system app 16294 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16295 continue; 16296 } 16297 if (DEBUG_CLEAN_APKS) { 16298 Slog.i(TAG, "Checking package " + packageName); 16299 } 16300 boolean keep = false; 16301 for (int i = 0; i < users.length; i++) { 16302 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16303 keep = true; 16304 if (DEBUG_CLEAN_APKS) { 16305 Slog.i(TAG, " Keeping package " + packageName + " for user " 16306 + users[i]); 16307 } 16308 break; 16309 } 16310 } 16311 if (!keep) { 16312 if (DEBUG_CLEAN_APKS) { 16313 Slog.i(TAG, " Removing package " + packageName); 16314 } 16315 mHandler.post(new Runnable() { 16316 public void run() { 16317 deletePackageX(packageName, userHandle, 0); 16318 } //end run 16319 }); 16320 } 16321 } 16322 } 16323 16324 /** Called by UserManagerService */ 16325 void createNewUserLILPw(int userHandle) { 16326 if (mInstaller != null) { 16327 mInstaller.createUserConfig(userHandle); 16328 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16329 applyFactoryDefaultBrowserLPw(userHandle); 16330 primeDomainVerificationsLPw(userHandle); 16331 } 16332 } 16333 16334 void newUserCreated(final int userHandle) { 16335 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16336 } 16337 16338 @Override 16339 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16340 mContext.enforceCallingOrSelfPermission( 16341 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16342 "Only package verification agents can read the verifier device identity"); 16343 16344 synchronized (mPackages) { 16345 return mSettings.getVerifierDeviceIdentityLPw(); 16346 } 16347 } 16348 16349 @Override 16350 public void setPermissionEnforced(String permission, boolean enforced) { 16351 // TODO: Now that we no longer change GID for storage, this should to away. 16352 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16353 "setPermissionEnforced"); 16354 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16355 synchronized (mPackages) { 16356 if (mSettings.mReadExternalStorageEnforced == null 16357 || mSettings.mReadExternalStorageEnforced != enforced) { 16358 mSettings.mReadExternalStorageEnforced = enforced; 16359 mSettings.writeLPr(); 16360 } 16361 } 16362 // kill any non-foreground processes so we restart them and 16363 // grant/revoke the GID. 16364 final IActivityManager am = ActivityManagerNative.getDefault(); 16365 if (am != null) { 16366 final long token = Binder.clearCallingIdentity(); 16367 try { 16368 am.killProcessesBelowForeground("setPermissionEnforcement"); 16369 } catch (RemoteException e) { 16370 } finally { 16371 Binder.restoreCallingIdentity(token); 16372 } 16373 } 16374 } else { 16375 throw new IllegalArgumentException("No selective enforcement for " + permission); 16376 } 16377 } 16378 16379 @Override 16380 @Deprecated 16381 public boolean isPermissionEnforced(String permission) { 16382 return true; 16383 } 16384 16385 @Override 16386 public boolean isStorageLow() { 16387 final long token = Binder.clearCallingIdentity(); 16388 try { 16389 final DeviceStorageMonitorInternal 16390 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16391 if (dsm != null) { 16392 return dsm.isMemoryLow(); 16393 } else { 16394 return false; 16395 } 16396 } finally { 16397 Binder.restoreCallingIdentity(token); 16398 } 16399 } 16400 16401 @Override 16402 public IPackageInstaller getPackageInstaller() { 16403 return mInstallerService; 16404 } 16405 16406 private boolean userNeedsBadging(int userId) { 16407 int index = mUserNeedsBadging.indexOfKey(userId); 16408 if (index < 0) { 16409 final UserInfo userInfo; 16410 final long token = Binder.clearCallingIdentity(); 16411 try { 16412 userInfo = sUserManager.getUserInfo(userId); 16413 } finally { 16414 Binder.restoreCallingIdentity(token); 16415 } 16416 final boolean b; 16417 if (userInfo != null && userInfo.isManagedProfile()) { 16418 b = true; 16419 } else { 16420 b = false; 16421 } 16422 mUserNeedsBadging.put(userId, b); 16423 return b; 16424 } 16425 return mUserNeedsBadging.valueAt(index); 16426 } 16427 16428 @Override 16429 public KeySet getKeySetByAlias(String packageName, String alias) { 16430 if (packageName == null || alias == null) { 16431 return null; 16432 } 16433 synchronized(mPackages) { 16434 final PackageParser.Package pkg = mPackages.get(packageName); 16435 if (pkg == null) { 16436 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16437 throw new IllegalArgumentException("Unknown package: " + packageName); 16438 } 16439 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16440 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16441 } 16442 } 16443 16444 @Override 16445 public KeySet getSigningKeySet(String packageName) { 16446 if (packageName == null) { 16447 return null; 16448 } 16449 synchronized(mPackages) { 16450 final PackageParser.Package pkg = mPackages.get(packageName); 16451 if (pkg == null) { 16452 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16453 throw new IllegalArgumentException("Unknown package: " + packageName); 16454 } 16455 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16456 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16457 throw new SecurityException("May not access signing KeySet of other apps."); 16458 } 16459 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16460 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16461 } 16462 } 16463 16464 @Override 16465 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16466 if (packageName == null || ks == null) { 16467 return false; 16468 } 16469 synchronized(mPackages) { 16470 final PackageParser.Package pkg = mPackages.get(packageName); 16471 if (pkg == null) { 16472 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16473 throw new IllegalArgumentException("Unknown package: " + packageName); 16474 } 16475 IBinder ksh = ks.getToken(); 16476 if (ksh instanceof KeySetHandle) { 16477 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16478 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16479 } 16480 return false; 16481 } 16482 } 16483 16484 @Override 16485 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16486 if (packageName == null || ks == null) { 16487 return false; 16488 } 16489 synchronized(mPackages) { 16490 final PackageParser.Package pkg = mPackages.get(packageName); 16491 if (pkg == null) { 16492 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16493 throw new IllegalArgumentException("Unknown package: " + packageName); 16494 } 16495 IBinder ksh = ks.getToken(); 16496 if (ksh instanceof KeySetHandle) { 16497 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16498 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16499 } 16500 return false; 16501 } 16502 } 16503 16504 public void getUsageStatsIfNoPackageUsageInfo() { 16505 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16506 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16507 if (usm == null) { 16508 throw new IllegalStateException("UsageStatsManager must be initialized"); 16509 } 16510 long now = System.currentTimeMillis(); 16511 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16512 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16513 String packageName = entry.getKey(); 16514 PackageParser.Package pkg = mPackages.get(packageName); 16515 if (pkg == null) { 16516 continue; 16517 } 16518 UsageStats usage = entry.getValue(); 16519 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16520 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16521 } 16522 } 16523 } 16524 16525 /** 16526 * Check and throw if the given before/after packages would be considered a 16527 * downgrade. 16528 */ 16529 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16530 throws PackageManagerException { 16531 if (after.versionCode < before.mVersionCode) { 16532 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16533 "Update version code " + after.versionCode + " is older than current " 16534 + before.mVersionCode); 16535 } else if (after.versionCode == before.mVersionCode) { 16536 if (after.baseRevisionCode < before.baseRevisionCode) { 16537 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16538 "Update base revision code " + after.baseRevisionCode 16539 + " is older than current " + before.baseRevisionCode); 16540 } 16541 16542 if (!ArrayUtils.isEmpty(after.splitNames)) { 16543 for (int i = 0; i < after.splitNames.length; i++) { 16544 final String splitName = after.splitNames[i]; 16545 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16546 if (j != -1) { 16547 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16548 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16549 "Update split " + splitName + " revision code " 16550 + after.splitRevisionCodes[i] + " is older than current " 16551 + before.splitRevisionCodes[j]); 16552 } 16553 } 16554 } 16555 } 16556 } 16557 } 16558 16559 private static class MoveCallbacks extends Handler { 16560 private static final int MSG_CREATED = 1; 16561 private static final int MSG_STATUS_CHANGED = 2; 16562 16563 private final RemoteCallbackList<IPackageMoveObserver> 16564 mCallbacks = new RemoteCallbackList<>(); 16565 16566 private final SparseIntArray mLastStatus = new SparseIntArray(); 16567 16568 public MoveCallbacks(Looper looper) { 16569 super(looper); 16570 } 16571 16572 public void register(IPackageMoveObserver callback) { 16573 mCallbacks.register(callback); 16574 } 16575 16576 public void unregister(IPackageMoveObserver callback) { 16577 mCallbacks.unregister(callback); 16578 } 16579 16580 @Override 16581 public void handleMessage(Message msg) { 16582 final SomeArgs args = (SomeArgs) msg.obj; 16583 final int n = mCallbacks.beginBroadcast(); 16584 for (int i = 0; i < n; i++) { 16585 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16586 try { 16587 invokeCallback(callback, msg.what, args); 16588 } catch (RemoteException ignored) { 16589 } 16590 } 16591 mCallbacks.finishBroadcast(); 16592 args.recycle(); 16593 } 16594 16595 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16596 throws RemoteException { 16597 switch (what) { 16598 case MSG_CREATED: { 16599 callback.onCreated(args.argi1, (Bundle) args.arg2); 16600 break; 16601 } 16602 case MSG_STATUS_CHANGED: { 16603 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16604 break; 16605 } 16606 } 16607 } 16608 16609 private void notifyCreated(int moveId, Bundle extras) { 16610 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16611 16612 final SomeArgs args = SomeArgs.obtain(); 16613 args.argi1 = moveId; 16614 args.arg2 = extras; 16615 obtainMessage(MSG_CREATED, args).sendToTarget(); 16616 } 16617 16618 private void notifyStatusChanged(int moveId, int status) { 16619 notifyStatusChanged(moveId, status, -1); 16620 } 16621 16622 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16623 Slog.v(TAG, "Move " + moveId + " status " + status); 16624 16625 final SomeArgs args = SomeArgs.obtain(); 16626 args.argi1 = moveId; 16627 args.argi2 = status; 16628 args.arg3 = estMillis; 16629 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16630 16631 synchronized (mLastStatus) { 16632 mLastStatus.put(moveId, status); 16633 } 16634 } 16635 } 16636 16637 private final class OnPermissionChangeListeners extends Handler { 16638 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16639 16640 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16641 new RemoteCallbackList<>(); 16642 16643 public OnPermissionChangeListeners(Looper looper) { 16644 super(looper); 16645 } 16646 16647 @Override 16648 public void handleMessage(Message msg) { 16649 switch (msg.what) { 16650 case MSG_ON_PERMISSIONS_CHANGED: { 16651 final int uid = msg.arg1; 16652 handleOnPermissionsChanged(uid); 16653 } break; 16654 } 16655 } 16656 16657 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16658 mPermissionListeners.register(listener); 16659 16660 } 16661 16662 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16663 mPermissionListeners.unregister(listener); 16664 } 16665 16666 public void onPermissionsChanged(int uid) { 16667 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16668 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16669 } 16670 } 16671 16672 private void handleOnPermissionsChanged(int uid) { 16673 final int count = mPermissionListeners.beginBroadcast(); 16674 try { 16675 for (int i = 0; i < count; i++) { 16676 IOnPermissionsChangeListener callback = mPermissionListeners 16677 .getBroadcastItem(i); 16678 try { 16679 callback.onPermissionsChanged(uid); 16680 } catch (RemoteException e) { 16681 Log.e(TAG, "Permission listener is dead", e); 16682 } 16683 } 16684 } finally { 16685 mPermissionListeners.finishBroadcast(); 16686 } 16687 } 16688 } 16689 16690 private class PackageManagerInternalImpl extends PackageManagerInternal { 16691 @Override 16692 public void setLocationPackagesProvider(PackagesProvider provider) { 16693 synchronized (mPackages) { 16694 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16695 } 16696 } 16697 16698 @Override 16699 public void setImePackagesProvider(PackagesProvider provider) { 16700 synchronized (mPackages) { 16701 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16702 } 16703 } 16704 16705 @Override 16706 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16707 synchronized (mPackages) { 16708 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16709 } 16710 } 16711 16712 @Override 16713 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16714 synchronized (mPackages) { 16715 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16716 } 16717 } 16718 16719 @Override 16720 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16721 synchronized (mPackages) { 16722 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16723 } 16724 } 16725 16726 @Override 16727 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16728 synchronized (mPackages) { 16729 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16730 } 16731 } 16732 16733 @Override 16734 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16735 synchronized (mPackages) { 16736 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16737 } 16738 } 16739 16740 @Override 16741 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16742 synchronized (mPackages) { 16743 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16744 packageName, userId); 16745 } 16746 } 16747 16748 @Override 16749 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16750 synchronized (mPackages) { 16751 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16752 packageName, userId); 16753 } 16754 } 16755 @Override 16756 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16757 synchronized (mPackages) { 16758 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16759 packageName, userId); 16760 } 16761 } 16762 } 16763 16764 @Override 16765 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16766 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16767 synchronized (mPackages) { 16768 final long identity = Binder.clearCallingIdentity(); 16769 try { 16770 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16771 packageNames, userId); 16772 } finally { 16773 Binder.restoreCallingIdentity(identity); 16774 } 16775 } 16776 } 16777 16778 private static void enforceSystemOrPhoneCaller(String tag) { 16779 int callingUid = Binder.getCallingUid(); 16780 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16781 throw new SecurityException( 16782 "Cannot call " + tag + " from UID " + callingUid); 16783 } 16784 } 16785} 16786