PackageManagerService.java revision f2e81e904a57660eabcb4c0c24bf8e6e6b1f6467
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 && (getPermissionFlags(permission, pkg.packageName, userId) 1724 & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) == 0) { 1725 grantRuntimePermission(pkg.packageName, permission, userId); 1726 } 1727 } 1728 } 1729 } 1730 1731 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1732 Bundle extras = null; 1733 switch (res.returnCode) { 1734 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1735 extras = new Bundle(); 1736 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1737 res.origPermission); 1738 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1739 res.origPackage); 1740 break; 1741 } 1742 case PackageManager.INSTALL_SUCCEEDED: { 1743 extras = new Bundle(); 1744 extras.putBoolean(Intent.EXTRA_REPLACING, 1745 res.removedInfo != null && res.removedInfo.removedPackage != null); 1746 break; 1747 } 1748 } 1749 return extras; 1750 } 1751 1752 void scheduleWriteSettingsLocked() { 1753 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1754 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1755 } 1756 } 1757 1758 void scheduleWritePackageRestrictionsLocked(int userId) { 1759 if (!sUserManager.exists(userId)) return; 1760 mDirtyUsers.add(userId); 1761 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1762 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1763 } 1764 } 1765 1766 public static PackageManagerService main(Context context, Installer installer, 1767 boolean factoryTest, boolean onlyCore) { 1768 PackageManagerService m = new PackageManagerService(context, installer, 1769 factoryTest, onlyCore); 1770 ServiceManager.addService("package", m); 1771 return m; 1772 } 1773 1774 static String[] splitString(String str, char sep) { 1775 int count = 1; 1776 int i = 0; 1777 while ((i=str.indexOf(sep, i)) >= 0) { 1778 count++; 1779 i++; 1780 } 1781 1782 String[] res = new String[count]; 1783 i=0; 1784 count = 0; 1785 int lastI=0; 1786 while ((i=str.indexOf(sep, i)) >= 0) { 1787 res[count] = str.substring(lastI, i); 1788 count++; 1789 i++; 1790 lastI = i; 1791 } 1792 res[count] = str.substring(lastI, str.length()); 1793 return res; 1794 } 1795 1796 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1797 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1798 Context.DISPLAY_SERVICE); 1799 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1800 } 1801 1802 public PackageManagerService(Context context, Installer installer, 1803 boolean factoryTest, boolean onlyCore) { 1804 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1805 SystemClock.uptimeMillis()); 1806 1807 if (mSdkVersion <= 0) { 1808 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1809 } 1810 1811 mContext = context; 1812 mFactoryTest = factoryTest; 1813 mOnlyCore = onlyCore; 1814 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1815 mMetrics = new DisplayMetrics(); 1816 mSettings = new Settings(mPackages); 1817 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1818 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1819 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1820 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1821 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1822 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1823 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1824 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1825 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1826 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1827 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1828 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1829 1830 // TODO: add a property to control this? 1831 long dexOptLRUThresholdInMinutes; 1832 if (mLazyDexOpt) { 1833 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1834 } else { 1835 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1836 } 1837 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1838 1839 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1840 if (separateProcesses != null && separateProcesses.length() > 0) { 1841 if ("*".equals(separateProcesses)) { 1842 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1843 mSeparateProcesses = null; 1844 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1845 } else { 1846 mDefParseFlags = 0; 1847 mSeparateProcesses = separateProcesses.split(","); 1848 Slog.w(TAG, "Running with debug.separate_processes: " 1849 + separateProcesses); 1850 } 1851 } else { 1852 mDefParseFlags = 0; 1853 mSeparateProcesses = null; 1854 } 1855 1856 mInstaller = installer; 1857 mPackageDexOptimizer = new PackageDexOptimizer(this); 1858 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1859 1860 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1861 FgThread.get().getLooper()); 1862 1863 getDefaultDisplayMetrics(context, mMetrics); 1864 1865 SystemConfig systemConfig = SystemConfig.getInstance(); 1866 mGlobalGids = systemConfig.getGlobalGids(); 1867 mSystemPermissions = systemConfig.getSystemPermissions(); 1868 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1869 1870 synchronized (mInstallLock) { 1871 // writer 1872 synchronized (mPackages) { 1873 mHandlerThread = new ServiceThread(TAG, 1874 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1875 mHandlerThread.start(); 1876 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1877 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1878 1879 File dataDir = Environment.getDataDirectory(); 1880 mAppDataDir = new File(dataDir, "data"); 1881 mAppInstallDir = new File(dataDir, "app"); 1882 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1883 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1884 mUserAppDataDir = new File(dataDir, "user"); 1885 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1886 1887 sUserManager = new UserManagerService(context, this, 1888 mInstallLock, mPackages); 1889 1890 // Propagate permission configuration in to package manager. 1891 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1892 = systemConfig.getPermissions(); 1893 for (int i=0; i<permConfig.size(); i++) { 1894 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1895 BasePermission bp = mSettings.mPermissions.get(perm.name); 1896 if (bp == null) { 1897 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1898 mSettings.mPermissions.put(perm.name, bp); 1899 } 1900 if (perm.gids != null) { 1901 bp.setGids(perm.gids, perm.perUser); 1902 } 1903 } 1904 1905 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1906 for (int i=0; i<libConfig.size(); i++) { 1907 mSharedLibraries.put(libConfig.keyAt(i), 1908 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1909 } 1910 1911 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1912 1913 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1914 mSdkVersion, mOnlyCore); 1915 1916 String customResolverActivity = Resources.getSystem().getString( 1917 R.string.config_customResolverActivity); 1918 if (TextUtils.isEmpty(customResolverActivity)) { 1919 customResolverActivity = null; 1920 } else { 1921 mCustomResolverComponentName = ComponentName.unflattenFromString( 1922 customResolverActivity); 1923 } 1924 1925 long startTime = SystemClock.uptimeMillis(); 1926 1927 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1928 startTime); 1929 1930 // Set flag to monitor and not change apk file paths when 1931 // scanning install directories. 1932 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1933 1934 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1935 1936 /** 1937 * Add everything in the in the boot class path to the 1938 * list of process files because dexopt will have been run 1939 * if necessary during zygote startup. 1940 */ 1941 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1942 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1943 1944 if (bootClassPath != null) { 1945 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1946 for (String element : bootClassPathElements) { 1947 alreadyDexOpted.add(element); 1948 } 1949 } else { 1950 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1951 } 1952 1953 if (systemServerClassPath != null) { 1954 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1955 for (String element : systemServerClassPathElements) { 1956 alreadyDexOpted.add(element); 1957 } 1958 } else { 1959 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1960 } 1961 1962 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1963 final String[] dexCodeInstructionSets = 1964 getDexCodeInstructionSets( 1965 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1966 1967 /** 1968 * Ensure all external libraries have had dexopt run on them. 1969 */ 1970 if (mSharedLibraries.size() > 0) { 1971 // NOTE: For now, we're compiling these system "shared libraries" 1972 // (and framework jars) into all available architectures. It's possible 1973 // to compile them only when we come across an app that uses them (there's 1974 // already logic for that in scanPackageLI) but that adds some complexity. 1975 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1976 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1977 final String lib = libEntry.path; 1978 if (lib == null) { 1979 continue; 1980 } 1981 1982 try { 1983 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1984 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1985 alreadyDexOpted.add(lib); 1986 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 1987 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 1988 } 1989 } catch (FileNotFoundException e) { 1990 Slog.w(TAG, "Library not found: " + lib); 1991 } catch (IOException e) { 1992 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1993 + e.getMessage()); 1994 } 1995 } 1996 } 1997 } 1998 1999 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2000 2001 // Gross hack for now: we know this file doesn't contain any 2002 // code, so don't dexopt it to avoid the resulting log spew. 2003 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2004 2005 // Gross hack for now: we know this file is only part of 2006 // the boot class path for art, so don't dexopt it to 2007 // avoid the resulting log spew. 2008 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2009 2010 /** 2011 * There are a number of commands implemented in Java, which 2012 * we currently need to do the dexopt on so that they can be 2013 * run from a non-root shell. 2014 */ 2015 String[] frameworkFiles = frameworkDir.list(); 2016 if (frameworkFiles != null) { 2017 // TODO: We could compile these only for the most preferred ABI. We should 2018 // first double check that the dex files for these commands are not referenced 2019 // by other system apps. 2020 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2021 for (int i=0; i<frameworkFiles.length; i++) { 2022 File libPath = new File(frameworkDir, frameworkFiles[i]); 2023 String path = libPath.getPath(); 2024 // Skip the file if we already did it. 2025 if (alreadyDexOpted.contains(path)) { 2026 continue; 2027 } 2028 // Skip the file if it is not a type we want to dexopt. 2029 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2030 continue; 2031 } 2032 try { 2033 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2034 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2035 mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet, 2036 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2037 } 2038 } catch (FileNotFoundException e) { 2039 Slog.w(TAG, "Jar not found: " + path); 2040 } catch (IOException e) { 2041 Slog.w(TAG, "Exception reading jar: " + path, e); 2042 } 2043 } 2044 } 2045 } 2046 2047 final VersionInfo ver = mSettings.getInternalVersion(); 2048 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2049 // when upgrading from pre-M, promote system app permissions from install to runtime 2050 mPromoteSystemApps = 2051 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2052 2053 // save off the names of pre-existing system packages prior to scanning; we don't 2054 // want to automatically grant runtime permissions for new system apps 2055 if (mPromoteSystemApps) { 2056 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2057 while (pkgSettingIter.hasNext()) { 2058 PackageSetting ps = pkgSettingIter.next(); 2059 if (isSystemApp(ps)) { 2060 mExistingSystemPackages.add(ps.name); 2061 } 2062 } 2063 } 2064 2065 // Collect vendor overlay packages. 2066 // (Do this before scanning any apps.) 2067 // For security and version matching reason, only consider 2068 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2069 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2070 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2071 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2072 2073 // Find base frameworks (resource packages without code). 2074 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2075 | PackageParser.PARSE_IS_SYSTEM_DIR 2076 | PackageParser.PARSE_IS_PRIVILEGED, 2077 scanFlags | SCAN_NO_DEX, 0); 2078 2079 // Collected privileged system packages. 2080 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2081 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2082 | PackageParser.PARSE_IS_SYSTEM_DIR 2083 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2084 2085 // Collect ordinary system packages. 2086 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2087 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2088 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2089 2090 // Collect all vendor packages. 2091 File vendorAppDir = new File("/vendor/app"); 2092 try { 2093 vendorAppDir = vendorAppDir.getCanonicalFile(); 2094 } catch (IOException e) { 2095 // failed to look up canonical path, continue with original one 2096 } 2097 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2098 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2099 2100 // Collect all OEM packages. 2101 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2102 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2103 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2104 2105 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2106 mInstaller.moveFiles(); 2107 2108 // Prune any system packages that no longer exist. 2109 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2110 if (!mOnlyCore) { 2111 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2112 while (psit.hasNext()) { 2113 PackageSetting ps = psit.next(); 2114 2115 /* 2116 * If this is not a system app, it can't be a 2117 * disable system app. 2118 */ 2119 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2120 continue; 2121 } 2122 2123 /* 2124 * If the package is scanned, it's not erased. 2125 */ 2126 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2127 if (scannedPkg != null) { 2128 /* 2129 * If the system app is both scanned and in the 2130 * disabled packages list, then it must have been 2131 * added via OTA. Remove it from the currently 2132 * scanned package so the previously user-installed 2133 * application can be scanned. 2134 */ 2135 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2136 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2137 + ps.name + "; removing system app. Last known codePath=" 2138 + ps.codePathString + ", installStatus=" + ps.installStatus 2139 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2140 + scannedPkg.mVersionCode); 2141 removePackageLI(ps, true); 2142 mExpectingBetter.put(ps.name, ps.codePath); 2143 } 2144 2145 continue; 2146 } 2147 2148 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2149 psit.remove(); 2150 logCriticalInfo(Log.WARN, "System package " + ps.name 2151 + " no longer exists; wiping its data"); 2152 removeDataDirsLI(null, ps.name); 2153 } else { 2154 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2155 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2156 possiblyDeletedUpdatedSystemApps.add(ps.name); 2157 } 2158 } 2159 } 2160 } 2161 2162 //look for any incomplete package installations 2163 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2164 //clean up list 2165 for(int i = 0; i < deletePkgsList.size(); i++) { 2166 //clean up here 2167 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2168 } 2169 //delete tmp files 2170 deleteTempPackageFiles(); 2171 2172 // Remove any shared userIDs that have no associated packages 2173 mSettings.pruneSharedUsersLPw(); 2174 2175 if (!mOnlyCore) { 2176 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2177 SystemClock.uptimeMillis()); 2178 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2179 2180 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2181 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2182 2183 /** 2184 * Remove disable package settings for any updated system 2185 * apps that were removed via an OTA. If they're not a 2186 * previously-updated app, remove them completely. 2187 * Otherwise, just revoke their system-level permissions. 2188 */ 2189 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2190 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2191 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2192 2193 String msg; 2194 if (deletedPkg == null) { 2195 msg = "Updated system package " + deletedAppName 2196 + " no longer exists; wiping its data"; 2197 removeDataDirsLI(null, deletedAppName); 2198 } else { 2199 msg = "Updated system app + " + deletedAppName 2200 + " no longer present; removing system privileges for " 2201 + deletedAppName; 2202 2203 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2204 2205 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2206 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2207 } 2208 logCriticalInfo(Log.WARN, msg); 2209 } 2210 2211 /** 2212 * Make sure all system apps that we expected to appear on 2213 * the userdata partition actually showed up. If they never 2214 * appeared, crawl back and revive the system version. 2215 */ 2216 for (int i = 0; i < mExpectingBetter.size(); i++) { 2217 final String packageName = mExpectingBetter.keyAt(i); 2218 if (!mPackages.containsKey(packageName)) { 2219 final File scanFile = mExpectingBetter.valueAt(i); 2220 2221 logCriticalInfo(Log.WARN, "Expected better " + packageName 2222 + " but never showed up; reverting to system"); 2223 2224 final int reparseFlags; 2225 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2226 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2227 | PackageParser.PARSE_IS_SYSTEM_DIR 2228 | PackageParser.PARSE_IS_PRIVILEGED; 2229 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2230 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2231 | PackageParser.PARSE_IS_SYSTEM_DIR; 2232 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2233 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2234 | PackageParser.PARSE_IS_SYSTEM_DIR; 2235 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2236 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2237 | PackageParser.PARSE_IS_SYSTEM_DIR; 2238 } else { 2239 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2240 continue; 2241 } 2242 2243 mSettings.enableSystemPackageLPw(packageName); 2244 2245 try { 2246 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2247 } catch (PackageManagerException e) { 2248 Slog.e(TAG, "Failed to parse original system package: " 2249 + e.getMessage()); 2250 } 2251 } 2252 } 2253 } 2254 mExpectingBetter.clear(); 2255 2256 // Now that we know all of the shared libraries, update all clients to have 2257 // the correct library paths. 2258 updateAllSharedLibrariesLPw(); 2259 2260 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2261 // NOTE: We ignore potential failures here during a system scan (like 2262 // the rest of the commands above) because there's precious little we 2263 // can do about it. A settings error is reported, though. 2264 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2265 false /* force dexopt */, false /* defer dexopt */, 2266 false /* boot complete */); 2267 } 2268 2269 // Now that we know all the packages we are keeping, 2270 // read and update their last usage times. 2271 mPackageUsage.readLP(); 2272 2273 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2274 SystemClock.uptimeMillis()); 2275 Slog.i(TAG, "Time to scan packages: " 2276 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2277 + " seconds"); 2278 2279 // If the platform SDK has changed since the last time we booted, 2280 // we need to re-grant app permission to catch any new ones that 2281 // appear. This is really a hack, and means that apps can in some 2282 // cases get permissions that the user didn't initially explicitly 2283 // allow... it would be nice to have some better way to handle 2284 // this situation. 2285 int updateFlags = UPDATE_PERMISSIONS_ALL; 2286 if (ver.sdkVersion != mSdkVersion) { 2287 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2288 + mSdkVersion + "; regranting permissions for internal storage"); 2289 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2290 } 2291 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2292 ver.sdkVersion = mSdkVersion; 2293 2294 // If this is the first boot or an update from pre-M, and it is a normal 2295 // boot, then we need to initialize the default preferred apps across 2296 // all defined users. 2297 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2298 for (UserInfo user : sUserManager.getUsers(true)) { 2299 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2300 applyFactoryDefaultBrowserLPw(user.id); 2301 primeDomainVerificationsLPw(user.id); 2302 } 2303 } 2304 2305 // If this is first boot after an OTA, and a normal boot, then 2306 // we need to clear code cache directories. 2307 if (mIsUpgrade && !onlyCore) { 2308 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2309 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2310 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2311 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2312 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2313 } 2314 } 2315 ver.fingerprint = Build.FINGERPRINT; 2316 } 2317 2318 checkDefaultBrowser(); 2319 2320 // clear only after permissions and other defaults have been updated 2321 mExistingSystemPackages.clear(); 2322 mPromoteSystemApps = false; 2323 2324 // All the changes are done during package scanning. 2325 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2326 2327 // can downgrade to reader 2328 mSettings.writeLPr(); 2329 2330 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2331 SystemClock.uptimeMillis()); 2332 2333 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2334 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2335 2336 mInstallerService = new PackageInstallerService(context, this); 2337 2338 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2339 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2340 mIntentFilterVerifierComponent); 2341 2342 } // synchronized (mPackages) 2343 } // synchronized (mInstallLock) 2344 2345 // Now after opening every single application zip, make sure they 2346 // are all flushed. Not really needed, but keeps things nice and 2347 // tidy. 2348 Runtime.getRuntime().gc(); 2349 2350 // Expose private service for system components to use. 2351 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2352 } 2353 2354 @Override 2355 public boolean isFirstBoot() { 2356 return !mRestoredSettings; 2357 } 2358 2359 @Override 2360 public boolean isOnlyCoreApps() { 2361 return mOnlyCore; 2362 } 2363 2364 @Override 2365 public boolean isUpgrade() { 2366 return mIsUpgrade; 2367 } 2368 2369 private String getRequiredVerifierLPr() { 2370 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2371 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2372 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2373 2374 String requiredVerifier = null; 2375 2376 final int N = receivers.size(); 2377 for (int i = 0; i < N; i++) { 2378 final ResolveInfo info = receivers.get(i); 2379 2380 if (info.activityInfo == null) { 2381 continue; 2382 } 2383 2384 final String packageName = info.activityInfo.packageName; 2385 2386 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2387 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2388 continue; 2389 } 2390 2391 if (requiredVerifier != null) { 2392 throw new RuntimeException("There can be only one required verifier"); 2393 } 2394 2395 requiredVerifier = packageName; 2396 } 2397 2398 return requiredVerifier; 2399 } 2400 2401 private String getRequiredInstallerLPr() { 2402 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2403 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2404 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2405 2406 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2407 PACKAGE_MIME_TYPE, 0, 0); 2408 2409 String requiredInstaller = null; 2410 2411 final int N = installers.size(); 2412 for (int i = 0; i < N; i++) { 2413 final ResolveInfo info = installers.get(i); 2414 final String packageName = info.activityInfo.packageName; 2415 2416 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2417 continue; 2418 } 2419 2420 if (requiredInstaller != null) { 2421 throw new RuntimeException("There must be one required installer"); 2422 } 2423 2424 requiredInstaller = packageName; 2425 } 2426 2427 if (requiredInstaller == null) { 2428 throw new RuntimeException("There must be one required installer"); 2429 } 2430 2431 return requiredInstaller; 2432 } 2433 2434 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2435 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2436 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2437 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2438 2439 ComponentName verifierComponentName = null; 2440 2441 int priority = -1000; 2442 final int N = receivers.size(); 2443 for (int i = 0; i < N; i++) { 2444 final ResolveInfo info = receivers.get(i); 2445 2446 if (info.activityInfo == null) { 2447 continue; 2448 } 2449 2450 final String packageName = info.activityInfo.packageName; 2451 2452 final PackageSetting ps = mSettings.mPackages.get(packageName); 2453 if (ps == null) { 2454 continue; 2455 } 2456 2457 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2458 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2459 continue; 2460 } 2461 2462 // Select the IntentFilterVerifier with the highest priority 2463 if (priority < info.priority) { 2464 priority = info.priority; 2465 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2466 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2467 + verifierComponentName + " with priority: " + info.priority); 2468 } 2469 } 2470 2471 return verifierComponentName; 2472 } 2473 2474 private void primeDomainVerificationsLPw(int userId) { 2475 if (DEBUG_DOMAIN_VERIFICATION) { 2476 Slog.d(TAG, "Priming domain verifications in user " + userId); 2477 } 2478 2479 SystemConfig systemConfig = SystemConfig.getInstance(); 2480 ArraySet<String> packages = systemConfig.getLinkedApps(); 2481 ArraySet<String> domains = new ArraySet<String>(); 2482 2483 for (String packageName : packages) { 2484 PackageParser.Package pkg = mPackages.get(packageName); 2485 if (pkg != null) { 2486 if (!pkg.isSystemApp()) { 2487 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2488 continue; 2489 } 2490 2491 domains.clear(); 2492 for (PackageParser.Activity a : pkg.activities) { 2493 for (ActivityIntentInfo filter : a.intents) { 2494 if (hasValidDomains(filter)) { 2495 domains.addAll(filter.getHostsList()); 2496 } 2497 } 2498 } 2499 2500 if (domains.size() > 0) { 2501 if (DEBUG_DOMAIN_VERIFICATION) { 2502 Slog.v(TAG, " + " + packageName); 2503 } 2504 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2505 // state w.r.t. the formal app-linkage "no verification attempted" state; 2506 // and then 'always' in the per-user state actually used for intent resolution. 2507 final IntentFilterVerificationInfo ivi; 2508 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2509 new ArrayList<String>(domains)); 2510 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2511 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2512 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2513 } else { 2514 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2515 + "' does not handle web links"); 2516 } 2517 } else { 2518 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2519 } 2520 } 2521 2522 scheduleWritePackageRestrictionsLocked(userId); 2523 scheduleWriteSettingsLocked(); 2524 } 2525 2526 private void applyFactoryDefaultBrowserLPw(int userId) { 2527 // The default browser app's package name is stored in a string resource, 2528 // with a product-specific overlay used for vendor customization. 2529 String browserPkg = mContext.getResources().getString( 2530 com.android.internal.R.string.default_browser); 2531 if (!TextUtils.isEmpty(browserPkg)) { 2532 // non-empty string => required to be a known package 2533 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2534 if (ps == null) { 2535 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2536 browserPkg = null; 2537 } else { 2538 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2539 } 2540 } 2541 2542 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2543 // default. If there's more than one, just leave everything alone. 2544 if (browserPkg == null) { 2545 calculateDefaultBrowserLPw(userId); 2546 } 2547 } 2548 2549 private void calculateDefaultBrowserLPw(int userId) { 2550 List<String> allBrowsers = resolveAllBrowserApps(userId); 2551 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2552 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2553 } 2554 2555 private List<String> resolveAllBrowserApps(int userId) { 2556 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2557 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2558 PackageManager.MATCH_ALL, userId); 2559 2560 final int count = list.size(); 2561 List<String> result = new ArrayList<String>(count); 2562 for (int i=0; i<count; i++) { 2563 ResolveInfo info = list.get(i); 2564 if (info.activityInfo == null 2565 || !info.handleAllWebDataURI 2566 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2567 || result.contains(info.activityInfo.packageName)) { 2568 continue; 2569 } 2570 result.add(info.activityInfo.packageName); 2571 } 2572 2573 return result; 2574 } 2575 2576 private boolean packageIsBrowser(String packageName, int userId) { 2577 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2578 PackageManager.MATCH_ALL, userId); 2579 final int N = list.size(); 2580 for (int i = 0; i < N; i++) { 2581 ResolveInfo info = list.get(i); 2582 if (packageName.equals(info.activityInfo.packageName)) { 2583 return true; 2584 } 2585 } 2586 return false; 2587 } 2588 2589 private void checkDefaultBrowser() { 2590 final int myUserId = UserHandle.myUserId(); 2591 final String packageName = getDefaultBrowserPackageName(myUserId); 2592 if (packageName != null) { 2593 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2594 if (info == null) { 2595 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2596 synchronized (mPackages) { 2597 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2598 } 2599 } 2600 } 2601 } 2602 2603 @Override 2604 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2605 throws RemoteException { 2606 try { 2607 return super.onTransact(code, data, reply, flags); 2608 } catch (RuntimeException e) { 2609 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2610 Slog.wtf(TAG, "Package Manager Crash", e); 2611 } 2612 throw e; 2613 } 2614 } 2615 2616 void cleanupInstallFailedPackage(PackageSetting ps) { 2617 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2618 2619 removeDataDirsLI(ps.volumeUuid, ps.name); 2620 if (ps.codePath != null) { 2621 if (ps.codePath.isDirectory()) { 2622 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2623 } else { 2624 ps.codePath.delete(); 2625 } 2626 } 2627 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2628 if (ps.resourcePath.isDirectory()) { 2629 FileUtils.deleteContents(ps.resourcePath); 2630 } 2631 ps.resourcePath.delete(); 2632 } 2633 mSettings.removePackageLPw(ps.name); 2634 } 2635 2636 static int[] appendInts(int[] cur, int[] add) { 2637 if (add == null) return cur; 2638 if (cur == null) return add; 2639 final int N = add.length; 2640 for (int i=0; i<N; i++) { 2641 cur = appendInt(cur, add[i]); 2642 } 2643 return cur; 2644 } 2645 2646 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2647 if (!sUserManager.exists(userId)) return null; 2648 final PackageSetting ps = (PackageSetting) p.mExtras; 2649 if (ps == null) { 2650 return null; 2651 } 2652 2653 final PermissionsState permissionsState = ps.getPermissionsState(); 2654 2655 final int[] gids = permissionsState.computeGids(userId); 2656 final Set<String> permissions = permissionsState.getPermissions(userId); 2657 final PackageUserState state = ps.readUserState(userId); 2658 2659 return PackageParser.generatePackageInfo(p, gids, flags, 2660 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2661 } 2662 2663 @Override 2664 public boolean isPackageFrozen(String packageName) { 2665 synchronized (mPackages) { 2666 final PackageSetting ps = mSettings.mPackages.get(packageName); 2667 if (ps != null) { 2668 return ps.frozen; 2669 } 2670 } 2671 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2672 return true; 2673 } 2674 2675 @Override 2676 public boolean isPackageAvailable(String packageName, int userId) { 2677 if (!sUserManager.exists(userId)) return false; 2678 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2679 synchronized (mPackages) { 2680 PackageParser.Package p = mPackages.get(packageName); 2681 if (p != null) { 2682 final PackageSetting ps = (PackageSetting) p.mExtras; 2683 if (ps != null) { 2684 final PackageUserState state = ps.readUserState(userId); 2685 if (state != null) { 2686 return PackageParser.isAvailable(state); 2687 } 2688 } 2689 } 2690 } 2691 return false; 2692 } 2693 2694 @Override 2695 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2696 if (!sUserManager.exists(userId)) return null; 2697 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2698 // reader 2699 synchronized (mPackages) { 2700 PackageParser.Package p = mPackages.get(packageName); 2701 if (DEBUG_PACKAGE_INFO) 2702 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2703 if (p != null) { 2704 return generatePackageInfo(p, flags, userId); 2705 } 2706 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2707 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2708 } 2709 } 2710 return null; 2711 } 2712 2713 @Override 2714 public String[] currentToCanonicalPackageNames(String[] names) { 2715 String[] out = new String[names.length]; 2716 // reader 2717 synchronized (mPackages) { 2718 for (int i=names.length-1; i>=0; i--) { 2719 PackageSetting ps = mSettings.mPackages.get(names[i]); 2720 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2721 } 2722 } 2723 return out; 2724 } 2725 2726 @Override 2727 public String[] canonicalToCurrentPackageNames(String[] names) { 2728 String[] out = new String[names.length]; 2729 // reader 2730 synchronized (mPackages) { 2731 for (int i=names.length-1; i>=0; i--) { 2732 String cur = mSettings.mRenamedPackages.get(names[i]); 2733 out[i] = cur != null ? cur : names[i]; 2734 } 2735 } 2736 return out; 2737 } 2738 2739 @Override 2740 public int getPackageUid(String packageName, int userId) { 2741 return getPackageUidEtc(packageName, 0, userId); 2742 } 2743 2744 @Override 2745 public int getPackageUidEtc(String packageName, int flags, int userId) { 2746 if (!sUserManager.exists(userId)) return -1; 2747 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2748 2749 // reader 2750 synchronized (mPackages) { 2751 final PackageParser.Package p = mPackages.get(packageName); 2752 if (p != null) { 2753 return UserHandle.getUid(userId, p.applicationInfo.uid); 2754 } 2755 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2756 final PackageSetting ps = mSettings.mPackages.get(packageName); 2757 if (ps != null) { 2758 return UserHandle.getUid(userId, ps.appId); 2759 } 2760 } 2761 } 2762 2763 return -1; 2764 } 2765 2766 @Override 2767 public int[] getPackageGids(String packageName, int userId) { 2768 return getPackageGidsEtc(packageName, 0, userId); 2769 } 2770 2771 @Override 2772 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2773 if (!sUserManager.exists(userId)) { 2774 return null; 2775 } 2776 2777 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2778 "getPackageGids"); 2779 2780 // reader 2781 synchronized (mPackages) { 2782 final PackageParser.Package p = mPackages.get(packageName); 2783 if (p != null) { 2784 PackageSetting ps = (PackageSetting) p.mExtras; 2785 return ps.getPermissionsState().computeGids(userId); 2786 } 2787 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2788 final PackageSetting ps = mSettings.mPackages.get(packageName); 2789 if (ps != null) { 2790 return ps.getPermissionsState().computeGids(userId); 2791 } 2792 } 2793 } 2794 2795 return null; 2796 } 2797 2798 static PermissionInfo generatePermissionInfo( 2799 BasePermission bp, int flags) { 2800 if (bp.perm != null) { 2801 return PackageParser.generatePermissionInfo(bp.perm, flags); 2802 } 2803 PermissionInfo pi = new PermissionInfo(); 2804 pi.name = bp.name; 2805 pi.packageName = bp.sourcePackage; 2806 pi.nonLocalizedLabel = bp.name; 2807 pi.protectionLevel = bp.protectionLevel; 2808 return pi; 2809 } 2810 2811 @Override 2812 public PermissionInfo getPermissionInfo(String name, int flags) { 2813 // reader 2814 synchronized (mPackages) { 2815 final BasePermission p = mSettings.mPermissions.get(name); 2816 if (p != null) { 2817 return generatePermissionInfo(p, flags); 2818 } 2819 return null; 2820 } 2821 } 2822 2823 @Override 2824 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2825 // reader 2826 synchronized (mPackages) { 2827 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2828 for (BasePermission p : mSettings.mPermissions.values()) { 2829 if (group == null) { 2830 if (p.perm == null || p.perm.info.group == null) { 2831 out.add(generatePermissionInfo(p, flags)); 2832 } 2833 } else { 2834 if (p.perm != null && group.equals(p.perm.info.group)) { 2835 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2836 } 2837 } 2838 } 2839 2840 if (out.size() > 0) { 2841 return out; 2842 } 2843 return mPermissionGroups.containsKey(group) ? out : null; 2844 } 2845 } 2846 2847 @Override 2848 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2849 // reader 2850 synchronized (mPackages) { 2851 return PackageParser.generatePermissionGroupInfo( 2852 mPermissionGroups.get(name), flags); 2853 } 2854 } 2855 2856 @Override 2857 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2858 // reader 2859 synchronized (mPackages) { 2860 final int N = mPermissionGroups.size(); 2861 ArrayList<PermissionGroupInfo> out 2862 = new ArrayList<PermissionGroupInfo>(N); 2863 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2864 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2865 } 2866 return out; 2867 } 2868 } 2869 2870 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2871 int userId) { 2872 if (!sUserManager.exists(userId)) return null; 2873 PackageSetting ps = mSettings.mPackages.get(packageName); 2874 if (ps != null) { 2875 if (ps.pkg == null) { 2876 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2877 flags, userId); 2878 if (pInfo != null) { 2879 return pInfo.applicationInfo; 2880 } 2881 return null; 2882 } 2883 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2884 ps.readUserState(userId), userId); 2885 } 2886 return null; 2887 } 2888 2889 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2890 int userId) { 2891 if (!sUserManager.exists(userId)) return null; 2892 PackageSetting ps = mSettings.mPackages.get(packageName); 2893 if (ps != null) { 2894 PackageParser.Package pkg = ps.pkg; 2895 if (pkg == null) { 2896 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2897 return null; 2898 } 2899 // Only data remains, so we aren't worried about code paths 2900 pkg = new PackageParser.Package(packageName); 2901 pkg.applicationInfo.packageName = packageName; 2902 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2903 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2904 pkg.applicationInfo.dataDir = Environment 2905 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2906 .getAbsolutePath(); 2907 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2908 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2909 } 2910 return generatePackageInfo(pkg, flags, userId); 2911 } 2912 return null; 2913 } 2914 2915 @Override 2916 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2917 if (!sUserManager.exists(userId)) return null; 2918 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2919 // writer 2920 synchronized (mPackages) { 2921 PackageParser.Package p = mPackages.get(packageName); 2922 if (DEBUG_PACKAGE_INFO) Log.v( 2923 TAG, "getApplicationInfo " + packageName 2924 + ": " + p); 2925 if (p != null) { 2926 PackageSetting ps = mSettings.mPackages.get(packageName); 2927 if (ps == null) return null; 2928 // Note: isEnabledLP() does not apply here - always return info 2929 return PackageParser.generateApplicationInfo( 2930 p, flags, ps.readUserState(userId), userId); 2931 } 2932 if ("android".equals(packageName)||"system".equals(packageName)) { 2933 return mAndroidApplication; 2934 } 2935 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2936 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2937 } 2938 } 2939 return null; 2940 } 2941 2942 @Override 2943 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2944 final IPackageDataObserver observer) { 2945 mContext.enforceCallingOrSelfPermission( 2946 android.Manifest.permission.CLEAR_APP_CACHE, null); 2947 // Queue up an async operation since clearing cache may take a little while. 2948 mHandler.post(new Runnable() { 2949 public void run() { 2950 mHandler.removeCallbacks(this); 2951 int retCode = -1; 2952 synchronized (mInstallLock) { 2953 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2954 if (retCode < 0) { 2955 Slog.w(TAG, "Couldn't clear application caches"); 2956 } 2957 } 2958 if (observer != null) { 2959 try { 2960 observer.onRemoveCompleted(null, (retCode >= 0)); 2961 } catch (RemoteException e) { 2962 Slog.w(TAG, "RemoveException when invoking call back"); 2963 } 2964 } 2965 } 2966 }); 2967 } 2968 2969 @Override 2970 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2971 final IntentSender pi) { 2972 mContext.enforceCallingOrSelfPermission( 2973 android.Manifest.permission.CLEAR_APP_CACHE, null); 2974 // Queue up an async operation since clearing cache may take a little while. 2975 mHandler.post(new Runnable() { 2976 public void run() { 2977 mHandler.removeCallbacks(this); 2978 int retCode = -1; 2979 synchronized (mInstallLock) { 2980 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2981 if (retCode < 0) { 2982 Slog.w(TAG, "Couldn't clear application caches"); 2983 } 2984 } 2985 if(pi != null) { 2986 try { 2987 // Callback via pending intent 2988 int code = (retCode >= 0) ? 1 : 0; 2989 pi.sendIntent(null, code, null, 2990 null, null); 2991 } catch (SendIntentException e1) { 2992 Slog.i(TAG, "Failed to send pending intent"); 2993 } 2994 } 2995 } 2996 }); 2997 } 2998 2999 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3000 synchronized (mInstallLock) { 3001 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3002 throw new IOException("Failed to free enough space"); 3003 } 3004 } 3005 } 3006 3007 @Override 3008 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3009 if (!sUserManager.exists(userId)) return null; 3010 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3011 synchronized (mPackages) { 3012 PackageParser.Activity a = mActivities.mActivities.get(component); 3013 3014 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3015 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3016 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3017 if (ps == null) return null; 3018 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3019 userId); 3020 } 3021 if (mResolveComponentName.equals(component)) { 3022 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3023 new PackageUserState(), userId); 3024 } 3025 } 3026 return null; 3027 } 3028 3029 @Override 3030 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3031 String resolvedType) { 3032 synchronized (mPackages) { 3033 if (component.equals(mResolveComponentName)) { 3034 // The resolver supports EVERYTHING! 3035 return true; 3036 } 3037 PackageParser.Activity a = mActivities.mActivities.get(component); 3038 if (a == null) { 3039 return false; 3040 } 3041 for (int i=0; i<a.intents.size(); i++) { 3042 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3043 intent.getData(), intent.getCategories(), TAG) >= 0) { 3044 return true; 3045 } 3046 } 3047 return false; 3048 } 3049 } 3050 3051 @Override 3052 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3053 if (!sUserManager.exists(userId)) return null; 3054 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3055 synchronized (mPackages) { 3056 PackageParser.Activity a = mReceivers.mActivities.get(component); 3057 if (DEBUG_PACKAGE_INFO) Log.v( 3058 TAG, "getReceiverInfo " + component + ": " + a); 3059 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3060 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3061 if (ps == null) return null; 3062 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3063 userId); 3064 } 3065 } 3066 return null; 3067 } 3068 3069 @Override 3070 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3071 if (!sUserManager.exists(userId)) return null; 3072 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3073 synchronized (mPackages) { 3074 PackageParser.Service s = mServices.mServices.get(component); 3075 if (DEBUG_PACKAGE_INFO) Log.v( 3076 TAG, "getServiceInfo " + component + ": " + s); 3077 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3078 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3079 if (ps == null) return null; 3080 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3081 userId); 3082 } 3083 } 3084 return null; 3085 } 3086 3087 @Override 3088 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3089 if (!sUserManager.exists(userId)) return null; 3090 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3091 synchronized (mPackages) { 3092 PackageParser.Provider p = mProviders.mProviders.get(component); 3093 if (DEBUG_PACKAGE_INFO) Log.v( 3094 TAG, "getProviderInfo " + component + ": " + p); 3095 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3096 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3097 if (ps == null) return null; 3098 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3099 userId); 3100 } 3101 } 3102 return null; 3103 } 3104 3105 @Override 3106 public String[] getSystemSharedLibraryNames() { 3107 Set<String> libSet; 3108 synchronized (mPackages) { 3109 libSet = mSharedLibraries.keySet(); 3110 int size = libSet.size(); 3111 if (size > 0) { 3112 String[] libs = new String[size]; 3113 libSet.toArray(libs); 3114 return libs; 3115 } 3116 } 3117 return null; 3118 } 3119 3120 /** 3121 * @hide 3122 */ 3123 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3124 synchronized (mPackages) { 3125 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3126 if (lib != null && lib.apk != null) { 3127 return mPackages.get(lib.apk); 3128 } 3129 } 3130 return null; 3131 } 3132 3133 @Override 3134 public FeatureInfo[] getSystemAvailableFeatures() { 3135 Collection<FeatureInfo> featSet; 3136 synchronized (mPackages) { 3137 featSet = mAvailableFeatures.values(); 3138 int size = featSet.size(); 3139 if (size > 0) { 3140 FeatureInfo[] features = new FeatureInfo[size+1]; 3141 featSet.toArray(features); 3142 FeatureInfo fi = new FeatureInfo(); 3143 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3144 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3145 features[size] = fi; 3146 return features; 3147 } 3148 } 3149 return null; 3150 } 3151 3152 @Override 3153 public boolean hasSystemFeature(String name) { 3154 synchronized (mPackages) { 3155 return mAvailableFeatures.containsKey(name); 3156 } 3157 } 3158 3159 private void checkValidCaller(int uid, int userId) { 3160 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3161 return; 3162 3163 throw new SecurityException("Caller uid=" + uid 3164 + " is not privileged to communicate with user=" + userId); 3165 } 3166 3167 @Override 3168 public int checkPermission(String permName, String pkgName, int userId) { 3169 if (!sUserManager.exists(userId)) { 3170 return PackageManager.PERMISSION_DENIED; 3171 } 3172 3173 synchronized (mPackages) { 3174 final PackageParser.Package p = mPackages.get(pkgName); 3175 if (p != null && p.mExtras != null) { 3176 final PackageSetting ps = (PackageSetting) p.mExtras; 3177 final PermissionsState permissionsState = ps.getPermissionsState(); 3178 if (permissionsState.hasPermission(permName, userId)) { 3179 return PackageManager.PERMISSION_GRANTED; 3180 } 3181 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3182 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3183 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3184 return PackageManager.PERMISSION_GRANTED; 3185 } 3186 } 3187 } 3188 3189 return PackageManager.PERMISSION_DENIED; 3190 } 3191 3192 @Override 3193 public int checkUidPermission(String permName, int uid) { 3194 final int userId = UserHandle.getUserId(uid); 3195 3196 if (!sUserManager.exists(userId)) { 3197 return PackageManager.PERMISSION_DENIED; 3198 } 3199 3200 synchronized (mPackages) { 3201 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3202 if (obj != null) { 3203 final SettingBase ps = (SettingBase) obj; 3204 final PermissionsState permissionsState = ps.getPermissionsState(); 3205 if (permissionsState.hasPermission(permName, userId)) { 3206 return PackageManager.PERMISSION_GRANTED; 3207 } 3208 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3209 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3210 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3211 return PackageManager.PERMISSION_GRANTED; 3212 } 3213 } else { 3214 ArraySet<String> perms = mSystemPermissions.get(uid); 3215 if (perms != null) { 3216 if (perms.contains(permName)) { 3217 return PackageManager.PERMISSION_GRANTED; 3218 } 3219 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3220 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3221 return PackageManager.PERMISSION_GRANTED; 3222 } 3223 } 3224 } 3225 } 3226 3227 return PackageManager.PERMISSION_DENIED; 3228 } 3229 3230 @Override 3231 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3232 if (UserHandle.getCallingUserId() != userId) { 3233 mContext.enforceCallingPermission( 3234 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3235 "isPermissionRevokedByPolicy for user " + userId); 3236 } 3237 3238 if (checkPermission(permission, packageName, userId) 3239 == PackageManager.PERMISSION_GRANTED) { 3240 return false; 3241 } 3242 3243 final long identity = Binder.clearCallingIdentity(); 3244 try { 3245 final int flags = getPermissionFlags(permission, packageName, userId); 3246 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3247 } finally { 3248 Binder.restoreCallingIdentity(identity); 3249 } 3250 } 3251 3252 @Override 3253 public String getPermissionControllerPackageName() { 3254 synchronized (mPackages) { 3255 return mRequiredInstallerPackage; 3256 } 3257 } 3258 3259 /** 3260 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3261 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3262 * @param checkShell TODO(yamasani): 3263 * @param message the message to log on security exception 3264 */ 3265 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3266 boolean checkShell, String message) { 3267 if (userId < 0) { 3268 throw new IllegalArgumentException("Invalid userId " + userId); 3269 } 3270 if (checkShell) { 3271 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3272 } 3273 if (userId == UserHandle.getUserId(callingUid)) return; 3274 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3275 if (requireFullPermission) { 3276 mContext.enforceCallingOrSelfPermission( 3277 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3278 } else { 3279 try { 3280 mContext.enforceCallingOrSelfPermission( 3281 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3282 } catch (SecurityException se) { 3283 mContext.enforceCallingOrSelfPermission( 3284 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3285 } 3286 } 3287 } 3288 } 3289 3290 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3291 if (callingUid == Process.SHELL_UID) { 3292 if (userHandle >= 0 3293 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3294 throw new SecurityException("Shell does not have permission to access user " 3295 + userHandle); 3296 } else if (userHandle < 0) { 3297 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3298 + Debug.getCallers(3)); 3299 } 3300 } 3301 } 3302 3303 private BasePermission findPermissionTreeLP(String permName) { 3304 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3305 if (permName.startsWith(bp.name) && 3306 permName.length() > bp.name.length() && 3307 permName.charAt(bp.name.length()) == '.') { 3308 return bp; 3309 } 3310 } 3311 return null; 3312 } 3313 3314 private BasePermission checkPermissionTreeLP(String permName) { 3315 if (permName != null) { 3316 BasePermission bp = findPermissionTreeLP(permName); 3317 if (bp != null) { 3318 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3319 return bp; 3320 } 3321 throw new SecurityException("Calling uid " 3322 + Binder.getCallingUid() 3323 + " is not allowed to add to permission tree " 3324 + bp.name + " owned by uid " + bp.uid); 3325 } 3326 } 3327 throw new SecurityException("No permission tree found for " + permName); 3328 } 3329 3330 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3331 if (s1 == null) { 3332 return s2 == null; 3333 } 3334 if (s2 == null) { 3335 return false; 3336 } 3337 if (s1.getClass() != s2.getClass()) { 3338 return false; 3339 } 3340 return s1.equals(s2); 3341 } 3342 3343 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3344 if (pi1.icon != pi2.icon) return false; 3345 if (pi1.logo != pi2.logo) return false; 3346 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3347 if (!compareStrings(pi1.name, pi2.name)) return false; 3348 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3349 // We'll take care of setting this one. 3350 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3351 // These are not currently stored in settings. 3352 //if (!compareStrings(pi1.group, pi2.group)) return false; 3353 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3354 //if (pi1.labelRes != pi2.labelRes) return false; 3355 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3356 return true; 3357 } 3358 3359 int permissionInfoFootprint(PermissionInfo info) { 3360 int size = info.name.length(); 3361 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3362 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3363 return size; 3364 } 3365 3366 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3367 int size = 0; 3368 for (BasePermission perm : mSettings.mPermissions.values()) { 3369 if (perm.uid == tree.uid) { 3370 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3371 } 3372 } 3373 return size; 3374 } 3375 3376 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3377 // We calculate the max size of permissions defined by this uid and throw 3378 // if that plus the size of 'info' would exceed our stated maximum. 3379 if (tree.uid != Process.SYSTEM_UID) { 3380 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3381 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3382 throw new SecurityException("Permission tree size cap exceeded"); 3383 } 3384 } 3385 } 3386 3387 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3388 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3389 throw new SecurityException("Label must be specified in permission"); 3390 } 3391 BasePermission tree = checkPermissionTreeLP(info.name); 3392 BasePermission bp = mSettings.mPermissions.get(info.name); 3393 boolean added = bp == null; 3394 boolean changed = true; 3395 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3396 if (added) { 3397 enforcePermissionCapLocked(info, tree); 3398 bp = new BasePermission(info.name, tree.sourcePackage, 3399 BasePermission.TYPE_DYNAMIC); 3400 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3401 throw new SecurityException( 3402 "Not allowed to modify non-dynamic permission " 3403 + info.name); 3404 } else { 3405 if (bp.protectionLevel == fixedLevel 3406 && bp.perm.owner.equals(tree.perm.owner) 3407 && bp.uid == tree.uid 3408 && comparePermissionInfos(bp.perm.info, info)) { 3409 changed = false; 3410 } 3411 } 3412 bp.protectionLevel = fixedLevel; 3413 info = new PermissionInfo(info); 3414 info.protectionLevel = fixedLevel; 3415 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3416 bp.perm.info.packageName = tree.perm.info.packageName; 3417 bp.uid = tree.uid; 3418 if (added) { 3419 mSettings.mPermissions.put(info.name, bp); 3420 } 3421 if (changed) { 3422 if (!async) { 3423 mSettings.writeLPr(); 3424 } else { 3425 scheduleWriteSettingsLocked(); 3426 } 3427 } 3428 return added; 3429 } 3430 3431 @Override 3432 public boolean addPermission(PermissionInfo info) { 3433 synchronized (mPackages) { 3434 return addPermissionLocked(info, false); 3435 } 3436 } 3437 3438 @Override 3439 public boolean addPermissionAsync(PermissionInfo info) { 3440 synchronized (mPackages) { 3441 return addPermissionLocked(info, true); 3442 } 3443 } 3444 3445 @Override 3446 public void removePermission(String name) { 3447 synchronized (mPackages) { 3448 checkPermissionTreeLP(name); 3449 BasePermission bp = mSettings.mPermissions.get(name); 3450 if (bp != null) { 3451 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3452 throw new SecurityException( 3453 "Not allowed to modify non-dynamic permission " 3454 + name); 3455 } 3456 mSettings.mPermissions.remove(name); 3457 mSettings.writeLPr(); 3458 } 3459 } 3460 } 3461 3462 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3463 BasePermission bp) { 3464 int index = pkg.requestedPermissions.indexOf(bp.name); 3465 if (index == -1) { 3466 throw new SecurityException("Package " + pkg.packageName 3467 + " has not requested permission " + bp.name); 3468 } 3469 if (!bp.isRuntime() && !bp.isDevelopment()) { 3470 throw new SecurityException("Permission " + bp.name 3471 + " is not a changeable permission type"); 3472 } 3473 } 3474 3475 @Override 3476 public void grantRuntimePermission(String packageName, String name, final int userId) { 3477 if (!sUserManager.exists(userId)) { 3478 Log.e(TAG, "No such user:" + userId); 3479 return; 3480 } 3481 3482 mContext.enforceCallingOrSelfPermission( 3483 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3484 "grantRuntimePermission"); 3485 3486 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3487 "grantRuntimePermission"); 3488 3489 final int uid; 3490 final SettingBase sb; 3491 3492 synchronized (mPackages) { 3493 final PackageParser.Package pkg = mPackages.get(packageName); 3494 if (pkg == null) { 3495 throw new IllegalArgumentException("Unknown package: " + packageName); 3496 } 3497 3498 final BasePermission bp = mSettings.mPermissions.get(name); 3499 if (bp == null) { 3500 throw new IllegalArgumentException("Unknown permission: " + name); 3501 } 3502 3503 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3504 3505 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3506 sb = (SettingBase) pkg.mExtras; 3507 if (sb == null) { 3508 throw new IllegalArgumentException("Unknown package: " + packageName); 3509 } 3510 3511 final PermissionsState permissionsState = sb.getPermissionsState(); 3512 3513 final int flags = permissionsState.getPermissionFlags(name, userId); 3514 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3515 throw new SecurityException("Cannot grant system fixed permission: " 3516 + name + " for package: " + packageName); 3517 } 3518 3519 if (bp.isDevelopment()) { 3520 // Development permissions must be handled specially, since they are not 3521 // normal runtime permissions. For now they apply to all users. 3522 if (permissionsState.grantInstallPermission(bp) != 3523 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3524 scheduleWriteSettingsLocked(); 3525 } 3526 return; 3527 } 3528 3529 final int result = permissionsState.grantRuntimePermission(bp, userId); 3530 switch (result) { 3531 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3532 return; 3533 } 3534 3535 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3536 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3537 mHandler.post(new Runnable() { 3538 @Override 3539 public void run() { 3540 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3541 } 3542 }); 3543 } 3544 break; 3545 } 3546 3547 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3548 3549 // Not critical if that is lost - app has to request again. 3550 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3551 } 3552 3553 // Only need to do this if user is initialized. Otherwise it's a new user 3554 // and there are no processes running as the user yet and there's no need 3555 // to make an expensive call to remount processes for the changed permissions. 3556 if (READ_EXTERNAL_STORAGE.equals(name) 3557 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3558 final long token = Binder.clearCallingIdentity(); 3559 try { 3560 if (sUserManager.isInitialized(userId)) { 3561 MountServiceInternal mountServiceInternal = LocalServices.getService( 3562 MountServiceInternal.class); 3563 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3564 } 3565 } finally { 3566 Binder.restoreCallingIdentity(token); 3567 } 3568 } 3569 } 3570 3571 @Override 3572 public void revokeRuntimePermission(String packageName, String name, int userId) { 3573 if (!sUserManager.exists(userId)) { 3574 Log.e(TAG, "No such user:" + userId); 3575 return; 3576 } 3577 3578 mContext.enforceCallingOrSelfPermission( 3579 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3580 "revokeRuntimePermission"); 3581 3582 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3583 "revokeRuntimePermission"); 3584 3585 final int appId; 3586 3587 synchronized (mPackages) { 3588 final PackageParser.Package pkg = mPackages.get(packageName); 3589 if (pkg == null) { 3590 throw new IllegalArgumentException("Unknown package: " + packageName); 3591 } 3592 3593 final BasePermission bp = mSettings.mPermissions.get(name); 3594 if (bp == null) { 3595 throw new IllegalArgumentException("Unknown permission: " + name); 3596 } 3597 3598 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3599 3600 SettingBase sb = (SettingBase) pkg.mExtras; 3601 if (sb == null) { 3602 throw new IllegalArgumentException("Unknown package: " + packageName); 3603 } 3604 3605 final PermissionsState permissionsState = sb.getPermissionsState(); 3606 3607 final int flags = permissionsState.getPermissionFlags(name, userId); 3608 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3609 throw new SecurityException("Cannot revoke system fixed permission: " 3610 + name + " for package: " + packageName); 3611 } 3612 3613 if (bp.isDevelopment()) { 3614 // Development permissions must be handled specially, since they are not 3615 // normal runtime permissions. For now they apply to all users. 3616 if (permissionsState.revokeInstallPermission(bp) != 3617 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3618 scheduleWriteSettingsLocked(); 3619 } 3620 return; 3621 } 3622 3623 if (permissionsState.revokeRuntimePermission(bp, userId) == 3624 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3625 return; 3626 } 3627 3628 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3629 3630 // Critical, after this call app should never have the permission. 3631 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3632 3633 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3634 } 3635 3636 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3637 } 3638 3639 @Override 3640 public void resetRuntimePermissions() { 3641 mContext.enforceCallingOrSelfPermission( 3642 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3643 "revokeRuntimePermission"); 3644 3645 int callingUid = Binder.getCallingUid(); 3646 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3647 mContext.enforceCallingOrSelfPermission( 3648 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3649 "resetRuntimePermissions"); 3650 } 3651 3652 synchronized (mPackages) { 3653 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3654 for (int userId : UserManagerService.getInstance().getUserIds()) { 3655 final int packageCount = mPackages.size(); 3656 for (int i = 0; i < packageCount; i++) { 3657 PackageParser.Package pkg = mPackages.valueAt(i); 3658 if (!(pkg.mExtras instanceof PackageSetting)) { 3659 continue; 3660 } 3661 PackageSetting ps = (PackageSetting) pkg.mExtras; 3662 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3663 } 3664 } 3665 } 3666 } 3667 3668 @Override 3669 public int getPermissionFlags(String name, String packageName, int userId) { 3670 if (!sUserManager.exists(userId)) { 3671 return 0; 3672 } 3673 3674 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3675 3676 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3677 "getPermissionFlags"); 3678 3679 synchronized (mPackages) { 3680 final PackageParser.Package pkg = mPackages.get(packageName); 3681 if (pkg == null) { 3682 throw new IllegalArgumentException("Unknown package: " + packageName); 3683 } 3684 3685 final BasePermission bp = mSettings.mPermissions.get(name); 3686 if (bp == null) { 3687 throw new IllegalArgumentException("Unknown permission: " + name); 3688 } 3689 3690 SettingBase sb = (SettingBase) pkg.mExtras; 3691 if (sb == null) { 3692 throw new IllegalArgumentException("Unknown package: " + packageName); 3693 } 3694 3695 PermissionsState permissionsState = sb.getPermissionsState(); 3696 return permissionsState.getPermissionFlags(name, userId); 3697 } 3698 } 3699 3700 @Override 3701 public void updatePermissionFlags(String name, String packageName, int flagMask, 3702 int flagValues, int userId) { 3703 if (!sUserManager.exists(userId)) { 3704 return; 3705 } 3706 3707 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3708 3709 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3710 "updatePermissionFlags"); 3711 3712 // Only the system can change these flags and nothing else. 3713 if (getCallingUid() != Process.SYSTEM_UID) { 3714 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3715 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3716 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3717 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3718 } 3719 3720 synchronized (mPackages) { 3721 final PackageParser.Package pkg = mPackages.get(packageName); 3722 if (pkg == null) { 3723 throw new IllegalArgumentException("Unknown package: " + packageName); 3724 } 3725 3726 final BasePermission bp = mSettings.mPermissions.get(name); 3727 if (bp == null) { 3728 throw new IllegalArgumentException("Unknown permission: " + name); 3729 } 3730 3731 SettingBase sb = (SettingBase) pkg.mExtras; 3732 if (sb == null) { 3733 throw new IllegalArgumentException("Unknown package: " + packageName); 3734 } 3735 3736 PermissionsState permissionsState = sb.getPermissionsState(); 3737 3738 // Only the package manager can change flags for system component permissions. 3739 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3740 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3741 return; 3742 } 3743 3744 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3745 3746 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3747 // Install and runtime permissions are stored in different places, 3748 // so figure out what permission changed and persist the change. 3749 if (permissionsState.getInstallPermissionState(name) != null) { 3750 scheduleWriteSettingsLocked(); 3751 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3752 || hadState) { 3753 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3754 } 3755 } 3756 } 3757 } 3758 3759 /** 3760 * Update the permission flags for all packages and runtime permissions of a user in order 3761 * to allow device or profile owner to remove POLICY_FIXED. 3762 */ 3763 @Override 3764 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3765 if (!sUserManager.exists(userId)) { 3766 return; 3767 } 3768 3769 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3770 3771 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3772 "updatePermissionFlagsForAllApps"); 3773 3774 // Only the system can change system fixed flags. 3775 if (getCallingUid() != Process.SYSTEM_UID) { 3776 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3777 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3778 } 3779 3780 synchronized (mPackages) { 3781 boolean changed = false; 3782 final int packageCount = mPackages.size(); 3783 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3784 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3785 SettingBase sb = (SettingBase) pkg.mExtras; 3786 if (sb == null) { 3787 continue; 3788 } 3789 PermissionsState permissionsState = sb.getPermissionsState(); 3790 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3791 userId, flagMask, flagValues); 3792 } 3793 if (changed) { 3794 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3795 } 3796 } 3797 } 3798 3799 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3800 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3801 != PackageManager.PERMISSION_GRANTED 3802 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3803 != PackageManager.PERMISSION_GRANTED) { 3804 throw new SecurityException(message + " requires " 3805 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3806 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3807 } 3808 } 3809 3810 @Override 3811 public boolean shouldShowRequestPermissionRationale(String permissionName, 3812 String packageName, int userId) { 3813 if (UserHandle.getCallingUserId() != userId) { 3814 mContext.enforceCallingPermission( 3815 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3816 "canShowRequestPermissionRationale for user " + userId); 3817 } 3818 3819 final int uid = getPackageUid(packageName, userId); 3820 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3821 return false; 3822 } 3823 3824 if (checkPermission(permissionName, packageName, userId) 3825 == PackageManager.PERMISSION_GRANTED) { 3826 return false; 3827 } 3828 3829 final int flags; 3830 3831 final long identity = Binder.clearCallingIdentity(); 3832 try { 3833 flags = getPermissionFlags(permissionName, 3834 packageName, userId); 3835 } finally { 3836 Binder.restoreCallingIdentity(identity); 3837 } 3838 3839 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3840 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3841 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3842 3843 if ((flags & fixedFlags) != 0) { 3844 return false; 3845 } 3846 3847 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3848 } 3849 3850 @Override 3851 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3852 mContext.enforceCallingOrSelfPermission( 3853 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3854 "addOnPermissionsChangeListener"); 3855 3856 synchronized (mPackages) { 3857 mOnPermissionChangeListeners.addListenerLocked(listener); 3858 } 3859 } 3860 3861 @Override 3862 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3863 synchronized (mPackages) { 3864 mOnPermissionChangeListeners.removeListenerLocked(listener); 3865 } 3866 } 3867 3868 @Override 3869 public boolean isProtectedBroadcast(String actionName) { 3870 synchronized (mPackages) { 3871 return mProtectedBroadcasts.contains(actionName); 3872 } 3873 } 3874 3875 @Override 3876 public int checkSignatures(String pkg1, String pkg2) { 3877 synchronized (mPackages) { 3878 final PackageParser.Package p1 = mPackages.get(pkg1); 3879 final PackageParser.Package p2 = mPackages.get(pkg2); 3880 if (p1 == null || p1.mExtras == null 3881 || p2 == null || p2.mExtras == null) { 3882 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3883 } 3884 return compareSignatures(p1.mSignatures, p2.mSignatures); 3885 } 3886 } 3887 3888 @Override 3889 public int checkUidSignatures(int uid1, int uid2) { 3890 // Map to base uids. 3891 uid1 = UserHandle.getAppId(uid1); 3892 uid2 = UserHandle.getAppId(uid2); 3893 // reader 3894 synchronized (mPackages) { 3895 Signature[] s1; 3896 Signature[] s2; 3897 Object obj = mSettings.getUserIdLPr(uid1); 3898 if (obj != null) { 3899 if (obj instanceof SharedUserSetting) { 3900 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3901 } else if (obj instanceof PackageSetting) { 3902 s1 = ((PackageSetting)obj).signatures.mSignatures; 3903 } else { 3904 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3905 } 3906 } else { 3907 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3908 } 3909 obj = mSettings.getUserIdLPr(uid2); 3910 if (obj != null) { 3911 if (obj instanceof SharedUserSetting) { 3912 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3913 } else if (obj instanceof PackageSetting) { 3914 s2 = ((PackageSetting)obj).signatures.mSignatures; 3915 } else { 3916 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3917 } 3918 } else { 3919 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3920 } 3921 return compareSignatures(s1, s2); 3922 } 3923 } 3924 3925 private void killUid(int appId, int userId, String reason) { 3926 final long identity = Binder.clearCallingIdentity(); 3927 try { 3928 IActivityManager am = ActivityManagerNative.getDefault(); 3929 if (am != null) { 3930 try { 3931 am.killUid(appId, userId, reason); 3932 } catch (RemoteException e) { 3933 /* ignore - same process */ 3934 } 3935 } 3936 } finally { 3937 Binder.restoreCallingIdentity(identity); 3938 } 3939 } 3940 3941 /** 3942 * Compares two sets of signatures. Returns: 3943 * <br /> 3944 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3945 * <br /> 3946 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3947 * <br /> 3948 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3949 * <br /> 3950 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3951 * <br /> 3952 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3953 */ 3954 static int compareSignatures(Signature[] s1, Signature[] s2) { 3955 if (s1 == null) { 3956 return s2 == null 3957 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3958 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3959 } 3960 3961 if (s2 == null) { 3962 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3963 } 3964 3965 if (s1.length != s2.length) { 3966 return PackageManager.SIGNATURE_NO_MATCH; 3967 } 3968 3969 // Since both signature sets are of size 1, we can compare without HashSets. 3970 if (s1.length == 1) { 3971 return s1[0].equals(s2[0]) ? 3972 PackageManager.SIGNATURE_MATCH : 3973 PackageManager.SIGNATURE_NO_MATCH; 3974 } 3975 3976 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3977 for (Signature sig : s1) { 3978 set1.add(sig); 3979 } 3980 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3981 for (Signature sig : s2) { 3982 set2.add(sig); 3983 } 3984 // Make sure s2 contains all signatures in s1. 3985 if (set1.equals(set2)) { 3986 return PackageManager.SIGNATURE_MATCH; 3987 } 3988 return PackageManager.SIGNATURE_NO_MATCH; 3989 } 3990 3991 /** 3992 * If the database version for this type of package (internal storage or 3993 * external storage) is less than the version where package signatures 3994 * were updated, return true. 3995 */ 3996 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3997 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3998 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3999 } 4000 4001 /** 4002 * Used for backward compatibility to make sure any packages with 4003 * certificate chains get upgraded to the new style. {@code existingSigs} 4004 * will be in the old format (since they were stored on disk from before the 4005 * system upgrade) and {@code scannedSigs} will be in the newer format. 4006 */ 4007 private int compareSignaturesCompat(PackageSignatures existingSigs, 4008 PackageParser.Package scannedPkg) { 4009 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4010 return PackageManager.SIGNATURE_NO_MATCH; 4011 } 4012 4013 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4014 for (Signature sig : existingSigs.mSignatures) { 4015 existingSet.add(sig); 4016 } 4017 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4018 for (Signature sig : scannedPkg.mSignatures) { 4019 try { 4020 Signature[] chainSignatures = sig.getChainSignatures(); 4021 for (Signature chainSig : chainSignatures) { 4022 scannedCompatSet.add(chainSig); 4023 } 4024 } catch (CertificateEncodingException e) { 4025 scannedCompatSet.add(sig); 4026 } 4027 } 4028 /* 4029 * Make sure the expanded scanned set contains all signatures in the 4030 * existing one. 4031 */ 4032 if (scannedCompatSet.equals(existingSet)) { 4033 // Migrate the old signatures to the new scheme. 4034 existingSigs.assignSignatures(scannedPkg.mSignatures); 4035 // The new KeySets will be re-added later in the scanning process. 4036 synchronized (mPackages) { 4037 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4038 } 4039 return PackageManager.SIGNATURE_MATCH; 4040 } 4041 return PackageManager.SIGNATURE_NO_MATCH; 4042 } 4043 4044 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4045 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4046 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4047 } 4048 4049 private int compareSignaturesRecover(PackageSignatures existingSigs, 4050 PackageParser.Package scannedPkg) { 4051 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4052 return PackageManager.SIGNATURE_NO_MATCH; 4053 } 4054 4055 String msg = null; 4056 try { 4057 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4058 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4059 + scannedPkg.packageName); 4060 return PackageManager.SIGNATURE_MATCH; 4061 } 4062 } catch (CertificateException e) { 4063 msg = e.getMessage(); 4064 } 4065 4066 logCriticalInfo(Log.INFO, 4067 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4068 return PackageManager.SIGNATURE_NO_MATCH; 4069 } 4070 4071 @Override 4072 public String[] getPackagesForUid(int uid) { 4073 uid = UserHandle.getAppId(uid); 4074 // reader 4075 synchronized (mPackages) { 4076 Object obj = mSettings.getUserIdLPr(uid); 4077 if (obj instanceof SharedUserSetting) { 4078 final SharedUserSetting sus = (SharedUserSetting) obj; 4079 final int N = sus.packages.size(); 4080 final String[] res = new String[N]; 4081 final Iterator<PackageSetting> it = sus.packages.iterator(); 4082 int i = 0; 4083 while (it.hasNext()) { 4084 res[i++] = it.next().name; 4085 } 4086 return res; 4087 } else if (obj instanceof PackageSetting) { 4088 final PackageSetting ps = (PackageSetting) obj; 4089 return new String[] { ps.name }; 4090 } 4091 } 4092 return null; 4093 } 4094 4095 @Override 4096 public String getNameForUid(int uid) { 4097 // reader 4098 synchronized (mPackages) { 4099 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4100 if (obj instanceof SharedUserSetting) { 4101 final SharedUserSetting sus = (SharedUserSetting) obj; 4102 return sus.name + ":" + sus.userId; 4103 } else if (obj instanceof PackageSetting) { 4104 final PackageSetting ps = (PackageSetting) obj; 4105 return ps.name; 4106 } 4107 } 4108 return null; 4109 } 4110 4111 @Override 4112 public int getUidForSharedUser(String sharedUserName) { 4113 if(sharedUserName == null) { 4114 return -1; 4115 } 4116 // reader 4117 synchronized (mPackages) { 4118 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4119 if (suid == null) { 4120 return -1; 4121 } 4122 return suid.userId; 4123 } 4124 } 4125 4126 @Override 4127 public int getFlagsForUid(int uid) { 4128 synchronized (mPackages) { 4129 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4130 if (obj instanceof SharedUserSetting) { 4131 final SharedUserSetting sus = (SharedUserSetting) obj; 4132 return sus.pkgFlags; 4133 } else if (obj instanceof PackageSetting) { 4134 final PackageSetting ps = (PackageSetting) obj; 4135 return ps.pkgFlags; 4136 } 4137 } 4138 return 0; 4139 } 4140 4141 @Override 4142 public int getPrivateFlagsForUid(int uid) { 4143 synchronized (mPackages) { 4144 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4145 if (obj instanceof SharedUserSetting) { 4146 final SharedUserSetting sus = (SharedUserSetting) obj; 4147 return sus.pkgPrivateFlags; 4148 } else if (obj instanceof PackageSetting) { 4149 final PackageSetting ps = (PackageSetting) obj; 4150 return ps.pkgPrivateFlags; 4151 } 4152 } 4153 return 0; 4154 } 4155 4156 @Override 4157 public boolean isUidPrivileged(int uid) { 4158 uid = UserHandle.getAppId(uid); 4159 // reader 4160 synchronized (mPackages) { 4161 Object obj = mSettings.getUserIdLPr(uid); 4162 if (obj instanceof SharedUserSetting) { 4163 final SharedUserSetting sus = (SharedUserSetting) obj; 4164 final Iterator<PackageSetting> it = sus.packages.iterator(); 4165 while (it.hasNext()) { 4166 if (it.next().isPrivileged()) { 4167 return true; 4168 } 4169 } 4170 } else if (obj instanceof PackageSetting) { 4171 final PackageSetting ps = (PackageSetting) obj; 4172 return ps.isPrivileged(); 4173 } 4174 } 4175 return false; 4176 } 4177 4178 @Override 4179 public String[] getAppOpPermissionPackages(String permissionName) { 4180 synchronized (mPackages) { 4181 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4182 if (pkgs == null) { 4183 return null; 4184 } 4185 return pkgs.toArray(new String[pkgs.size()]); 4186 } 4187 } 4188 4189 @Override 4190 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4191 int flags, int userId) { 4192 if (!sUserManager.exists(userId)) return null; 4193 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4194 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4195 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4196 } 4197 4198 @Override 4199 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4200 IntentFilter filter, int match, ComponentName activity) { 4201 final int userId = UserHandle.getCallingUserId(); 4202 if (DEBUG_PREFERRED) { 4203 Log.v(TAG, "setLastChosenActivity intent=" + intent 4204 + " resolvedType=" + resolvedType 4205 + " flags=" + flags 4206 + " filter=" + filter 4207 + " match=" + match 4208 + " activity=" + activity); 4209 filter.dump(new PrintStreamPrinter(System.out), " "); 4210 } 4211 intent.setComponent(null); 4212 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4213 // Find any earlier preferred or last chosen entries and nuke them 4214 findPreferredActivity(intent, resolvedType, 4215 flags, query, 0, false, true, false, userId); 4216 // Add the new activity as the last chosen for this filter 4217 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4218 "Setting last chosen"); 4219 } 4220 4221 @Override 4222 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4223 final int userId = UserHandle.getCallingUserId(); 4224 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4225 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4226 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4227 false, false, false, userId); 4228 } 4229 4230 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4231 int flags, List<ResolveInfo> query, int userId) { 4232 if (query != null) { 4233 final int N = query.size(); 4234 if (N == 1) { 4235 return query.get(0); 4236 } else if (N > 1) { 4237 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4238 // If there is more than one activity with the same priority, 4239 // then let the user decide between them. 4240 ResolveInfo r0 = query.get(0); 4241 ResolveInfo r1 = query.get(1); 4242 if (DEBUG_INTENT_MATCHING || debug) { 4243 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4244 + r1.activityInfo.name + "=" + r1.priority); 4245 } 4246 // If the first activity has a higher priority, or a different 4247 // default, then it is always desireable to pick it. 4248 if (r0.priority != r1.priority 4249 || r0.preferredOrder != r1.preferredOrder 4250 || r0.isDefault != r1.isDefault) { 4251 return query.get(0); 4252 } 4253 // If we have saved a preference for a preferred activity for 4254 // this Intent, use that. 4255 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4256 flags, query, r0.priority, true, false, debug, userId); 4257 if (ri != null) { 4258 return ri; 4259 } 4260 ri = new ResolveInfo(mResolveInfo); 4261 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4262 ri.activityInfo.applicationInfo = new ApplicationInfo( 4263 ri.activityInfo.applicationInfo); 4264 if (userId != 0) { 4265 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4266 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4267 } 4268 // Make sure that the resolver is displayable in car mode 4269 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4270 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4271 return ri; 4272 } 4273 } 4274 return null; 4275 } 4276 4277 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4278 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4279 final int N = query.size(); 4280 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4281 .get(userId); 4282 // Get the list of persistent preferred activities that handle the intent 4283 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4284 List<PersistentPreferredActivity> pprefs = ppir != null 4285 ? ppir.queryIntent(intent, resolvedType, 4286 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4287 : null; 4288 if (pprefs != null && pprefs.size() > 0) { 4289 final int M = pprefs.size(); 4290 for (int i=0; i<M; i++) { 4291 final PersistentPreferredActivity ppa = pprefs.get(i); 4292 if (DEBUG_PREFERRED || debug) { 4293 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4294 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4295 + "\n component=" + ppa.mComponent); 4296 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4297 } 4298 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4299 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4300 if (DEBUG_PREFERRED || debug) { 4301 Slog.v(TAG, "Found persistent preferred activity:"); 4302 if (ai != null) { 4303 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4304 } else { 4305 Slog.v(TAG, " null"); 4306 } 4307 } 4308 if (ai == null) { 4309 // This previously registered persistent preferred activity 4310 // component is no longer known. Ignore it and do NOT remove it. 4311 continue; 4312 } 4313 for (int j=0; j<N; j++) { 4314 final ResolveInfo ri = query.get(j); 4315 if (!ri.activityInfo.applicationInfo.packageName 4316 .equals(ai.applicationInfo.packageName)) { 4317 continue; 4318 } 4319 if (!ri.activityInfo.name.equals(ai.name)) { 4320 continue; 4321 } 4322 // Found a persistent preference that can handle the intent. 4323 if (DEBUG_PREFERRED || debug) { 4324 Slog.v(TAG, "Returning persistent preferred activity: " + 4325 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4326 } 4327 return ri; 4328 } 4329 } 4330 } 4331 return null; 4332 } 4333 4334 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4335 List<ResolveInfo> query, int priority, boolean always, 4336 boolean removeMatches, boolean debug, int userId) { 4337 if (!sUserManager.exists(userId)) return null; 4338 // writer 4339 synchronized (mPackages) { 4340 if (intent.getSelector() != null) { 4341 intent = intent.getSelector(); 4342 } 4343 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4344 4345 // Try to find a matching persistent preferred activity. 4346 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4347 debug, userId); 4348 4349 // If a persistent preferred activity matched, use it. 4350 if (pri != null) { 4351 return pri; 4352 } 4353 4354 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4355 // Get the list of preferred activities that handle the intent 4356 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4357 List<PreferredActivity> prefs = pir != null 4358 ? pir.queryIntent(intent, resolvedType, 4359 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4360 : null; 4361 if (prefs != null && prefs.size() > 0) { 4362 boolean changed = false; 4363 try { 4364 // First figure out how good the original match set is. 4365 // We will only allow preferred activities that came 4366 // from the same match quality. 4367 int match = 0; 4368 4369 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4370 4371 final int N = query.size(); 4372 for (int j=0; j<N; j++) { 4373 final ResolveInfo ri = query.get(j); 4374 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4375 + ": 0x" + Integer.toHexString(match)); 4376 if (ri.match > match) { 4377 match = ri.match; 4378 } 4379 } 4380 4381 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4382 + Integer.toHexString(match)); 4383 4384 match &= IntentFilter.MATCH_CATEGORY_MASK; 4385 final int M = prefs.size(); 4386 for (int i=0; i<M; i++) { 4387 final PreferredActivity pa = prefs.get(i); 4388 if (DEBUG_PREFERRED || debug) { 4389 Slog.v(TAG, "Checking PreferredActivity ds=" 4390 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4391 + "\n component=" + pa.mPref.mComponent); 4392 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4393 } 4394 if (pa.mPref.mMatch != match) { 4395 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4396 + Integer.toHexString(pa.mPref.mMatch)); 4397 continue; 4398 } 4399 // If it's not an "always" type preferred activity and that's what we're 4400 // looking for, skip it. 4401 if (always && !pa.mPref.mAlways) { 4402 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4403 continue; 4404 } 4405 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4406 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4407 if (DEBUG_PREFERRED || debug) { 4408 Slog.v(TAG, "Found preferred activity:"); 4409 if (ai != null) { 4410 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4411 } else { 4412 Slog.v(TAG, " null"); 4413 } 4414 } 4415 if (ai == null) { 4416 // This previously registered preferred activity 4417 // component is no longer known. Most likely an update 4418 // to the app was installed and in the new version this 4419 // component no longer exists. Clean it up by removing 4420 // it from the preferred activities list, and skip it. 4421 Slog.w(TAG, "Removing dangling preferred activity: " 4422 + pa.mPref.mComponent); 4423 pir.removeFilter(pa); 4424 changed = true; 4425 continue; 4426 } 4427 for (int j=0; j<N; j++) { 4428 final ResolveInfo ri = query.get(j); 4429 if (!ri.activityInfo.applicationInfo.packageName 4430 .equals(ai.applicationInfo.packageName)) { 4431 continue; 4432 } 4433 if (!ri.activityInfo.name.equals(ai.name)) { 4434 continue; 4435 } 4436 4437 if (removeMatches) { 4438 pir.removeFilter(pa); 4439 changed = true; 4440 if (DEBUG_PREFERRED) { 4441 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4442 } 4443 break; 4444 } 4445 4446 // Okay we found a previously set preferred or last chosen app. 4447 // If the result set is different from when this 4448 // was created, we need to clear it and re-ask the 4449 // user their preference, if we're looking for an "always" type entry. 4450 if (always && !pa.mPref.sameSet(query)) { 4451 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4452 + intent + " type " + resolvedType); 4453 if (DEBUG_PREFERRED) { 4454 Slog.v(TAG, "Removing preferred activity since set changed " 4455 + pa.mPref.mComponent); 4456 } 4457 pir.removeFilter(pa); 4458 // Re-add the filter as a "last chosen" entry (!always) 4459 PreferredActivity lastChosen = new PreferredActivity( 4460 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4461 pir.addFilter(lastChosen); 4462 changed = true; 4463 return null; 4464 } 4465 4466 // Yay! Either the set matched or we're looking for the last chosen 4467 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4468 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4469 return ri; 4470 } 4471 } 4472 } finally { 4473 if (changed) { 4474 if (DEBUG_PREFERRED) { 4475 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4476 } 4477 scheduleWritePackageRestrictionsLocked(userId); 4478 } 4479 } 4480 } 4481 } 4482 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4483 return null; 4484 } 4485 4486 /* 4487 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4488 */ 4489 @Override 4490 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4491 int targetUserId) { 4492 mContext.enforceCallingOrSelfPermission( 4493 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4494 List<CrossProfileIntentFilter> matches = 4495 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4496 if (matches != null) { 4497 int size = matches.size(); 4498 for (int i = 0; i < size; i++) { 4499 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4500 } 4501 } 4502 if (hasWebURI(intent)) { 4503 // cross-profile app linking works only towards the parent. 4504 final UserInfo parent = getProfileParent(sourceUserId); 4505 synchronized(mPackages) { 4506 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4507 intent, resolvedType, 0, sourceUserId, parent.id); 4508 return xpDomainInfo != null; 4509 } 4510 } 4511 return false; 4512 } 4513 4514 private UserInfo getProfileParent(int userId) { 4515 final long identity = Binder.clearCallingIdentity(); 4516 try { 4517 return sUserManager.getProfileParent(userId); 4518 } finally { 4519 Binder.restoreCallingIdentity(identity); 4520 } 4521 } 4522 4523 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4524 String resolvedType, int userId) { 4525 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4526 if (resolver != null) { 4527 return resolver.queryIntent(intent, resolvedType, false, userId); 4528 } 4529 return null; 4530 } 4531 4532 @Override 4533 public List<ResolveInfo> queryIntentActivities(Intent intent, 4534 String resolvedType, int flags, int userId) { 4535 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4536 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4537 ComponentName comp = intent.getComponent(); 4538 if (comp == null) { 4539 if (intent.getSelector() != null) { 4540 intent = intent.getSelector(); 4541 comp = intent.getComponent(); 4542 } 4543 } 4544 4545 if (comp != null) { 4546 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4547 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4548 if (ai != null) { 4549 final ResolveInfo ri = new ResolveInfo(); 4550 ri.activityInfo = ai; 4551 list.add(ri); 4552 } 4553 return list; 4554 } 4555 4556 // reader 4557 synchronized (mPackages) { 4558 final String pkgName = intent.getPackage(); 4559 if (pkgName == null) { 4560 List<CrossProfileIntentFilter> matchingFilters = 4561 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4562 // Check for results that need to skip the current profile. 4563 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4564 resolvedType, flags, userId); 4565 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4566 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4567 result.add(xpResolveInfo); 4568 return filterIfNotPrimaryUser(result, userId); 4569 } 4570 4571 // Check for results in the current profile. 4572 List<ResolveInfo> result = mActivities.queryIntent( 4573 intent, resolvedType, flags, userId); 4574 4575 // Check for cross profile results. 4576 xpResolveInfo = queryCrossProfileIntents( 4577 matchingFilters, intent, resolvedType, flags, userId); 4578 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4579 result.add(xpResolveInfo); 4580 Collections.sort(result, mResolvePrioritySorter); 4581 } 4582 result = filterIfNotPrimaryUser(result, userId); 4583 if (hasWebURI(intent)) { 4584 CrossProfileDomainInfo xpDomainInfo = null; 4585 final UserInfo parent = getProfileParent(userId); 4586 if (parent != null) { 4587 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4588 flags, userId, parent.id); 4589 } 4590 if (xpDomainInfo != null) { 4591 if (xpResolveInfo != null) { 4592 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4593 // in the result. 4594 result.remove(xpResolveInfo); 4595 } 4596 if (result.size() == 0) { 4597 result.add(xpDomainInfo.resolveInfo); 4598 return result; 4599 } 4600 } else if (result.size() <= 1) { 4601 return result; 4602 } 4603 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4604 xpDomainInfo, userId); 4605 Collections.sort(result, mResolvePrioritySorter); 4606 } 4607 return result; 4608 } 4609 final PackageParser.Package pkg = mPackages.get(pkgName); 4610 if (pkg != null) { 4611 return filterIfNotPrimaryUser( 4612 mActivities.queryIntentForPackage( 4613 intent, resolvedType, flags, pkg.activities, userId), 4614 userId); 4615 } 4616 return new ArrayList<ResolveInfo>(); 4617 } 4618 } 4619 4620 private static class CrossProfileDomainInfo { 4621 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4622 ResolveInfo resolveInfo; 4623 /* Best domain verification status of the activities found in the other profile */ 4624 int bestDomainVerificationStatus; 4625 } 4626 4627 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4628 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4629 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4630 sourceUserId)) { 4631 return null; 4632 } 4633 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4634 resolvedType, flags, parentUserId); 4635 4636 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4637 return null; 4638 } 4639 CrossProfileDomainInfo result = null; 4640 int size = resultTargetUser.size(); 4641 for (int i = 0; i < size; i++) { 4642 ResolveInfo riTargetUser = resultTargetUser.get(i); 4643 // Intent filter verification is only for filters that specify a host. So don't return 4644 // those that handle all web uris. 4645 if (riTargetUser.handleAllWebDataURI) { 4646 continue; 4647 } 4648 String packageName = riTargetUser.activityInfo.packageName; 4649 PackageSetting ps = mSettings.mPackages.get(packageName); 4650 if (ps == null) { 4651 continue; 4652 } 4653 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4654 int status = (int)(verificationState >> 32); 4655 if (result == null) { 4656 result = new CrossProfileDomainInfo(); 4657 result.resolveInfo = 4658 createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId); 4659 result.bestDomainVerificationStatus = status; 4660 } else { 4661 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4662 result.bestDomainVerificationStatus); 4663 } 4664 } 4665 // Don't consider matches with status NEVER across profiles. 4666 if (result != null && result.bestDomainVerificationStatus 4667 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4668 return null; 4669 } 4670 return result; 4671 } 4672 4673 /** 4674 * Verification statuses are ordered from the worse to the best, except for 4675 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4676 */ 4677 private int bestDomainVerificationStatus(int status1, int status2) { 4678 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4679 return status2; 4680 } 4681 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4682 return status1; 4683 } 4684 return (int) MathUtils.max(status1, status2); 4685 } 4686 4687 private boolean isUserEnabled(int userId) { 4688 long callingId = Binder.clearCallingIdentity(); 4689 try { 4690 UserInfo userInfo = sUserManager.getUserInfo(userId); 4691 return userInfo != null && userInfo.isEnabled(); 4692 } finally { 4693 Binder.restoreCallingIdentity(callingId); 4694 } 4695 } 4696 4697 /** 4698 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4699 * 4700 * @return filtered list 4701 */ 4702 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4703 if (userId == UserHandle.USER_OWNER) { 4704 return resolveInfos; 4705 } 4706 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4707 ResolveInfo info = resolveInfos.get(i); 4708 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4709 resolveInfos.remove(i); 4710 } 4711 } 4712 return resolveInfos; 4713 } 4714 4715 private static boolean hasWebURI(Intent intent) { 4716 if (intent.getData() == null) { 4717 return false; 4718 } 4719 final String scheme = intent.getScheme(); 4720 if (TextUtils.isEmpty(scheme)) { 4721 return false; 4722 } 4723 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4724 } 4725 4726 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4727 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4728 int userId) { 4729 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4730 4731 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4732 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4733 candidates.size()); 4734 } 4735 4736 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4737 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4738 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4739 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4740 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4741 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4742 4743 synchronized (mPackages) { 4744 final int count = candidates.size(); 4745 // First, try to use linked apps. Partition the candidates into four lists: 4746 // one for the final results, one for the "do not use ever", one for "undefined status" 4747 // and finally one for "browser app type". 4748 for (int n=0; n<count; n++) { 4749 ResolveInfo info = candidates.get(n); 4750 String packageName = info.activityInfo.packageName; 4751 PackageSetting ps = mSettings.mPackages.get(packageName); 4752 if (ps != null) { 4753 // Add to the special match all list (Browser use case) 4754 if (info.handleAllWebDataURI) { 4755 matchAllList.add(info); 4756 continue; 4757 } 4758 // Try to get the status from User settings first 4759 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4760 int status = (int)(packedStatus >> 32); 4761 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4762 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4763 if (DEBUG_DOMAIN_VERIFICATION) { 4764 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4765 + " : linkgen=" + linkGeneration); 4766 } 4767 // Use link-enabled generation as preferredOrder, i.e. 4768 // prefer newly-enabled over earlier-enabled. 4769 info.preferredOrder = linkGeneration; 4770 alwaysList.add(info); 4771 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4772 if (DEBUG_DOMAIN_VERIFICATION) { 4773 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4774 } 4775 neverList.add(info); 4776 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4777 if (DEBUG_DOMAIN_VERIFICATION) { 4778 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4779 } 4780 alwaysAskList.add(info); 4781 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4782 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4783 if (DEBUG_DOMAIN_VERIFICATION) { 4784 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4785 } 4786 undefinedList.add(info); 4787 } 4788 } 4789 } 4790 4791 // We'll want to include browser possibilities in a few cases 4792 boolean includeBrowser = false; 4793 4794 // First try to add the "always" resolution(s) for the current user, if any 4795 if (alwaysList.size() > 0) { 4796 result.addAll(alwaysList); 4797 } else { 4798 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4799 result.addAll(undefinedList); 4800 // Maybe add one for the other profile. 4801 if (xpDomainInfo != null && ( 4802 xpDomainInfo.bestDomainVerificationStatus 4803 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 4804 result.add(xpDomainInfo.resolveInfo); 4805 } 4806 includeBrowser = true; 4807 } 4808 4809 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4810 // If there were 'always' entries their preferred order has been set, so we also 4811 // back that off to make the alternatives equivalent 4812 if (alwaysAskList.size() > 0) { 4813 for (ResolveInfo i : result) { 4814 i.preferredOrder = 0; 4815 } 4816 result.addAll(alwaysAskList); 4817 includeBrowser = true; 4818 } 4819 4820 if (includeBrowser) { 4821 // Also add browsers (all of them or only the default one) 4822 if (DEBUG_DOMAIN_VERIFICATION) { 4823 Slog.v(TAG, " ...including browsers in candidate set"); 4824 } 4825 if ((matchFlags & MATCH_ALL) != 0) { 4826 result.addAll(matchAllList); 4827 } else { 4828 // Browser/generic handling case. If there's a default browser, go straight 4829 // to that (but only if there is no other higher-priority match). 4830 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4831 int maxMatchPrio = 0; 4832 ResolveInfo defaultBrowserMatch = null; 4833 final int numCandidates = matchAllList.size(); 4834 for (int n = 0; n < numCandidates; n++) { 4835 ResolveInfo info = matchAllList.get(n); 4836 // track the highest overall match priority... 4837 if (info.priority > maxMatchPrio) { 4838 maxMatchPrio = info.priority; 4839 } 4840 // ...and the highest-priority default browser match 4841 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4842 if (defaultBrowserMatch == null 4843 || (defaultBrowserMatch.priority < info.priority)) { 4844 if (debug) { 4845 Slog.v(TAG, "Considering default browser match " + info); 4846 } 4847 defaultBrowserMatch = info; 4848 } 4849 } 4850 } 4851 if (defaultBrowserMatch != null 4852 && defaultBrowserMatch.priority >= maxMatchPrio 4853 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4854 { 4855 if (debug) { 4856 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4857 } 4858 result.add(defaultBrowserMatch); 4859 } else { 4860 result.addAll(matchAllList); 4861 } 4862 } 4863 4864 // If there is nothing selected, add all candidates and remove the ones that the user 4865 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4866 if (result.size() == 0) { 4867 result.addAll(candidates); 4868 result.removeAll(neverList); 4869 } 4870 } 4871 } 4872 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4873 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4874 result.size()); 4875 for (ResolveInfo info : result) { 4876 Slog.v(TAG, " + " + info.activityInfo); 4877 } 4878 } 4879 return result; 4880 } 4881 4882 // Returns a packed value as a long: 4883 // 4884 // high 'int'-sized word: link status: undefined/ask/never/always. 4885 // low 'int'-sized word: relative priority among 'always' results. 4886 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4887 long result = ps.getDomainVerificationStatusForUser(userId); 4888 // if none available, get the master status 4889 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4890 if (ps.getIntentFilterVerificationInfo() != null) { 4891 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4892 } 4893 } 4894 return result; 4895 } 4896 4897 private ResolveInfo querySkipCurrentProfileIntents( 4898 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4899 int flags, int sourceUserId) { 4900 if (matchingFilters != null) { 4901 int size = matchingFilters.size(); 4902 for (int i = 0; i < size; i ++) { 4903 CrossProfileIntentFilter filter = matchingFilters.get(i); 4904 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4905 // Checking if there are activities in the target user that can handle the 4906 // intent. 4907 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4908 flags, sourceUserId); 4909 if (resolveInfo != null) { 4910 return resolveInfo; 4911 } 4912 } 4913 } 4914 } 4915 return null; 4916 } 4917 4918 // Return matching ResolveInfo if any for skip current profile intent filters. 4919 private ResolveInfo queryCrossProfileIntents( 4920 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4921 int flags, int sourceUserId) { 4922 if (matchingFilters != null) { 4923 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4924 // match the same intent. For performance reasons, it is better not to 4925 // run queryIntent twice for the same userId 4926 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4927 int size = matchingFilters.size(); 4928 for (int i = 0; i < size; i++) { 4929 CrossProfileIntentFilter filter = matchingFilters.get(i); 4930 int targetUserId = filter.getTargetUserId(); 4931 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4932 && !alreadyTriedUserIds.get(targetUserId)) { 4933 // Checking if there are activities in the target user that can handle the 4934 // intent. 4935 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4936 flags, sourceUserId); 4937 if (resolveInfo != null) return resolveInfo; 4938 alreadyTriedUserIds.put(targetUserId, true); 4939 } 4940 } 4941 } 4942 return null; 4943 } 4944 4945 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4946 String resolvedType, int flags, int sourceUserId) { 4947 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4948 resolvedType, flags, filter.getTargetUserId()); 4949 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4950 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4951 } 4952 return null; 4953 } 4954 4955 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4956 int sourceUserId, int targetUserId) { 4957 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4958 String className; 4959 if (targetUserId == UserHandle.USER_OWNER) { 4960 className = FORWARD_INTENT_TO_USER_OWNER; 4961 } else { 4962 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4963 } 4964 ComponentName forwardingActivityComponentName = new ComponentName( 4965 mAndroidApplication.packageName, className); 4966 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4967 sourceUserId); 4968 if (targetUserId == UserHandle.USER_OWNER) { 4969 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4970 forwardingResolveInfo.noResourceId = true; 4971 } 4972 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4973 forwardingResolveInfo.priority = 0; 4974 forwardingResolveInfo.preferredOrder = 0; 4975 forwardingResolveInfo.match = 0; 4976 forwardingResolveInfo.isDefault = true; 4977 forwardingResolveInfo.filter = filter; 4978 forwardingResolveInfo.targetUserId = targetUserId; 4979 return forwardingResolveInfo; 4980 } 4981 4982 @Override 4983 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4984 Intent[] specifics, String[] specificTypes, Intent intent, 4985 String resolvedType, int flags, int userId) { 4986 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4987 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4988 false, "query intent activity options"); 4989 final String resultsAction = intent.getAction(); 4990 4991 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4992 | PackageManager.GET_RESOLVED_FILTER, userId); 4993 4994 if (DEBUG_INTENT_MATCHING) { 4995 Log.v(TAG, "Query " + intent + ": " + results); 4996 } 4997 4998 int specificsPos = 0; 4999 int N; 5000 5001 // todo: note that the algorithm used here is O(N^2). This 5002 // isn't a problem in our current environment, but if we start running 5003 // into situations where we have more than 5 or 10 matches then this 5004 // should probably be changed to something smarter... 5005 5006 // First we go through and resolve each of the specific items 5007 // that were supplied, taking care of removing any corresponding 5008 // duplicate items in the generic resolve list. 5009 if (specifics != null) { 5010 for (int i=0; i<specifics.length; i++) { 5011 final Intent sintent = specifics[i]; 5012 if (sintent == null) { 5013 continue; 5014 } 5015 5016 if (DEBUG_INTENT_MATCHING) { 5017 Log.v(TAG, "Specific #" + i + ": " + sintent); 5018 } 5019 5020 String action = sintent.getAction(); 5021 if (resultsAction != null && resultsAction.equals(action)) { 5022 // If this action was explicitly requested, then don't 5023 // remove things that have it. 5024 action = null; 5025 } 5026 5027 ResolveInfo ri = null; 5028 ActivityInfo ai = null; 5029 5030 ComponentName comp = sintent.getComponent(); 5031 if (comp == null) { 5032 ri = resolveIntent( 5033 sintent, 5034 specificTypes != null ? specificTypes[i] : null, 5035 flags, userId); 5036 if (ri == null) { 5037 continue; 5038 } 5039 if (ri == mResolveInfo) { 5040 // ACK! Must do something better with this. 5041 } 5042 ai = ri.activityInfo; 5043 comp = new ComponentName(ai.applicationInfo.packageName, 5044 ai.name); 5045 } else { 5046 ai = getActivityInfo(comp, flags, userId); 5047 if (ai == null) { 5048 continue; 5049 } 5050 } 5051 5052 // Look for any generic query activities that are duplicates 5053 // of this specific one, and remove them from the results. 5054 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5055 N = results.size(); 5056 int j; 5057 for (j=specificsPos; j<N; j++) { 5058 ResolveInfo sri = results.get(j); 5059 if ((sri.activityInfo.name.equals(comp.getClassName()) 5060 && sri.activityInfo.applicationInfo.packageName.equals( 5061 comp.getPackageName())) 5062 || (action != null && sri.filter.matchAction(action))) { 5063 results.remove(j); 5064 if (DEBUG_INTENT_MATCHING) Log.v( 5065 TAG, "Removing duplicate item from " + j 5066 + " due to specific " + specificsPos); 5067 if (ri == null) { 5068 ri = sri; 5069 } 5070 j--; 5071 N--; 5072 } 5073 } 5074 5075 // Add this specific item to its proper place. 5076 if (ri == null) { 5077 ri = new ResolveInfo(); 5078 ri.activityInfo = ai; 5079 } 5080 results.add(specificsPos, ri); 5081 ri.specificIndex = i; 5082 specificsPos++; 5083 } 5084 } 5085 5086 // Now we go through the remaining generic results and remove any 5087 // duplicate actions that are found here. 5088 N = results.size(); 5089 for (int i=specificsPos; i<N-1; i++) { 5090 final ResolveInfo rii = results.get(i); 5091 if (rii.filter == null) { 5092 continue; 5093 } 5094 5095 // Iterate over all of the actions of this result's intent 5096 // filter... typically this should be just one. 5097 final Iterator<String> it = rii.filter.actionsIterator(); 5098 if (it == null) { 5099 continue; 5100 } 5101 while (it.hasNext()) { 5102 final String action = it.next(); 5103 if (resultsAction != null && resultsAction.equals(action)) { 5104 // If this action was explicitly requested, then don't 5105 // remove things that have it. 5106 continue; 5107 } 5108 for (int j=i+1; j<N; j++) { 5109 final ResolveInfo rij = results.get(j); 5110 if (rij.filter != null && rij.filter.hasAction(action)) { 5111 results.remove(j); 5112 if (DEBUG_INTENT_MATCHING) Log.v( 5113 TAG, "Removing duplicate item from " + j 5114 + " due to action " + action + " at " + i); 5115 j--; 5116 N--; 5117 } 5118 } 5119 } 5120 5121 // If the caller didn't request filter information, drop it now 5122 // so we don't have to marshall/unmarshall it. 5123 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5124 rii.filter = null; 5125 } 5126 } 5127 5128 // Filter out the caller activity if so requested. 5129 if (caller != null) { 5130 N = results.size(); 5131 for (int i=0; i<N; i++) { 5132 ActivityInfo ainfo = results.get(i).activityInfo; 5133 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5134 && caller.getClassName().equals(ainfo.name)) { 5135 results.remove(i); 5136 break; 5137 } 5138 } 5139 } 5140 5141 // If the caller didn't request filter information, 5142 // drop them now so we don't have to 5143 // marshall/unmarshall it. 5144 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5145 N = results.size(); 5146 for (int i=0; i<N; i++) { 5147 results.get(i).filter = null; 5148 } 5149 } 5150 5151 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5152 return results; 5153 } 5154 5155 @Override 5156 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5157 int userId) { 5158 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5159 ComponentName comp = intent.getComponent(); 5160 if (comp == null) { 5161 if (intent.getSelector() != null) { 5162 intent = intent.getSelector(); 5163 comp = intent.getComponent(); 5164 } 5165 } 5166 if (comp != null) { 5167 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5168 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5169 if (ai != null) { 5170 ResolveInfo ri = new ResolveInfo(); 5171 ri.activityInfo = ai; 5172 list.add(ri); 5173 } 5174 return list; 5175 } 5176 5177 // reader 5178 synchronized (mPackages) { 5179 String pkgName = intent.getPackage(); 5180 if (pkgName == null) { 5181 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5182 } 5183 final PackageParser.Package pkg = mPackages.get(pkgName); 5184 if (pkg != null) { 5185 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5186 userId); 5187 } 5188 return null; 5189 } 5190 } 5191 5192 @Override 5193 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5194 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5195 if (!sUserManager.exists(userId)) return null; 5196 if (query != null) { 5197 if (query.size() >= 1) { 5198 // If there is more than one service with the same priority, 5199 // just arbitrarily pick the first one. 5200 return query.get(0); 5201 } 5202 } 5203 return null; 5204 } 5205 5206 @Override 5207 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5208 int userId) { 5209 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5210 ComponentName comp = intent.getComponent(); 5211 if (comp == null) { 5212 if (intent.getSelector() != null) { 5213 intent = intent.getSelector(); 5214 comp = intent.getComponent(); 5215 } 5216 } 5217 if (comp != null) { 5218 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5219 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5220 if (si != null) { 5221 final ResolveInfo ri = new ResolveInfo(); 5222 ri.serviceInfo = si; 5223 list.add(ri); 5224 } 5225 return list; 5226 } 5227 5228 // reader 5229 synchronized (mPackages) { 5230 String pkgName = intent.getPackage(); 5231 if (pkgName == null) { 5232 return mServices.queryIntent(intent, resolvedType, flags, userId); 5233 } 5234 final PackageParser.Package pkg = mPackages.get(pkgName); 5235 if (pkg != null) { 5236 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5237 userId); 5238 } 5239 return null; 5240 } 5241 } 5242 5243 @Override 5244 public List<ResolveInfo> queryIntentContentProviders( 5245 Intent intent, String resolvedType, int flags, int userId) { 5246 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5247 ComponentName comp = intent.getComponent(); 5248 if (comp == null) { 5249 if (intent.getSelector() != null) { 5250 intent = intent.getSelector(); 5251 comp = intent.getComponent(); 5252 } 5253 } 5254 if (comp != null) { 5255 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5256 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5257 if (pi != null) { 5258 final ResolveInfo ri = new ResolveInfo(); 5259 ri.providerInfo = pi; 5260 list.add(ri); 5261 } 5262 return list; 5263 } 5264 5265 // reader 5266 synchronized (mPackages) { 5267 String pkgName = intent.getPackage(); 5268 if (pkgName == null) { 5269 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5270 } 5271 final PackageParser.Package pkg = mPackages.get(pkgName); 5272 if (pkg != null) { 5273 return mProviders.queryIntentForPackage( 5274 intent, resolvedType, flags, pkg.providers, userId); 5275 } 5276 return null; 5277 } 5278 } 5279 5280 @Override 5281 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5282 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5283 5284 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5285 5286 // writer 5287 synchronized (mPackages) { 5288 ArrayList<PackageInfo> list; 5289 if (listUninstalled) { 5290 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5291 for (PackageSetting ps : mSettings.mPackages.values()) { 5292 PackageInfo pi; 5293 if (ps.pkg != null) { 5294 pi = generatePackageInfo(ps.pkg, flags, userId); 5295 } else { 5296 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5297 } 5298 if (pi != null) { 5299 list.add(pi); 5300 } 5301 } 5302 } else { 5303 list = new ArrayList<PackageInfo>(mPackages.size()); 5304 for (PackageParser.Package p : mPackages.values()) { 5305 PackageInfo pi = generatePackageInfo(p, flags, userId); 5306 if (pi != null) { 5307 list.add(pi); 5308 } 5309 } 5310 } 5311 5312 return new ParceledListSlice<PackageInfo>(list); 5313 } 5314 } 5315 5316 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5317 String[] permissions, boolean[] tmp, int flags, int userId) { 5318 int numMatch = 0; 5319 final PermissionsState permissionsState = ps.getPermissionsState(); 5320 for (int i=0; i<permissions.length; i++) { 5321 final String permission = permissions[i]; 5322 if (permissionsState.hasPermission(permission, userId)) { 5323 tmp[i] = true; 5324 numMatch++; 5325 } else { 5326 tmp[i] = false; 5327 } 5328 } 5329 if (numMatch == 0) { 5330 return; 5331 } 5332 PackageInfo pi; 5333 if (ps.pkg != null) { 5334 pi = generatePackageInfo(ps.pkg, flags, userId); 5335 } else { 5336 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5337 } 5338 // The above might return null in cases of uninstalled apps or install-state 5339 // skew across users/profiles. 5340 if (pi != null) { 5341 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5342 if (numMatch == permissions.length) { 5343 pi.requestedPermissions = permissions; 5344 } else { 5345 pi.requestedPermissions = new String[numMatch]; 5346 numMatch = 0; 5347 for (int i=0; i<permissions.length; i++) { 5348 if (tmp[i]) { 5349 pi.requestedPermissions[numMatch] = permissions[i]; 5350 numMatch++; 5351 } 5352 } 5353 } 5354 } 5355 list.add(pi); 5356 } 5357 } 5358 5359 @Override 5360 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5361 String[] permissions, int flags, int userId) { 5362 if (!sUserManager.exists(userId)) return null; 5363 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5364 5365 // writer 5366 synchronized (mPackages) { 5367 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5368 boolean[] tmpBools = new boolean[permissions.length]; 5369 if (listUninstalled) { 5370 for (PackageSetting ps : mSettings.mPackages.values()) { 5371 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5372 } 5373 } else { 5374 for (PackageParser.Package pkg : mPackages.values()) { 5375 PackageSetting ps = (PackageSetting)pkg.mExtras; 5376 if (ps != null) { 5377 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5378 userId); 5379 } 5380 } 5381 } 5382 5383 return new ParceledListSlice<PackageInfo>(list); 5384 } 5385 } 5386 5387 @Override 5388 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5389 if (!sUserManager.exists(userId)) return null; 5390 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5391 5392 // writer 5393 synchronized (mPackages) { 5394 ArrayList<ApplicationInfo> list; 5395 if (listUninstalled) { 5396 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5397 for (PackageSetting ps : mSettings.mPackages.values()) { 5398 ApplicationInfo ai; 5399 if (ps.pkg != null) { 5400 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5401 ps.readUserState(userId), userId); 5402 } else { 5403 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5404 } 5405 if (ai != null) { 5406 list.add(ai); 5407 } 5408 } 5409 } else { 5410 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5411 for (PackageParser.Package p : mPackages.values()) { 5412 if (p.mExtras != null) { 5413 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5414 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5415 if (ai != null) { 5416 list.add(ai); 5417 } 5418 } 5419 } 5420 } 5421 5422 return new ParceledListSlice<ApplicationInfo>(list); 5423 } 5424 } 5425 5426 public List<ApplicationInfo> getPersistentApplications(int flags) { 5427 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5428 5429 // reader 5430 synchronized (mPackages) { 5431 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5432 final int userId = UserHandle.getCallingUserId(); 5433 while (i.hasNext()) { 5434 final PackageParser.Package p = i.next(); 5435 if (p.applicationInfo != null 5436 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5437 && (!mSafeMode || isSystemApp(p))) { 5438 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5439 if (ps != null) { 5440 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5441 ps.readUserState(userId), userId); 5442 if (ai != null) { 5443 finalList.add(ai); 5444 } 5445 } 5446 } 5447 } 5448 } 5449 5450 return finalList; 5451 } 5452 5453 @Override 5454 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5455 if (!sUserManager.exists(userId)) return null; 5456 // reader 5457 synchronized (mPackages) { 5458 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5459 PackageSetting ps = provider != null 5460 ? mSettings.mPackages.get(provider.owner.packageName) 5461 : null; 5462 return ps != null 5463 && mSettings.isEnabledLPr(provider.info, flags, userId) 5464 && (!mSafeMode || (provider.info.applicationInfo.flags 5465 &ApplicationInfo.FLAG_SYSTEM) != 0) 5466 ? PackageParser.generateProviderInfo(provider, flags, 5467 ps.readUserState(userId), userId) 5468 : null; 5469 } 5470 } 5471 5472 /** 5473 * @deprecated 5474 */ 5475 @Deprecated 5476 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5477 // reader 5478 synchronized (mPackages) { 5479 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5480 .entrySet().iterator(); 5481 final int userId = UserHandle.getCallingUserId(); 5482 while (i.hasNext()) { 5483 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5484 PackageParser.Provider p = entry.getValue(); 5485 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5486 5487 if (ps != null && p.syncable 5488 && (!mSafeMode || (p.info.applicationInfo.flags 5489 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5490 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5491 ps.readUserState(userId), userId); 5492 if (info != null) { 5493 outNames.add(entry.getKey()); 5494 outInfo.add(info); 5495 } 5496 } 5497 } 5498 } 5499 } 5500 5501 @Override 5502 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5503 int uid, int flags) { 5504 ArrayList<ProviderInfo> finalList = null; 5505 // reader 5506 synchronized (mPackages) { 5507 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5508 final int userId = processName != null ? 5509 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5510 while (i.hasNext()) { 5511 final PackageParser.Provider p = i.next(); 5512 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5513 if (ps != null && p.info.authority != null 5514 && (processName == null 5515 || (p.info.processName.equals(processName) 5516 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5517 && mSettings.isEnabledLPr(p.info, flags, userId) 5518 && (!mSafeMode 5519 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5520 if (finalList == null) { 5521 finalList = new ArrayList<ProviderInfo>(3); 5522 } 5523 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5524 ps.readUserState(userId), userId); 5525 if (info != null) { 5526 finalList.add(info); 5527 } 5528 } 5529 } 5530 } 5531 5532 if (finalList != null) { 5533 Collections.sort(finalList, mProviderInitOrderSorter); 5534 return new ParceledListSlice<ProviderInfo>(finalList); 5535 } 5536 5537 return null; 5538 } 5539 5540 @Override 5541 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5542 int flags) { 5543 // reader 5544 synchronized (mPackages) { 5545 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5546 return PackageParser.generateInstrumentationInfo(i, flags); 5547 } 5548 } 5549 5550 @Override 5551 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5552 int flags) { 5553 ArrayList<InstrumentationInfo> finalList = 5554 new ArrayList<InstrumentationInfo>(); 5555 5556 // reader 5557 synchronized (mPackages) { 5558 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5559 while (i.hasNext()) { 5560 final PackageParser.Instrumentation p = i.next(); 5561 if (targetPackage == null 5562 || targetPackage.equals(p.info.targetPackage)) { 5563 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5564 flags); 5565 if (ii != null) { 5566 finalList.add(ii); 5567 } 5568 } 5569 } 5570 } 5571 5572 return finalList; 5573 } 5574 5575 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5576 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5577 if (overlays == null) { 5578 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5579 return; 5580 } 5581 for (PackageParser.Package opkg : overlays.values()) { 5582 // Not much to do if idmap fails: we already logged the error 5583 // and we certainly don't want to abort installation of pkg simply 5584 // because an overlay didn't fit properly. For these reasons, 5585 // ignore the return value of createIdmapForPackagePairLI. 5586 createIdmapForPackagePairLI(pkg, opkg); 5587 } 5588 } 5589 5590 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5591 PackageParser.Package opkg) { 5592 if (!opkg.mTrustedOverlay) { 5593 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5594 opkg.baseCodePath + ": overlay not trusted"); 5595 return false; 5596 } 5597 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5598 if (overlaySet == null) { 5599 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5600 opkg.baseCodePath + " but target package has no known overlays"); 5601 return false; 5602 } 5603 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5604 // TODO: generate idmap for split APKs 5605 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5606 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5607 + opkg.baseCodePath); 5608 return false; 5609 } 5610 PackageParser.Package[] overlayArray = 5611 overlaySet.values().toArray(new PackageParser.Package[0]); 5612 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5613 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5614 return p1.mOverlayPriority - p2.mOverlayPriority; 5615 } 5616 }; 5617 Arrays.sort(overlayArray, cmp); 5618 5619 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5620 int i = 0; 5621 for (PackageParser.Package p : overlayArray) { 5622 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5623 } 5624 return true; 5625 } 5626 5627 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5628 final File[] files = dir.listFiles(); 5629 if (ArrayUtils.isEmpty(files)) { 5630 Log.d(TAG, "No files in app dir " + dir); 5631 return; 5632 } 5633 5634 if (DEBUG_PACKAGE_SCANNING) { 5635 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5636 + " flags=0x" + Integer.toHexString(parseFlags)); 5637 } 5638 5639 for (File file : files) { 5640 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5641 && !PackageInstallerService.isStageName(file.getName()); 5642 if (!isPackage) { 5643 // Ignore entries which are not packages 5644 continue; 5645 } 5646 try { 5647 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5648 scanFlags, currentTime, null); 5649 } catch (PackageManagerException e) { 5650 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5651 5652 // Delete invalid userdata apps 5653 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5654 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5655 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5656 if (file.isDirectory()) { 5657 mInstaller.rmPackageDir(file.getAbsolutePath()); 5658 } else { 5659 file.delete(); 5660 } 5661 } 5662 } 5663 } 5664 } 5665 5666 private static File getSettingsProblemFile() { 5667 File dataDir = Environment.getDataDirectory(); 5668 File systemDir = new File(dataDir, "system"); 5669 File fname = new File(systemDir, "uiderrors.txt"); 5670 return fname; 5671 } 5672 5673 static void reportSettingsProblem(int priority, String msg) { 5674 logCriticalInfo(priority, msg); 5675 } 5676 5677 static void logCriticalInfo(int priority, String msg) { 5678 Slog.println(priority, TAG, msg); 5679 EventLogTags.writePmCriticalInfo(msg); 5680 try { 5681 File fname = getSettingsProblemFile(); 5682 FileOutputStream out = new FileOutputStream(fname, true); 5683 PrintWriter pw = new FastPrintWriter(out); 5684 SimpleDateFormat formatter = new SimpleDateFormat(); 5685 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5686 pw.println(dateString + ": " + msg); 5687 pw.close(); 5688 FileUtils.setPermissions( 5689 fname.toString(), 5690 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5691 -1, -1); 5692 } catch (java.io.IOException e) { 5693 } 5694 } 5695 5696 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5697 PackageParser.Package pkg, File srcFile, int parseFlags) 5698 throws PackageManagerException { 5699 if (ps != null 5700 && ps.codePath.equals(srcFile) 5701 && ps.timeStamp == srcFile.lastModified() 5702 && !isCompatSignatureUpdateNeeded(pkg) 5703 && !isRecoverSignatureUpdateNeeded(pkg)) { 5704 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5705 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5706 ArraySet<PublicKey> signingKs; 5707 synchronized (mPackages) { 5708 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5709 } 5710 if (ps.signatures.mSignatures != null 5711 && ps.signatures.mSignatures.length != 0 5712 && signingKs != null) { 5713 // Optimization: reuse the existing cached certificates 5714 // if the package appears to be unchanged. 5715 pkg.mSignatures = ps.signatures.mSignatures; 5716 pkg.mSigningKeys = signingKs; 5717 return; 5718 } 5719 5720 Slog.w(TAG, "PackageSetting for " + ps.name 5721 + " is missing signatures. Collecting certs again to recover them."); 5722 } else { 5723 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5724 } 5725 5726 try { 5727 pp.collectCertificates(pkg, parseFlags); 5728 pp.collectManifestDigest(pkg); 5729 } catch (PackageParserException e) { 5730 throw PackageManagerException.from(e); 5731 } 5732 } 5733 5734 /* 5735 * Scan a package and return the newly parsed package. 5736 * Returns null in case of errors and the error code is stored in mLastScanError 5737 */ 5738 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5739 long currentTime, UserHandle user) throws PackageManagerException { 5740 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5741 parseFlags |= mDefParseFlags; 5742 PackageParser pp = new PackageParser(); 5743 pp.setSeparateProcesses(mSeparateProcesses); 5744 pp.setOnlyCoreApps(mOnlyCore); 5745 pp.setDisplayMetrics(mMetrics); 5746 5747 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5748 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5749 } 5750 5751 final PackageParser.Package pkg; 5752 try { 5753 pkg = pp.parsePackage(scanFile, parseFlags); 5754 } catch (PackageParserException e) { 5755 throw PackageManagerException.from(e); 5756 } 5757 5758 PackageSetting ps = null; 5759 PackageSetting updatedPkg; 5760 // reader 5761 synchronized (mPackages) { 5762 // Look to see if we already know about this package. 5763 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5764 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5765 // This package has been renamed to its original name. Let's 5766 // use that. 5767 ps = mSettings.peekPackageLPr(oldName); 5768 } 5769 // If there was no original package, see one for the real package name. 5770 if (ps == null) { 5771 ps = mSettings.peekPackageLPr(pkg.packageName); 5772 } 5773 // Check to see if this package could be hiding/updating a system 5774 // package. Must look for it either under the original or real 5775 // package name depending on our state. 5776 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5777 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5778 } 5779 boolean updatedPkgBetter = false; 5780 // First check if this is a system package that may involve an update 5781 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5782 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5783 // it needs to drop FLAG_PRIVILEGED. 5784 if (locationIsPrivileged(scanFile)) { 5785 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5786 } else { 5787 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5788 } 5789 5790 if (ps != null && !ps.codePath.equals(scanFile)) { 5791 // The path has changed from what was last scanned... check the 5792 // version of the new path against what we have stored to determine 5793 // what to do. 5794 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5795 if (pkg.mVersionCode <= ps.versionCode) { 5796 // The system package has been updated and the code path does not match 5797 // Ignore entry. Skip it. 5798 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5799 + " ignored: updated version " + ps.versionCode 5800 + " better than this " + pkg.mVersionCode); 5801 if (!updatedPkg.codePath.equals(scanFile)) { 5802 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5803 + ps.name + " changing from " + updatedPkg.codePathString 5804 + " to " + scanFile); 5805 updatedPkg.codePath = scanFile; 5806 updatedPkg.codePathString = scanFile.toString(); 5807 updatedPkg.resourcePath = scanFile; 5808 updatedPkg.resourcePathString = scanFile.toString(); 5809 } 5810 updatedPkg.pkg = pkg; 5811 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5812 "Package " + ps.name + " at " + scanFile 5813 + " ignored: updated version " + ps.versionCode 5814 + " better than this " + pkg.mVersionCode); 5815 } else { 5816 // The current app on the system partition is better than 5817 // what we have updated to on the data partition; switch 5818 // back to the system partition version. 5819 // At this point, its safely assumed that package installation for 5820 // apps in system partition will go through. If not there won't be a working 5821 // version of the app 5822 // writer 5823 synchronized (mPackages) { 5824 // Just remove the loaded entries from package lists. 5825 mPackages.remove(ps.name); 5826 } 5827 5828 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5829 + " reverting from " + ps.codePathString 5830 + ": new version " + pkg.mVersionCode 5831 + " better than installed " + ps.versionCode); 5832 5833 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5834 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5835 synchronized (mInstallLock) { 5836 args.cleanUpResourcesLI(); 5837 } 5838 synchronized (mPackages) { 5839 mSettings.enableSystemPackageLPw(ps.name); 5840 } 5841 updatedPkgBetter = true; 5842 } 5843 } 5844 } 5845 5846 if (updatedPkg != null) { 5847 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5848 // initially 5849 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5850 5851 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5852 // flag set initially 5853 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5854 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5855 } 5856 } 5857 5858 // Verify certificates against what was last scanned 5859 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5860 5861 /* 5862 * A new system app appeared, but we already had a non-system one of the 5863 * same name installed earlier. 5864 */ 5865 boolean shouldHideSystemApp = false; 5866 if (updatedPkg == null && ps != null 5867 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5868 /* 5869 * Check to make sure the signatures match first. If they don't, 5870 * wipe the installed application and its data. 5871 */ 5872 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5873 != PackageManager.SIGNATURE_MATCH) { 5874 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5875 + " signatures don't match existing userdata copy; removing"); 5876 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5877 ps = null; 5878 } else { 5879 /* 5880 * If the newly-added system app is an older version than the 5881 * already installed version, hide it. It will be scanned later 5882 * and re-added like an update. 5883 */ 5884 if (pkg.mVersionCode <= ps.versionCode) { 5885 shouldHideSystemApp = true; 5886 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5887 + " but new version " + pkg.mVersionCode + " better than installed " 5888 + ps.versionCode + "; hiding system"); 5889 } else { 5890 /* 5891 * The newly found system app is a newer version that the 5892 * one previously installed. Simply remove the 5893 * already-installed application and replace it with our own 5894 * while keeping the application data. 5895 */ 5896 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5897 + " reverting from " + ps.codePathString + ": new version " 5898 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5899 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5900 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5901 synchronized (mInstallLock) { 5902 args.cleanUpResourcesLI(); 5903 } 5904 } 5905 } 5906 } 5907 5908 // The apk is forward locked (not public) if its code and resources 5909 // are kept in different files. (except for app in either system or 5910 // vendor path). 5911 // TODO grab this value from PackageSettings 5912 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5913 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5914 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5915 } 5916 } 5917 5918 // TODO: extend to support forward-locked splits 5919 String resourcePath = null; 5920 String baseResourcePath = null; 5921 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5922 if (ps != null && ps.resourcePathString != null) { 5923 resourcePath = ps.resourcePathString; 5924 baseResourcePath = ps.resourcePathString; 5925 } else { 5926 // Should not happen at all. Just log an error. 5927 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5928 } 5929 } else { 5930 resourcePath = pkg.codePath; 5931 baseResourcePath = pkg.baseCodePath; 5932 } 5933 5934 // Set application objects path explicitly. 5935 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5936 pkg.applicationInfo.setCodePath(pkg.codePath); 5937 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5938 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5939 pkg.applicationInfo.setResourcePath(resourcePath); 5940 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5941 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5942 5943 // Note that we invoke the following method only if we are about to unpack an application 5944 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5945 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5946 5947 /* 5948 * If the system app should be overridden by a previously installed 5949 * data, hide the system app now and let the /data/app scan pick it up 5950 * again. 5951 */ 5952 if (shouldHideSystemApp) { 5953 synchronized (mPackages) { 5954 mSettings.disableSystemPackageLPw(pkg.packageName); 5955 } 5956 } 5957 5958 return scannedPkg; 5959 } 5960 5961 private static String fixProcessName(String defProcessName, 5962 String processName, int uid) { 5963 if (processName == null) { 5964 return defProcessName; 5965 } 5966 return processName; 5967 } 5968 5969 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5970 throws PackageManagerException { 5971 if (pkgSetting.signatures.mSignatures != null) { 5972 // Already existing package. Make sure signatures match 5973 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5974 == PackageManager.SIGNATURE_MATCH; 5975 if (!match) { 5976 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5977 == PackageManager.SIGNATURE_MATCH; 5978 } 5979 if (!match) { 5980 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5981 == PackageManager.SIGNATURE_MATCH; 5982 } 5983 if (!match) { 5984 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5985 + pkg.packageName + " signatures do not match the " 5986 + "previously installed version; ignoring!"); 5987 } 5988 } 5989 5990 // Check for shared user signatures 5991 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5992 // Already existing package. Make sure signatures match 5993 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5994 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5995 if (!match) { 5996 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5997 == PackageManager.SIGNATURE_MATCH; 5998 } 5999 if (!match) { 6000 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6001 == PackageManager.SIGNATURE_MATCH; 6002 } 6003 if (!match) { 6004 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6005 "Package " + pkg.packageName 6006 + " has no signatures that match those in shared user " 6007 + pkgSetting.sharedUser.name + "; ignoring!"); 6008 } 6009 } 6010 } 6011 6012 /** 6013 * Enforces that only the system UID or root's UID can call a method exposed 6014 * via Binder. 6015 * 6016 * @param message used as message if SecurityException is thrown 6017 * @throws SecurityException if the caller is not system or root 6018 */ 6019 private static final void enforceSystemOrRoot(String message) { 6020 final int uid = Binder.getCallingUid(); 6021 if (uid != Process.SYSTEM_UID && uid != 0) { 6022 throw new SecurityException(message); 6023 } 6024 } 6025 6026 @Override 6027 public void performBootDexOpt() { 6028 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6029 6030 // Before everything else, see whether we need to fstrim. 6031 try { 6032 IMountService ms = PackageHelper.getMountService(); 6033 if (ms != null) { 6034 final boolean isUpgrade = isUpgrade(); 6035 boolean doTrim = isUpgrade; 6036 if (doTrim) { 6037 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6038 } else { 6039 final long interval = android.provider.Settings.Global.getLong( 6040 mContext.getContentResolver(), 6041 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6042 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6043 if (interval > 0) { 6044 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6045 if (timeSinceLast > interval) { 6046 doTrim = true; 6047 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6048 + "; running immediately"); 6049 } 6050 } 6051 } 6052 if (doTrim) { 6053 if (!isFirstBoot()) { 6054 try { 6055 ActivityManagerNative.getDefault().showBootMessage( 6056 mContext.getResources().getString( 6057 R.string.android_upgrading_fstrim), true); 6058 } catch (RemoteException e) { 6059 } 6060 } 6061 ms.runMaintenance(); 6062 } 6063 } else { 6064 Slog.e(TAG, "Mount service unavailable!"); 6065 } 6066 } catch (RemoteException e) { 6067 // Can't happen; MountService is local 6068 } 6069 6070 final ArraySet<PackageParser.Package> pkgs; 6071 synchronized (mPackages) { 6072 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6073 } 6074 6075 if (pkgs != null) { 6076 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6077 // in case the device runs out of space. 6078 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6079 // Give priority to core apps. 6080 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6081 PackageParser.Package pkg = it.next(); 6082 if (pkg.coreApp) { 6083 if (DEBUG_DEXOPT) { 6084 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6085 } 6086 sortedPkgs.add(pkg); 6087 it.remove(); 6088 } 6089 } 6090 // Give priority to system apps that listen for pre boot complete. 6091 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6092 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6093 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6094 PackageParser.Package pkg = it.next(); 6095 if (pkgNames.contains(pkg.packageName)) { 6096 if (DEBUG_DEXOPT) { 6097 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6098 } 6099 sortedPkgs.add(pkg); 6100 it.remove(); 6101 } 6102 } 6103 // Filter out packages that aren't recently used. 6104 filterRecentlyUsedApps(pkgs); 6105 // Add all remaining apps. 6106 for (PackageParser.Package pkg : pkgs) { 6107 if (DEBUG_DEXOPT) { 6108 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6109 } 6110 sortedPkgs.add(pkg); 6111 } 6112 6113 // If we want to be lazy, filter everything that wasn't recently used. 6114 if (mLazyDexOpt) { 6115 filterRecentlyUsedApps(sortedPkgs); 6116 } 6117 6118 int i = 0; 6119 int total = sortedPkgs.size(); 6120 File dataDir = Environment.getDataDirectory(); 6121 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6122 if (lowThreshold == 0) { 6123 throw new IllegalStateException("Invalid low memory threshold"); 6124 } 6125 for (PackageParser.Package pkg : sortedPkgs) { 6126 long usableSpace = dataDir.getUsableSpace(); 6127 if (usableSpace < lowThreshold) { 6128 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6129 break; 6130 } 6131 performBootDexOpt(pkg, ++i, total); 6132 } 6133 } 6134 } 6135 6136 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6137 // Filter out packages that aren't recently used. 6138 // 6139 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6140 // should do a full dexopt. 6141 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6142 int total = pkgs.size(); 6143 int skipped = 0; 6144 long now = System.currentTimeMillis(); 6145 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6146 PackageParser.Package pkg = i.next(); 6147 long then = pkg.mLastPackageUsageTimeInMills; 6148 if (then + mDexOptLRUThresholdInMills < now) { 6149 if (DEBUG_DEXOPT) { 6150 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6151 ((then == 0) ? "never" : new Date(then))); 6152 } 6153 i.remove(); 6154 skipped++; 6155 } 6156 } 6157 if (DEBUG_DEXOPT) { 6158 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6159 } 6160 } 6161 } 6162 6163 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6164 List<ResolveInfo> ris = null; 6165 try { 6166 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6167 intent, null, 0, UserHandle.USER_OWNER); 6168 } catch (RemoteException e) { 6169 } 6170 ArraySet<String> pkgNames = new ArraySet<String>(); 6171 if (ris != null) { 6172 for (ResolveInfo ri : ris) { 6173 pkgNames.add(ri.activityInfo.packageName); 6174 } 6175 } 6176 return pkgNames; 6177 } 6178 6179 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6180 if (DEBUG_DEXOPT) { 6181 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6182 } 6183 if (!isFirstBoot()) { 6184 try { 6185 ActivityManagerNative.getDefault().showBootMessage( 6186 mContext.getResources().getString(R.string.android_upgrading_apk, 6187 curr, total), true); 6188 } catch (RemoteException e) { 6189 } 6190 } 6191 PackageParser.Package p = pkg; 6192 synchronized (mInstallLock) { 6193 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6194 false /* force dex */, false /* defer */, true /* include dependencies */, 6195 false /* boot complete */, false /*useJit*/); 6196 } 6197 } 6198 6199 @Override 6200 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6201 return performDexOpt(packageName, instructionSet, false); 6202 } 6203 6204 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6205 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6206 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6207 if (!dexopt && !updateUsage) { 6208 // We aren't going to dexopt or update usage, so bail early. 6209 return false; 6210 } 6211 PackageParser.Package p; 6212 final String targetInstructionSet; 6213 synchronized (mPackages) { 6214 p = mPackages.get(packageName); 6215 if (p == null) { 6216 return false; 6217 } 6218 if (updateUsage) { 6219 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6220 } 6221 mPackageUsage.write(false); 6222 if (!dexopt) { 6223 // We aren't going to dexopt, so bail early. 6224 return false; 6225 } 6226 6227 targetInstructionSet = instructionSet != null ? instructionSet : 6228 getPrimaryInstructionSet(p.applicationInfo); 6229 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6230 return false; 6231 } 6232 } 6233 long callingId = Binder.clearCallingIdentity(); 6234 try { 6235 synchronized (mInstallLock) { 6236 final String[] instructionSets = new String[] { targetInstructionSet }; 6237 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6238 false /* forceDex */, false /* defer */, true /* inclDependencies */, 6239 true /* boot complete */, false /*useJit*/); 6240 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6241 } 6242 } finally { 6243 Binder.restoreCallingIdentity(callingId); 6244 } 6245 } 6246 6247 public ArraySet<String> getPackagesThatNeedDexOpt() { 6248 ArraySet<String> pkgs = null; 6249 synchronized (mPackages) { 6250 for (PackageParser.Package p : mPackages.values()) { 6251 if (DEBUG_DEXOPT) { 6252 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6253 } 6254 if (!p.mDexOptPerformed.isEmpty()) { 6255 continue; 6256 } 6257 if (pkgs == null) { 6258 pkgs = new ArraySet<String>(); 6259 } 6260 pkgs.add(p.packageName); 6261 } 6262 } 6263 return pkgs; 6264 } 6265 6266 public void shutdown() { 6267 mPackageUsage.write(true); 6268 } 6269 6270 @Override 6271 public void forceDexOpt(String packageName) { 6272 enforceSystemOrRoot("forceDexOpt"); 6273 6274 PackageParser.Package pkg; 6275 synchronized (mPackages) { 6276 pkg = mPackages.get(packageName); 6277 if (pkg == null) { 6278 throw new IllegalArgumentException("Missing package: " + packageName); 6279 } 6280 } 6281 6282 synchronized (mInstallLock) { 6283 final String[] instructionSets = new String[] { 6284 getPrimaryInstructionSet(pkg.applicationInfo) }; 6285 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6286 true /*forceDex*/, false /* defer */, true /* inclDependencies */, 6287 true /* boot complete */, false /*useJit*/); 6288 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6289 throw new IllegalStateException("Failed to dexopt: " + res); 6290 } 6291 } 6292 } 6293 6294 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6295 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6296 Slog.w(TAG, "Unable to update from " + oldPkg.name 6297 + " to " + newPkg.packageName 6298 + ": old package not in system partition"); 6299 return false; 6300 } else if (mPackages.get(oldPkg.name) != null) { 6301 Slog.w(TAG, "Unable to update from " + oldPkg.name 6302 + " to " + newPkg.packageName 6303 + ": old package still exists"); 6304 return false; 6305 } 6306 return true; 6307 } 6308 6309 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6310 int[] users = sUserManager.getUserIds(); 6311 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6312 if (res < 0) { 6313 return res; 6314 } 6315 for (int user : users) { 6316 if (user != 0) { 6317 res = mInstaller.createUserData(volumeUuid, packageName, 6318 UserHandle.getUid(user, uid), user, seinfo); 6319 if (res < 0) { 6320 return res; 6321 } 6322 } 6323 } 6324 return res; 6325 } 6326 6327 private int removeDataDirsLI(String volumeUuid, String packageName) { 6328 int[] users = sUserManager.getUserIds(); 6329 int res = 0; 6330 for (int user : users) { 6331 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6332 if (resInner < 0) { 6333 res = resInner; 6334 } 6335 } 6336 6337 return res; 6338 } 6339 6340 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6341 int[] users = sUserManager.getUserIds(); 6342 int res = 0; 6343 for (int user : users) { 6344 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6345 if (resInner < 0) { 6346 res = resInner; 6347 } 6348 } 6349 return res; 6350 } 6351 6352 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6353 PackageParser.Package changingLib) { 6354 if (file.path != null) { 6355 usesLibraryFiles.add(file.path); 6356 return; 6357 } 6358 PackageParser.Package p = mPackages.get(file.apk); 6359 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6360 // If we are doing this while in the middle of updating a library apk, 6361 // then we need to make sure to use that new apk for determining the 6362 // dependencies here. (We haven't yet finished committing the new apk 6363 // to the package manager state.) 6364 if (p == null || p.packageName.equals(changingLib.packageName)) { 6365 p = changingLib; 6366 } 6367 } 6368 if (p != null) { 6369 usesLibraryFiles.addAll(p.getAllCodePaths()); 6370 } 6371 } 6372 6373 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6374 PackageParser.Package changingLib) throws PackageManagerException { 6375 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6376 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6377 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6378 for (int i=0; i<N; i++) { 6379 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6380 if (file == null) { 6381 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6382 "Package " + pkg.packageName + " requires unavailable shared library " 6383 + pkg.usesLibraries.get(i) + "; failing!"); 6384 } 6385 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6386 } 6387 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6388 for (int i=0; i<N; i++) { 6389 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6390 if (file == null) { 6391 Slog.w(TAG, "Package " + pkg.packageName 6392 + " desires unavailable shared library " 6393 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6394 } else { 6395 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6396 } 6397 } 6398 N = usesLibraryFiles.size(); 6399 if (N > 0) { 6400 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6401 } else { 6402 pkg.usesLibraryFiles = null; 6403 } 6404 } 6405 } 6406 6407 private static boolean hasString(List<String> list, List<String> which) { 6408 if (list == null) { 6409 return false; 6410 } 6411 for (int i=list.size()-1; i>=0; i--) { 6412 for (int j=which.size()-1; j>=0; j--) { 6413 if (which.get(j).equals(list.get(i))) { 6414 return true; 6415 } 6416 } 6417 } 6418 return false; 6419 } 6420 6421 private void updateAllSharedLibrariesLPw() { 6422 for (PackageParser.Package pkg : mPackages.values()) { 6423 try { 6424 updateSharedLibrariesLPw(pkg, null); 6425 } catch (PackageManagerException e) { 6426 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6427 } 6428 } 6429 } 6430 6431 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6432 PackageParser.Package changingPkg) { 6433 ArrayList<PackageParser.Package> res = null; 6434 for (PackageParser.Package pkg : mPackages.values()) { 6435 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6436 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6437 if (res == null) { 6438 res = new ArrayList<PackageParser.Package>(); 6439 } 6440 res.add(pkg); 6441 try { 6442 updateSharedLibrariesLPw(pkg, changingPkg); 6443 } catch (PackageManagerException e) { 6444 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6445 } 6446 } 6447 } 6448 return res; 6449 } 6450 6451 /** 6452 * Derive the value of the {@code cpuAbiOverride} based on the provided 6453 * value and an optional stored value from the package settings. 6454 */ 6455 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6456 String cpuAbiOverride = null; 6457 6458 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6459 cpuAbiOverride = null; 6460 } else if (abiOverride != null) { 6461 cpuAbiOverride = abiOverride; 6462 } else if (settings != null) { 6463 cpuAbiOverride = settings.cpuAbiOverrideString; 6464 } 6465 6466 return cpuAbiOverride; 6467 } 6468 6469 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6470 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6471 boolean success = false; 6472 try { 6473 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6474 currentTime, user); 6475 success = true; 6476 return res; 6477 } finally { 6478 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6479 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6480 } 6481 } 6482 } 6483 6484 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6485 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6486 final File scanFile = new File(pkg.codePath); 6487 if (pkg.applicationInfo.getCodePath() == null || 6488 pkg.applicationInfo.getResourcePath() == null) { 6489 // Bail out. The resource and code paths haven't been set. 6490 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6491 "Code and resource paths haven't been set correctly"); 6492 } 6493 6494 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6495 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6496 } else { 6497 // Only allow system apps to be flagged as core apps. 6498 pkg.coreApp = false; 6499 } 6500 6501 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6502 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6503 } 6504 6505 if (mCustomResolverComponentName != null && 6506 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6507 setUpCustomResolverActivity(pkg); 6508 } 6509 6510 if (pkg.packageName.equals("android")) { 6511 synchronized (mPackages) { 6512 if (mAndroidApplication != null) { 6513 Slog.w(TAG, "*************************************************"); 6514 Slog.w(TAG, "Core android package being redefined. Skipping."); 6515 Slog.w(TAG, " file=" + scanFile); 6516 Slog.w(TAG, "*************************************************"); 6517 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6518 "Core android package being redefined. Skipping."); 6519 } 6520 6521 // Set up information for our fall-back user intent resolution activity. 6522 mPlatformPackage = pkg; 6523 pkg.mVersionCode = mSdkVersion; 6524 mAndroidApplication = pkg.applicationInfo; 6525 6526 if (!mResolverReplaced) { 6527 mResolveActivity.applicationInfo = mAndroidApplication; 6528 mResolveActivity.name = ResolverActivity.class.getName(); 6529 mResolveActivity.packageName = mAndroidApplication.packageName; 6530 mResolveActivity.processName = "system:ui"; 6531 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6532 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6533 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6534 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6535 mResolveActivity.exported = true; 6536 mResolveActivity.enabled = true; 6537 mResolveInfo.activityInfo = mResolveActivity; 6538 mResolveInfo.priority = 0; 6539 mResolveInfo.preferredOrder = 0; 6540 mResolveInfo.match = 0; 6541 mResolveComponentName = new ComponentName( 6542 mAndroidApplication.packageName, mResolveActivity.name); 6543 } 6544 } 6545 } 6546 6547 if (DEBUG_PACKAGE_SCANNING) { 6548 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6549 Log.d(TAG, "Scanning package " + pkg.packageName); 6550 } 6551 6552 if (mPackages.containsKey(pkg.packageName) 6553 || mSharedLibraries.containsKey(pkg.packageName)) { 6554 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6555 "Application package " + pkg.packageName 6556 + " already installed. Skipping duplicate."); 6557 } 6558 6559 // If we're only installing presumed-existing packages, require that the 6560 // scanned APK is both already known and at the path previously established 6561 // for it. Previously unknown packages we pick up normally, but if we have an 6562 // a priori expectation about this package's install presence, enforce it. 6563 // With a singular exception for new system packages. When an OTA contains 6564 // a new system package, we allow the codepath to change from a system location 6565 // to the user-installed location. If we don't allow this change, any newer, 6566 // user-installed version of the application will be ignored. 6567 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6568 if (mExpectingBetter.containsKey(pkg.packageName)) { 6569 logCriticalInfo(Log.WARN, 6570 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6571 } else { 6572 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6573 if (known != null) { 6574 if (DEBUG_PACKAGE_SCANNING) { 6575 Log.d(TAG, "Examining " + pkg.codePath 6576 + " and requiring known paths " + known.codePathString 6577 + " & " + known.resourcePathString); 6578 } 6579 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6580 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6581 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6582 "Application package " + pkg.packageName 6583 + " found at " + pkg.applicationInfo.getCodePath() 6584 + " but expected at " + known.codePathString + "; ignoring."); 6585 } 6586 } 6587 } 6588 } 6589 6590 // Initialize package source and resource directories 6591 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6592 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6593 6594 SharedUserSetting suid = null; 6595 PackageSetting pkgSetting = null; 6596 6597 if (!isSystemApp(pkg)) { 6598 // Only system apps can use these features. 6599 pkg.mOriginalPackages = null; 6600 pkg.mRealPackage = null; 6601 pkg.mAdoptPermissions = null; 6602 } 6603 6604 // writer 6605 synchronized (mPackages) { 6606 if (pkg.mSharedUserId != null) { 6607 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6608 if (suid == null) { 6609 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6610 "Creating application package " + pkg.packageName 6611 + " for shared user failed"); 6612 } 6613 if (DEBUG_PACKAGE_SCANNING) { 6614 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6615 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6616 + "): packages=" + suid.packages); 6617 } 6618 } 6619 6620 // Check if we are renaming from an original package name. 6621 PackageSetting origPackage = null; 6622 String realName = null; 6623 if (pkg.mOriginalPackages != null) { 6624 // This package may need to be renamed to a previously 6625 // installed name. Let's check on that... 6626 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6627 if (pkg.mOriginalPackages.contains(renamed)) { 6628 // This package had originally been installed as the 6629 // original name, and we have already taken care of 6630 // transitioning to the new one. Just update the new 6631 // one to continue using the old name. 6632 realName = pkg.mRealPackage; 6633 if (!pkg.packageName.equals(renamed)) { 6634 // Callers into this function may have already taken 6635 // care of renaming the package; only do it here if 6636 // it is not already done. 6637 pkg.setPackageName(renamed); 6638 } 6639 6640 } else { 6641 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6642 if ((origPackage = mSettings.peekPackageLPr( 6643 pkg.mOriginalPackages.get(i))) != null) { 6644 // We do have the package already installed under its 6645 // original name... should we use it? 6646 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6647 // New package is not compatible with original. 6648 origPackage = null; 6649 continue; 6650 } else if (origPackage.sharedUser != null) { 6651 // Make sure uid is compatible between packages. 6652 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6653 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6654 + " to " + pkg.packageName + ": old uid " 6655 + origPackage.sharedUser.name 6656 + " differs from " + pkg.mSharedUserId); 6657 origPackage = null; 6658 continue; 6659 } 6660 } else { 6661 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6662 + pkg.packageName + " to old name " + origPackage.name); 6663 } 6664 break; 6665 } 6666 } 6667 } 6668 } 6669 6670 if (mTransferedPackages.contains(pkg.packageName)) { 6671 Slog.w(TAG, "Package " + pkg.packageName 6672 + " was transferred to another, but its .apk remains"); 6673 } 6674 6675 // Just create the setting, don't add it yet. For already existing packages 6676 // the PkgSetting exists already and doesn't have to be created. 6677 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6678 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6679 pkg.applicationInfo.primaryCpuAbi, 6680 pkg.applicationInfo.secondaryCpuAbi, 6681 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6682 user, false); 6683 if (pkgSetting == null) { 6684 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6685 "Creating application package " + pkg.packageName + " failed"); 6686 } 6687 6688 if (pkgSetting.origPackage != null) { 6689 // If we are first transitioning from an original package, 6690 // fix up the new package's name now. We need to do this after 6691 // looking up the package under its new name, so getPackageLP 6692 // can take care of fiddling things correctly. 6693 pkg.setPackageName(origPackage.name); 6694 6695 // File a report about this. 6696 String msg = "New package " + pkgSetting.realName 6697 + " renamed to replace old package " + pkgSetting.name; 6698 reportSettingsProblem(Log.WARN, msg); 6699 6700 // Make a note of it. 6701 mTransferedPackages.add(origPackage.name); 6702 6703 // No longer need to retain this. 6704 pkgSetting.origPackage = null; 6705 } 6706 6707 if (realName != null) { 6708 // Make a note of it. 6709 mTransferedPackages.add(pkg.packageName); 6710 } 6711 6712 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6713 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6714 } 6715 6716 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6717 // Check all shared libraries and map to their actual file path. 6718 // We only do this here for apps not on a system dir, because those 6719 // are the only ones that can fail an install due to this. We 6720 // will take care of the system apps by updating all of their 6721 // library paths after the scan is done. 6722 updateSharedLibrariesLPw(pkg, null); 6723 } 6724 6725 if (mFoundPolicyFile) { 6726 SELinuxMMAC.assignSeinfoValue(pkg); 6727 } 6728 6729 pkg.applicationInfo.uid = pkgSetting.appId; 6730 pkg.mExtras = pkgSetting; 6731 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6732 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6733 // We just determined the app is signed correctly, so bring 6734 // over the latest parsed certs. 6735 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6736 } else { 6737 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6738 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6739 "Package " + pkg.packageName + " upgrade keys do not match the " 6740 + "previously installed version"); 6741 } else { 6742 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6743 String msg = "System package " + pkg.packageName 6744 + " signature changed; retaining data."; 6745 reportSettingsProblem(Log.WARN, msg); 6746 } 6747 } 6748 } else { 6749 try { 6750 verifySignaturesLP(pkgSetting, pkg); 6751 // We just determined the app is signed correctly, so bring 6752 // over the latest parsed certs. 6753 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6754 } catch (PackageManagerException e) { 6755 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6756 throw e; 6757 } 6758 // The signature has changed, but this package is in the system 6759 // image... let's recover! 6760 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6761 // However... if this package is part of a shared user, but it 6762 // doesn't match the signature of the shared user, let's fail. 6763 // What this means is that you can't change the signatures 6764 // associated with an overall shared user, which doesn't seem all 6765 // that unreasonable. 6766 if (pkgSetting.sharedUser != null) { 6767 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6768 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6769 throw new PackageManagerException( 6770 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6771 "Signature mismatch for shared user : " 6772 + pkgSetting.sharedUser); 6773 } 6774 } 6775 // File a report about this. 6776 String msg = "System package " + pkg.packageName 6777 + " signature changed; retaining data."; 6778 reportSettingsProblem(Log.WARN, msg); 6779 } 6780 } 6781 // Verify that this new package doesn't have any content providers 6782 // that conflict with existing packages. Only do this if the 6783 // package isn't already installed, since we don't want to break 6784 // things that are installed. 6785 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6786 final int N = pkg.providers.size(); 6787 int i; 6788 for (i=0; i<N; i++) { 6789 PackageParser.Provider p = pkg.providers.get(i); 6790 if (p.info.authority != null) { 6791 String names[] = p.info.authority.split(";"); 6792 for (int j = 0; j < names.length; j++) { 6793 if (mProvidersByAuthority.containsKey(names[j])) { 6794 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6795 final String otherPackageName = 6796 ((other != null && other.getComponentName() != null) ? 6797 other.getComponentName().getPackageName() : "?"); 6798 throw new PackageManagerException( 6799 INSTALL_FAILED_CONFLICTING_PROVIDER, 6800 "Can't install because provider name " + names[j] 6801 + " (in package " + pkg.applicationInfo.packageName 6802 + ") is already used by " + otherPackageName); 6803 } 6804 } 6805 } 6806 } 6807 } 6808 6809 if (pkg.mAdoptPermissions != null) { 6810 // This package wants to adopt ownership of permissions from 6811 // another package. 6812 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6813 final String origName = pkg.mAdoptPermissions.get(i); 6814 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6815 if (orig != null) { 6816 if (verifyPackageUpdateLPr(orig, pkg)) { 6817 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6818 + pkg.packageName); 6819 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6820 } 6821 } 6822 } 6823 } 6824 } 6825 6826 final String pkgName = pkg.packageName; 6827 6828 final long scanFileTime = scanFile.lastModified(); 6829 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6830 pkg.applicationInfo.processName = fixProcessName( 6831 pkg.applicationInfo.packageName, 6832 pkg.applicationInfo.processName, 6833 pkg.applicationInfo.uid); 6834 6835 File dataPath; 6836 if (mPlatformPackage == pkg) { 6837 // The system package is special. 6838 dataPath = new File(Environment.getDataDirectory(), "system"); 6839 6840 pkg.applicationInfo.dataDir = dataPath.getPath(); 6841 6842 } else { 6843 // This is a normal package, need to make its data directory. 6844 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6845 UserHandle.USER_OWNER, pkg.packageName); 6846 6847 boolean uidError = false; 6848 if (dataPath.exists()) { 6849 int currentUid = 0; 6850 try { 6851 StructStat stat = Os.stat(dataPath.getPath()); 6852 currentUid = stat.st_uid; 6853 } catch (ErrnoException e) { 6854 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6855 } 6856 6857 // If we have mismatched owners for the data path, we have a problem. 6858 if (currentUid != pkg.applicationInfo.uid) { 6859 boolean recovered = false; 6860 if (currentUid == 0) { 6861 // The directory somehow became owned by root. Wow. 6862 // This is probably because the system was stopped while 6863 // installd was in the middle of messing with its libs 6864 // directory. Ask installd to fix that. 6865 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6866 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6867 if (ret >= 0) { 6868 recovered = true; 6869 String msg = "Package " + pkg.packageName 6870 + " unexpectedly changed to uid 0; recovered to " + 6871 + pkg.applicationInfo.uid; 6872 reportSettingsProblem(Log.WARN, msg); 6873 } 6874 } 6875 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6876 || (scanFlags&SCAN_BOOTING) != 0)) { 6877 // If this is a system app, we can at least delete its 6878 // current data so the application will still work. 6879 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6880 if (ret >= 0) { 6881 // TODO: Kill the processes first 6882 // Old data gone! 6883 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6884 ? "System package " : "Third party package "; 6885 String msg = prefix + pkg.packageName 6886 + " has changed from uid: " 6887 + currentUid + " to " 6888 + pkg.applicationInfo.uid + "; old data erased"; 6889 reportSettingsProblem(Log.WARN, msg); 6890 recovered = true; 6891 6892 // And now re-install the app. 6893 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6894 pkg.applicationInfo.seinfo); 6895 if (ret == -1) { 6896 // Ack should not happen! 6897 msg = prefix + pkg.packageName 6898 + " could not have data directory re-created after delete."; 6899 reportSettingsProblem(Log.WARN, msg); 6900 throw new PackageManagerException( 6901 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6902 } 6903 } 6904 if (!recovered) { 6905 mHasSystemUidErrors = true; 6906 } 6907 } else if (!recovered) { 6908 // If we allow this install to proceed, we will be broken. 6909 // Abort, abort! 6910 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6911 "scanPackageLI"); 6912 } 6913 if (!recovered) { 6914 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6915 + pkg.applicationInfo.uid + "/fs_" 6916 + currentUid; 6917 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6918 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6919 String msg = "Package " + pkg.packageName 6920 + " has mismatched uid: " 6921 + currentUid + " on disk, " 6922 + pkg.applicationInfo.uid + " in settings"; 6923 // writer 6924 synchronized (mPackages) { 6925 mSettings.mReadMessages.append(msg); 6926 mSettings.mReadMessages.append('\n'); 6927 uidError = true; 6928 if (!pkgSetting.uidError) { 6929 reportSettingsProblem(Log.ERROR, msg); 6930 } 6931 } 6932 } 6933 } 6934 pkg.applicationInfo.dataDir = dataPath.getPath(); 6935 if (mShouldRestoreconData) { 6936 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6937 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6938 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6939 } 6940 } else { 6941 if (DEBUG_PACKAGE_SCANNING) { 6942 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6943 Log.v(TAG, "Want this data dir: " + dataPath); 6944 } 6945 //invoke installer to do the actual installation 6946 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6947 pkg.applicationInfo.seinfo); 6948 if (ret < 0) { 6949 // Error from installer 6950 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6951 "Unable to create data dirs [errorCode=" + ret + "]"); 6952 } 6953 6954 if (dataPath.exists()) { 6955 pkg.applicationInfo.dataDir = dataPath.getPath(); 6956 } else { 6957 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6958 pkg.applicationInfo.dataDir = null; 6959 } 6960 } 6961 6962 pkgSetting.uidError = uidError; 6963 } 6964 6965 final String path = scanFile.getPath(); 6966 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6967 6968 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6969 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6970 6971 // Some system apps still use directory structure for native libraries 6972 // in which case we might end up not detecting abi solely based on apk 6973 // structure. Try to detect abi based on directory structure. 6974 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6975 pkg.applicationInfo.primaryCpuAbi == null) { 6976 setBundledAppAbisAndRoots(pkg, pkgSetting); 6977 setNativeLibraryPaths(pkg); 6978 } 6979 6980 } else { 6981 if ((scanFlags & SCAN_MOVE) != 0) { 6982 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6983 // but we already have this packages package info in the PackageSetting. We just 6984 // use that and derive the native library path based on the new codepath. 6985 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6986 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6987 } 6988 6989 // Set native library paths again. For moves, the path will be updated based on the 6990 // ABIs we've determined above. For non-moves, the path will be updated based on the 6991 // ABIs we determined during compilation, but the path will depend on the final 6992 // package path (after the rename away from the stage path). 6993 setNativeLibraryPaths(pkg); 6994 } 6995 6996 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6997 final int[] userIds = sUserManager.getUserIds(); 6998 synchronized (mInstallLock) { 6999 // Make sure all user data directories are ready to roll; we're okay 7000 // if they already exist 7001 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7002 for (int userId : userIds) { 7003 if (userId != 0) { 7004 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7005 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7006 pkg.applicationInfo.seinfo); 7007 } 7008 } 7009 } 7010 7011 // Create a native library symlink only if we have native libraries 7012 // and if the native libraries are 32 bit libraries. We do not provide 7013 // this symlink for 64 bit libraries. 7014 if (pkg.applicationInfo.primaryCpuAbi != null && 7015 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7016 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7017 for (int userId : userIds) { 7018 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7019 nativeLibPath, userId) < 0) { 7020 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7021 "Failed linking native library dir (user=" + userId + ")"); 7022 } 7023 } 7024 } 7025 } 7026 7027 // This is a special case for the "system" package, where the ABI is 7028 // dictated by the zygote configuration (and init.rc). We should keep track 7029 // of this ABI so that we can deal with "normal" applications that run under 7030 // the same UID correctly. 7031 if (mPlatformPackage == pkg) { 7032 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7033 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7034 } 7035 7036 // If there's a mismatch between the abi-override in the package setting 7037 // and the abiOverride specified for the install. Warn about this because we 7038 // would've already compiled the app without taking the package setting into 7039 // account. 7040 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7041 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7042 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7043 " for package: " + pkg.packageName); 7044 } 7045 } 7046 7047 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7048 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7049 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7050 7051 // Copy the derived override back to the parsed package, so that we can 7052 // update the package settings accordingly. 7053 pkg.cpuAbiOverride = cpuAbiOverride; 7054 7055 if (DEBUG_ABI_SELECTION) { 7056 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7057 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7058 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7059 } 7060 7061 // Push the derived path down into PackageSettings so we know what to 7062 // clean up at uninstall time. 7063 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7064 7065 if (DEBUG_ABI_SELECTION) { 7066 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7067 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7068 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7069 } 7070 7071 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7072 // We don't do this here during boot because we can do it all 7073 // at once after scanning all existing packages. 7074 // 7075 // We also do this *before* we perform dexopt on this package, so that 7076 // we can avoid redundant dexopts, and also to make sure we've got the 7077 // code and package path correct. 7078 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7079 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */); 7080 } 7081 7082 if ((scanFlags & SCAN_NO_DEX) == 0) { 7083 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7084 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */, 7085 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7086 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7087 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7088 } 7089 } 7090 if (mFactoryTest && pkg.requestedPermissions.contains( 7091 android.Manifest.permission.FACTORY_TEST)) { 7092 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7093 } 7094 7095 ArrayList<PackageParser.Package> clientLibPkgs = null; 7096 7097 // writer 7098 synchronized (mPackages) { 7099 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7100 // Only system apps can add new shared libraries. 7101 if (pkg.libraryNames != null) { 7102 for (int i=0; i<pkg.libraryNames.size(); i++) { 7103 String name = pkg.libraryNames.get(i); 7104 boolean allowed = false; 7105 if (pkg.isUpdatedSystemApp()) { 7106 // New library entries can only be added through the 7107 // system image. This is important to get rid of a lot 7108 // of nasty edge cases: for example if we allowed a non- 7109 // system update of the app to add a library, then uninstalling 7110 // the update would make the library go away, and assumptions 7111 // we made such as through app install filtering would now 7112 // have allowed apps on the device which aren't compatible 7113 // with it. Better to just have the restriction here, be 7114 // conservative, and create many fewer cases that can negatively 7115 // impact the user experience. 7116 final PackageSetting sysPs = mSettings 7117 .getDisabledSystemPkgLPr(pkg.packageName); 7118 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7119 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7120 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7121 allowed = true; 7122 allowed = true; 7123 break; 7124 } 7125 } 7126 } 7127 } else { 7128 allowed = true; 7129 } 7130 if (allowed) { 7131 if (!mSharedLibraries.containsKey(name)) { 7132 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7133 } else if (!name.equals(pkg.packageName)) { 7134 Slog.w(TAG, "Package " + pkg.packageName + " library " 7135 + name + " already exists; skipping"); 7136 } 7137 } else { 7138 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7139 + name + " that is not declared on system image; skipping"); 7140 } 7141 } 7142 if ((scanFlags&SCAN_BOOTING) == 0) { 7143 // If we are not booting, we need to update any applications 7144 // that are clients of our shared library. If we are booting, 7145 // this will all be done once the scan is complete. 7146 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7147 } 7148 } 7149 } 7150 } 7151 7152 // We also need to dexopt any apps that are dependent on this library. Note that 7153 // if these fail, we should abort the install since installing the library will 7154 // result in some apps being broken. 7155 if (clientLibPkgs != null) { 7156 if ((scanFlags & SCAN_NO_DEX) == 0) { 7157 for (int i = 0; i < clientLibPkgs.size(); i++) { 7158 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7159 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7160 null /* instruction sets */, forceDex, 7161 (scanFlags & SCAN_DEFER_DEX) != 0, false, 7162 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7163 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7164 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7165 "scanPackageLI failed to dexopt clientLibPkgs"); 7166 } 7167 } 7168 } 7169 } 7170 7171 // Request the ActivityManager to kill the process(only for existing packages) 7172 // so that we do not end up in a confused state while the user is still using the older 7173 // version of the application while the new one gets installed. 7174 if ((scanFlags & SCAN_REPLACING) != 0) { 7175 killApplication(pkg.applicationInfo.packageName, 7176 pkg.applicationInfo.uid, "replace pkg"); 7177 } 7178 7179 // Also need to kill any apps that are dependent on the library. 7180 if (clientLibPkgs != null) { 7181 for (int i=0; i<clientLibPkgs.size(); i++) { 7182 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7183 killApplication(clientPkg.applicationInfo.packageName, 7184 clientPkg.applicationInfo.uid, "update lib"); 7185 } 7186 } 7187 7188 // Make sure we're not adding any bogus keyset info 7189 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7190 ksms.assertScannedPackageValid(pkg); 7191 7192 // writer 7193 synchronized (mPackages) { 7194 // We don't expect installation to fail beyond this point 7195 7196 // Add the new setting to mSettings 7197 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7198 // Add the new setting to mPackages 7199 mPackages.put(pkg.applicationInfo.packageName, pkg); 7200 // Make sure we don't accidentally delete its data. 7201 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7202 while (iter.hasNext()) { 7203 PackageCleanItem item = iter.next(); 7204 if (pkgName.equals(item.packageName)) { 7205 iter.remove(); 7206 } 7207 } 7208 7209 // Take care of first install / last update times. 7210 if (currentTime != 0) { 7211 if (pkgSetting.firstInstallTime == 0) { 7212 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7213 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7214 pkgSetting.lastUpdateTime = currentTime; 7215 } 7216 } else if (pkgSetting.firstInstallTime == 0) { 7217 // We need *something*. Take time time stamp of the file. 7218 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7219 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7220 if (scanFileTime != pkgSetting.timeStamp) { 7221 // A package on the system image has changed; consider this 7222 // to be an update. 7223 pkgSetting.lastUpdateTime = scanFileTime; 7224 } 7225 } 7226 7227 // Add the package's KeySets to the global KeySetManagerService 7228 ksms.addScannedPackageLPw(pkg); 7229 7230 int N = pkg.providers.size(); 7231 StringBuilder r = null; 7232 int i; 7233 for (i=0; i<N; i++) { 7234 PackageParser.Provider p = pkg.providers.get(i); 7235 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7236 p.info.processName, pkg.applicationInfo.uid); 7237 mProviders.addProvider(p); 7238 p.syncable = p.info.isSyncable; 7239 if (p.info.authority != null) { 7240 String names[] = p.info.authority.split(";"); 7241 p.info.authority = null; 7242 for (int j = 0; j < names.length; j++) { 7243 if (j == 1 && p.syncable) { 7244 // We only want the first authority for a provider to possibly be 7245 // syncable, so if we already added this provider using a different 7246 // authority clear the syncable flag. We copy the provider before 7247 // changing it because the mProviders object contains a reference 7248 // to a provider that we don't want to change. 7249 // Only do this for the second authority since the resulting provider 7250 // object can be the same for all future authorities for this provider. 7251 p = new PackageParser.Provider(p); 7252 p.syncable = false; 7253 } 7254 if (!mProvidersByAuthority.containsKey(names[j])) { 7255 mProvidersByAuthority.put(names[j], p); 7256 if (p.info.authority == null) { 7257 p.info.authority = names[j]; 7258 } else { 7259 p.info.authority = p.info.authority + ";" + names[j]; 7260 } 7261 if (DEBUG_PACKAGE_SCANNING) { 7262 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7263 Log.d(TAG, "Registered content provider: " + names[j] 7264 + ", className = " + p.info.name + ", isSyncable = " 7265 + p.info.isSyncable); 7266 } 7267 } else { 7268 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7269 Slog.w(TAG, "Skipping provider name " + names[j] + 7270 " (in package " + pkg.applicationInfo.packageName + 7271 "): name already used by " 7272 + ((other != null && other.getComponentName() != null) 7273 ? other.getComponentName().getPackageName() : "?")); 7274 } 7275 } 7276 } 7277 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7278 if (r == null) { 7279 r = new StringBuilder(256); 7280 } else { 7281 r.append(' '); 7282 } 7283 r.append(p.info.name); 7284 } 7285 } 7286 if (r != null) { 7287 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7288 } 7289 7290 N = pkg.services.size(); 7291 r = null; 7292 for (i=0; i<N; i++) { 7293 PackageParser.Service s = pkg.services.get(i); 7294 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7295 s.info.processName, pkg.applicationInfo.uid); 7296 mServices.addService(s); 7297 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7298 if (r == null) { 7299 r = new StringBuilder(256); 7300 } else { 7301 r.append(' '); 7302 } 7303 r.append(s.info.name); 7304 } 7305 } 7306 if (r != null) { 7307 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7308 } 7309 7310 N = pkg.receivers.size(); 7311 r = null; 7312 for (i=0; i<N; i++) { 7313 PackageParser.Activity a = pkg.receivers.get(i); 7314 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7315 a.info.processName, pkg.applicationInfo.uid); 7316 mReceivers.addActivity(a, "receiver"); 7317 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7318 if (r == null) { 7319 r = new StringBuilder(256); 7320 } else { 7321 r.append(' '); 7322 } 7323 r.append(a.info.name); 7324 } 7325 } 7326 if (r != null) { 7327 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7328 } 7329 7330 N = pkg.activities.size(); 7331 r = null; 7332 for (i=0; i<N; i++) { 7333 PackageParser.Activity a = pkg.activities.get(i); 7334 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7335 a.info.processName, pkg.applicationInfo.uid); 7336 mActivities.addActivity(a, "activity"); 7337 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7338 if (r == null) { 7339 r = new StringBuilder(256); 7340 } else { 7341 r.append(' '); 7342 } 7343 r.append(a.info.name); 7344 } 7345 } 7346 if (r != null) { 7347 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7348 } 7349 7350 N = pkg.permissionGroups.size(); 7351 r = null; 7352 for (i=0; i<N; i++) { 7353 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7354 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7355 if (cur == null) { 7356 mPermissionGroups.put(pg.info.name, pg); 7357 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7358 if (r == null) { 7359 r = new StringBuilder(256); 7360 } else { 7361 r.append(' '); 7362 } 7363 r.append(pg.info.name); 7364 } 7365 } else { 7366 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7367 + pg.info.packageName + " ignored: original from " 7368 + cur.info.packageName); 7369 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7370 if (r == null) { 7371 r = new StringBuilder(256); 7372 } else { 7373 r.append(' '); 7374 } 7375 r.append("DUP:"); 7376 r.append(pg.info.name); 7377 } 7378 } 7379 } 7380 if (r != null) { 7381 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7382 } 7383 7384 N = pkg.permissions.size(); 7385 r = null; 7386 for (i=0; i<N; i++) { 7387 PackageParser.Permission p = pkg.permissions.get(i); 7388 7389 // Assume by default that we did not install this permission into the system. 7390 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7391 7392 // Now that permission groups have a special meaning, we ignore permission 7393 // groups for legacy apps to prevent unexpected behavior. In particular, 7394 // permissions for one app being granted to someone just becuase they happen 7395 // to be in a group defined by another app (before this had no implications). 7396 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7397 p.group = mPermissionGroups.get(p.info.group); 7398 // Warn for a permission in an unknown group. 7399 if (p.info.group != null && p.group == null) { 7400 Slog.w(TAG, "Permission " + p.info.name + " from package " 7401 + p.info.packageName + " in an unknown group " + p.info.group); 7402 } 7403 } 7404 7405 ArrayMap<String, BasePermission> permissionMap = 7406 p.tree ? mSettings.mPermissionTrees 7407 : mSettings.mPermissions; 7408 BasePermission bp = permissionMap.get(p.info.name); 7409 7410 // Allow system apps to redefine non-system permissions 7411 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7412 final boolean currentOwnerIsSystem = (bp.perm != null 7413 && isSystemApp(bp.perm.owner)); 7414 if (isSystemApp(p.owner)) { 7415 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7416 // It's a built-in permission and no owner, take ownership now 7417 bp.packageSetting = pkgSetting; 7418 bp.perm = p; 7419 bp.uid = pkg.applicationInfo.uid; 7420 bp.sourcePackage = p.info.packageName; 7421 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7422 } else if (!currentOwnerIsSystem) { 7423 String msg = "New decl " + p.owner + " of permission " 7424 + p.info.name + " is system; overriding " + bp.sourcePackage; 7425 reportSettingsProblem(Log.WARN, msg); 7426 bp = null; 7427 } 7428 } 7429 } 7430 7431 if (bp == null) { 7432 bp = new BasePermission(p.info.name, p.info.packageName, 7433 BasePermission.TYPE_NORMAL); 7434 permissionMap.put(p.info.name, bp); 7435 } 7436 7437 if (bp.perm == null) { 7438 if (bp.sourcePackage == null 7439 || bp.sourcePackage.equals(p.info.packageName)) { 7440 BasePermission tree = findPermissionTreeLP(p.info.name); 7441 if (tree == null 7442 || tree.sourcePackage.equals(p.info.packageName)) { 7443 bp.packageSetting = pkgSetting; 7444 bp.perm = p; 7445 bp.uid = pkg.applicationInfo.uid; 7446 bp.sourcePackage = p.info.packageName; 7447 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7448 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7449 if (r == null) { 7450 r = new StringBuilder(256); 7451 } else { 7452 r.append(' '); 7453 } 7454 r.append(p.info.name); 7455 } 7456 } else { 7457 Slog.w(TAG, "Permission " + p.info.name + " from package " 7458 + p.info.packageName + " ignored: base tree " 7459 + tree.name + " is from package " 7460 + tree.sourcePackage); 7461 } 7462 } else { 7463 Slog.w(TAG, "Permission " + p.info.name + " from package " 7464 + p.info.packageName + " ignored: original from " 7465 + bp.sourcePackage); 7466 } 7467 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7468 if (r == null) { 7469 r = new StringBuilder(256); 7470 } else { 7471 r.append(' '); 7472 } 7473 r.append("DUP:"); 7474 r.append(p.info.name); 7475 } 7476 if (bp.perm == p) { 7477 bp.protectionLevel = p.info.protectionLevel; 7478 } 7479 } 7480 7481 if (r != null) { 7482 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7483 } 7484 7485 N = pkg.instrumentation.size(); 7486 r = null; 7487 for (i=0; i<N; i++) { 7488 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7489 a.info.packageName = pkg.applicationInfo.packageName; 7490 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7491 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7492 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7493 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7494 a.info.dataDir = pkg.applicationInfo.dataDir; 7495 7496 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7497 // need other information about the application, like the ABI and what not ? 7498 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7499 mInstrumentation.put(a.getComponentName(), a); 7500 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7501 if (r == null) { 7502 r = new StringBuilder(256); 7503 } else { 7504 r.append(' '); 7505 } 7506 r.append(a.info.name); 7507 } 7508 } 7509 if (r != null) { 7510 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7511 } 7512 7513 if (pkg.protectedBroadcasts != null) { 7514 N = pkg.protectedBroadcasts.size(); 7515 for (i=0; i<N; i++) { 7516 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7517 } 7518 } 7519 7520 pkgSetting.setTimeStamp(scanFileTime); 7521 7522 // Create idmap files for pairs of (packages, overlay packages). 7523 // Note: "android", ie framework-res.apk, is handled by native layers. 7524 if (pkg.mOverlayTarget != null) { 7525 // This is an overlay package. 7526 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7527 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7528 mOverlays.put(pkg.mOverlayTarget, 7529 new ArrayMap<String, PackageParser.Package>()); 7530 } 7531 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7532 map.put(pkg.packageName, pkg); 7533 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7534 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7535 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7536 "scanPackageLI failed to createIdmap"); 7537 } 7538 } 7539 } else if (mOverlays.containsKey(pkg.packageName) && 7540 !pkg.packageName.equals("android")) { 7541 // This is a regular package, with one or more known overlay packages. 7542 createIdmapsForPackageLI(pkg); 7543 } 7544 } 7545 7546 return pkg; 7547 } 7548 7549 /** 7550 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7551 * is derived purely on the basis of the contents of {@code scanFile} and 7552 * {@code cpuAbiOverride}. 7553 * 7554 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7555 */ 7556 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7557 String cpuAbiOverride, boolean extractLibs) 7558 throws PackageManagerException { 7559 // TODO: We can probably be smarter about this stuff. For installed apps, 7560 // we can calculate this information at install time once and for all. For 7561 // system apps, we can probably assume that this information doesn't change 7562 // after the first boot scan. As things stand, we do lots of unnecessary work. 7563 7564 // Give ourselves some initial paths; we'll come back for another 7565 // pass once we've determined ABI below. 7566 setNativeLibraryPaths(pkg); 7567 7568 // We would never need to extract libs for forward-locked and external packages, 7569 // since the container service will do it for us. We shouldn't attempt to 7570 // extract libs from system app when it was not updated. 7571 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7572 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7573 extractLibs = false; 7574 } 7575 7576 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7577 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7578 7579 NativeLibraryHelper.Handle handle = null; 7580 try { 7581 handle = NativeLibraryHelper.Handle.create(scanFile); 7582 // TODO(multiArch): This can be null for apps that didn't go through the 7583 // usual installation process. We can calculate it again, like we 7584 // do during install time. 7585 // 7586 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7587 // unnecessary. 7588 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7589 7590 // Null out the abis so that they can be recalculated. 7591 pkg.applicationInfo.primaryCpuAbi = null; 7592 pkg.applicationInfo.secondaryCpuAbi = null; 7593 if (isMultiArch(pkg.applicationInfo)) { 7594 // Warn if we've set an abiOverride for multi-lib packages.. 7595 // By definition, we need to copy both 32 and 64 bit libraries for 7596 // such packages. 7597 if (pkg.cpuAbiOverride != null 7598 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7599 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7600 } 7601 7602 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7603 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7604 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7605 if (extractLibs) { 7606 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7607 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7608 useIsaSpecificSubdirs); 7609 } else { 7610 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7611 } 7612 } 7613 7614 maybeThrowExceptionForMultiArchCopy( 7615 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7616 7617 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7618 if (extractLibs) { 7619 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7620 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7621 useIsaSpecificSubdirs); 7622 } else { 7623 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7624 } 7625 } 7626 7627 maybeThrowExceptionForMultiArchCopy( 7628 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7629 7630 if (abi64 >= 0) { 7631 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7632 } 7633 7634 if (abi32 >= 0) { 7635 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7636 if (abi64 >= 0) { 7637 pkg.applicationInfo.secondaryCpuAbi = abi; 7638 } else { 7639 pkg.applicationInfo.primaryCpuAbi = abi; 7640 } 7641 } 7642 } else { 7643 String[] abiList = (cpuAbiOverride != null) ? 7644 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7645 7646 // Enable gross and lame hacks for apps that are built with old 7647 // SDK tools. We must scan their APKs for renderscript bitcode and 7648 // not launch them if it's present. Don't bother checking on devices 7649 // that don't have 64 bit support. 7650 boolean needsRenderScriptOverride = false; 7651 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7652 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7653 abiList = Build.SUPPORTED_32_BIT_ABIS; 7654 needsRenderScriptOverride = true; 7655 } 7656 7657 final int copyRet; 7658 if (extractLibs) { 7659 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7660 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7661 } else { 7662 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7663 } 7664 7665 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7666 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7667 "Error unpackaging native libs for app, errorCode=" + copyRet); 7668 } 7669 7670 if (copyRet >= 0) { 7671 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7672 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7673 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7674 } else if (needsRenderScriptOverride) { 7675 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7676 } 7677 } 7678 } catch (IOException ioe) { 7679 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7680 } finally { 7681 IoUtils.closeQuietly(handle); 7682 } 7683 7684 // Now that we've calculated the ABIs and determined if it's an internal app, 7685 // we will go ahead and populate the nativeLibraryPath. 7686 setNativeLibraryPaths(pkg); 7687 } 7688 7689 /** 7690 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7691 * i.e, so that all packages can be run inside a single process if required. 7692 * 7693 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7694 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7695 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7696 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7697 * updating a package that belongs to a shared user. 7698 * 7699 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7700 * adds unnecessary complexity. 7701 */ 7702 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7703 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt, 7704 boolean bootComplete) { 7705 String requiredInstructionSet = null; 7706 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7707 requiredInstructionSet = VMRuntime.getInstructionSet( 7708 scannedPackage.applicationInfo.primaryCpuAbi); 7709 } 7710 7711 PackageSetting requirer = null; 7712 for (PackageSetting ps : packagesForUser) { 7713 // If packagesForUser contains scannedPackage, we skip it. This will happen 7714 // when scannedPackage is an update of an existing package. Without this check, 7715 // we will never be able to change the ABI of any package belonging to a shared 7716 // user, even if it's compatible with other packages. 7717 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7718 if (ps.primaryCpuAbiString == null) { 7719 continue; 7720 } 7721 7722 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7723 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7724 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7725 // this but there's not much we can do. 7726 String errorMessage = "Instruction set mismatch, " 7727 + ((requirer == null) ? "[caller]" : requirer) 7728 + " requires " + requiredInstructionSet + " whereas " + ps 7729 + " requires " + instructionSet; 7730 Slog.w(TAG, errorMessage); 7731 } 7732 7733 if (requiredInstructionSet == null) { 7734 requiredInstructionSet = instructionSet; 7735 requirer = ps; 7736 } 7737 } 7738 } 7739 7740 if (requiredInstructionSet != null) { 7741 String adjustedAbi; 7742 if (requirer != null) { 7743 // requirer != null implies that either scannedPackage was null or that scannedPackage 7744 // did not require an ABI, in which case we have to adjust scannedPackage to match 7745 // the ABI of the set (which is the same as requirer's ABI) 7746 adjustedAbi = requirer.primaryCpuAbiString; 7747 if (scannedPackage != null) { 7748 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7749 } 7750 } else { 7751 // requirer == null implies that we're updating all ABIs in the set to 7752 // match scannedPackage. 7753 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7754 } 7755 7756 for (PackageSetting ps : packagesForUser) { 7757 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7758 if (ps.primaryCpuAbiString != null) { 7759 continue; 7760 } 7761 7762 ps.primaryCpuAbiString = adjustedAbi; 7763 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7764 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7765 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7766 7767 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7768 null /* instruction sets */, forceDexOpt, deferDexOpt, true, 7769 bootComplete, false /*useJit*/); 7770 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7771 ps.primaryCpuAbiString = null; 7772 ps.pkg.applicationInfo.primaryCpuAbi = null; 7773 return; 7774 } else { 7775 mInstaller.rmdex(ps.codePathString, 7776 getDexCodeInstructionSet(getPreferredInstructionSet())); 7777 } 7778 } 7779 } 7780 } 7781 } 7782 } 7783 7784 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7785 synchronized (mPackages) { 7786 mResolverReplaced = true; 7787 // Set up information for custom user intent resolution activity. 7788 mResolveActivity.applicationInfo = pkg.applicationInfo; 7789 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7790 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7791 mResolveActivity.processName = pkg.applicationInfo.packageName; 7792 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7793 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7794 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7795 mResolveActivity.theme = 0; 7796 mResolveActivity.exported = true; 7797 mResolveActivity.enabled = true; 7798 mResolveInfo.activityInfo = mResolveActivity; 7799 mResolveInfo.priority = 0; 7800 mResolveInfo.preferredOrder = 0; 7801 mResolveInfo.match = 0; 7802 mResolveComponentName = mCustomResolverComponentName; 7803 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7804 mResolveComponentName); 7805 } 7806 } 7807 7808 private static String calculateBundledApkRoot(final String codePathString) { 7809 final File codePath = new File(codePathString); 7810 final File codeRoot; 7811 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7812 codeRoot = Environment.getRootDirectory(); 7813 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7814 codeRoot = Environment.getOemDirectory(); 7815 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7816 codeRoot = Environment.getVendorDirectory(); 7817 } else { 7818 // Unrecognized code path; take its top real segment as the apk root: 7819 // e.g. /something/app/blah.apk => /something 7820 try { 7821 File f = codePath.getCanonicalFile(); 7822 File parent = f.getParentFile(); // non-null because codePath is a file 7823 File tmp; 7824 while ((tmp = parent.getParentFile()) != null) { 7825 f = parent; 7826 parent = tmp; 7827 } 7828 codeRoot = f; 7829 Slog.w(TAG, "Unrecognized code path " 7830 + codePath + " - using " + codeRoot); 7831 } catch (IOException e) { 7832 // Can't canonicalize the code path -- shenanigans? 7833 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7834 return Environment.getRootDirectory().getPath(); 7835 } 7836 } 7837 return codeRoot.getPath(); 7838 } 7839 7840 /** 7841 * Derive and set the location of native libraries for the given package, 7842 * which varies depending on where and how the package was installed. 7843 */ 7844 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7845 final ApplicationInfo info = pkg.applicationInfo; 7846 final String codePath = pkg.codePath; 7847 final File codeFile = new File(codePath); 7848 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7849 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 7850 7851 info.nativeLibraryRootDir = null; 7852 info.nativeLibraryRootRequiresIsa = false; 7853 info.nativeLibraryDir = null; 7854 info.secondaryNativeLibraryDir = null; 7855 7856 if (isApkFile(codeFile)) { 7857 // Monolithic install 7858 if (bundledApp) { 7859 // If "/system/lib64/apkname" exists, assume that is the per-package 7860 // native library directory to use; otherwise use "/system/lib/apkname". 7861 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7862 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7863 getPrimaryInstructionSet(info)); 7864 7865 // This is a bundled system app so choose the path based on the ABI. 7866 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7867 // is just the default path. 7868 final String apkName = deriveCodePathName(codePath); 7869 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7870 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7871 apkName).getAbsolutePath(); 7872 7873 if (info.secondaryCpuAbi != null) { 7874 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7875 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7876 secondaryLibDir, apkName).getAbsolutePath(); 7877 } 7878 } else if (asecApp) { 7879 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7880 .getAbsolutePath(); 7881 } else { 7882 final String apkName = deriveCodePathName(codePath); 7883 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7884 .getAbsolutePath(); 7885 } 7886 7887 info.nativeLibraryRootRequiresIsa = false; 7888 info.nativeLibraryDir = info.nativeLibraryRootDir; 7889 } else { 7890 // Cluster install 7891 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7892 info.nativeLibraryRootRequiresIsa = true; 7893 7894 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7895 getPrimaryInstructionSet(info)).getAbsolutePath(); 7896 7897 if (info.secondaryCpuAbi != null) { 7898 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7899 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7900 } 7901 } 7902 } 7903 7904 /** 7905 * Calculate the abis and roots for a bundled app. These can uniquely 7906 * be determined from the contents of the system partition, i.e whether 7907 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7908 * of this information, and instead assume that the system was built 7909 * sensibly. 7910 */ 7911 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7912 PackageSetting pkgSetting) { 7913 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7914 7915 // If "/system/lib64/apkname" exists, assume that is the per-package 7916 // native library directory to use; otherwise use "/system/lib/apkname". 7917 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7918 setBundledAppAbi(pkg, apkRoot, apkName); 7919 // pkgSetting might be null during rescan following uninstall of updates 7920 // to a bundled app, so accommodate that possibility. The settings in 7921 // that case will be established later from the parsed package. 7922 // 7923 // If the settings aren't null, sync them up with what we've just derived. 7924 // note that apkRoot isn't stored in the package settings. 7925 if (pkgSetting != null) { 7926 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7927 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7928 } 7929 } 7930 7931 /** 7932 * Deduces the ABI of a bundled app and sets the relevant fields on the 7933 * parsed pkg object. 7934 * 7935 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7936 * under which system libraries are installed. 7937 * @param apkName the name of the installed package. 7938 */ 7939 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7940 final File codeFile = new File(pkg.codePath); 7941 7942 final boolean has64BitLibs; 7943 final boolean has32BitLibs; 7944 if (isApkFile(codeFile)) { 7945 // Monolithic install 7946 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7947 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7948 } else { 7949 // Cluster install 7950 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7951 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7952 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7953 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7954 has64BitLibs = (new File(rootDir, isa)).exists(); 7955 } else { 7956 has64BitLibs = false; 7957 } 7958 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7959 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7960 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7961 has32BitLibs = (new File(rootDir, isa)).exists(); 7962 } else { 7963 has32BitLibs = false; 7964 } 7965 } 7966 7967 if (has64BitLibs && !has32BitLibs) { 7968 // The package has 64 bit libs, but not 32 bit libs. Its primary 7969 // ABI should be 64 bit. We can safely assume here that the bundled 7970 // native libraries correspond to the most preferred ABI in the list. 7971 7972 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7973 pkg.applicationInfo.secondaryCpuAbi = null; 7974 } else if (has32BitLibs && !has64BitLibs) { 7975 // The package has 32 bit libs but not 64 bit libs. Its primary 7976 // ABI should be 32 bit. 7977 7978 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7979 pkg.applicationInfo.secondaryCpuAbi = null; 7980 } else if (has32BitLibs && has64BitLibs) { 7981 // The application has both 64 and 32 bit bundled libraries. We check 7982 // here that the app declares multiArch support, and warn if it doesn't. 7983 // 7984 // We will be lenient here and record both ABIs. The primary will be the 7985 // ABI that's higher on the list, i.e, a device that's configured to prefer 7986 // 64 bit apps will see a 64 bit primary ABI, 7987 7988 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7989 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7990 } 7991 7992 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7993 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7994 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7995 } else { 7996 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7997 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7998 } 7999 } else { 8000 pkg.applicationInfo.primaryCpuAbi = null; 8001 pkg.applicationInfo.secondaryCpuAbi = null; 8002 } 8003 } 8004 8005 private void killApplication(String pkgName, int appId, String reason) { 8006 // Request the ActivityManager to kill the process(only for existing packages) 8007 // so that we do not end up in a confused state while the user is still using the older 8008 // version of the application while the new one gets installed. 8009 IActivityManager am = ActivityManagerNative.getDefault(); 8010 if (am != null) { 8011 try { 8012 am.killApplicationWithAppId(pkgName, appId, reason); 8013 } catch (RemoteException e) { 8014 } 8015 } 8016 } 8017 8018 void removePackageLI(PackageSetting ps, boolean chatty) { 8019 if (DEBUG_INSTALL) { 8020 if (chatty) 8021 Log.d(TAG, "Removing package " + ps.name); 8022 } 8023 8024 // writer 8025 synchronized (mPackages) { 8026 mPackages.remove(ps.name); 8027 final PackageParser.Package pkg = ps.pkg; 8028 if (pkg != null) { 8029 cleanPackageDataStructuresLILPw(pkg, chatty); 8030 } 8031 } 8032 } 8033 8034 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8035 if (DEBUG_INSTALL) { 8036 if (chatty) 8037 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8038 } 8039 8040 // writer 8041 synchronized (mPackages) { 8042 mPackages.remove(pkg.applicationInfo.packageName); 8043 cleanPackageDataStructuresLILPw(pkg, chatty); 8044 } 8045 } 8046 8047 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8048 int N = pkg.providers.size(); 8049 StringBuilder r = null; 8050 int i; 8051 for (i=0; i<N; i++) { 8052 PackageParser.Provider p = pkg.providers.get(i); 8053 mProviders.removeProvider(p); 8054 if (p.info.authority == null) { 8055 8056 /* There was another ContentProvider with this authority when 8057 * this app was installed so this authority is null, 8058 * Ignore it as we don't have to unregister the provider. 8059 */ 8060 continue; 8061 } 8062 String names[] = p.info.authority.split(";"); 8063 for (int j = 0; j < names.length; j++) { 8064 if (mProvidersByAuthority.get(names[j]) == p) { 8065 mProvidersByAuthority.remove(names[j]); 8066 if (DEBUG_REMOVE) { 8067 if (chatty) 8068 Log.d(TAG, "Unregistered content provider: " + names[j] 8069 + ", className = " + p.info.name + ", isSyncable = " 8070 + p.info.isSyncable); 8071 } 8072 } 8073 } 8074 if (DEBUG_REMOVE && chatty) { 8075 if (r == null) { 8076 r = new StringBuilder(256); 8077 } else { 8078 r.append(' '); 8079 } 8080 r.append(p.info.name); 8081 } 8082 } 8083 if (r != null) { 8084 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8085 } 8086 8087 N = pkg.services.size(); 8088 r = null; 8089 for (i=0; i<N; i++) { 8090 PackageParser.Service s = pkg.services.get(i); 8091 mServices.removeService(s); 8092 if (chatty) { 8093 if (r == null) { 8094 r = new StringBuilder(256); 8095 } else { 8096 r.append(' '); 8097 } 8098 r.append(s.info.name); 8099 } 8100 } 8101 if (r != null) { 8102 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8103 } 8104 8105 N = pkg.receivers.size(); 8106 r = null; 8107 for (i=0; i<N; i++) { 8108 PackageParser.Activity a = pkg.receivers.get(i); 8109 mReceivers.removeActivity(a, "receiver"); 8110 if (DEBUG_REMOVE && chatty) { 8111 if (r == null) { 8112 r = new StringBuilder(256); 8113 } else { 8114 r.append(' '); 8115 } 8116 r.append(a.info.name); 8117 } 8118 } 8119 if (r != null) { 8120 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8121 } 8122 8123 N = pkg.activities.size(); 8124 r = null; 8125 for (i=0; i<N; i++) { 8126 PackageParser.Activity a = pkg.activities.get(i); 8127 mActivities.removeActivity(a, "activity"); 8128 if (DEBUG_REMOVE && chatty) { 8129 if (r == null) { 8130 r = new StringBuilder(256); 8131 } else { 8132 r.append(' '); 8133 } 8134 r.append(a.info.name); 8135 } 8136 } 8137 if (r != null) { 8138 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8139 } 8140 8141 N = pkg.permissions.size(); 8142 r = null; 8143 for (i=0; i<N; i++) { 8144 PackageParser.Permission p = pkg.permissions.get(i); 8145 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8146 if (bp == null) { 8147 bp = mSettings.mPermissionTrees.get(p.info.name); 8148 } 8149 if (bp != null && bp.perm == p) { 8150 bp.perm = null; 8151 if (DEBUG_REMOVE && chatty) { 8152 if (r == null) { 8153 r = new StringBuilder(256); 8154 } else { 8155 r.append(' '); 8156 } 8157 r.append(p.info.name); 8158 } 8159 } 8160 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8161 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8162 if (appOpPerms != null) { 8163 appOpPerms.remove(pkg.packageName); 8164 } 8165 } 8166 } 8167 if (r != null) { 8168 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8169 } 8170 8171 N = pkg.requestedPermissions.size(); 8172 r = null; 8173 for (i=0; i<N; i++) { 8174 String perm = pkg.requestedPermissions.get(i); 8175 BasePermission bp = mSettings.mPermissions.get(perm); 8176 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8177 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8178 if (appOpPerms != null) { 8179 appOpPerms.remove(pkg.packageName); 8180 if (appOpPerms.isEmpty()) { 8181 mAppOpPermissionPackages.remove(perm); 8182 } 8183 } 8184 } 8185 } 8186 if (r != null) { 8187 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8188 } 8189 8190 N = pkg.instrumentation.size(); 8191 r = null; 8192 for (i=0; i<N; i++) { 8193 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8194 mInstrumentation.remove(a.getComponentName()); 8195 if (DEBUG_REMOVE && chatty) { 8196 if (r == null) { 8197 r = new StringBuilder(256); 8198 } else { 8199 r.append(' '); 8200 } 8201 r.append(a.info.name); 8202 } 8203 } 8204 if (r != null) { 8205 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8206 } 8207 8208 r = null; 8209 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8210 // Only system apps can hold shared libraries. 8211 if (pkg.libraryNames != null) { 8212 for (i=0; i<pkg.libraryNames.size(); i++) { 8213 String name = pkg.libraryNames.get(i); 8214 SharedLibraryEntry cur = mSharedLibraries.get(name); 8215 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8216 mSharedLibraries.remove(name); 8217 if (DEBUG_REMOVE && chatty) { 8218 if (r == null) { 8219 r = new StringBuilder(256); 8220 } else { 8221 r.append(' '); 8222 } 8223 r.append(name); 8224 } 8225 } 8226 } 8227 } 8228 } 8229 if (r != null) { 8230 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8231 } 8232 } 8233 8234 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8235 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8236 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8237 return true; 8238 } 8239 } 8240 return false; 8241 } 8242 8243 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8244 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8245 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8246 8247 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8248 int flags) { 8249 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8250 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8251 } 8252 8253 private void updatePermissionsLPw(String changingPkg, 8254 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8255 // Make sure there are no dangling permission trees. 8256 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8257 while (it.hasNext()) { 8258 final BasePermission bp = it.next(); 8259 if (bp.packageSetting == null) { 8260 // We may not yet have parsed the package, so just see if 8261 // we still know about its settings. 8262 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8263 } 8264 if (bp.packageSetting == null) { 8265 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8266 + " from package " + bp.sourcePackage); 8267 it.remove(); 8268 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8269 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8270 Slog.i(TAG, "Removing old permission tree: " + bp.name 8271 + " from package " + bp.sourcePackage); 8272 flags |= UPDATE_PERMISSIONS_ALL; 8273 it.remove(); 8274 } 8275 } 8276 } 8277 8278 // Make sure all dynamic permissions have been assigned to a package, 8279 // and make sure there are no dangling permissions. 8280 it = mSettings.mPermissions.values().iterator(); 8281 while (it.hasNext()) { 8282 final BasePermission bp = it.next(); 8283 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8284 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8285 + bp.name + " pkg=" + bp.sourcePackage 8286 + " info=" + bp.pendingInfo); 8287 if (bp.packageSetting == null && bp.pendingInfo != null) { 8288 final BasePermission tree = findPermissionTreeLP(bp.name); 8289 if (tree != null && tree.perm != null) { 8290 bp.packageSetting = tree.packageSetting; 8291 bp.perm = new PackageParser.Permission(tree.perm.owner, 8292 new PermissionInfo(bp.pendingInfo)); 8293 bp.perm.info.packageName = tree.perm.info.packageName; 8294 bp.perm.info.name = bp.name; 8295 bp.uid = tree.uid; 8296 } 8297 } 8298 } 8299 if (bp.packageSetting == null) { 8300 // We may not yet have parsed the package, so just see if 8301 // we still know about its settings. 8302 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8303 } 8304 if (bp.packageSetting == null) { 8305 Slog.w(TAG, "Removing dangling permission: " + bp.name 8306 + " from package " + bp.sourcePackage); 8307 it.remove(); 8308 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8309 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8310 Slog.i(TAG, "Removing old permission: " + bp.name 8311 + " from package " + bp.sourcePackage); 8312 flags |= UPDATE_PERMISSIONS_ALL; 8313 it.remove(); 8314 } 8315 } 8316 } 8317 8318 // Now update the permissions for all packages, in particular 8319 // replace the granted permissions of the system packages. 8320 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8321 for (PackageParser.Package pkg : mPackages.values()) { 8322 if (pkg != pkgInfo) { 8323 // Only replace for packages on requested volume 8324 final String volumeUuid = getVolumeUuidForPackage(pkg); 8325 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8326 && Objects.equals(replaceVolumeUuid, volumeUuid); 8327 grantPermissionsLPw(pkg, replace, changingPkg); 8328 } 8329 } 8330 } 8331 8332 if (pkgInfo != null) { 8333 // Only replace for packages on requested volume 8334 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8335 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8336 && Objects.equals(replaceVolumeUuid, volumeUuid); 8337 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8338 } 8339 } 8340 8341 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8342 String packageOfInterest) { 8343 // IMPORTANT: There are two types of permissions: install and runtime. 8344 // Install time permissions are granted when the app is installed to 8345 // all device users and users added in the future. Runtime permissions 8346 // are granted at runtime explicitly to specific users. Normal and signature 8347 // protected permissions are install time permissions. Dangerous permissions 8348 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8349 // otherwise they are runtime permissions. This function does not manage 8350 // runtime permissions except for the case an app targeting Lollipop MR1 8351 // being upgraded to target a newer SDK, in which case dangerous permissions 8352 // are transformed from install time to runtime ones. 8353 8354 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8355 if (ps == null) { 8356 return; 8357 } 8358 8359 PermissionsState permissionsState = ps.getPermissionsState(); 8360 PermissionsState origPermissions = permissionsState; 8361 8362 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8363 8364 boolean runtimePermissionsRevoked = false; 8365 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8366 8367 boolean changedInstallPermission = false; 8368 8369 if (replace) { 8370 ps.installPermissionsFixed = false; 8371 if (!ps.isSharedUser()) { 8372 origPermissions = new PermissionsState(permissionsState); 8373 permissionsState.reset(); 8374 } else { 8375 // We need to know only about runtime permission changes since the 8376 // calling code always writes the install permissions state but 8377 // the runtime ones are written only if changed. The only cases of 8378 // changed runtime permissions here are promotion of an install to 8379 // runtime and revocation of a runtime from a shared user. 8380 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8381 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8382 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8383 runtimePermissionsRevoked = true; 8384 } 8385 } 8386 } 8387 8388 permissionsState.setGlobalGids(mGlobalGids); 8389 8390 final int N = pkg.requestedPermissions.size(); 8391 for (int i=0; i<N; i++) { 8392 final String name = pkg.requestedPermissions.get(i); 8393 final BasePermission bp = mSettings.mPermissions.get(name); 8394 8395 if (DEBUG_INSTALL) { 8396 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8397 } 8398 8399 if (bp == null || bp.packageSetting == null) { 8400 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8401 Slog.w(TAG, "Unknown permission " + name 8402 + " in package " + pkg.packageName); 8403 } 8404 continue; 8405 } 8406 8407 final String perm = bp.name; 8408 boolean allowedSig = false; 8409 int grant = GRANT_DENIED; 8410 8411 // Keep track of app op permissions. 8412 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8413 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8414 if (pkgs == null) { 8415 pkgs = new ArraySet<>(); 8416 mAppOpPermissionPackages.put(bp.name, pkgs); 8417 } 8418 pkgs.add(pkg.packageName); 8419 } 8420 8421 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8422 switch (level) { 8423 case PermissionInfo.PROTECTION_NORMAL: { 8424 // For all apps normal permissions are install time ones. 8425 grant = GRANT_INSTALL; 8426 } break; 8427 8428 case PermissionInfo.PROTECTION_DANGEROUS: { 8429 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8430 // For legacy apps dangerous permissions are install time ones. 8431 grant = GRANT_INSTALL_LEGACY; 8432 } else if (origPermissions.hasInstallPermission(bp.name)) { 8433 // For legacy apps that became modern, install becomes runtime. 8434 grant = GRANT_UPGRADE; 8435 } else if (mPromoteSystemApps 8436 && isSystemApp(ps) 8437 && mExistingSystemPackages.contains(ps.name)) { 8438 // For legacy system apps, install becomes runtime. 8439 // We cannot check hasInstallPermission() for system apps since those 8440 // permissions were granted implicitly and not persisted pre-M. 8441 grant = GRANT_UPGRADE; 8442 } else { 8443 // For modern apps keep runtime permissions unchanged. 8444 grant = GRANT_RUNTIME; 8445 } 8446 } break; 8447 8448 case PermissionInfo.PROTECTION_SIGNATURE: { 8449 // For all apps signature permissions are install time ones. 8450 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8451 if (allowedSig) { 8452 grant = GRANT_INSTALL; 8453 } 8454 } break; 8455 } 8456 8457 if (DEBUG_INSTALL) { 8458 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8459 } 8460 8461 if (grant != GRANT_DENIED) { 8462 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8463 // If this is an existing, non-system package, then 8464 // we can't add any new permissions to it. 8465 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8466 // Except... if this is a permission that was added 8467 // to the platform (note: need to only do this when 8468 // updating the platform). 8469 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8470 grant = GRANT_DENIED; 8471 } 8472 } 8473 } 8474 8475 switch (grant) { 8476 case GRANT_INSTALL: { 8477 // Revoke this as runtime permission to handle the case of 8478 // a runtime permission being downgraded to an install one. 8479 for (int userId : UserManagerService.getInstance().getUserIds()) { 8480 if (origPermissions.getRuntimePermissionState( 8481 bp.name, userId) != null) { 8482 // Revoke the runtime permission and clear the flags. 8483 origPermissions.revokeRuntimePermission(bp, userId); 8484 origPermissions.updatePermissionFlags(bp, userId, 8485 PackageManager.MASK_PERMISSION_FLAGS, 0); 8486 // If we revoked a permission permission, we have to write. 8487 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8488 changedRuntimePermissionUserIds, userId); 8489 } 8490 } 8491 // Grant an install permission. 8492 if (permissionsState.grantInstallPermission(bp) != 8493 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8494 changedInstallPermission = true; 8495 } 8496 } break; 8497 8498 case GRANT_INSTALL_LEGACY: { 8499 // Grant an install permission. 8500 if (permissionsState.grantInstallPermission(bp) != 8501 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8502 changedInstallPermission = true; 8503 } 8504 } break; 8505 8506 case GRANT_RUNTIME: { 8507 // Grant previously granted runtime permissions. 8508 for (int userId : UserManagerService.getInstance().getUserIds()) { 8509 PermissionState permissionState = origPermissions 8510 .getRuntimePermissionState(bp.name, userId); 8511 final int flags = permissionState != null 8512 ? permissionState.getFlags() : 0; 8513 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8514 if (permissionsState.grantRuntimePermission(bp, userId) == 8515 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8516 // If we cannot put the permission as it was, we have to write. 8517 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8518 changedRuntimePermissionUserIds, userId); 8519 } 8520 } 8521 // Propagate the permission flags. 8522 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8523 } 8524 } break; 8525 8526 case GRANT_UPGRADE: { 8527 // Grant runtime permissions for a previously held install permission. 8528 PermissionState permissionState = origPermissions 8529 .getInstallPermissionState(bp.name); 8530 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8531 8532 if (origPermissions.revokeInstallPermission(bp) 8533 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8534 // We will be transferring the permission flags, so clear them. 8535 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8536 PackageManager.MASK_PERMISSION_FLAGS, 0); 8537 changedInstallPermission = true; 8538 } 8539 8540 // If the permission is not to be promoted to runtime we ignore it and 8541 // also its other flags as they are not applicable to install permissions. 8542 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8543 for (int userId : currentUserIds) { 8544 if (permissionsState.grantRuntimePermission(bp, userId) != 8545 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8546 // Transfer the permission flags. 8547 permissionsState.updatePermissionFlags(bp, userId, 8548 flags, flags); 8549 // If we granted the permission, we have to write. 8550 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8551 changedRuntimePermissionUserIds, userId); 8552 } 8553 } 8554 } 8555 } break; 8556 8557 default: { 8558 if (packageOfInterest == null 8559 || packageOfInterest.equals(pkg.packageName)) { 8560 Slog.w(TAG, "Not granting permission " + perm 8561 + " to package " + pkg.packageName 8562 + " because it was previously installed without"); 8563 } 8564 } break; 8565 } 8566 } else { 8567 if (permissionsState.revokeInstallPermission(bp) != 8568 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8569 // Also drop the permission flags. 8570 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8571 PackageManager.MASK_PERMISSION_FLAGS, 0); 8572 changedInstallPermission = true; 8573 Slog.i(TAG, "Un-granting permission " + perm 8574 + " from package " + pkg.packageName 8575 + " (protectionLevel=" + bp.protectionLevel 8576 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8577 + ")"); 8578 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8579 // Don't print warning for app op permissions, since it is fine for them 8580 // not to be granted, there is a UI for the user to decide. 8581 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8582 Slog.w(TAG, "Not granting permission " + perm 8583 + " to package " + pkg.packageName 8584 + " (protectionLevel=" + bp.protectionLevel 8585 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8586 + ")"); 8587 } 8588 } 8589 } 8590 } 8591 8592 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8593 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8594 // This is the first that we have heard about this package, so the 8595 // permissions we have now selected are fixed until explicitly 8596 // changed. 8597 ps.installPermissionsFixed = true; 8598 } 8599 8600 // Persist the runtime permissions state for users with changes. If permissions 8601 // were revoked because no app in the shared user declares them we have to 8602 // write synchronously to avoid losing runtime permissions state. 8603 for (int userId : changedRuntimePermissionUserIds) { 8604 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8605 } 8606 } 8607 8608 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8609 boolean allowed = false; 8610 final int NP = PackageParser.NEW_PERMISSIONS.length; 8611 for (int ip=0; ip<NP; ip++) { 8612 final PackageParser.NewPermissionInfo npi 8613 = PackageParser.NEW_PERMISSIONS[ip]; 8614 if (npi.name.equals(perm) 8615 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8616 allowed = true; 8617 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8618 + pkg.packageName); 8619 break; 8620 } 8621 } 8622 return allowed; 8623 } 8624 8625 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8626 BasePermission bp, PermissionsState origPermissions) { 8627 boolean allowed; 8628 allowed = (compareSignatures( 8629 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8630 == PackageManager.SIGNATURE_MATCH) 8631 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8632 == PackageManager.SIGNATURE_MATCH); 8633 if (!allowed && (bp.protectionLevel 8634 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8635 if (isSystemApp(pkg)) { 8636 // For updated system applications, a system permission 8637 // is granted only if it had been defined by the original application. 8638 if (pkg.isUpdatedSystemApp()) { 8639 final PackageSetting sysPs = mSettings 8640 .getDisabledSystemPkgLPr(pkg.packageName); 8641 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8642 // If the original was granted this permission, we take 8643 // that grant decision as read and propagate it to the 8644 // update. 8645 if (sysPs.isPrivileged()) { 8646 allowed = true; 8647 } 8648 } else { 8649 // The system apk may have been updated with an older 8650 // version of the one on the data partition, but which 8651 // granted a new system permission that it didn't have 8652 // before. In this case we do want to allow the app to 8653 // now get the new permission if the ancestral apk is 8654 // privileged to get it. 8655 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8656 for (int j=0; 8657 j<sysPs.pkg.requestedPermissions.size(); j++) { 8658 if (perm.equals( 8659 sysPs.pkg.requestedPermissions.get(j))) { 8660 allowed = true; 8661 break; 8662 } 8663 } 8664 } 8665 } 8666 } else { 8667 allowed = isPrivilegedApp(pkg); 8668 } 8669 } 8670 } 8671 if (!allowed) { 8672 if (!allowed && (bp.protectionLevel 8673 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8674 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8675 // If this was a previously normal/dangerous permission that got moved 8676 // to a system permission as part of the runtime permission redesign, then 8677 // we still want to blindly grant it to old apps. 8678 allowed = true; 8679 } 8680 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8681 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8682 // If this permission is to be granted to the system installer and 8683 // this app is an installer, then it gets the permission. 8684 allowed = true; 8685 } 8686 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8687 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8688 // If this permission is to be granted to the system verifier and 8689 // this app is a verifier, then it gets the permission. 8690 allowed = true; 8691 } 8692 if (!allowed && (bp.protectionLevel 8693 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8694 && isSystemApp(pkg)) { 8695 // Any pre-installed system app is allowed to get this permission. 8696 allowed = true; 8697 } 8698 if (!allowed && (bp.protectionLevel 8699 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8700 // For development permissions, a development permission 8701 // is granted only if it was already granted. 8702 allowed = origPermissions.hasInstallPermission(perm); 8703 } 8704 } 8705 return allowed; 8706 } 8707 8708 final class ActivityIntentResolver 8709 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8710 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8711 boolean defaultOnly, int userId) { 8712 if (!sUserManager.exists(userId)) return null; 8713 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8714 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8715 } 8716 8717 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8718 int userId) { 8719 if (!sUserManager.exists(userId)) return null; 8720 mFlags = flags; 8721 return super.queryIntent(intent, resolvedType, 8722 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8723 } 8724 8725 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8726 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8727 if (!sUserManager.exists(userId)) return null; 8728 if (packageActivities == null) { 8729 return null; 8730 } 8731 mFlags = flags; 8732 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8733 final int N = packageActivities.size(); 8734 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8735 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8736 8737 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8738 for (int i = 0; i < N; ++i) { 8739 intentFilters = packageActivities.get(i).intents; 8740 if (intentFilters != null && intentFilters.size() > 0) { 8741 PackageParser.ActivityIntentInfo[] array = 8742 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8743 intentFilters.toArray(array); 8744 listCut.add(array); 8745 } 8746 } 8747 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8748 } 8749 8750 public final void addActivity(PackageParser.Activity a, String type) { 8751 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8752 mActivities.put(a.getComponentName(), a); 8753 if (DEBUG_SHOW_INFO) 8754 Log.v( 8755 TAG, " " + type + " " + 8756 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8757 if (DEBUG_SHOW_INFO) 8758 Log.v(TAG, " Class=" + a.info.name); 8759 final int NI = a.intents.size(); 8760 for (int j=0; j<NI; j++) { 8761 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8762 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8763 intent.setPriority(0); 8764 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8765 + a.className + " with priority > 0, forcing to 0"); 8766 } 8767 if (DEBUG_SHOW_INFO) { 8768 Log.v(TAG, " IntentFilter:"); 8769 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8770 } 8771 if (!intent.debugCheck()) { 8772 Log.w(TAG, "==> For Activity " + a.info.name); 8773 } 8774 addFilter(intent); 8775 } 8776 } 8777 8778 public final void removeActivity(PackageParser.Activity a, String type) { 8779 mActivities.remove(a.getComponentName()); 8780 if (DEBUG_SHOW_INFO) { 8781 Log.v(TAG, " " + type + " " 8782 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8783 : a.info.name) + ":"); 8784 Log.v(TAG, " Class=" + a.info.name); 8785 } 8786 final int NI = a.intents.size(); 8787 for (int j=0; j<NI; j++) { 8788 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8789 if (DEBUG_SHOW_INFO) { 8790 Log.v(TAG, " IntentFilter:"); 8791 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8792 } 8793 removeFilter(intent); 8794 } 8795 } 8796 8797 @Override 8798 protected boolean allowFilterResult( 8799 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8800 ActivityInfo filterAi = filter.activity.info; 8801 for (int i=dest.size()-1; i>=0; i--) { 8802 ActivityInfo destAi = dest.get(i).activityInfo; 8803 if (destAi.name == filterAi.name 8804 && destAi.packageName == filterAi.packageName) { 8805 return false; 8806 } 8807 } 8808 return true; 8809 } 8810 8811 @Override 8812 protected ActivityIntentInfo[] newArray(int size) { 8813 return new ActivityIntentInfo[size]; 8814 } 8815 8816 @Override 8817 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8818 if (!sUserManager.exists(userId)) return true; 8819 PackageParser.Package p = filter.activity.owner; 8820 if (p != null) { 8821 PackageSetting ps = (PackageSetting)p.mExtras; 8822 if (ps != null) { 8823 // System apps are never considered stopped for purposes of 8824 // filtering, because there may be no way for the user to 8825 // actually re-launch them. 8826 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8827 && ps.getStopped(userId); 8828 } 8829 } 8830 return false; 8831 } 8832 8833 @Override 8834 protected boolean isPackageForFilter(String packageName, 8835 PackageParser.ActivityIntentInfo info) { 8836 return packageName.equals(info.activity.owner.packageName); 8837 } 8838 8839 @Override 8840 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8841 int match, int userId) { 8842 if (!sUserManager.exists(userId)) return null; 8843 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8844 return null; 8845 } 8846 final PackageParser.Activity activity = info.activity; 8847 if (mSafeMode && (activity.info.applicationInfo.flags 8848 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8849 return null; 8850 } 8851 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8852 if (ps == null) { 8853 return null; 8854 } 8855 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8856 ps.readUserState(userId), userId); 8857 if (ai == null) { 8858 return null; 8859 } 8860 final ResolveInfo res = new ResolveInfo(); 8861 res.activityInfo = ai; 8862 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8863 res.filter = info; 8864 } 8865 if (info != null) { 8866 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8867 } 8868 res.priority = info.getPriority(); 8869 res.preferredOrder = activity.owner.mPreferredOrder; 8870 //System.out.println("Result: " + res.activityInfo.className + 8871 // " = " + res.priority); 8872 res.match = match; 8873 res.isDefault = info.hasDefault; 8874 res.labelRes = info.labelRes; 8875 res.nonLocalizedLabel = info.nonLocalizedLabel; 8876 if (userNeedsBadging(userId)) { 8877 res.noResourceId = true; 8878 } else { 8879 res.icon = info.icon; 8880 } 8881 res.iconResourceId = info.icon; 8882 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8883 return res; 8884 } 8885 8886 @Override 8887 protected void sortResults(List<ResolveInfo> results) { 8888 Collections.sort(results, mResolvePrioritySorter); 8889 } 8890 8891 @Override 8892 protected void dumpFilter(PrintWriter out, String prefix, 8893 PackageParser.ActivityIntentInfo filter) { 8894 out.print(prefix); out.print( 8895 Integer.toHexString(System.identityHashCode(filter.activity))); 8896 out.print(' '); 8897 filter.activity.printComponentShortName(out); 8898 out.print(" filter "); 8899 out.println(Integer.toHexString(System.identityHashCode(filter))); 8900 } 8901 8902 @Override 8903 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8904 return filter.activity; 8905 } 8906 8907 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8908 PackageParser.Activity activity = (PackageParser.Activity)label; 8909 out.print(prefix); out.print( 8910 Integer.toHexString(System.identityHashCode(activity))); 8911 out.print(' '); 8912 activity.printComponentShortName(out); 8913 if (count > 1) { 8914 out.print(" ("); out.print(count); out.print(" filters)"); 8915 } 8916 out.println(); 8917 } 8918 8919// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8920// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8921// final List<ResolveInfo> retList = Lists.newArrayList(); 8922// while (i.hasNext()) { 8923// final ResolveInfo resolveInfo = i.next(); 8924// if (isEnabledLP(resolveInfo.activityInfo)) { 8925// retList.add(resolveInfo); 8926// } 8927// } 8928// return retList; 8929// } 8930 8931 // Keys are String (activity class name), values are Activity. 8932 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8933 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8934 private int mFlags; 8935 } 8936 8937 private final class ServiceIntentResolver 8938 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8939 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8940 boolean defaultOnly, int userId) { 8941 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8942 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8943 } 8944 8945 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8946 int userId) { 8947 if (!sUserManager.exists(userId)) return null; 8948 mFlags = flags; 8949 return super.queryIntent(intent, resolvedType, 8950 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8951 } 8952 8953 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8954 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8955 if (!sUserManager.exists(userId)) return null; 8956 if (packageServices == null) { 8957 return null; 8958 } 8959 mFlags = flags; 8960 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8961 final int N = packageServices.size(); 8962 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8963 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8964 8965 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8966 for (int i = 0; i < N; ++i) { 8967 intentFilters = packageServices.get(i).intents; 8968 if (intentFilters != null && intentFilters.size() > 0) { 8969 PackageParser.ServiceIntentInfo[] array = 8970 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8971 intentFilters.toArray(array); 8972 listCut.add(array); 8973 } 8974 } 8975 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8976 } 8977 8978 public final void addService(PackageParser.Service s) { 8979 mServices.put(s.getComponentName(), s); 8980 if (DEBUG_SHOW_INFO) { 8981 Log.v(TAG, " " 8982 + (s.info.nonLocalizedLabel != null 8983 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8984 Log.v(TAG, " Class=" + s.info.name); 8985 } 8986 final int NI = s.intents.size(); 8987 int j; 8988 for (j=0; j<NI; j++) { 8989 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8990 if (DEBUG_SHOW_INFO) { 8991 Log.v(TAG, " IntentFilter:"); 8992 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8993 } 8994 if (!intent.debugCheck()) { 8995 Log.w(TAG, "==> For Service " + s.info.name); 8996 } 8997 addFilter(intent); 8998 } 8999 } 9000 9001 public final void removeService(PackageParser.Service s) { 9002 mServices.remove(s.getComponentName()); 9003 if (DEBUG_SHOW_INFO) { 9004 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9005 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9006 Log.v(TAG, " Class=" + s.info.name); 9007 } 9008 final int NI = s.intents.size(); 9009 int j; 9010 for (j=0; j<NI; j++) { 9011 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9012 if (DEBUG_SHOW_INFO) { 9013 Log.v(TAG, " IntentFilter:"); 9014 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9015 } 9016 removeFilter(intent); 9017 } 9018 } 9019 9020 @Override 9021 protected boolean allowFilterResult( 9022 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9023 ServiceInfo filterSi = filter.service.info; 9024 for (int i=dest.size()-1; i>=0; i--) { 9025 ServiceInfo destAi = dest.get(i).serviceInfo; 9026 if (destAi.name == filterSi.name 9027 && destAi.packageName == filterSi.packageName) { 9028 return false; 9029 } 9030 } 9031 return true; 9032 } 9033 9034 @Override 9035 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9036 return new PackageParser.ServiceIntentInfo[size]; 9037 } 9038 9039 @Override 9040 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9041 if (!sUserManager.exists(userId)) return true; 9042 PackageParser.Package p = filter.service.owner; 9043 if (p != null) { 9044 PackageSetting ps = (PackageSetting)p.mExtras; 9045 if (ps != null) { 9046 // System apps are never considered stopped for purposes of 9047 // filtering, because there may be no way for the user to 9048 // actually re-launch them. 9049 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9050 && ps.getStopped(userId); 9051 } 9052 } 9053 return false; 9054 } 9055 9056 @Override 9057 protected boolean isPackageForFilter(String packageName, 9058 PackageParser.ServiceIntentInfo info) { 9059 return packageName.equals(info.service.owner.packageName); 9060 } 9061 9062 @Override 9063 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9064 int match, int userId) { 9065 if (!sUserManager.exists(userId)) return null; 9066 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9067 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9068 return null; 9069 } 9070 final PackageParser.Service service = info.service; 9071 if (mSafeMode && (service.info.applicationInfo.flags 9072 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9073 return null; 9074 } 9075 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9076 if (ps == null) { 9077 return null; 9078 } 9079 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9080 ps.readUserState(userId), userId); 9081 if (si == null) { 9082 return null; 9083 } 9084 final ResolveInfo res = new ResolveInfo(); 9085 res.serviceInfo = si; 9086 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9087 res.filter = filter; 9088 } 9089 res.priority = info.getPriority(); 9090 res.preferredOrder = service.owner.mPreferredOrder; 9091 res.match = match; 9092 res.isDefault = info.hasDefault; 9093 res.labelRes = info.labelRes; 9094 res.nonLocalizedLabel = info.nonLocalizedLabel; 9095 res.icon = info.icon; 9096 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9097 return res; 9098 } 9099 9100 @Override 9101 protected void sortResults(List<ResolveInfo> results) { 9102 Collections.sort(results, mResolvePrioritySorter); 9103 } 9104 9105 @Override 9106 protected void dumpFilter(PrintWriter out, String prefix, 9107 PackageParser.ServiceIntentInfo filter) { 9108 out.print(prefix); out.print( 9109 Integer.toHexString(System.identityHashCode(filter.service))); 9110 out.print(' '); 9111 filter.service.printComponentShortName(out); 9112 out.print(" filter "); 9113 out.println(Integer.toHexString(System.identityHashCode(filter))); 9114 } 9115 9116 @Override 9117 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9118 return filter.service; 9119 } 9120 9121 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9122 PackageParser.Service service = (PackageParser.Service)label; 9123 out.print(prefix); out.print( 9124 Integer.toHexString(System.identityHashCode(service))); 9125 out.print(' '); 9126 service.printComponentShortName(out); 9127 if (count > 1) { 9128 out.print(" ("); out.print(count); out.print(" filters)"); 9129 } 9130 out.println(); 9131 } 9132 9133// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9134// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9135// final List<ResolveInfo> retList = Lists.newArrayList(); 9136// while (i.hasNext()) { 9137// final ResolveInfo resolveInfo = (ResolveInfo) i; 9138// if (isEnabledLP(resolveInfo.serviceInfo)) { 9139// retList.add(resolveInfo); 9140// } 9141// } 9142// return retList; 9143// } 9144 9145 // Keys are String (activity class name), values are Activity. 9146 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9147 = new ArrayMap<ComponentName, PackageParser.Service>(); 9148 private int mFlags; 9149 }; 9150 9151 private final class ProviderIntentResolver 9152 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9153 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9154 boolean defaultOnly, int userId) { 9155 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9156 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9157 } 9158 9159 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9160 int userId) { 9161 if (!sUserManager.exists(userId)) 9162 return null; 9163 mFlags = flags; 9164 return super.queryIntent(intent, resolvedType, 9165 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9166 } 9167 9168 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9169 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9170 if (!sUserManager.exists(userId)) 9171 return null; 9172 if (packageProviders == null) { 9173 return null; 9174 } 9175 mFlags = flags; 9176 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9177 final int N = packageProviders.size(); 9178 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9179 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9180 9181 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9182 for (int i = 0; i < N; ++i) { 9183 intentFilters = packageProviders.get(i).intents; 9184 if (intentFilters != null && intentFilters.size() > 0) { 9185 PackageParser.ProviderIntentInfo[] array = 9186 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9187 intentFilters.toArray(array); 9188 listCut.add(array); 9189 } 9190 } 9191 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9192 } 9193 9194 public final void addProvider(PackageParser.Provider p) { 9195 if (mProviders.containsKey(p.getComponentName())) { 9196 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9197 return; 9198 } 9199 9200 mProviders.put(p.getComponentName(), p); 9201 if (DEBUG_SHOW_INFO) { 9202 Log.v(TAG, " " 9203 + (p.info.nonLocalizedLabel != null 9204 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9205 Log.v(TAG, " Class=" + p.info.name); 9206 } 9207 final int NI = p.intents.size(); 9208 int j; 9209 for (j = 0; j < NI; j++) { 9210 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9211 if (DEBUG_SHOW_INFO) { 9212 Log.v(TAG, " IntentFilter:"); 9213 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9214 } 9215 if (!intent.debugCheck()) { 9216 Log.w(TAG, "==> For Provider " + p.info.name); 9217 } 9218 addFilter(intent); 9219 } 9220 } 9221 9222 public final void removeProvider(PackageParser.Provider p) { 9223 mProviders.remove(p.getComponentName()); 9224 if (DEBUG_SHOW_INFO) { 9225 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9226 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9227 Log.v(TAG, " Class=" + p.info.name); 9228 } 9229 final int NI = p.intents.size(); 9230 int j; 9231 for (j = 0; j < NI; j++) { 9232 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9233 if (DEBUG_SHOW_INFO) { 9234 Log.v(TAG, " IntentFilter:"); 9235 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9236 } 9237 removeFilter(intent); 9238 } 9239 } 9240 9241 @Override 9242 protected boolean allowFilterResult( 9243 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9244 ProviderInfo filterPi = filter.provider.info; 9245 for (int i = dest.size() - 1; i >= 0; i--) { 9246 ProviderInfo destPi = dest.get(i).providerInfo; 9247 if (destPi.name == filterPi.name 9248 && destPi.packageName == filterPi.packageName) { 9249 return false; 9250 } 9251 } 9252 return true; 9253 } 9254 9255 @Override 9256 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9257 return new PackageParser.ProviderIntentInfo[size]; 9258 } 9259 9260 @Override 9261 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9262 if (!sUserManager.exists(userId)) 9263 return true; 9264 PackageParser.Package p = filter.provider.owner; 9265 if (p != null) { 9266 PackageSetting ps = (PackageSetting) p.mExtras; 9267 if (ps != null) { 9268 // System apps are never considered stopped for purposes of 9269 // filtering, because there may be no way for the user to 9270 // actually re-launch them. 9271 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9272 && ps.getStopped(userId); 9273 } 9274 } 9275 return false; 9276 } 9277 9278 @Override 9279 protected boolean isPackageForFilter(String packageName, 9280 PackageParser.ProviderIntentInfo info) { 9281 return packageName.equals(info.provider.owner.packageName); 9282 } 9283 9284 @Override 9285 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9286 int match, int userId) { 9287 if (!sUserManager.exists(userId)) 9288 return null; 9289 final PackageParser.ProviderIntentInfo info = filter; 9290 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9291 return null; 9292 } 9293 final PackageParser.Provider provider = info.provider; 9294 if (mSafeMode && (provider.info.applicationInfo.flags 9295 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9296 return null; 9297 } 9298 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9299 if (ps == null) { 9300 return null; 9301 } 9302 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9303 ps.readUserState(userId), userId); 9304 if (pi == null) { 9305 return null; 9306 } 9307 final ResolveInfo res = new ResolveInfo(); 9308 res.providerInfo = pi; 9309 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9310 res.filter = filter; 9311 } 9312 res.priority = info.getPriority(); 9313 res.preferredOrder = provider.owner.mPreferredOrder; 9314 res.match = match; 9315 res.isDefault = info.hasDefault; 9316 res.labelRes = info.labelRes; 9317 res.nonLocalizedLabel = info.nonLocalizedLabel; 9318 res.icon = info.icon; 9319 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9320 return res; 9321 } 9322 9323 @Override 9324 protected void sortResults(List<ResolveInfo> results) { 9325 Collections.sort(results, mResolvePrioritySorter); 9326 } 9327 9328 @Override 9329 protected void dumpFilter(PrintWriter out, String prefix, 9330 PackageParser.ProviderIntentInfo filter) { 9331 out.print(prefix); 9332 out.print( 9333 Integer.toHexString(System.identityHashCode(filter.provider))); 9334 out.print(' '); 9335 filter.provider.printComponentShortName(out); 9336 out.print(" filter "); 9337 out.println(Integer.toHexString(System.identityHashCode(filter))); 9338 } 9339 9340 @Override 9341 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9342 return filter.provider; 9343 } 9344 9345 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9346 PackageParser.Provider provider = (PackageParser.Provider)label; 9347 out.print(prefix); out.print( 9348 Integer.toHexString(System.identityHashCode(provider))); 9349 out.print(' '); 9350 provider.printComponentShortName(out); 9351 if (count > 1) { 9352 out.print(" ("); out.print(count); out.print(" filters)"); 9353 } 9354 out.println(); 9355 } 9356 9357 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9358 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9359 private int mFlags; 9360 }; 9361 9362 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9363 new Comparator<ResolveInfo>() { 9364 public int compare(ResolveInfo r1, ResolveInfo r2) { 9365 int v1 = r1.priority; 9366 int v2 = r2.priority; 9367 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9368 if (v1 != v2) { 9369 return (v1 > v2) ? -1 : 1; 9370 } 9371 v1 = r1.preferredOrder; 9372 v2 = r2.preferredOrder; 9373 if (v1 != v2) { 9374 return (v1 > v2) ? -1 : 1; 9375 } 9376 if (r1.isDefault != r2.isDefault) { 9377 return r1.isDefault ? -1 : 1; 9378 } 9379 v1 = r1.match; 9380 v2 = r2.match; 9381 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9382 if (v1 != v2) { 9383 return (v1 > v2) ? -1 : 1; 9384 } 9385 if (r1.system != r2.system) { 9386 return r1.system ? -1 : 1; 9387 } 9388 return 0; 9389 } 9390 }; 9391 9392 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9393 new Comparator<ProviderInfo>() { 9394 public int compare(ProviderInfo p1, ProviderInfo p2) { 9395 final int v1 = p1.initOrder; 9396 final int v2 = p2.initOrder; 9397 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9398 } 9399 }; 9400 9401 final void sendPackageBroadcast(final String action, final String pkg, 9402 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9403 final int[] userIds) { 9404 mHandler.post(new Runnable() { 9405 @Override 9406 public void run() { 9407 try { 9408 final IActivityManager am = ActivityManagerNative.getDefault(); 9409 if (am == null) return; 9410 final int[] resolvedUserIds; 9411 if (userIds == null) { 9412 resolvedUserIds = am.getRunningUserIds(); 9413 } else { 9414 resolvedUserIds = userIds; 9415 } 9416 for (int id : resolvedUserIds) { 9417 final Intent intent = new Intent(action, 9418 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9419 if (extras != null) { 9420 intent.putExtras(extras); 9421 } 9422 if (targetPkg != null) { 9423 intent.setPackage(targetPkg); 9424 } 9425 // Modify the UID when posting to other users 9426 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9427 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9428 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9429 intent.putExtra(Intent.EXTRA_UID, uid); 9430 } 9431 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9432 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9433 if (DEBUG_BROADCASTS) { 9434 RuntimeException here = new RuntimeException("here"); 9435 here.fillInStackTrace(); 9436 Slog.d(TAG, "Sending to user " + id + ": " 9437 + intent.toShortString(false, true, false, false) 9438 + " " + intent.getExtras(), here); 9439 } 9440 am.broadcastIntent(null, intent, null, finishedReceiver, 9441 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9442 null, finishedReceiver != null, false, id); 9443 } 9444 } catch (RemoteException ex) { 9445 } 9446 } 9447 }); 9448 } 9449 9450 /** 9451 * Check if the external storage media is available. This is true if there 9452 * is a mounted external storage medium or if the external storage is 9453 * emulated. 9454 */ 9455 private boolean isExternalMediaAvailable() { 9456 return mMediaMounted || Environment.isExternalStorageEmulated(); 9457 } 9458 9459 @Override 9460 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9461 // writer 9462 synchronized (mPackages) { 9463 if (!isExternalMediaAvailable()) { 9464 // If the external storage is no longer mounted at this point, 9465 // the caller may not have been able to delete all of this 9466 // packages files and can not delete any more. Bail. 9467 return null; 9468 } 9469 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9470 if (lastPackage != null) { 9471 pkgs.remove(lastPackage); 9472 } 9473 if (pkgs.size() > 0) { 9474 return pkgs.get(0); 9475 } 9476 } 9477 return null; 9478 } 9479 9480 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9481 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9482 userId, andCode ? 1 : 0, packageName); 9483 if (mSystemReady) { 9484 msg.sendToTarget(); 9485 } else { 9486 if (mPostSystemReadyMessages == null) { 9487 mPostSystemReadyMessages = new ArrayList<>(); 9488 } 9489 mPostSystemReadyMessages.add(msg); 9490 } 9491 } 9492 9493 void startCleaningPackages() { 9494 // reader 9495 synchronized (mPackages) { 9496 if (!isExternalMediaAvailable()) { 9497 return; 9498 } 9499 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9500 return; 9501 } 9502 } 9503 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9504 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9505 IActivityManager am = ActivityManagerNative.getDefault(); 9506 if (am != null) { 9507 try { 9508 am.startService(null, intent, null, mContext.getOpPackageName(), 9509 UserHandle.USER_OWNER); 9510 } catch (RemoteException e) { 9511 } 9512 } 9513 } 9514 9515 @Override 9516 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9517 int installFlags, String installerPackageName, VerificationParams verificationParams, 9518 String packageAbiOverride) { 9519 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9520 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9521 } 9522 9523 @Override 9524 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9525 int installFlags, String installerPackageName, VerificationParams verificationParams, 9526 String packageAbiOverride, int userId) { 9527 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9528 9529 final int callingUid = Binder.getCallingUid(); 9530 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9531 9532 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9533 try { 9534 if (observer != null) { 9535 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9536 } 9537 } catch (RemoteException re) { 9538 } 9539 return; 9540 } 9541 9542 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9543 installFlags |= PackageManager.INSTALL_FROM_ADB; 9544 9545 } else { 9546 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9547 // about installerPackageName. 9548 9549 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9550 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9551 } 9552 9553 UserHandle user; 9554 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9555 user = UserHandle.ALL; 9556 } else { 9557 user = new UserHandle(userId); 9558 } 9559 9560 // Only system components can circumvent runtime permissions when installing. 9561 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9562 && mContext.checkCallingOrSelfPermission(Manifest.permission 9563 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9564 throw new SecurityException("You need the " 9565 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9566 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9567 } 9568 9569 verificationParams.setInstallerUid(callingUid); 9570 9571 final File originFile = new File(originPath); 9572 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9573 9574 final Message msg = mHandler.obtainMessage(INIT_COPY); 9575 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9576 null, verificationParams, user, packageAbiOverride, null); 9577 mHandler.sendMessage(msg); 9578 } 9579 9580 void installStage(String packageName, File stagedDir, String stagedCid, 9581 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9582 String installerPackageName, int installerUid, UserHandle user) { 9583 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9584 params.referrerUri, installerUid, null); 9585 verifParams.setInstallerUid(installerUid); 9586 9587 final OriginInfo origin; 9588 if (stagedDir != null) { 9589 origin = OriginInfo.fromStagedFile(stagedDir); 9590 } else { 9591 origin = OriginInfo.fromStagedContainer(stagedCid); 9592 } 9593 9594 final Message msg = mHandler.obtainMessage(INIT_COPY); 9595 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9596 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9597 params.grantedRuntimePermissions); 9598 mHandler.sendMessage(msg); 9599 } 9600 9601 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9602 Bundle extras = new Bundle(1); 9603 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9604 9605 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9606 packageName, extras, null, null, new int[] {userId}); 9607 try { 9608 IActivityManager am = ActivityManagerNative.getDefault(); 9609 final boolean isSystem = 9610 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9611 if (isSystem && am.isUserRunning(userId, false)) { 9612 // The just-installed/enabled app is bundled on the system, so presumed 9613 // to be able to run automatically without needing an explicit launch. 9614 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9615 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9616 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9617 .setPackage(packageName); 9618 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9619 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9620 } 9621 } catch (RemoteException e) { 9622 // shouldn't happen 9623 Slog.w(TAG, "Unable to bootstrap installed package", e); 9624 } 9625 } 9626 9627 @Override 9628 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9629 int userId) { 9630 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9631 PackageSetting pkgSetting; 9632 final int uid = Binder.getCallingUid(); 9633 enforceCrossUserPermission(uid, userId, true, true, 9634 "setApplicationHiddenSetting for user " + userId); 9635 9636 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9637 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9638 return false; 9639 } 9640 9641 long callingId = Binder.clearCallingIdentity(); 9642 try { 9643 boolean sendAdded = false; 9644 boolean sendRemoved = false; 9645 // writer 9646 synchronized (mPackages) { 9647 pkgSetting = mSettings.mPackages.get(packageName); 9648 if (pkgSetting == null) { 9649 return false; 9650 } 9651 if (pkgSetting.getHidden(userId) != hidden) { 9652 pkgSetting.setHidden(hidden, userId); 9653 mSettings.writePackageRestrictionsLPr(userId); 9654 if (hidden) { 9655 sendRemoved = true; 9656 } else { 9657 sendAdded = true; 9658 } 9659 } 9660 } 9661 if (sendAdded) { 9662 sendPackageAddedForUser(packageName, pkgSetting, userId); 9663 return true; 9664 } 9665 if (sendRemoved) { 9666 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9667 "hiding pkg"); 9668 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9669 return true; 9670 } 9671 } finally { 9672 Binder.restoreCallingIdentity(callingId); 9673 } 9674 return false; 9675 } 9676 9677 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9678 int userId) { 9679 final PackageRemovedInfo info = new PackageRemovedInfo(); 9680 info.removedPackage = packageName; 9681 info.removedUsers = new int[] {userId}; 9682 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9683 info.sendBroadcast(false, false, false); 9684 } 9685 9686 /** 9687 * Returns true if application is not found or there was an error. Otherwise it returns 9688 * the hidden state of the package for the given user. 9689 */ 9690 @Override 9691 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9692 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9693 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9694 false, "getApplicationHidden for user " + userId); 9695 PackageSetting pkgSetting; 9696 long callingId = Binder.clearCallingIdentity(); 9697 try { 9698 // writer 9699 synchronized (mPackages) { 9700 pkgSetting = mSettings.mPackages.get(packageName); 9701 if (pkgSetting == null) { 9702 return true; 9703 } 9704 return pkgSetting.getHidden(userId); 9705 } 9706 } finally { 9707 Binder.restoreCallingIdentity(callingId); 9708 } 9709 } 9710 9711 /** 9712 * @hide 9713 */ 9714 @Override 9715 public int installExistingPackageAsUser(String packageName, int userId) { 9716 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9717 null); 9718 PackageSetting pkgSetting; 9719 final int uid = Binder.getCallingUid(); 9720 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9721 + userId); 9722 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9723 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9724 } 9725 9726 long callingId = Binder.clearCallingIdentity(); 9727 try { 9728 boolean sendAdded = false; 9729 9730 // writer 9731 synchronized (mPackages) { 9732 pkgSetting = mSettings.mPackages.get(packageName); 9733 if (pkgSetting == null) { 9734 return PackageManager.INSTALL_FAILED_INVALID_URI; 9735 } 9736 if (!pkgSetting.getInstalled(userId)) { 9737 pkgSetting.setInstalled(true, userId); 9738 pkgSetting.setHidden(false, userId); 9739 mSettings.writePackageRestrictionsLPr(userId); 9740 sendAdded = true; 9741 } 9742 } 9743 9744 if (sendAdded) { 9745 sendPackageAddedForUser(packageName, pkgSetting, userId); 9746 } 9747 } finally { 9748 Binder.restoreCallingIdentity(callingId); 9749 } 9750 9751 return PackageManager.INSTALL_SUCCEEDED; 9752 } 9753 9754 boolean isUserRestricted(int userId, String restrictionKey) { 9755 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9756 if (restrictions.getBoolean(restrictionKey, false)) { 9757 Log.w(TAG, "User is restricted: " + restrictionKey); 9758 return true; 9759 } 9760 return false; 9761 } 9762 9763 @Override 9764 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9765 mContext.enforceCallingOrSelfPermission( 9766 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9767 "Only package verification agents can verify applications"); 9768 9769 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9770 final PackageVerificationResponse response = new PackageVerificationResponse( 9771 verificationCode, Binder.getCallingUid()); 9772 msg.arg1 = id; 9773 msg.obj = response; 9774 mHandler.sendMessage(msg); 9775 } 9776 9777 @Override 9778 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9779 long millisecondsToDelay) { 9780 mContext.enforceCallingOrSelfPermission( 9781 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9782 "Only package verification agents can extend verification timeouts"); 9783 9784 final PackageVerificationState state = mPendingVerification.get(id); 9785 final PackageVerificationResponse response = new PackageVerificationResponse( 9786 verificationCodeAtTimeout, Binder.getCallingUid()); 9787 9788 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9789 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9790 } 9791 if (millisecondsToDelay < 0) { 9792 millisecondsToDelay = 0; 9793 } 9794 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9795 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9796 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9797 } 9798 9799 if ((state != null) && !state.timeoutExtended()) { 9800 state.extendTimeout(); 9801 9802 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9803 msg.arg1 = id; 9804 msg.obj = response; 9805 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9806 } 9807 } 9808 9809 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9810 int verificationCode, UserHandle user) { 9811 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9812 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9813 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9814 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9815 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9816 9817 mContext.sendBroadcastAsUser(intent, user, 9818 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9819 } 9820 9821 private ComponentName matchComponentForVerifier(String packageName, 9822 List<ResolveInfo> receivers) { 9823 ActivityInfo targetReceiver = null; 9824 9825 final int NR = receivers.size(); 9826 for (int i = 0; i < NR; i++) { 9827 final ResolveInfo info = receivers.get(i); 9828 if (info.activityInfo == null) { 9829 continue; 9830 } 9831 9832 if (packageName.equals(info.activityInfo.packageName)) { 9833 targetReceiver = info.activityInfo; 9834 break; 9835 } 9836 } 9837 9838 if (targetReceiver == null) { 9839 return null; 9840 } 9841 9842 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9843 } 9844 9845 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9846 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9847 if (pkgInfo.verifiers.length == 0) { 9848 return null; 9849 } 9850 9851 final int N = pkgInfo.verifiers.length; 9852 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9853 for (int i = 0; i < N; i++) { 9854 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9855 9856 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9857 receivers); 9858 if (comp == null) { 9859 continue; 9860 } 9861 9862 final int verifierUid = getUidForVerifier(verifierInfo); 9863 if (verifierUid == -1) { 9864 continue; 9865 } 9866 9867 if (DEBUG_VERIFY) { 9868 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9869 + " with the correct signature"); 9870 } 9871 sufficientVerifiers.add(comp); 9872 verificationState.addSufficientVerifier(verifierUid); 9873 } 9874 9875 return sufficientVerifiers; 9876 } 9877 9878 private int getUidForVerifier(VerifierInfo verifierInfo) { 9879 synchronized (mPackages) { 9880 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9881 if (pkg == null) { 9882 return -1; 9883 } else if (pkg.mSignatures.length != 1) { 9884 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9885 + " has more than one signature; ignoring"); 9886 return -1; 9887 } 9888 9889 /* 9890 * If the public key of the package's signature does not match 9891 * our expected public key, then this is a different package and 9892 * we should skip. 9893 */ 9894 9895 final byte[] expectedPublicKey; 9896 try { 9897 final Signature verifierSig = pkg.mSignatures[0]; 9898 final PublicKey publicKey = verifierSig.getPublicKey(); 9899 expectedPublicKey = publicKey.getEncoded(); 9900 } catch (CertificateException e) { 9901 return -1; 9902 } 9903 9904 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9905 9906 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9907 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9908 + " does not have the expected public key; ignoring"); 9909 return -1; 9910 } 9911 9912 return pkg.applicationInfo.uid; 9913 } 9914 } 9915 9916 @Override 9917 public void finishPackageInstall(int token) { 9918 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9919 9920 if (DEBUG_INSTALL) { 9921 Slog.v(TAG, "BM finishing package install for " + token); 9922 } 9923 9924 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9925 mHandler.sendMessage(msg); 9926 } 9927 9928 /** 9929 * Get the verification agent timeout. 9930 * 9931 * @return verification timeout in milliseconds 9932 */ 9933 private long getVerificationTimeout() { 9934 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9935 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9936 DEFAULT_VERIFICATION_TIMEOUT); 9937 } 9938 9939 /** 9940 * Get the default verification agent response code. 9941 * 9942 * @return default verification response code 9943 */ 9944 private int getDefaultVerificationResponse() { 9945 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9946 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9947 DEFAULT_VERIFICATION_RESPONSE); 9948 } 9949 9950 /** 9951 * Check whether or not package verification has been enabled. 9952 * 9953 * @return true if verification should be performed 9954 */ 9955 private boolean isVerificationEnabled(int userId, int installFlags) { 9956 if (!DEFAULT_VERIFY_ENABLE) { 9957 return false; 9958 } 9959 9960 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9961 9962 // Check if installing from ADB 9963 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9964 // Do not run verification in a test harness environment 9965 if (ActivityManager.isRunningInTestHarness()) { 9966 return false; 9967 } 9968 if (ensureVerifyAppsEnabled) { 9969 return true; 9970 } 9971 // Check if the developer does not want package verification for ADB installs 9972 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9973 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9974 return false; 9975 } 9976 } 9977 9978 if (ensureVerifyAppsEnabled) { 9979 return true; 9980 } 9981 9982 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9983 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9984 } 9985 9986 @Override 9987 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9988 throws RemoteException { 9989 mContext.enforceCallingOrSelfPermission( 9990 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9991 "Only intentfilter verification agents can verify applications"); 9992 9993 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9994 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9995 Binder.getCallingUid(), verificationCode, failedDomains); 9996 msg.arg1 = id; 9997 msg.obj = response; 9998 mHandler.sendMessage(msg); 9999 } 10000 10001 @Override 10002 public int getIntentVerificationStatus(String packageName, int userId) { 10003 synchronized (mPackages) { 10004 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10005 } 10006 } 10007 10008 @Override 10009 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10010 mContext.enforceCallingOrSelfPermission( 10011 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10012 10013 boolean result = false; 10014 synchronized (mPackages) { 10015 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10016 } 10017 if (result) { 10018 scheduleWritePackageRestrictionsLocked(userId); 10019 } 10020 return result; 10021 } 10022 10023 @Override 10024 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10025 synchronized (mPackages) { 10026 return mSettings.getIntentFilterVerificationsLPr(packageName); 10027 } 10028 } 10029 10030 @Override 10031 public List<IntentFilter> getAllIntentFilters(String packageName) { 10032 if (TextUtils.isEmpty(packageName)) { 10033 return Collections.<IntentFilter>emptyList(); 10034 } 10035 synchronized (mPackages) { 10036 PackageParser.Package pkg = mPackages.get(packageName); 10037 if (pkg == null || pkg.activities == null) { 10038 return Collections.<IntentFilter>emptyList(); 10039 } 10040 final int count = pkg.activities.size(); 10041 ArrayList<IntentFilter> result = new ArrayList<>(); 10042 for (int n=0; n<count; n++) { 10043 PackageParser.Activity activity = pkg.activities.get(n); 10044 if (activity.intents != null || activity.intents.size() > 0) { 10045 result.addAll(activity.intents); 10046 } 10047 } 10048 return result; 10049 } 10050 } 10051 10052 @Override 10053 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10054 mContext.enforceCallingOrSelfPermission( 10055 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10056 10057 synchronized (mPackages) { 10058 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10059 if (packageName != null) { 10060 result |= updateIntentVerificationStatus(packageName, 10061 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10062 userId); 10063 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10064 packageName, userId); 10065 } 10066 return result; 10067 } 10068 } 10069 10070 @Override 10071 public String getDefaultBrowserPackageName(int userId) { 10072 synchronized (mPackages) { 10073 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10074 } 10075 } 10076 10077 /** 10078 * Get the "allow unknown sources" setting. 10079 * 10080 * @return the current "allow unknown sources" setting 10081 */ 10082 private int getUnknownSourcesSettings() { 10083 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10084 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10085 -1); 10086 } 10087 10088 @Override 10089 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10090 final int uid = Binder.getCallingUid(); 10091 // writer 10092 synchronized (mPackages) { 10093 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10094 if (targetPackageSetting == null) { 10095 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10096 } 10097 10098 PackageSetting installerPackageSetting; 10099 if (installerPackageName != null) { 10100 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10101 if (installerPackageSetting == null) { 10102 throw new IllegalArgumentException("Unknown installer package: " 10103 + installerPackageName); 10104 } 10105 } else { 10106 installerPackageSetting = null; 10107 } 10108 10109 Signature[] callerSignature; 10110 Object obj = mSettings.getUserIdLPr(uid); 10111 if (obj != null) { 10112 if (obj instanceof SharedUserSetting) { 10113 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10114 } else if (obj instanceof PackageSetting) { 10115 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10116 } else { 10117 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10118 } 10119 } else { 10120 throw new SecurityException("Unknown calling uid " + uid); 10121 } 10122 10123 // Verify: can't set installerPackageName to a package that is 10124 // not signed with the same cert as the caller. 10125 if (installerPackageSetting != null) { 10126 if (compareSignatures(callerSignature, 10127 installerPackageSetting.signatures.mSignatures) 10128 != PackageManager.SIGNATURE_MATCH) { 10129 throw new SecurityException( 10130 "Caller does not have same cert as new installer package " 10131 + installerPackageName); 10132 } 10133 } 10134 10135 // Verify: if target already has an installer package, it must 10136 // be signed with the same cert as the caller. 10137 if (targetPackageSetting.installerPackageName != null) { 10138 PackageSetting setting = mSettings.mPackages.get( 10139 targetPackageSetting.installerPackageName); 10140 // If the currently set package isn't valid, then it's always 10141 // okay to change it. 10142 if (setting != null) { 10143 if (compareSignatures(callerSignature, 10144 setting.signatures.mSignatures) 10145 != PackageManager.SIGNATURE_MATCH) { 10146 throw new SecurityException( 10147 "Caller does not have same cert as old installer package " 10148 + targetPackageSetting.installerPackageName); 10149 } 10150 } 10151 } 10152 10153 // Okay! 10154 targetPackageSetting.installerPackageName = installerPackageName; 10155 scheduleWriteSettingsLocked(); 10156 } 10157 } 10158 10159 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10160 // Queue up an async operation since the package installation may take a little while. 10161 mHandler.post(new Runnable() { 10162 public void run() { 10163 mHandler.removeCallbacks(this); 10164 // Result object to be returned 10165 PackageInstalledInfo res = new PackageInstalledInfo(); 10166 res.returnCode = currentStatus; 10167 res.uid = -1; 10168 res.pkg = null; 10169 res.removedInfo = new PackageRemovedInfo(); 10170 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10171 args.doPreInstall(res.returnCode); 10172 synchronized (mInstallLock) { 10173 installPackageLI(args, res); 10174 } 10175 args.doPostInstall(res.returnCode, res.uid); 10176 } 10177 10178 // A restore should be performed at this point if (a) the install 10179 // succeeded, (b) the operation is not an update, and (c) the new 10180 // package has not opted out of backup participation. 10181 final boolean update = res.removedInfo.removedPackage != null; 10182 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10183 boolean doRestore = !update 10184 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10185 10186 // Set up the post-install work request bookkeeping. This will be used 10187 // and cleaned up by the post-install event handling regardless of whether 10188 // there's a restore pass performed. Token values are >= 1. 10189 int token; 10190 if (mNextInstallToken < 0) mNextInstallToken = 1; 10191 token = mNextInstallToken++; 10192 10193 PostInstallData data = new PostInstallData(args, res); 10194 mRunningInstalls.put(token, data); 10195 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10196 10197 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10198 // Pass responsibility to the Backup Manager. It will perform a 10199 // restore if appropriate, then pass responsibility back to the 10200 // Package Manager to run the post-install observer callbacks 10201 // and broadcasts. 10202 IBackupManager bm = IBackupManager.Stub.asInterface( 10203 ServiceManager.getService(Context.BACKUP_SERVICE)); 10204 if (bm != null) { 10205 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10206 + " to BM for possible restore"); 10207 try { 10208 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10209 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10210 } else { 10211 doRestore = false; 10212 } 10213 } catch (RemoteException e) { 10214 // can't happen; the backup manager is local 10215 } catch (Exception e) { 10216 Slog.e(TAG, "Exception trying to enqueue restore", e); 10217 doRestore = false; 10218 } 10219 } else { 10220 Slog.e(TAG, "Backup Manager not found!"); 10221 doRestore = false; 10222 } 10223 } 10224 10225 if (!doRestore) { 10226 // No restore possible, or the Backup Manager was mysteriously not 10227 // available -- just fire the post-install work request directly. 10228 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10229 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10230 mHandler.sendMessage(msg); 10231 } 10232 } 10233 }); 10234 } 10235 10236 private abstract class HandlerParams { 10237 private static final int MAX_RETRIES = 4; 10238 10239 /** 10240 * Number of times startCopy() has been attempted and had a non-fatal 10241 * error. 10242 */ 10243 private int mRetries = 0; 10244 10245 /** User handle for the user requesting the information or installation. */ 10246 private final UserHandle mUser; 10247 10248 HandlerParams(UserHandle user) { 10249 mUser = user; 10250 } 10251 10252 UserHandle getUser() { 10253 return mUser; 10254 } 10255 10256 final boolean startCopy() { 10257 boolean res; 10258 try { 10259 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10260 10261 if (++mRetries > MAX_RETRIES) { 10262 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10263 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10264 handleServiceError(); 10265 return false; 10266 } else { 10267 handleStartCopy(); 10268 res = true; 10269 } 10270 } catch (RemoteException e) { 10271 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10272 mHandler.sendEmptyMessage(MCS_RECONNECT); 10273 res = false; 10274 } 10275 handleReturnCode(); 10276 return res; 10277 } 10278 10279 final void serviceError() { 10280 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10281 handleServiceError(); 10282 handleReturnCode(); 10283 } 10284 10285 abstract void handleStartCopy() throws RemoteException; 10286 abstract void handleServiceError(); 10287 abstract void handleReturnCode(); 10288 } 10289 10290 class MeasureParams extends HandlerParams { 10291 private final PackageStats mStats; 10292 private boolean mSuccess; 10293 10294 private final IPackageStatsObserver mObserver; 10295 10296 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10297 super(new UserHandle(stats.userHandle)); 10298 mObserver = observer; 10299 mStats = stats; 10300 } 10301 10302 @Override 10303 public String toString() { 10304 return "MeasureParams{" 10305 + Integer.toHexString(System.identityHashCode(this)) 10306 + " " + mStats.packageName + "}"; 10307 } 10308 10309 @Override 10310 void handleStartCopy() throws RemoteException { 10311 synchronized (mInstallLock) { 10312 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10313 } 10314 10315 if (mSuccess) { 10316 final boolean mounted; 10317 if (Environment.isExternalStorageEmulated()) { 10318 mounted = true; 10319 } else { 10320 final String status = Environment.getExternalStorageState(); 10321 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10322 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10323 } 10324 10325 if (mounted) { 10326 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10327 10328 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10329 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10330 10331 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10332 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10333 10334 // Always subtract cache size, since it's a subdirectory 10335 mStats.externalDataSize -= mStats.externalCacheSize; 10336 10337 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10338 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10339 10340 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10341 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10342 } 10343 } 10344 } 10345 10346 @Override 10347 void handleReturnCode() { 10348 if (mObserver != null) { 10349 try { 10350 mObserver.onGetStatsCompleted(mStats, mSuccess); 10351 } catch (RemoteException e) { 10352 Slog.i(TAG, "Observer no longer exists."); 10353 } 10354 } 10355 } 10356 10357 @Override 10358 void handleServiceError() { 10359 Slog.e(TAG, "Could not measure application " + mStats.packageName 10360 + " external storage"); 10361 } 10362 } 10363 10364 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10365 throws RemoteException { 10366 long result = 0; 10367 for (File path : paths) { 10368 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10369 } 10370 return result; 10371 } 10372 10373 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10374 for (File path : paths) { 10375 try { 10376 mcs.clearDirectory(path.getAbsolutePath()); 10377 } catch (RemoteException e) { 10378 } 10379 } 10380 } 10381 10382 static class OriginInfo { 10383 /** 10384 * Location where install is coming from, before it has been 10385 * copied/renamed into place. This could be a single monolithic APK 10386 * file, or a cluster directory. This location may be untrusted. 10387 */ 10388 final File file; 10389 final String cid; 10390 10391 /** 10392 * Flag indicating that {@link #file} or {@link #cid} has already been 10393 * staged, meaning downstream users don't need to defensively copy the 10394 * contents. 10395 */ 10396 final boolean staged; 10397 10398 /** 10399 * Flag indicating that {@link #file} or {@link #cid} is an already 10400 * installed app that is being moved. 10401 */ 10402 final boolean existing; 10403 10404 final String resolvedPath; 10405 final File resolvedFile; 10406 10407 static OriginInfo fromNothing() { 10408 return new OriginInfo(null, null, false, false); 10409 } 10410 10411 static OriginInfo fromUntrustedFile(File file) { 10412 return new OriginInfo(file, null, false, false); 10413 } 10414 10415 static OriginInfo fromExistingFile(File file) { 10416 return new OriginInfo(file, null, false, true); 10417 } 10418 10419 static OriginInfo fromStagedFile(File file) { 10420 return new OriginInfo(file, null, true, false); 10421 } 10422 10423 static OriginInfo fromStagedContainer(String cid) { 10424 return new OriginInfo(null, cid, true, false); 10425 } 10426 10427 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10428 this.file = file; 10429 this.cid = cid; 10430 this.staged = staged; 10431 this.existing = existing; 10432 10433 if (cid != null) { 10434 resolvedPath = PackageHelper.getSdDir(cid); 10435 resolvedFile = new File(resolvedPath); 10436 } else if (file != null) { 10437 resolvedPath = file.getAbsolutePath(); 10438 resolvedFile = file; 10439 } else { 10440 resolvedPath = null; 10441 resolvedFile = null; 10442 } 10443 } 10444 } 10445 10446 class MoveInfo { 10447 final int moveId; 10448 final String fromUuid; 10449 final String toUuid; 10450 final String packageName; 10451 final String dataAppName; 10452 final int appId; 10453 final String seinfo; 10454 10455 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10456 String dataAppName, int appId, String seinfo) { 10457 this.moveId = moveId; 10458 this.fromUuid = fromUuid; 10459 this.toUuid = toUuid; 10460 this.packageName = packageName; 10461 this.dataAppName = dataAppName; 10462 this.appId = appId; 10463 this.seinfo = seinfo; 10464 } 10465 } 10466 10467 class InstallParams extends HandlerParams { 10468 final OriginInfo origin; 10469 final MoveInfo move; 10470 final IPackageInstallObserver2 observer; 10471 int installFlags; 10472 final String installerPackageName; 10473 final String volumeUuid; 10474 final VerificationParams verificationParams; 10475 private InstallArgs mArgs; 10476 private int mRet; 10477 final String packageAbiOverride; 10478 final String[] grantedRuntimePermissions; 10479 10480 10481 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10482 int installFlags, String installerPackageName, String volumeUuid, 10483 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10484 String[] grantedPermissions) { 10485 super(user); 10486 this.origin = origin; 10487 this.move = move; 10488 this.observer = observer; 10489 this.installFlags = installFlags; 10490 this.installerPackageName = installerPackageName; 10491 this.volumeUuid = volumeUuid; 10492 this.verificationParams = verificationParams; 10493 this.packageAbiOverride = packageAbiOverride; 10494 this.grantedRuntimePermissions = grantedPermissions; 10495 } 10496 10497 @Override 10498 public String toString() { 10499 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10500 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10501 } 10502 10503 public ManifestDigest getManifestDigest() { 10504 if (verificationParams == null) { 10505 return null; 10506 } 10507 return verificationParams.getManifestDigest(); 10508 } 10509 10510 private int installLocationPolicy(PackageInfoLite pkgLite) { 10511 String packageName = pkgLite.packageName; 10512 int installLocation = pkgLite.installLocation; 10513 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10514 // reader 10515 synchronized (mPackages) { 10516 PackageParser.Package pkg = mPackages.get(packageName); 10517 if (pkg != null) { 10518 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10519 // Check for downgrading. 10520 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10521 try { 10522 checkDowngrade(pkg, pkgLite); 10523 } catch (PackageManagerException e) { 10524 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10525 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10526 } 10527 } 10528 // Check for updated system application. 10529 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10530 if (onSd) { 10531 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10532 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10533 } 10534 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10535 } else { 10536 if (onSd) { 10537 // Install flag overrides everything. 10538 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10539 } 10540 // If current upgrade specifies particular preference 10541 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10542 // Application explicitly specified internal. 10543 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10544 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10545 // App explictly prefers external. Let policy decide 10546 } else { 10547 // Prefer previous location 10548 if (isExternal(pkg)) { 10549 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10550 } 10551 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10552 } 10553 } 10554 } else { 10555 // Invalid install. Return error code 10556 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10557 } 10558 } 10559 } 10560 // All the special cases have been taken care of. 10561 // Return result based on recommended install location. 10562 if (onSd) { 10563 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10564 } 10565 return pkgLite.recommendedInstallLocation; 10566 } 10567 10568 /* 10569 * Invoke remote method to get package information and install 10570 * location values. Override install location based on default 10571 * policy if needed and then create install arguments based 10572 * on the install location. 10573 */ 10574 public void handleStartCopy() throws RemoteException { 10575 int ret = PackageManager.INSTALL_SUCCEEDED; 10576 10577 // If we're already staged, we've firmly committed to an install location 10578 if (origin.staged) { 10579 if (origin.file != null) { 10580 installFlags |= PackageManager.INSTALL_INTERNAL; 10581 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10582 } else if (origin.cid != null) { 10583 installFlags |= PackageManager.INSTALL_EXTERNAL; 10584 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10585 } else { 10586 throw new IllegalStateException("Invalid stage location"); 10587 } 10588 } 10589 10590 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10591 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10592 10593 PackageInfoLite pkgLite = null; 10594 10595 if (onInt && onSd) { 10596 // Check if both bits are set. 10597 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10598 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10599 } else { 10600 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10601 packageAbiOverride); 10602 10603 /* 10604 * If we have too little free space, try to free cache 10605 * before giving up. 10606 */ 10607 if (!origin.staged && pkgLite.recommendedInstallLocation 10608 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10609 // TODO: focus freeing disk space on the target device 10610 final StorageManager storage = StorageManager.from(mContext); 10611 final long lowThreshold = storage.getStorageLowBytes( 10612 Environment.getDataDirectory()); 10613 10614 final long sizeBytes = mContainerService.calculateInstalledSize( 10615 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10616 10617 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10618 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10619 installFlags, packageAbiOverride); 10620 } 10621 10622 /* 10623 * The cache free must have deleted the file we 10624 * downloaded to install. 10625 * 10626 * TODO: fix the "freeCache" call to not delete 10627 * the file we care about. 10628 */ 10629 if (pkgLite.recommendedInstallLocation 10630 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10631 pkgLite.recommendedInstallLocation 10632 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10633 } 10634 } 10635 } 10636 10637 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10638 int loc = pkgLite.recommendedInstallLocation; 10639 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10640 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10641 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10642 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10643 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10644 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10645 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10646 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10647 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10648 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10649 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10650 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10651 } else { 10652 // Override with defaults if needed. 10653 loc = installLocationPolicy(pkgLite); 10654 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10655 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10656 } else if (!onSd && !onInt) { 10657 // Override install location with flags 10658 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10659 // Set the flag to install on external media. 10660 installFlags |= PackageManager.INSTALL_EXTERNAL; 10661 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10662 } else { 10663 // Make sure the flag for installing on external 10664 // media is unset 10665 installFlags |= PackageManager.INSTALL_INTERNAL; 10666 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10667 } 10668 } 10669 } 10670 } 10671 10672 final InstallArgs args = createInstallArgs(this); 10673 mArgs = args; 10674 10675 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10676 /* 10677 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10678 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10679 */ 10680 int userIdentifier = getUser().getIdentifier(); 10681 if (userIdentifier == UserHandle.USER_ALL 10682 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10683 userIdentifier = UserHandle.USER_OWNER; 10684 } 10685 10686 /* 10687 * Determine if we have any installed package verifiers. If we 10688 * do, then we'll defer to them to verify the packages. 10689 */ 10690 final int requiredUid = mRequiredVerifierPackage == null ? -1 10691 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10692 if (!origin.existing && requiredUid != -1 10693 && isVerificationEnabled(userIdentifier, installFlags)) { 10694 final Intent verification = new Intent( 10695 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10696 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10697 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10698 PACKAGE_MIME_TYPE); 10699 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10700 10701 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10702 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10703 0 /* TODO: Which userId? */); 10704 10705 if (DEBUG_VERIFY) { 10706 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10707 + verification.toString() + " with " + pkgLite.verifiers.length 10708 + " optional verifiers"); 10709 } 10710 10711 final int verificationId = mPendingVerificationToken++; 10712 10713 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10714 10715 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10716 installerPackageName); 10717 10718 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10719 installFlags); 10720 10721 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10722 pkgLite.packageName); 10723 10724 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10725 pkgLite.versionCode); 10726 10727 if (verificationParams != null) { 10728 if (verificationParams.getVerificationURI() != null) { 10729 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10730 verificationParams.getVerificationURI()); 10731 } 10732 if (verificationParams.getOriginatingURI() != null) { 10733 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10734 verificationParams.getOriginatingURI()); 10735 } 10736 if (verificationParams.getReferrer() != null) { 10737 verification.putExtra(Intent.EXTRA_REFERRER, 10738 verificationParams.getReferrer()); 10739 } 10740 if (verificationParams.getOriginatingUid() >= 0) { 10741 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10742 verificationParams.getOriginatingUid()); 10743 } 10744 if (verificationParams.getInstallerUid() >= 0) { 10745 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10746 verificationParams.getInstallerUid()); 10747 } 10748 } 10749 10750 final PackageVerificationState verificationState = new PackageVerificationState( 10751 requiredUid, args); 10752 10753 mPendingVerification.append(verificationId, verificationState); 10754 10755 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10756 receivers, verificationState); 10757 10758 // Apps installed for "all" users use the device owner to verify the app 10759 UserHandle verifierUser = getUser(); 10760 if (verifierUser == UserHandle.ALL) { 10761 verifierUser = UserHandle.OWNER; 10762 } 10763 10764 /* 10765 * If any sufficient verifiers were listed in the package 10766 * manifest, attempt to ask them. 10767 */ 10768 if (sufficientVerifiers != null) { 10769 final int N = sufficientVerifiers.size(); 10770 if (N == 0) { 10771 Slog.i(TAG, "Additional verifiers required, but none installed."); 10772 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10773 } else { 10774 for (int i = 0; i < N; i++) { 10775 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10776 10777 final Intent sufficientIntent = new Intent(verification); 10778 sufficientIntent.setComponent(verifierComponent); 10779 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10780 } 10781 } 10782 } 10783 10784 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10785 mRequiredVerifierPackage, receivers); 10786 if (ret == PackageManager.INSTALL_SUCCEEDED 10787 && mRequiredVerifierPackage != null) { 10788 /* 10789 * Send the intent to the required verification agent, 10790 * but only start the verification timeout after the 10791 * target BroadcastReceivers have run. 10792 */ 10793 verification.setComponent(requiredVerifierComponent); 10794 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10795 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10796 new BroadcastReceiver() { 10797 @Override 10798 public void onReceive(Context context, Intent intent) { 10799 final Message msg = mHandler 10800 .obtainMessage(CHECK_PENDING_VERIFICATION); 10801 msg.arg1 = verificationId; 10802 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10803 } 10804 }, null, 0, null, null); 10805 10806 /* 10807 * We don't want the copy to proceed until verification 10808 * succeeds, so null out this field. 10809 */ 10810 mArgs = null; 10811 } 10812 } else { 10813 /* 10814 * No package verification is enabled, so immediately start 10815 * the remote call to initiate copy using temporary file. 10816 */ 10817 ret = args.copyApk(mContainerService, true); 10818 } 10819 } 10820 10821 mRet = ret; 10822 } 10823 10824 @Override 10825 void handleReturnCode() { 10826 // If mArgs is null, then MCS couldn't be reached. When it 10827 // reconnects, it will try again to install. At that point, this 10828 // will succeed. 10829 if (mArgs != null) { 10830 processPendingInstall(mArgs, mRet); 10831 } 10832 } 10833 10834 @Override 10835 void handleServiceError() { 10836 mArgs = createInstallArgs(this); 10837 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10838 } 10839 10840 public boolean isForwardLocked() { 10841 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10842 } 10843 } 10844 10845 /** 10846 * Used during creation of InstallArgs 10847 * 10848 * @param installFlags package installation flags 10849 * @return true if should be installed on external storage 10850 */ 10851 private static boolean installOnExternalAsec(int installFlags) { 10852 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10853 return false; 10854 } 10855 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10856 return true; 10857 } 10858 return false; 10859 } 10860 10861 /** 10862 * Used during creation of InstallArgs 10863 * 10864 * @param installFlags package installation flags 10865 * @return true if should be installed as forward locked 10866 */ 10867 private static boolean installForwardLocked(int installFlags) { 10868 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10869 } 10870 10871 private InstallArgs createInstallArgs(InstallParams params) { 10872 if (params.move != null) { 10873 return new MoveInstallArgs(params); 10874 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10875 return new AsecInstallArgs(params); 10876 } else { 10877 return new FileInstallArgs(params); 10878 } 10879 } 10880 10881 /** 10882 * Create args that describe an existing installed package. Typically used 10883 * when cleaning up old installs, or used as a move source. 10884 */ 10885 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10886 String resourcePath, String[] instructionSets) { 10887 final boolean isInAsec; 10888 if (installOnExternalAsec(installFlags)) { 10889 /* Apps on SD card are always in ASEC containers. */ 10890 isInAsec = true; 10891 } else if (installForwardLocked(installFlags) 10892 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10893 /* 10894 * Forward-locked apps are only in ASEC containers if they're the 10895 * new style 10896 */ 10897 isInAsec = true; 10898 } else { 10899 isInAsec = false; 10900 } 10901 10902 if (isInAsec) { 10903 return new AsecInstallArgs(codePath, instructionSets, 10904 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10905 } else { 10906 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10907 } 10908 } 10909 10910 static abstract class InstallArgs { 10911 /** @see InstallParams#origin */ 10912 final OriginInfo origin; 10913 /** @see InstallParams#move */ 10914 final MoveInfo move; 10915 10916 final IPackageInstallObserver2 observer; 10917 // Always refers to PackageManager flags only 10918 final int installFlags; 10919 final String installerPackageName; 10920 final String volumeUuid; 10921 final ManifestDigest manifestDigest; 10922 final UserHandle user; 10923 final String abiOverride; 10924 final String[] installGrantPermissions; 10925 10926 // The list of instruction sets supported by this app. This is currently 10927 // only used during the rmdex() phase to clean up resources. We can get rid of this 10928 // if we move dex files under the common app path. 10929 /* nullable */ String[] instructionSets; 10930 10931 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10932 int installFlags, String installerPackageName, String volumeUuid, 10933 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10934 String abiOverride, String[] installGrantPermissions) { 10935 this.origin = origin; 10936 this.move = move; 10937 this.installFlags = installFlags; 10938 this.observer = observer; 10939 this.installerPackageName = installerPackageName; 10940 this.volumeUuid = volumeUuid; 10941 this.manifestDigest = manifestDigest; 10942 this.user = user; 10943 this.instructionSets = instructionSets; 10944 this.abiOverride = abiOverride; 10945 this.installGrantPermissions = installGrantPermissions; 10946 } 10947 10948 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10949 abstract int doPreInstall(int status); 10950 10951 /** 10952 * Rename package into final resting place. All paths on the given 10953 * scanned package should be updated to reflect the rename. 10954 */ 10955 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10956 abstract int doPostInstall(int status, int uid); 10957 10958 /** @see PackageSettingBase#codePathString */ 10959 abstract String getCodePath(); 10960 /** @see PackageSettingBase#resourcePathString */ 10961 abstract String getResourcePath(); 10962 10963 // Need installer lock especially for dex file removal. 10964 abstract void cleanUpResourcesLI(); 10965 abstract boolean doPostDeleteLI(boolean delete); 10966 10967 /** 10968 * Called before the source arguments are copied. This is used mostly 10969 * for MoveParams when it needs to read the source file to put it in the 10970 * destination. 10971 */ 10972 int doPreCopy() { 10973 return PackageManager.INSTALL_SUCCEEDED; 10974 } 10975 10976 /** 10977 * Called after the source arguments are copied. This is used mostly for 10978 * MoveParams when it needs to read the source file to put it in the 10979 * destination. 10980 * 10981 * @return 10982 */ 10983 int doPostCopy(int uid) { 10984 return PackageManager.INSTALL_SUCCEEDED; 10985 } 10986 10987 protected boolean isFwdLocked() { 10988 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10989 } 10990 10991 protected boolean isExternalAsec() { 10992 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10993 } 10994 10995 UserHandle getUser() { 10996 return user; 10997 } 10998 } 10999 11000 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11001 if (!allCodePaths.isEmpty()) { 11002 if (instructionSets == null) { 11003 throw new IllegalStateException("instructionSet == null"); 11004 } 11005 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11006 for (String codePath : allCodePaths) { 11007 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11008 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11009 if (retCode < 0) { 11010 Slog.w(TAG, "Couldn't remove dex file for package: " 11011 + " at location " + codePath + ", retcode=" + retCode); 11012 // we don't consider this to be a failure of the core package deletion 11013 } 11014 } 11015 } 11016 } 11017 } 11018 11019 /** 11020 * Logic to handle installation of non-ASEC applications, including copying 11021 * and renaming logic. 11022 */ 11023 class FileInstallArgs extends InstallArgs { 11024 private File codeFile; 11025 private File resourceFile; 11026 11027 // Example topology: 11028 // /data/app/com.example/base.apk 11029 // /data/app/com.example/split_foo.apk 11030 // /data/app/com.example/lib/arm/libfoo.so 11031 // /data/app/com.example/lib/arm64/libfoo.so 11032 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11033 11034 /** New install */ 11035 FileInstallArgs(InstallParams params) { 11036 super(params.origin, params.move, params.observer, params.installFlags, 11037 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11038 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11039 params.grantedRuntimePermissions); 11040 if (isFwdLocked()) { 11041 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11042 } 11043 } 11044 11045 /** Existing install */ 11046 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11047 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11048 null, null); 11049 this.codeFile = (codePath != null) ? new File(codePath) : null; 11050 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11051 } 11052 11053 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11054 if (origin.staged) { 11055 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11056 codeFile = origin.file; 11057 resourceFile = origin.file; 11058 return PackageManager.INSTALL_SUCCEEDED; 11059 } 11060 11061 try { 11062 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11063 codeFile = tempDir; 11064 resourceFile = tempDir; 11065 } catch (IOException e) { 11066 Slog.w(TAG, "Failed to create copy file: " + e); 11067 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11068 } 11069 11070 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11071 @Override 11072 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11073 if (!FileUtils.isValidExtFilename(name)) { 11074 throw new IllegalArgumentException("Invalid filename: " + name); 11075 } 11076 try { 11077 final File file = new File(codeFile, name); 11078 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11079 O_RDWR | O_CREAT, 0644); 11080 Os.chmod(file.getAbsolutePath(), 0644); 11081 return new ParcelFileDescriptor(fd); 11082 } catch (ErrnoException e) { 11083 throw new RemoteException("Failed to open: " + e.getMessage()); 11084 } 11085 } 11086 }; 11087 11088 int ret = PackageManager.INSTALL_SUCCEEDED; 11089 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11090 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11091 Slog.e(TAG, "Failed to copy package"); 11092 return ret; 11093 } 11094 11095 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11096 NativeLibraryHelper.Handle handle = null; 11097 try { 11098 handle = NativeLibraryHelper.Handle.create(codeFile); 11099 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11100 abiOverride); 11101 } catch (IOException e) { 11102 Slog.e(TAG, "Copying native libraries failed", e); 11103 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11104 } finally { 11105 IoUtils.closeQuietly(handle); 11106 } 11107 11108 return ret; 11109 } 11110 11111 int doPreInstall(int status) { 11112 if (status != PackageManager.INSTALL_SUCCEEDED) { 11113 cleanUp(); 11114 } 11115 return status; 11116 } 11117 11118 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11119 if (status != PackageManager.INSTALL_SUCCEEDED) { 11120 cleanUp(); 11121 return false; 11122 } 11123 11124 final File targetDir = codeFile.getParentFile(); 11125 final File beforeCodeFile = codeFile; 11126 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11127 11128 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11129 try { 11130 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11131 } catch (ErrnoException e) { 11132 Slog.w(TAG, "Failed to rename", e); 11133 return false; 11134 } 11135 11136 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11137 Slog.w(TAG, "Failed to restorecon"); 11138 return false; 11139 } 11140 11141 // Reflect the rename internally 11142 codeFile = afterCodeFile; 11143 resourceFile = afterCodeFile; 11144 11145 // Reflect the rename in scanned details 11146 pkg.codePath = afterCodeFile.getAbsolutePath(); 11147 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11148 pkg.baseCodePath); 11149 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11150 pkg.splitCodePaths); 11151 11152 // Reflect the rename in app info 11153 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11154 pkg.applicationInfo.setCodePath(pkg.codePath); 11155 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11156 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11157 pkg.applicationInfo.setResourcePath(pkg.codePath); 11158 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11159 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11160 11161 return true; 11162 } 11163 11164 int doPostInstall(int status, int uid) { 11165 if (status != PackageManager.INSTALL_SUCCEEDED) { 11166 cleanUp(); 11167 } 11168 return status; 11169 } 11170 11171 @Override 11172 String getCodePath() { 11173 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11174 } 11175 11176 @Override 11177 String getResourcePath() { 11178 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11179 } 11180 11181 private boolean cleanUp() { 11182 if (codeFile == null || !codeFile.exists()) { 11183 return false; 11184 } 11185 11186 if (codeFile.isDirectory()) { 11187 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11188 } else { 11189 codeFile.delete(); 11190 } 11191 11192 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11193 resourceFile.delete(); 11194 } 11195 11196 return true; 11197 } 11198 11199 void cleanUpResourcesLI() { 11200 // Try enumerating all code paths before deleting 11201 List<String> allCodePaths = Collections.EMPTY_LIST; 11202 if (codeFile != null && codeFile.exists()) { 11203 try { 11204 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11205 allCodePaths = pkg.getAllCodePaths(); 11206 } catch (PackageParserException e) { 11207 // Ignored; we tried our best 11208 } 11209 } 11210 11211 cleanUp(); 11212 removeDexFiles(allCodePaths, instructionSets); 11213 } 11214 11215 boolean doPostDeleteLI(boolean delete) { 11216 // XXX err, shouldn't we respect the delete flag? 11217 cleanUpResourcesLI(); 11218 return true; 11219 } 11220 } 11221 11222 private boolean isAsecExternal(String cid) { 11223 final String asecPath = PackageHelper.getSdFilesystem(cid); 11224 return !asecPath.startsWith(mAsecInternalPath); 11225 } 11226 11227 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11228 PackageManagerException { 11229 if (copyRet < 0) { 11230 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11231 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11232 throw new PackageManagerException(copyRet, message); 11233 } 11234 } 11235 } 11236 11237 /** 11238 * Extract the MountService "container ID" from the full code path of an 11239 * .apk. 11240 */ 11241 static String cidFromCodePath(String fullCodePath) { 11242 int eidx = fullCodePath.lastIndexOf("/"); 11243 String subStr1 = fullCodePath.substring(0, eidx); 11244 int sidx = subStr1.lastIndexOf("/"); 11245 return subStr1.substring(sidx+1, eidx); 11246 } 11247 11248 /** 11249 * Logic to handle installation of ASEC applications, including copying and 11250 * renaming logic. 11251 */ 11252 class AsecInstallArgs extends InstallArgs { 11253 static final String RES_FILE_NAME = "pkg.apk"; 11254 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11255 11256 String cid; 11257 String packagePath; 11258 String resourcePath; 11259 11260 /** New install */ 11261 AsecInstallArgs(InstallParams params) { 11262 super(params.origin, params.move, params.observer, params.installFlags, 11263 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11264 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11265 params.grantedRuntimePermissions); 11266 } 11267 11268 /** Existing install */ 11269 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11270 boolean isExternal, boolean isForwardLocked) { 11271 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11272 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11273 instructionSets, null, null); 11274 // Hackily pretend we're still looking at a full code path 11275 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11276 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11277 } 11278 11279 // Extract cid from fullCodePath 11280 int eidx = fullCodePath.lastIndexOf("/"); 11281 String subStr1 = fullCodePath.substring(0, eidx); 11282 int sidx = subStr1.lastIndexOf("/"); 11283 cid = subStr1.substring(sidx+1, eidx); 11284 setMountPath(subStr1); 11285 } 11286 11287 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11288 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11289 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11290 instructionSets, null, null); 11291 this.cid = cid; 11292 setMountPath(PackageHelper.getSdDir(cid)); 11293 } 11294 11295 void createCopyFile() { 11296 cid = mInstallerService.allocateExternalStageCidLegacy(); 11297 } 11298 11299 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11300 if (origin.staged) { 11301 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11302 cid = origin.cid; 11303 setMountPath(PackageHelper.getSdDir(cid)); 11304 return PackageManager.INSTALL_SUCCEEDED; 11305 } 11306 11307 if (temp) { 11308 createCopyFile(); 11309 } else { 11310 /* 11311 * Pre-emptively destroy the container since it's destroyed if 11312 * copying fails due to it existing anyway. 11313 */ 11314 PackageHelper.destroySdDir(cid); 11315 } 11316 11317 final String newMountPath = imcs.copyPackageToContainer( 11318 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11319 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11320 11321 if (newMountPath != null) { 11322 setMountPath(newMountPath); 11323 return PackageManager.INSTALL_SUCCEEDED; 11324 } else { 11325 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11326 } 11327 } 11328 11329 @Override 11330 String getCodePath() { 11331 return packagePath; 11332 } 11333 11334 @Override 11335 String getResourcePath() { 11336 return resourcePath; 11337 } 11338 11339 int doPreInstall(int status) { 11340 if (status != PackageManager.INSTALL_SUCCEEDED) { 11341 // Destroy container 11342 PackageHelper.destroySdDir(cid); 11343 } else { 11344 boolean mounted = PackageHelper.isContainerMounted(cid); 11345 if (!mounted) { 11346 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11347 Process.SYSTEM_UID); 11348 if (newMountPath != null) { 11349 setMountPath(newMountPath); 11350 } else { 11351 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11352 } 11353 } 11354 } 11355 return status; 11356 } 11357 11358 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11359 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11360 String newMountPath = null; 11361 if (PackageHelper.isContainerMounted(cid)) { 11362 // Unmount the container 11363 if (!PackageHelper.unMountSdDir(cid)) { 11364 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11365 return false; 11366 } 11367 } 11368 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11369 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11370 " which might be stale. Will try to clean up."); 11371 // Clean up the stale container and proceed to recreate. 11372 if (!PackageHelper.destroySdDir(newCacheId)) { 11373 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11374 return false; 11375 } 11376 // Successfully cleaned up stale container. Try to rename again. 11377 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11378 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11379 + " inspite of cleaning it up."); 11380 return false; 11381 } 11382 } 11383 if (!PackageHelper.isContainerMounted(newCacheId)) { 11384 Slog.w(TAG, "Mounting container " + newCacheId); 11385 newMountPath = PackageHelper.mountSdDir(newCacheId, 11386 getEncryptKey(), Process.SYSTEM_UID); 11387 } else { 11388 newMountPath = PackageHelper.getSdDir(newCacheId); 11389 } 11390 if (newMountPath == null) { 11391 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11392 return false; 11393 } 11394 Log.i(TAG, "Succesfully renamed " + cid + 11395 " to " + newCacheId + 11396 " at new path: " + newMountPath); 11397 cid = newCacheId; 11398 11399 final File beforeCodeFile = new File(packagePath); 11400 setMountPath(newMountPath); 11401 final File afterCodeFile = new File(packagePath); 11402 11403 // Reflect the rename in scanned details 11404 pkg.codePath = afterCodeFile.getAbsolutePath(); 11405 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11406 pkg.baseCodePath); 11407 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11408 pkg.splitCodePaths); 11409 11410 // Reflect the rename in app info 11411 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11412 pkg.applicationInfo.setCodePath(pkg.codePath); 11413 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11414 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11415 pkg.applicationInfo.setResourcePath(pkg.codePath); 11416 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11417 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11418 11419 return true; 11420 } 11421 11422 private void setMountPath(String mountPath) { 11423 final File mountFile = new File(mountPath); 11424 11425 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11426 if (monolithicFile.exists()) { 11427 packagePath = monolithicFile.getAbsolutePath(); 11428 if (isFwdLocked()) { 11429 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11430 } else { 11431 resourcePath = packagePath; 11432 } 11433 } else { 11434 packagePath = mountFile.getAbsolutePath(); 11435 resourcePath = packagePath; 11436 } 11437 } 11438 11439 int doPostInstall(int status, int uid) { 11440 if (status != PackageManager.INSTALL_SUCCEEDED) { 11441 cleanUp(); 11442 } else { 11443 final int groupOwner; 11444 final String protectedFile; 11445 if (isFwdLocked()) { 11446 groupOwner = UserHandle.getSharedAppGid(uid); 11447 protectedFile = RES_FILE_NAME; 11448 } else { 11449 groupOwner = -1; 11450 protectedFile = null; 11451 } 11452 11453 if (uid < Process.FIRST_APPLICATION_UID 11454 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11455 Slog.e(TAG, "Failed to finalize " + cid); 11456 PackageHelper.destroySdDir(cid); 11457 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11458 } 11459 11460 boolean mounted = PackageHelper.isContainerMounted(cid); 11461 if (!mounted) { 11462 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11463 } 11464 } 11465 return status; 11466 } 11467 11468 private void cleanUp() { 11469 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11470 11471 // Destroy secure container 11472 PackageHelper.destroySdDir(cid); 11473 } 11474 11475 private List<String> getAllCodePaths() { 11476 final File codeFile = new File(getCodePath()); 11477 if (codeFile != null && codeFile.exists()) { 11478 try { 11479 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11480 return pkg.getAllCodePaths(); 11481 } catch (PackageParserException e) { 11482 // Ignored; we tried our best 11483 } 11484 } 11485 return Collections.EMPTY_LIST; 11486 } 11487 11488 void cleanUpResourcesLI() { 11489 // Enumerate all code paths before deleting 11490 cleanUpResourcesLI(getAllCodePaths()); 11491 } 11492 11493 private void cleanUpResourcesLI(List<String> allCodePaths) { 11494 cleanUp(); 11495 removeDexFiles(allCodePaths, instructionSets); 11496 } 11497 11498 String getPackageName() { 11499 return getAsecPackageName(cid); 11500 } 11501 11502 boolean doPostDeleteLI(boolean delete) { 11503 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11504 final List<String> allCodePaths = getAllCodePaths(); 11505 boolean mounted = PackageHelper.isContainerMounted(cid); 11506 if (mounted) { 11507 // Unmount first 11508 if (PackageHelper.unMountSdDir(cid)) { 11509 mounted = false; 11510 } 11511 } 11512 if (!mounted && delete) { 11513 cleanUpResourcesLI(allCodePaths); 11514 } 11515 return !mounted; 11516 } 11517 11518 @Override 11519 int doPreCopy() { 11520 if (isFwdLocked()) { 11521 if (!PackageHelper.fixSdPermissions(cid, 11522 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11523 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11524 } 11525 } 11526 11527 return PackageManager.INSTALL_SUCCEEDED; 11528 } 11529 11530 @Override 11531 int doPostCopy(int uid) { 11532 if (isFwdLocked()) { 11533 if (uid < Process.FIRST_APPLICATION_UID 11534 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11535 RES_FILE_NAME)) { 11536 Slog.e(TAG, "Failed to finalize " + cid); 11537 PackageHelper.destroySdDir(cid); 11538 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11539 } 11540 } 11541 11542 return PackageManager.INSTALL_SUCCEEDED; 11543 } 11544 } 11545 11546 /** 11547 * Logic to handle movement of existing installed applications. 11548 */ 11549 class MoveInstallArgs extends InstallArgs { 11550 private File codeFile; 11551 private File resourceFile; 11552 11553 /** New install */ 11554 MoveInstallArgs(InstallParams params) { 11555 super(params.origin, params.move, params.observer, params.installFlags, 11556 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11557 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11558 params.grantedRuntimePermissions); 11559 } 11560 11561 int copyApk(IMediaContainerService imcs, boolean temp) { 11562 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11563 + move.fromUuid + " to " + move.toUuid); 11564 synchronized (mInstaller) { 11565 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11566 move.dataAppName, move.appId, move.seinfo) != 0) { 11567 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11568 } 11569 } 11570 11571 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11572 resourceFile = codeFile; 11573 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11574 11575 return PackageManager.INSTALL_SUCCEEDED; 11576 } 11577 11578 int doPreInstall(int status) { 11579 if (status != PackageManager.INSTALL_SUCCEEDED) { 11580 cleanUp(move.toUuid); 11581 } 11582 return status; 11583 } 11584 11585 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11586 if (status != PackageManager.INSTALL_SUCCEEDED) { 11587 cleanUp(move.toUuid); 11588 return false; 11589 } 11590 11591 // Reflect the move in app info 11592 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11593 pkg.applicationInfo.setCodePath(pkg.codePath); 11594 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11595 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11596 pkg.applicationInfo.setResourcePath(pkg.codePath); 11597 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11598 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11599 11600 return true; 11601 } 11602 11603 int doPostInstall(int status, int uid) { 11604 if (status == PackageManager.INSTALL_SUCCEEDED) { 11605 cleanUp(move.fromUuid); 11606 } else { 11607 cleanUp(move.toUuid); 11608 } 11609 return status; 11610 } 11611 11612 @Override 11613 String getCodePath() { 11614 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11615 } 11616 11617 @Override 11618 String getResourcePath() { 11619 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11620 } 11621 11622 private boolean cleanUp(String volumeUuid) { 11623 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11624 move.dataAppName); 11625 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11626 synchronized (mInstallLock) { 11627 // Clean up both app data and code 11628 removeDataDirsLI(volumeUuid, move.packageName); 11629 if (codeFile.isDirectory()) { 11630 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11631 } else { 11632 codeFile.delete(); 11633 } 11634 } 11635 return true; 11636 } 11637 11638 void cleanUpResourcesLI() { 11639 throw new UnsupportedOperationException(); 11640 } 11641 11642 boolean doPostDeleteLI(boolean delete) { 11643 throw new UnsupportedOperationException(); 11644 } 11645 } 11646 11647 static String getAsecPackageName(String packageCid) { 11648 int idx = packageCid.lastIndexOf("-"); 11649 if (idx == -1) { 11650 return packageCid; 11651 } 11652 return packageCid.substring(0, idx); 11653 } 11654 11655 // Utility method used to create code paths based on package name and available index. 11656 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11657 String idxStr = ""; 11658 int idx = 1; 11659 // Fall back to default value of idx=1 if prefix is not 11660 // part of oldCodePath 11661 if (oldCodePath != null) { 11662 String subStr = oldCodePath; 11663 // Drop the suffix right away 11664 if (suffix != null && subStr.endsWith(suffix)) { 11665 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11666 } 11667 // If oldCodePath already contains prefix find out the 11668 // ending index to either increment or decrement. 11669 int sidx = subStr.lastIndexOf(prefix); 11670 if (sidx != -1) { 11671 subStr = subStr.substring(sidx + prefix.length()); 11672 if (subStr != null) { 11673 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11674 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11675 } 11676 try { 11677 idx = Integer.parseInt(subStr); 11678 if (idx <= 1) { 11679 idx++; 11680 } else { 11681 idx--; 11682 } 11683 } catch(NumberFormatException e) { 11684 } 11685 } 11686 } 11687 } 11688 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11689 return prefix + idxStr; 11690 } 11691 11692 private File getNextCodePath(File targetDir, String packageName) { 11693 int suffix = 1; 11694 File result; 11695 do { 11696 result = new File(targetDir, packageName + "-" + suffix); 11697 suffix++; 11698 } while (result.exists()); 11699 return result; 11700 } 11701 11702 // Utility method that returns the relative package path with respect 11703 // to the installation directory. Like say for /data/data/com.test-1.apk 11704 // string com.test-1 is returned. 11705 static String deriveCodePathName(String codePath) { 11706 if (codePath == null) { 11707 return null; 11708 } 11709 final File codeFile = new File(codePath); 11710 final String name = codeFile.getName(); 11711 if (codeFile.isDirectory()) { 11712 return name; 11713 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11714 final int lastDot = name.lastIndexOf('.'); 11715 return name.substring(0, lastDot); 11716 } else { 11717 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11718 return null; 11719 } 11720 } 11721 11722 class PackageInstalledInfo { 11723 String name; 11724 int uid; 11725 // The set of users that originally had this package installed. 11726 int[] origUsers; 11727 // The set of users that now have this package installed. 11728 int[] newUsers; 11729 PackageParser.Package pkg; 11730 int returnCode; 11731 String returnMsg; 11732 PackageRemovedInfo removedInfo; 11733 11734 public void setError(int code, String msg) { 11735 returnCode = code; 11736 returnMsg = msg; 11737 Slog.w(TAG, msg); 11738 } 11739 11740 public void setError(String msg, PackageParserException e) { 11741 returnCode = e.error; 11742 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11743 Slog.w(TAG, msg, e); 11744 } 11745 11746 public void setError(String msg, PackageManagerException e) { 11747 returnCode = e.error; 11748 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11749 Slog.w(TAG, msg, e); 11750 } 11751 11752 // In some error cases we want to convey more info back to the observer 11753 String origPackage; 11754 String origPermission; 11755 } 11756 11757 /* 11758 * Install a non-existing package. 11759 */ 11760 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11761 UserHandle user, String installerPackageName, String volumeUuid, 11762 PackageInstalledInfo res) { 11763 // Remember this for later, in case we need to rollback this install 11764 String pkgName = pkg.packageName; 11765 11766 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11767 final boolean dataDirExists = Environment 11768 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11769 synchronized(mPackages) { 11770 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11771 // A package with the same name is already installed, though 11772 // it has been renamed to an older name. The package we 11773 // are trying to install should be installed as an update to 11774 // the existing one, but that has not been requested, so bail. 11775 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11776 + " without first uninstalling package running as " 11777 + mSettings.mRenamedPackages.get(pkgName)); 11778 return; 11779 } 11780 if (mPackages.containsKey(pkgName)) { 11781 // Don't allow installation over an existing package with the same name. 11782 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11783 + " without first uninstalling."); 11784 return; 11785 } 11786 } 11787 11788 try { 11789 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11790 System.currentTimeMillis(), user); 11791 11792 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11793 // delete the partially installed application. the data directory will have to be 11794 // restored if it was already existing 11795 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11796 // remove package from internal structures. Note that we want deletePackageX to 11797 // delete the package data and cache directories that it created in 11798 // scanPackageLocked, unless those directories existed before we even tried to 11799 // install. 11800 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11801 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11802 res.removedInfo, true); 11803 } 11804 11805 } catch (PackageManagerException e) { 11806 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11807 } 11808 } 11809 11810 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11811 // Can't rotate keys during boot or if sharedUser. 11812 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11813 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11814 return false; 11815 } 11816 // app is using upgradeKeySets; make sure all are valid 11817 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11818 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11819 for (int i = 0; i < upgradeKeySets.length; i++) { 11820 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11821 Slog.wtf(TAG, "Package " 11822 + (oldPs.name != null ? oldPs.name : "<null>") 11823 + " contains upgrade-key-set reference to unknown key-set: " 11824 + upgradeKeySets[i] 11825 + " reverting to signatures check."); 11826 return false; 11827 } 11828 } 11829 return true; 11830 } 11831 11832 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11833 // Upgrade keysets are being used. Determine if new package has a superset of the 11834 // required keys. 11835 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11836 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11837 for (int i = 0; i < upgradeKeySets.length; i++) { 11838 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11839 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11840 return true; 11841 } 11842 } 11843 return false; 11844 } 11845 11846 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11847 UserHandle user, String installerPackageName, String volumeUuid, 11848 PackageInstalledInfo res) { 11849 final PackageParser.Package oldPackage; 11850 final String pkgName = pkg.packageName; 11851 final int[] allUsers; 11852 final boolean[] perUserInstalled; 11853 11854 // First find the old package info and check signatures 11855 synchronized(mPackages) { 11856 oldPackage = mPackages.get(pkgName); 11857 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11858 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11859 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11860 if(!checkUpgradeKeySetLP(ps, pkg)) { 11861 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11862 "New package not signed by keys specified by upgrade-keysets: " 11863 + pkgName); 11864 return; 11865 } 11866 } else { 11867 // default to original signature matching 11868 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11869 != PackageManager.SIGNATURE_MATCH) { 11870 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11871 "New package has a different signature: " + pkgName); 11872 return; 11873 } 11874 } 11875 11876 // In case of rollback, remember per-user/profile install state 11877 allUsers = sUserManager.getUserIds(); 11878 perUserInstalled = new boolean[allUsers.length]; 11879 for (int i = 0; i < allUsers.length; i++) { 11880 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11881 } 11882 } 11883 11884 boolean sysPkg = (isSystemApp(oldPackage)); 11885 if (sysPkg) { 11886 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11887 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11888 } else { 11889 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11890 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11891 } 11892 } 11893 11894 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11895 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11896 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11897 String volumeUuid, PackageInstalledInfo res) { 11898 String pkgName = deletedPackage.packageName; 11899 boolean deletedPkg = true; 11900 boolean updatedSettings = false; 11901 11902 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11903 + deletedPackage); 11904 long origUpdateTime; 11905 if (pkg.mExtras != null) { 11906 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11907 } else { 11908 origUpdateTime = 0; 11909 } 11910 11911 // First delete the existing package while retaining the data directory 11912 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11913 res.removedInfo, true)) { 11914 // If the existing package wasn't successfully deleted 11915 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11916 deletedPkg = false; 11917 } else { 11918 // Successfully deleted the old package; proceed with replace. 11919 11920 // If deleted package lived in a container, give users a chance to 11921 // relinquish resources before killing. 11922 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11923 if (DEBUG_INSTALL) { 11924 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11925 } 11926 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11927 final ArrayList<String> pkgList = new ArrayList<String>(1); 11928 pkgList.add(deletedPackage.applicationInfo.packageName); 11929 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11930 } 11931 11932 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11933 try { 11934 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11935 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11936 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11937 perUserInstalled, res, user); 11938 updatedSettings = true; 11939 } catch (PackageManagerException e) { 11940 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11941 } 11942 } 11943 11944 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11945 // remove package from internal structures. Note that we want deletePackageX to 11946 // delete the package data and cache directories that it created in 11947 // scanPackageLocked, unless those directories existed before we even tried to 11948 // install. 11949 if(updatedSettings) { 11950 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11951 deletePackageLI( 11952 pkgName, null, true, allUsers, perUserInstalled, 11953 PackageManager.DELETE_KEEP_DATA, 11954 res.removedInfo, true); 11955 } 11956 // Since we failed to install the new package we need to restore the old 11957 // package that we deleted. 11958 if (deletedPkg) { 11959 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11960 File restoreFile = new File(deletedPackage.codePath); 11961 // Parse old package 11962 boolean oldExternal = isExternal(deletedPackage); 11963 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11964 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11965 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11966 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11967 try { 11968 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11969 } catch (PackageManagerException e) { 11970 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11971 + e.getMessage()); 11972 return; 11973 } 11974 // Restore of old package succeeded. Update permissions. 11975 // writer 11976 synchronized (mPackages) { 11977 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11978 UPDATE_PERMISSIONS_ALL); 11979 // can downgrade to reader 11980 mSettings.writeLPr(); 11981 } 11982 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11983 } 11984 } 11985 } 11986 11987 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11988 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11989 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11990 String volumeUuid, PackageInstalledInfo res) { 11991 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11992 + ", old=" + deletedPackage); 11993 boolean disabledSystem = false; 11994 boolean updatedSettings = false; 11995 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11996 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11997 != 0) { 11998 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11999 } 12000 String packageName = deletedPackage.packageName; 12001 if (packageName == null) { 12002 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12003 "Attempt to delete null packageName."); 12004 return; 12005 } 12006 PackageParser.Package oldPkg; 12007 PackageSetting oldPkgSetting; 12008 // reader 12009 synchronized (mPackages) { 12010 oldPkg = mPackages.get(packageName); 12011 oldPkgSetting = mSettings.mPackages.get(packageName); 12012 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12013 (oldPkgSetting == null)) { 12014 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12015 "Couldn't find package:" + packageName + " information"); 12016 return; 12017 } 12018 } 12019 12020 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12021 12022 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12023 res.removedInfo.removedPackage = packageName; 12024 // Remove existing system package 12025 removePackageLI(oldPkgSetting, true); 12026 // writer 12027 synchronized (mPackages) { 12028 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12029 if (!disabledSystem && deletedPackage != null) { 12030 // We didn't need to disable the .apk as a current system package, 12031 // which means we are replacing another update that is already 12032 // installed. We need to make sure to delete the older one's .apk. 12033 res.removedInfo.args = createInstallArgsForExisting(0, 12034 deletedPackage.applicationInfo.getCodePath(), 12035 deletedPackage.applicationInfo.getResourcePath(), 12036 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12037 } else { 12038 res.removedInfo.args = null; 12039 } 12040 } 12041 12042 // Successfully disabled the old package. Now proceed with re-installation 12043 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12044 12045 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12046 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12047 12048 PackageParser.Package newPackage = null; 12049 try { 12050 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 12051 if (newPackage.mExtras != null) { 12052 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12053 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12054 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12055 12056 // is the update attempting to change shared user? that isn't going to work... 12057 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12058 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12059 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12060 + " to " + newPkgSetting.sharedUser); 12061 updatedSettings = true; 12062 } 12063 } 12064 12065 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12066 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12067 perUserInstalled, res, user); 12068 updatedSettings = true; 12069 } 12070 12071 } catch (PackageManagerException e) { 12072 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12073 } 12074 12075 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12076 // Re installation failed. Restore old information 12077 // Remove new pkg information 12078 if (newPackage != null) { 12079 removeInstalledPackageLI(newPackage, true); 12080 } 12081 // Add back the old system package 12082 try { 12083 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12084 } catch (PackageManagerException e) { 12085 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12086 } 12087 // Restore the old system information in Settings 12088 synchronized (mPackages) { 12089 if (disabledSystem) { 12090 mSettings.enableSystemPackageLPw(packageName); 12091 } 12092 if (updatedSettings) { 12093 mSettings.setInstallerPackageName(packageName, 12094 oldPkgSetting.installerPackageName); 12095 } 12096 mSettings.writeLPr(); 12097 } 12098 } 12099 } 12100 12101 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12102 // Collect all used permissions in the UID 12103 ArraySet<String> usedPermissions = new ArraySet<>(); 12104 final int packageCount = su.packages.size(); 12105 for (int i = 0; i < packageCount; i++) { 12106 PackageSetting ps = su.packages.valueAt(i); 12107 if (ps.pkg == null) { 12108 continue; 12109 } 12110 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12111 for (int j = 0; j < requestedPermCount; j++) { 12112 String permission = ps.pkg.requestedPermissions.get(j); 12113 BasePermission bp = mSettings.mPermissions.get(permission); 12114 if (bp != null) { 12115 usedPermissions.add(permission); 12116 } 12117 } 12118 } 12119 12120 PermissionsState permissionsState = su.getPermissionsState(); 12121 // Prune install permissions 12122 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12123 final int installPermCount = installPermStates.size(); 12124 for (int i = installPermCount - 1; i >= 0; i--) { 12125 PermissionState permissionState = installPermStates.get(i); 12126 if (!usedPermissions.contains(permissionState.getName())) { 12127 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12128 if (bp != null) { 12129 permissionsState.revokeInstallPermission(bp); 12130 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12131 PackageManager.MASK_PERMISSION_FLAGS, 0); 12132 } 12133 } 12134 } 12135 12136 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12137 12138 // Prune runtime permissions 12139 for (int userId : allUserIds) { 12140 List<PermissionState> runtimePermStates = permissionsState 12141 .getRuntimePermissionStates(userId); 12142 final int runtimePermCount = runtimePermStates.size(); 12143 for (int i = runtimePermCount - 1; i >= 0; i--) { 12144 PermissionState permissionState = runtimePermStates.get(i); 12145 if (!usedPermissions.contains(permissionState.getName())) { 12146 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12147 if (bp != null) { 12148 permissionsState.revokeRuntimePermission(bp, userId); 12149 permissionsState.updatePermissionFlags(bp, userId, 12150 PackageManager.MASK_PERMISSION_FLAGS, 0); 12151 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12152 runtimePermissionChangedUserIds, userId); 12153 } 12154 } 12155 } 12156 } 12157 12158 return runtimePermissionChangedUserIds; 12159 } 12160 12161 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12162 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12163 UserHandle user) { 12164 String pkgName = newPackage.packageName; 12165 synchronized (mPackages) { 12166 //write settings. the installStatus will be incomplete at this stage. 12167 //note that the new package setting would have already been 12168 //added to mPackages. It hasn't been persisted yet. 12169 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12170 mSettings.writeLPr(); 12171 } 12172 12173 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12174 12175 synchronized (mPackages) { 12176 updatePermissionsLPw(newPackage.packageName, newPackage, 12177 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12178 ? UPDATE_PERMISSIONS_ALL : 0)); 12179 // For system-bundled packages, we assume that installing an upgraded version 12180 // of the package implies that the user actually wants to run that new code, 12181 // so we enable the package. 12182 PackageSetting ps = mSettings.mPackages.get(pkgName); 12183 if (ps != null) { 12184 if (isSystemApp(newPackage)) { 12185 // NB: implicit assumption that system package upgrades apply to all users 12186 if (DEBUG_INSTALL) { 12187 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12188 } 12189 if (res.origUsers != null) { 12190 for (int userHandle : res.origUsers) { 12191 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12192 userHandle, installerPackageName); 12193 } 12194 } 12195 // Also convey the prior install/uninstall state 12196 if (allUsers != null && perUserInstalled != null) { 12197 for (int i = 0; i < allUsers.length; i++) { 12198 if (DEBUG_INSTALL) { 12199 Slog.d(TAG, " user " + allUsers[i] 12200 + " => " + perUserInstalled[i]); 12201 } 12202 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12203 } 12204 // these install state changes will be persisted in the 12205 // upcoming call to mSettings.writeLPr(). 12206 } 12207 } 12208 // It's implied that when a user requests installation, they want the app to be 12209 // installed and enabled. 12210 int userId = user.getIdentifier(); 12211 if (userId != UserHandle.USER_ALL) { 12212 ps.setInstalled(true, userId); 12213 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12214 } 12215 } 12216 res.name = pkgName; 12217 res.uid = newPackage.applicationInfo.uid; 12218 res.pkg = newPackage; 12219 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12220 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12221 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12222 //to update install status 12223 mSettings.writeLPr(); 12224 } 12225 } 12226 12227 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12228 final int installFlags = args.installFlags; 12229 final String installerPackageName = args.installerPackageName; 12230 final String volumeUuid = args.volumeUuid; 12231 final File tmpPackageFile = new File(args.getCodePath()); 12232 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12233 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12234 || (args.volumeUuid != null)); 12235 boolean replace = false; 12236 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12237 if (args.move != null) { 12238 // moving a complete application; perfom an initial scan on the new install location 12239 scanFlags |= SCAN_INITIAL; 12240 } 12241 // Result object to be returned 12242 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12243 12244 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12245 // Retrieve PackageSettings and parse package 12246 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12247 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12248 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12249 PackageParser pp = new PackageParser(); 12250 pp.setSeparateProcesses(mSeparateProcesses); 12251 pp.setDisplayMetrics(mMetrics); 12252 12253 final PackageParser.Package pkg; 12254 try { 12255 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12256 } catch (PackageParserException e) { 12257 res.setError("Failed parse during installPackageLI", e); 12258 return; 12259 } 12260 12261 // Mark that we have an install time CPU ABI override. 12262 pkg.cpuAbiOverride = args.abiOverride; 12263 12264 String pkgName = res.name = pkg.packageName; 12265 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12266 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12267 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12268 return; 12269 } 12270 } 12271 12272 try { 12273 pp.collectCertificates(pkg, parseFlags); 12274 pp.collectManifestDigest(pkg); 12275 } catch (PackageParserException e) { 12276 res.setError("Failed collect during installPackageLI", e); 12277 return; 12278 } 12279 12280 /* If the installer passed in a manifest digest, compare it now. */ 12281 if (args.manifestDigest != null) { 12282 if (DEBUG_INSTALL) { 12283 final String parsedManifest = pkg.manifestDigest == null ? "null" 12284 : pkg.manifestDigest.toString(); 12285 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12286 + parsedManifest); 12287 } 12288 12289 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12290 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12291 return; 12292 } 12293 } else if (DEBUG_INSTALL) { 12294 final String parsedManifest = pkg.manifestDigest == null 12295 ? "null" : pkg.manifestDigest.toString(); 12296 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12297 } 12298 12299 // Get rid of all references to package scan path via parser. 12300 pp = null; 12301 String oldCodePath = null; 12302 boolean systemApp = false; 12303 synchronized (mPackages) { 12304 // Check if installing already existing package 12305 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12306 String oldName = mSettings.mRenamedPackages.get(pkgName); 12307 if (pkg.mOriginalPackages != null 12308 && pkg.mOriginalPackages.contains(oldName) 12309 && mPackages.containsKey(oldName)) { 12310 // This package is derived from an original package, 12311 // and this device has been updating from that original 12312 // name. We must continue using the original name, so 12313 // rename the new package here. 12314 pkg.setPackageName(oldName); 12315 pkgName = pkg.packageName; 12316 replace = true; 12317 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12318 + oldName + " pkgName=" + pkgName); 12319 } else if (mPackages.containsKey(pkgName)) { 12320 // This package, under its official name, already exists 12321 // on the device; we should replace it. 12322 replace = true; 12323 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12324 } 12325 12326 // Prevent apps opting out from runtime permissions 12327 if (replace) { 12328 PackageParser.Package oldPackage = mPackages.get(pkgName); 12329 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12330 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12331 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12332 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12333 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12334 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12335 + " doesn't support runtime permissions but the old" 12336 + " target SDK " + oldTargetSdk + " does."); 12337 return; 12338 } 12339 } 12340 } 12341 12342 PackageSetting ps = mSettings.mPackages.get(pkgName); 12343 if (ps != null) { 12344 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12345 12346 // Quick sanity check that we're signed correctly if updating; 12347 // we'll check this again later when scanning, but we want to 12348 // bail early here before tripping over redefined permissions. 12349 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12350 if (!checkUpgradeKeySetLP(ps, pkg)) { 12351 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12352 + pkg.packageName + " upgrade keys do not match the " 12353 + "previously installed version"); 12354 return; 12355 } 12356 } else { 12357 try { 12358 verifySignaturesLP(ps, pkg); 12359 } catch (PackageManagerException e) { 12360 res.setError(e.error, e.getMessage()); 12361 return; 12362 } 12363 } 12364 12365 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12366 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12367 systemApp = (ps.pkg.applicationInfo.flags & 12368 ApplicationInfo.FLAG_SYSTEM) != 0; 12369 } 12370 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12371 } 12372 12373 // Check whether the newly-scanned package wants to define an already-defined perm 12374 int N = pkg.permissions.size(); 12375 for (int i = N-1; i >= 0; i--) { 12376 PackageParser.Permission perm = pkg.permissions.get(i); 12377 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12378 if (bp != null) { 12379 // If the defining package is signed with our cert, it's okay. This 12380 // also includes the "updating the same package" case, of course. 12381 // "updating same package" could also involve key-rotation. 12382 final boolean sigsOk; 12383 if (bp.sourcePackage.equals(pkg.packageName) 12384 && (bp.packageSetting instanceof PackageSetting) 12385 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12386 scanFlags))) { 12387 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12388 } else { 12389 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12390 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12391 } 12392 if (!sigsOk) { 12393 // If the owning package is the system itself, we log but allow 12394 // install to proceed; we fail the install on all other permission 12395 // redefinitions. 12396 if (!bp.sourcePackage.equals("android")) { 12397 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12398 + pkg.packageName + " attempting to redeclare permission " 12399 + perm.info.name + " already owned by " + bp.sourcePackage); 12400 res.origPermission = perm.info.name; 12401 res.origPackage = bp.sourcePackage; 12402 return; 12403 } else { 12404 Slog.w(TAG, "Package " + pkg.packageName 12405 + " attempting to redeclare system permission " 12406 + perm.info.name + "; ignoring new declaration"); 12407 pkg.permissions.remove(i); 12408 } 12409 } 12410 } 12411 } 12412 12413 } 12414 12415 if (systemApp && onExternal) { 12416 // Disable updates to system apps on sdcard 12417 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12418 "Cannot install updates to system apps on sdcard"); 12419 return; 12420 } 12421 12422 if (args.move != null) { 12423 // We did an in-place move, so dex is ready to roll 12424 scanFlags |= SCAN_NO_DEX; 12425 scanFlags |= SCAN_MOVE; 12426 12427 synchronized (mPackages) { 12428 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12429 if (ps == null) { 12430 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12431 "Missing settings for moved package " + pkgName); 12432 } 12433 12434 // We moved the entire application as-is, so bring over the 12435 // previously derived ABI information. 12436 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12437 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12438 } 12439 12440 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12441 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12442 scanFlags |= SCAN_NO_DEX; 12443 12444 try { 12445 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12446 true /* extract libs */); 12447 } catch (PackageManagerException pme) { 12448 Slog.e(TAG, "Error deriving application ABI", pme); 12449 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12450 return; 12451 } 12452 12453 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12454 int result = mPackageDexOptimizer 12455 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12456 false /* defer */, false /* inclDependencies */, 12457 true /*bootComplete*/, false /*useJit*/); 12458 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12459 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12460 return; 12461 } 12462 } 12463 12464 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12465 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12466 return; 12467 } 12468 12469 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12470 12471 if (replace) { 12472 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12473 installerPackageName, volumeUuid, res); 12474 } else { 12475 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12476 args.user, installerPackageName, volumeUuid, res); 12477 } 12478 synchronized (mPackages) { 12479 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12480 if (ps != null) { 12481 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12482 } 12483 } 12484 } 12485 12486 private void startIntentFilterVerifications(int userId, boolean replacing, 12487 PackageParser.Package pkg) { 12488 if (mIntentFilterVerifierComponent == null) { 12489 Slog.w(TAG, "No IntentFilter verification will not be done as " 12490 + "there is no IntentFilterVerifier available!"); 12491 return; 12492 } 12493 12494 final int verifierUid = getPackageUid( 12495 mIntentFilterVerifierComponent.getPackageName(), 12496 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12497 12498 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12499 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12500 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12501 mHandler.sendMessage(msg); 12502 } 12503 12504 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12505 PackageParser.Package pkg) { 12506 int size = pkg.activities.size(); 12507 if (size == 0) { 12508 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12509 "No activity, so no need to verify any IntentFilter!"); 12510 return; 12511 } 12512 12513 final boolean hasDomainURLs = hasDomainURLs(pkg); 12514 if (!hasDomainURLs) { 12515 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12516 "No domain URLs, so no need to verify any IntentFilter!"); 12517 return; 12518 } 12519 12520 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12521 + " if any IntentFilter from the " + size 12522 + " Activities needs verification ..."); 12523 12524 int count = 0; 12525 final String packageName = pkg.packageName; 12526 12527 synchronized (mPackages) { 12528 // If this is a new install and we see that we've already run verification for this 12529 // package, we have nothing to do: it means the state was restored from backup. 12530 if (!replacing) { 12531 IntentFilterVerificationInfo ivi = 12532 mSettings.getIntentFilterVerificationLPr(packageName); 12533 if (ivi != null) { 12534 if (DEBUG_DOMAIN_VERIFICATION) { 12535 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12536 + ivi.getStatusString()); 12537 } 12538 return; 12539 } 12540 } 12541 12542 // If any filters need to be verified, then all need to be. 12543 boolean needToVerify = false; 12544 for (PackageParser.Activity a : pkg.activities) { 12545 for (ActivityIntentInfo filter : a.intents) { 12546 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12547 if (DEBUG_DOMAIN_VERIFICATION) { 12548 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12549 } 12550 needToVerify = true; 12551 break; 12552 } 12553 } 12554 } 12555 12556 if (needToVerify) { 12557 final int verificationId = mIntentFilterVerificationToken++; 12558 for (PackageParser.Activity a : pkg.activities) { 12559 for (ActivityIntentInfo filter : a.intents) { 12560 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12561 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12562 "Verification needed for IntentFilter:" + filter.toString()); 12563 mIntentFilterVerifier.addOneIntentFilterVerification( 12564 verifierUid, userId, verificationId, filter, packageName); 12565 count++; 12566 } 12567 } 12568 } 12569 } 12570 } 12571 12572 if (count > 0) { 12573 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12574 + " IntentFilter verification" + (count > 1 ? "s" : "") 12575 + " for userId:" + userId); 12576 mIntentFilterVerifier.startVerifications(userId); 12577 } else { 12578 if (DEBUG_DOMAIN_VERIFICATION) { 12579 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12580 } 12581 } 12582 } 12583 12584 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12585 final ComponentName cn = filter.activity.getComponentName(); 12586 final String packageName = cn.getPackageName(); 12587 12588 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12589 packageName); 12590 if (ivi == null) { 12591 return true; 12592 } 12593 int status = ivi.getStatus(); 12594 switch (status) { 12595 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12596 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12597 return true; 12598 12599 default: 12600 // Nothing to do 12601 return false; 12602 } 12603 } 12604 12605 private static boolean isMultiArch(PackageSetting ps) { 12606 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12607 } 12608 12609 private static boolean isMultiArch(ApplicationInfo info) { 12610 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12611 } 12612 12613 private static boolean isExternal(PackageParser.Package pkg) { 12614 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12615 } 12616 12617 private static boolean isExternal(PackageSetting ps) { 12618 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12619 } 12620 12621 private static boolean isExternal(ApplicationInfo info) { 12622 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12623 } 12624 12625 private static boolean isSystemApp(PackageParser.Package pkg) { 12626 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12627 } 12628 12629 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12630 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12631 } 12632 12633 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12634 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12635 } 12636 12637 private static boolean isSystemApp(PackageSetting ps) { 12638 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12639 } 12640 12641 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12642 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12643 } 12644 12645 private int packageFlagsToInstallFlags(PackageSetting ps) { 12646 int installFlags = 0; 12647 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12648 // This existing package was an external ASEC install when we have 12649 // the external flag without a UUID 12650 installFlags |= PackageManager.INSTALL_EXTERNAL; 12651 } 12652 if (ps.isForwardLocked()) { 12653 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12654 } 12655 return installFlags; 12656 } 12657 12658 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 12659 if (isExternal(pkg)) { 12660 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12661 return StorageManager.UUID_PRIMARY_PHYSICAL; 12662 } else { 12663 return pkg.volumeUuid; 12664 } 12665 } else { 12666 return StorageManager.UUID_PRIVATE_INTERNAL; 12667 } 12668 } 12669 12670 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12671 if (isExternal(pkg)) { 12672 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12673 return mSettings.getExternalVersion(); 12674 } else { 12675 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12676 } 12677 } else { 12678 return mSettings.getInternalVersion(); 12679 } 12680 } 12681 12682 private void deleteTempPackageFiles() { 12683 final FilenameFilter filter = new FilenameFilter() { 12684 public boolean accept(File dir, String name) { 12685 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12686 } 12687 }; 12688 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12689 file.delete(); 12690 } 12691 } 12692 12693 @Override 12694 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12695 int flags) { 12696 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12697 flags); 12698 } 12699 12700 @Override 12701 public void deletePackage(final String packageName, 12702 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12703 mContext.enforceCallingOrSelfPermission( 12704 android.Manifest.permission.DELETE_PACKAGES, null); 12705 Preconditions.checkNotNull(packageName); 12706 Preconditions.checkNotNull(observer); 12707 final int uid = Binder.getCallingUid(); 12708 if (UserHandle.getUserId(uid) != userId) { 12709 mContext.enforceCallingPermission( 12710 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12711 "deletePackage for user " + userId); 12712 } 12713 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12714 try { 12715 observer.onPackageDeleted(packageName, 12716 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12717 } catch (RemoteException re) { 12718 } 12719 return; 12720 } 12721 12722 boolean uninstallBlocked = false; 12723 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12724 int[] users = sUserManager.getUserIds(); 12725 for (int i = 0; i < users.length; ++i) { 12726 if (getBlockUninstallForUser(packageName, users[i])) { 12727 uninstallBlocked = true; 12728 break; 12729 } 12730 } 12731 } else { 12732 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12733 } 12734 if (uninstallBlocked) { 12735 try { 12736 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12737 null); 12738 } catch (RemoteException re) { 12739 } 12740 return; 12741 } 12742 12743 if (DEBUG_REMOVE) { 12744 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12745 } 12746 // Queue up an async operation since the package deletion may take a little while. 12747 mHandler.post(new Runnable() { 12748 public void run() { 12749 mHandler.removeCallbacks(this); 12750 final int returnCode = deletePackageX(packageName, userId, flags); 12751 if (observer != null) { 12752 try { 12753 observer.onPackageDeleted(packageName, returnCode, null); 12754 } catch (RemoteException e) { 12755 Log.i(TAG, "Observer no longer exists."); 12756 } //end catch 12757 } //end if 12758 } //end run 12759 }); 12760 } 12761 12762 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12763 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12764 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12765 try { 12766 if (dpm != null) { 12767 if (dpm.isDeviceOwner(packageName)) { 12768 return true; 12769 } 12770 int[] users; 12771 if (userId == UserHandle.USER_ALL) { 12772 users = sUserManager.getUserIds(); 12773 } else { 12774 users = new int[]{userId}; 12775 } 12776 for (int i = 0; i < users.length; ++i) { 12777 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12778 return true; 12779 } 12780 } 12781 } 12782 } catch (RemoteException e) { 12783 } 12784 return false; 12785 } 12786 12787 /** 12788 * This method is an internal method that could be get invoked either 12789 * to delete an installed package or to clean up a failed installation. 12790 * After deleting an installed package, a broadcast is sent to notify any 12791 * listeners that the package has been installed. For cleaning up a failed 12792 * installation, the broadcast is not necessary since the package's 12793 * installation wouldn't have sent the initial broadcast either 12794 * The key steps in deleting a package are 12795 * deleting the package information in internal structures like mPackages, 12796 * deleting the packages base directories through installd 12797 * updating mSettings to reflect current status 12798 * persisting settings for later use 12799 * sending a broadcast if necessary 12800 */ 12801 private int deletePackageX(String packageName, int userId, int flags) { 12802 final PackageRemovedInfo info = new PackageRemovedInfo(); 12803 final boolean res; 12804 12805 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12806 ? UserHandle.ALL : new UserHandle(userId); 12807 12808 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12809 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12810 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12811 } 12812 12813 boolean removedForAllUsers = false; 12814 boolean systemUpdate = false; 12815 12816 // for the uninstall-updates case and restricted profiles, remember the per- 12817 // userhandle installed state 12818 int[] allUsers; 12819 boolean[] perUserInstalled; 12820 synchronized (mPackages) { 12821 PackageSetting ps = mSettings.mPackages.get(packageName); 12822 allUsers = sUserManager.getUserIds(); 12823 perUserInstalled = new boolean[allUsers.length]; 12824 for (int i = 0; i < allUsers.length; i++) { 12825 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12826 } 12827 } 12828 12829 synchronized (mInstallLock) { 12830 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12831 res = deletePackageLI(packageName, removeForUser, 12832 true, allUsers, perUserInstalled, 12833 flags | REMOVE_CHATTY, info, true); 12834 systemUpdate = info.isRemovedPackageSystemUpdate; 12835 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12836 removedForAllUsers = true; 12837 } 12838 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12839 + " removedForAllUsers=" + removedForAllUsers); 12840 } 12841 12842 if (res) { 12843 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12844 12845 // If the removed package was a system update, the old system package 12846 // was re-enabled; we need to broadcast this information 12847 if (systemUpdate) { 12848 Bundle extras = new Bundle(1); 12849 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12850 ? info.removedAppId : info.uid); 12851 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12852 12853 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12854 extras, null, null, null); 12855 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12856 extras, null, null, null); 12857 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12858 null, packageName, null, null); 12859 } 12860 } 12861 // Force a gc here. 12862 Runtime.getRuntime().gc(); 12863 // Delete the resources here after sending the broadcast to let 12864 // other processes clean up before deleting resources. 12865 if (info.args != null) { 12866 synchronized (mInstallLock) { 12867 info.args.doPostDeleteLI(true); 12868 } 12869 } 12870 12871 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12872 } 12873 12874 class PackageRemovedInfo { 12875 String removedPackage; 12876 int uid = -1; 12877 int removedAppId = -1; 12878 int[] removedUsers = null; 12879 boolean isRemovedPackageSystemUpdate = false; 12880 // Clean up resources deleted packages. 12881 InstallArgs args = null; 12882 12883 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12884 Bundle extras = new Bundle(1); 12885 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12886 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12887 if (replacing) { 12888 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12889 } 12890 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12891 if (removedPackage != null) { 12892 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12893 extras, null, null, removedUsers); 12894 if (fullRemove && !replacing) { 12895 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12896 extras, null, null, removedUsers); 12897 } 12898 } 12899 if (removedAppId >= 0) { 12900 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12901 removedUsers); 12902 } 12903 } 12904 } 12905 12906 /* 12907 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12908 * flag is not set, the data directory is removed as well. 12909 * make sure this flag is set for partially installed apps. If not its meaningless to 12910 * delete a partially installed application. 12911 */ 12912 private void removePackageDataLI(PackageSetting ps, 12913 int[] allUserHandles, boolean[] perUserInstalled, 12914 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12915 String packageName = ps.name; 12916 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12917 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12918 // Retrieve object to delete permissions for shared user later on 12919 final PackageSetting deletedPs; 12920 // reader 12921 synchronized (mPackages) { 12922 deletedPs = mSettings.mPackages.get(packageName); 12923 if (outInfo != null) { 12924 outInfo.removedPackage = packageName; 12925 outInfo.removedUsers = deletedPs != null 12926 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12927 : null; 12928 } 12929 } 12930 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12931 removeDataDirsLI(ps.volumeUuid, packageName); 12932 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12933 } 12934 // writer 12935 synchronized (mPackages) { 12936 if (deletedPs != null) { 12937 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12938 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12939 clearDefaultBrowserIfNeeded(packageName); 12940 if (outInfo != null) { 12941 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12942 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12943 } 12944 updatePermissionsLPw(deletedPs.name, null, 0); 12945 if (deletedPs.sharedUser != null) { 12946 // Remove permissions associated with package. Since runtime 12947 // permissions are per user we have to kill the removed package 12948 // or packages running under the shared user of the removed 12949 // package if revoking the permissions requested only by the removed 12950 // package is successful and this causes a change in gids. 12951 for (int userId : UserManagerService.getInstance().getUserIds()) { 12952 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12953 userId); 12954 if (userIdToKill == UserHandle.USER_ALL 12955 || userIdToKill >= UserHandle.USER_OWNER) { 12956 // If gids changed for this user, kill all affected packages. 12957 mHandler.post(new Runnable() { 12958 @Override 12959 public void run() { 12960 // This has to happen with no lock held. 12961 killApplication(deletedPs.name, deletedPs.appId, 12962 KILL_APP_REASON_GIDS_CHANGED); 12963 } 12964 }); 12965 break; 12966 } 12967 } 12968 } 12969 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12970 } 12971 // make sure to preserve per-user disabled state if this removal was just 12972 // a downgrade of a system app to the factory package 12973 if (allUserHandles != null && perUserInstalled != null) { 12974 if (DEBUG_REMOVE) { 12975 Slog.d(TAG, "Propagating install state across downgrade"); 12976 } 12977 for (int i = 0; i < allUserHandles.length; i++) { 12978 if (DEBUG_REMOVE) { 12979 Slog.d(TAG, " user " + allUserHandles[i] 12980 + " => " + perUserInstalled[i]); 12981 } 12982 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12983 } 12984 } 12985 } 12986 // can downgrade to reader 12987 if (writeSettings) { 12988 // Save settings now 12989 mSettings.writeLPr(); 12990 } 12991 } 12992 if (outInfo != null) { 12993 // A user ID was deleted here. Go through all users and remove it 12994 // from KeyStore. 12995 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12996 } 12997 } 12998 12999 static boolean locationIsPrivileged(File path) { 13000 try { 13001 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13002 .getCanonicalPath(); 13003 return path.getCanonicalPath().startsWith(privilegedAppDir); 13004 } catch (IOException e) { 13005 Slog.e(TAG, "Unable to access code path " + path); 13006 } 13007 return false; 13008 } 13009 13010 /* 13011 * Tries to delete system package. 13012 */ 13013 private boolean deleteSystemPackageLI(PackageSetting newPs, 13014 int[] allUserHandles, boolean[] perUserInstalled, 13015 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13016 final boolean applyUserRestrictions 13017 = (allUserHandles != null) && (perUserInstalled != null); 13018 PackageSetting disabledPs = null; 13019 // Confirm if the system package has been updated 13020 // An updated system app can be deleted. This will also have to restore 13021 // the system pkg from system partition 13022 // reader 13023 synchronized (mPackages) { 13024 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13025 } 13026 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13027 + " disabledPs=" + disabledPs); 13028 if (disabledPs == null) { 13029 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13030 return false; 13031 } else if (DEBUG_REMOVE) { 13032 Slog.d(TAG, "Deleting system pkg from data partition"); 13033 } 13034 if (DEBUG_REMOVE) { 13035 if (applyUserRestrictions) { 13036 Slog.d(TAG, "Remembering install states:"); 13037 for (int i = 0; i < allUserHandles.length; i++) { 13038 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13039 } 13040 } 13041 } 13042 // Delete the updated package 13043 outInfo.isRemovedPackageSystemUpdate = true; 13044 if (disabledPs.versionCode < newPs.versionCode) { 13045 // Delete data for downgrades 13046 flags &= ~PackageManager.DELETE_KEEP_DATA; 13047 } else { 13048 // Preserve data by setting flag 13049 flags |= PackageManager.DELETE_KEEP_DATA; 13050 } 13051 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13052 allUserHandles, perUserInstalled, outInfo, writeSettings); 13053 if (!ret) { 13054 return false; 13055 } 13056 // writer 13057 synchronized (mPackages) { 13058 // Reinstate the old system package 13059 mSettings.enableSystemPackageLPw(newPs.name); 13060 // Remove any native libraries from the upgraded package. 13061 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13062 } 13063 // Install the system package 13064 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13065 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13066 if (locationIsPrivileged(disabledPs.codePath)) { 13067 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13068 } 13069 13070 final PackageParser.Package newPkg; 13071 try { 13072 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13073 } catch (PackageManagerException e) { 13074 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13075 return false; 13076 } 13077 13078 // writer 13079 synchronized (mPackages) { 13080 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13081 13082 // Propagate the permissions state as we do not want to drop on the floor 13083 // runtime permissions. The update permissions method below will take 13084 // care of removing obsolete permissions and grant install permissions. 13085 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13086 updatePermissionsLPw(newPkg.packageName, newPkg, 13087 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13088 13089 if (applyUserRestrictions) { 13090 if (DEBUG_REMOVE) { 13091 Slog.d(TAG, "Propagating install state across reinstall"); 13092 } 13093 for (int i = 0; i < allUserHandles.length; i++) { 13094 if (DEBUG_REMOVE) { 13095 Slog.d(TAG, " user " + allUserHandles[i] 13096 + " => " + perUserInstalled[i]); 13097 } 13098 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13099 13100 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13101 } 13102 // Regardless of writeSettings we need to ensure that this restriction 13103 // state propagation is persisted 13104 mSettings.writeAllUsersPackageRestrictionsLPr(); 13105 } 13106 // can downgrade to reader here 13107 if (writeSettings) { 13108 mSettings.writeLPr(); 13109 } 13110 } 13111 return true; 13112 } 13113 13114 private boolean deleteInstalledPackageLI(PackageSetting ps, 13115 boolean deleteCodeAndResources, int flags, 13116 int[] allUserHandles, boolean[] perUserInstalled, 13117 PackageRemovedInfo outInfo, boolean writeSettings) { 13118 if (outInfo != null) { 13119 outInfo.uid = ps.appId; 13120 } 13121 13122 // Delete package data from internal structures and also remove data if flag is set 13123 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13124 13125 // Delete application code and resources 13126 if (deleteCodeAndResources && (outInfo != null)) { 13127 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13128 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13129 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13130 } 13131 return true; 13132 } 13133 13134 @Override 13135 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13136 int userId) { 13137 mContext.enforceCallingOrSelfPermission( 13138 android.Manifest.permission.DELETE_PACKAGES, null); 13139 synchronized (mPackages) { 13140 PackageSetting ps = mSettings.mPackages.get(packageName); 13141 if (ps == null) { 13142 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13143 return false; 13144 } 13145 if (!ps.getInstalled(userId)) { 13146 // Can't block uninstall for an app that is not installed or enabled. 13147 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13148 return false; 13149 } 13150 ps.setBlockUninstall(blockUninstall, userId); 13151 mSettings.writePackageRestrictionsLPr(userId); 13152 } 13153 return true; 13154 } 13155 13156 @Override 13157 public boolean getBlockUninstallForUser(String packageName, int userId) { 13158 synchronized (mPackages) { 13159 PackageSetting ps = mSettings.mPackages.get(packageName); 13160 if (ps == null) { 13161 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13162 return false; 13163 } 13164 return ps.getBlockUninstall(userId); 13165 } 13166 } 13167 13168 /* 13169 * This method handles package deletion in general 13170 */ 13171 private boolean deletePackageLI(String packageName, UserHandle user, 13172 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13173 int flags, PackageRemovedInfo outInfo, 13174 boolean writeSettings) { 13175 if (packageName == null) { 13176 Slog.w(TAG, "Attempt to delete null packageName."); 13177 return false; 13178 } 13179 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13180 PackageSetting ps; 13181 boolean dataOnly = false; 13182 int removeUser = -1; 13183 int appId = -1; 13184 synchronized (mPackages) { 13185 ps = mSettings.mPackages.get(packageName); 13186 if (ps == null) { 13187 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13188 return false; 13189 } 13190 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13191 && user.getIdentifier() != UserHandle.USER_ALL) { 13192 // The caller is asking that the package only be deleted for a single 13193 // user. To do this, we just mark its uninstalled state and delete 13194 // its data. If this is a system app, we only allow this to happen if 13195 // they have set the special DELETE_SYSTEM_APP which requests different 13196 // semantics than normal for uninstalling system apps. 13197 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13198 final int userId = user.getIdentifier(); 13199 ps.setUserState(userId, 13200 COMPONENT_ENABLED_STATE_DEFAULT, 13201 false, //installed 13202 true, //stopped 13203 true, //notLaunched 13204 false, //hidden 13205 null, null, null, 13206 false, // blockUninstall 13207 ps.readUserState(userId).domainVerificationStatus, 0); 13208 if (!isSystemApp(ps)) { 13209 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13210 // Other user still have this package installed, so all 13211 // we need to do is clear this user's data and save that 13212 // it is uninstalled. 13213 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13214 removeUser = user.getIdentifier(); 13215 appId = ps.appId; 13216 scheduleWritePackageRestrictionsLocked(removeUser); 13217 } else { 13218 // We need to set it back to 'installed' so the uninstall 13219 // broadcasts will be sent correctly. 13220 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13221 ps.setInstalled(true, user.getIdentifier()); 13222 } 13223 } else { 13224 // This is a system app, so we assume that the 13225 // other users still have this package installed, so all 13226 // we need to do is clear this user's data and save that 13227 // it is uninstalled. 13228 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13229 removeUser = user.getIdentifier(); 13230 appId = ps.appId; 13231 scheduleWritePackageRestrictionsLocked(removeUser); 13232 } 13233 } 13234 } 13235 13236 if (removeUser >= 0) { 13237 // From above, we determined that we are deleting this only 13238 // for a single user. Continue the work here. 13239 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13240 if (outInfo != null) { 13241 outInfo.removedPackage = packageName; 13242 outInfo.removedAppId = appId; 13243 outInfo.removedUsers = new int[] {removeUser}; 13244 } 13245 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13246 removeKeystoreDataIfNeeded(removeUser, appId); 13247 schedulePackageCleaning(packageName, removeUser, false); 13248 synchronized (mPackages) { 13249 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13250 scheduleWritePackageRestrictionsLocked(removeUser); 13251 } 13252 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13253 } 13254 return true; 13255 } 13256 13257 if (dataOnly) { 13258 // Delete application data first 13259 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13260 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13261 return true; 13262 } 13263 13264 boolean ret = false; 13265 if (isSystemApp(ps)) { 13266 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13267 // When an updated system application is deleted we delete the existing resources as well and 13268 // fall back to existing code in system partition 13269 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13270 flags, outInfo, writeSettings); 13271 } else { 13272 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13273 // Kill application pre-emptively especially for apps on sd. 13274 killApplication(packageName, ps.appId, "uninstall pkg"); 13275 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13276 allUserHandles, perUserInstalled, 13277 outInfo, writeSettings); 13278 } 13279 13280 return ret; 13281 } 13282 13283 private final class ClearStorageConnection implements ServiceConnection { 13284 IMediaContainerService mContainerService; 13285 13286 @Override 13287 public void onServiceConnected(ComponentName name, IBinder service) { 13288 synchronized (this) { 13289 mContainerService = IMediaContainerService.Stub.asInterface(service); 13290 notifyAll(); 13291 } 13292 } 13293 13294 @Override 13295 public void onServiceDisconnected(ComponentName name) { 13296 } 13297 } 13298 13299 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13300 final boolean mounted; 13301 if (Environment.isExternalStorageEmulated()) { 13302 mounted = true; 13303 } else { 13304 final String status = Environment.getExternalStorageState(); 13305 13306 mounted = status.equals(Environment.MEDIA_MOUNTED) 13307 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13308 } 13309 13310 if (!mounted) { 13311 return; 13312 } 13313 13314 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13315 int[] users; 13316 if (userId == UserHandle.USER_ALL) { 13317 users = sUserManager.getUserIds(); 13318 } else { 13319 users = new int[] { userId }; 13320 } 13321 final ClearStorageConnection conn = new ClearStorageConnection(); 13322 if (mContext.bindServiceAsUser( 13323 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13324 try { 13325 for (int curUser : users) { 13326 long timeout = SystemClock.uptimeMillis() + 5000; 13327 synchronized (conn) { 13328 long now = SystemClock.uptimeMillis(); 13329 while (conn.mContainerService == null && now < timeout) { 13330 try { 13331 conn.wait(timeout - now); 13332 } catch (InterruptedException e) { 13333 } 13334 } 13335 } 13336 if (conn.mContainerService == null) { 13337 return; 13338 } 13339 13340 final UserEnvironment userEnv = new UserEnvironment(curUser); 13341 clearDirectory(conn.mContainerService, 13342 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13343 if (allData) { 13344 clearDirectory(conn.mContainerService, 13345 userEnv.buildExternalStorageAppDataDirs(packageName)); 13346 clearDirectory(conn.mContainerService, 13347 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13348 } 13349 } 13350 } finally { 13351 mContext.unbindService(conn); 13352 } 13353 } 13354 } 13355 13356 @Override 13357 public void clearApplicationUserData(final String packageName, 13358 final IPackageDataObserver observer, final int userId) { 13359 mContext.enforceCallingOrSelfPermission( 13360 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13361 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13362 // Queue up an async operation since the package deletion may take a little while. 13363 mHandler.post(new Runnable() { 13364 public void run() { 13365 mHandler.removeCallbacks(this); 13366 final boolean succeeded; 13367 synchronized (mInstallLock) { 13368 succeeded = clearApplicationUserDataLI(packageName, userId); 13369 } 13370 clearExternalStorageDataSync(packageName, userId, true); 13371 if (succeeded) { 13372 // invoke DeviceStorageMonitor's update method to clear any notifications 13373 DeviceStorageMonitorInternal 13374 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13375 if (dsm != null) { 13376 dsm.checkMemory(); 13377 } 13378 } 13379 if(observer != null) { 13380 try { 13381 observer.onRemoveCompleted(packageName, succeeded); 13382 } catch (RemoteException e) { 13383 Log.i(TAG, "Observer no longer exists."); 13384 } 13385 } //end if observer 13386 } //end run 13387 }); 13388 } 13389 13390 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13391 if (packageName == null) { 13392 Slog.w(TAG, "Attempt to delete null packageName."); 13393 return false; 13394 } 13395 13396 // Try finding details about the requested package 13397 PackageParser.Package pkg; 13398 synchronized (mPackages) { 13399 pkg = mPackages.get(packageName); 13400 if (pkg == null) { 13401 final PackageSetting ps = mSettings.mPackages.get(packageName); 13402 if (ps != null) { 13403 pkg = ps.pkg; 13404 } 13405 } 13406 13407 if (pkg == null) { 13408 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13409 return false; 13410 } 13411 13412 PackageSetting ps = (PackageSetting) pkg.mExtras; 13413 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13414 } 13415 13416 // Always delete data directories for package, even if we found no other 13417 // record of app. This helps users recover from UID mismatches without 13418 // resorting to a full data wipe. 13419 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13420 if (retCode < 0) { 13421 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13422 return false; 13423 } 13424 13425 final int appId = pkg.applicationInfo.uid; 13426 removeKeystoreDataIfNeeded(userId, appId); 13427 13428 // Create a native library symlink only if we have native libraries 13429 // and if the native libraries are 32 bit libraries. We do not provide 13430 // this symlink for 64 bit libraries. 13431 if (pkg.applicationInfo.primaryCpuAbi != null && 13432 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13433 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13434 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13435 nativeLibPath, userId) < 0) { 13436 Slog.w(TAG, "Failed linking native library dir"); 13437 return false; 13438 } 13439 } 13440 13441 return true; 13442 } 13443 13444 /** 13445 * Reverts user permission state changes (permissions and flags) in 13446 * all packages for a given user. 13447 * 13448 * @param userId The device user for which to do a reset. 13449 */ 13450 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13451 final int packageCount = mPackages.size(); 13452 for (int i = 0; i < packageCount; i++) { 13453 PackageParser.Package pkg = mPackages.valueAt(i); 13454 PackageSetting ps = (PackageSetting) pkg.mExtras; 13455 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13456 } 13457 } 13458 13459 /** 13460 * Reverts user permission state changes (permissions and flags). 13461 * 13462 * @param ps The package for which to reset. 13463 * @param userId The device user for which to do a reset. 13464 */ 13465 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13466 final PackageSetting ps, final int userId) { 13467 if (ps.pkg == null) { 13468 return; 13469 } 13470 13471 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13472 | FLAG_PERMISSION_USER_FIXED 13473 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13474 13475 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13476 | FLAG_PERMISSION_POLICY_FIXED; 13477 13478 boolean writeInstallPermissions = false; 13479 boolean writeRuntimePermissions = false; 13480 13481 final int permissionCount = ps.pkg.requestedPermissions.size(); 13482 for (int i = 0; i < permissionCount; i++) { 13483 String permission = ps.pkg.requestedPermissions.get(i); 13484 13485 BasePermission bp = mSettings.mPermissions.get(permission); 13486 if (bp == null) { 13487 continue; 13488 } 13489 13490 // If shared user we just reset the state to which only this app contributed. 13491 if (ps.sharedUser != null) { 13492 boolean used = false; 13493 final int packageCount = ps.sharedUser.packages.size(); 13494 for (int j = 0; j < packageCount; j++) { 13495 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13496 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13497 && pkg.pkg.requestedPermissions.contains(permission)) { 13498 used = true; 13499 break; 13500 } 13501 } 13502 if (used) { 13503 continue; 13504 } 13505 } 13506 13507 PermissionsState permissionsState = ps.getPermissionsState(); 13508 13509 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13510 13511 // Always clear the user settable flags. 13512 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13513 bp.name) != null; 13514 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13515 if (hasInstallState) { 13516 writeInstallPermissions = true; 13517 } else { 13518 writeRuntimePermissions = true; 13519 } 13520 } 13521 13522 // Below is only runtime permission handling. 13523 if (!bp.isRuntime()) { 13524 continue; 13525 } 13526 13527 // Never clobber system or policy. 13528 if ((oldFlags & policyOrSystemFlags) != 0) { 13529 continue; 13530 } 13531 13532 // If this permission was granted by default, make sure it is. 13533 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13534 if (permissionsState.grantRuntimePermission(bp, userId) 13535 != PERMISSION_OPERATION_FAILURE) { 13536 writeRuntimePermissions = true; 13537 } 13538 } else { 13539 // Otherwise, reset the permission. 13540 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13541 switch (revokeResult) { 13542 case PERMISSION_OPERATION_SUCCESS: { 13543 writeRuntimePermissions = true; 13544 } break; 13545 13546 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13547 writeRuntimePermissions = true; 13548 final int appId = ps.appId; 13549 mHandler.post(new Runnable() { 13550 @Override 13551 public void run() { 13552 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13553 } 13554 }); 13555 } break; 13556 } 13557 } 13558 } 13559 13560 // Synchronously write as we are taking permissions away. 13561 if (writeRuntimePermissions) { 13562 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13563 } 13564 13565 // Synchronously write as we are taking permissions away. 13566 if (writeInstallPermissions) { 13567 mSettings.writeLPr(); 13568 } 13569 } 13570 13571 /** 13572 * Remove entries from the keystore daemon. Will only remove it if the 13573 * {@code appId} is valid. 13574 */ 13575 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13576 if (appId < 0) { 13577 return; 13578 } 13579 13580 final KeyStore keyStore = KeyStore.getInstance(); 13581 if (keyStore != null) { 13582 if (userId == UserHandle.USER_ALL) { 13583 for (final int individual : sUserManager.getUserIds()) { 13584 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13585 } 13586 } else { 13587 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13588 } 13589 } else { 13590 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13591 } 13592 } 13593 13594 @Override 13595 public void deleteApplicationCacheFiles(final String packageName, 13596 final IPackageDataObserver observer) { 13597 mContext.enforceCallingOrSelfPermission( 13598 android.Manifest.permission.DELETE_CACHE_FILES, null); 13599 // Queue up an async operation since the package deletion may take a little while. 13600 final int userId = UserHandle.getCallingUserId(); 13601 mHandler.post(new Runnable() { 13602 public void run() { 13603 mHandler.removeCallbacks(this); 13604 final boolean succeded; 13605 synchronized (mInstallLock) { 13606 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13607 } 13608 clearExternalStorageDataSync(packageName, userId, false); 13609 if (observer != null) { 13610 try { 13611 observer.onRemoveCompleted(packageName, succeded); 13612 } catch (RemoteException e) { 13613 Log.i(TAG, "Observer no longer exists."); 13614 } 13615 } //end if observer 13616 } //end run 13617 }); 13618 } 13619 13620 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13621 if (packageName == null) { 13622 Slog.w(TAG, "Attempt to delete null packageName."); 13623 return false; 13624 } 13625 PackageParser.Package p; 13626 synchronized (mPackages) { 13627 p = mPackages.get(packageName); 13628 } 13629 if (p == null) { 13630 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13631 return false; 13632 } 13633 final ApplicationInfo applicationInfo = p.applicationInfo; 13634 if (applicationInfo == null) { 13635 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13636 return false; 13637 } 13638 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13639 if (retCode < 0) { 13640 Slog.w(TAG, "Couldn't remove cache files for package: " 13641 + packageName + " u" + userId); 13642 return false; 13643 } 13644 return true; 13645 } 13646 13647 @Override 13648 public void getPackageSizeInfo(final String packageName, int userHandle, 13649 final IPackageStatsObserver observer) { 13650 mContext.enforceCallingOrSelfPermission( 13651 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13652 if (packageName == null) { 13653 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13654 } 13655 13656 PackageStats stats = new PackageStats(packageName, userHandle); 13657 13658 /* 13659 * Queue up an async operation since the package measurement may take a 13660 * little while. 13661 */ 13662 Message msg = mHandler.obtainMessage(INIT_COPY); 13663 msg.obj = new MeasureParams(stats, observer); 13664 mHandler.sendMessage(msg); 13665 } 13666 13667 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13668 PackageStats pStats) { 13669 if (packageName == null) { 13670 Slog.w(TAG, "Attempt to get size of null packageName."); 13671 return false; 13672 } 13673 PackageParser.Package p; 13674 boolean dataOnly = false; 13675 String libDirRoot = null; 13676 String asecPath = null; 13677 PackageSetting ps = null; 13678 synchronized (mPackages) { 13679 p = mPackages.get(packageName); 13680 ps = mSettings.mPackages.get(packageName); 13681 if(p == null) { 13682 dataOnly = true; 13683 if((ps == null) || (ps.pkg == null)) { 13684 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13685 return false; 13686 } 13687 p = ps.pkg; 13688 } 13689 if (ps != null) { 13690 libDirRoot = ps.legacyNativeLibraryPathString; 13691 } 13692 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 13693 final long token = Binder.clearCallingIdentity(); 13694 try { 13695 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13696 if (secureContainerId != null) { 13697 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13698 } 13699 } finally { 13700 Binder.restoreCallingIdentity(token); 13701 } 13702 } 13703 } 13704 String publicSrcDir = null; 13705 if(!dataOnly) { 13706 final ApplicationInfo applicationInfo = p.applicationInfo; 13707 if (applicationInfo == null) { 13708 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13709 return false; 13710 } 13711 if (p.isForwardLocked()) { 13712 publicSrcDir = applicationInfo.getBaseResourcePath(); 13713 } 13714 } 13715 // TODO: extend to measure size of split APKs 13716 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13717 // not just the first level. 13718 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13719 // just the primary. 13720 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13721 13722 String apkPath; 13723 File packageDir = new File(p.codePath); 13724 13725 if (packageDir.isDirectory() && p.canHaveOatDir()) { 13726 apkPath = packageDir.getAbsolutePath(); 13727 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 13728 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 13729 libDirRoot = null; 13730 } 13731 } else { 13732 apkPath = p.baseCodePath; 13733 } 13734 13735 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 13736 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13737 if (res < 0) { 13738 return false; 13739 } 13740 13741 // Fix-up for forward-locked applications in ASEC containers. 13742 if (!isExternal(p)) { 13743 pStats.codeSize += pStats.externalCodeSize; 13744 pStats.externalCodeSize = 0L; 13745 } 13746 13747 return true; 13748 } 13749 13750 13751 @Override 13752 public void addPackageToPreferred(String packageName) { 13753 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13754 } 13755 13756 @Override 13757 public void removePackageFromPreferred(String packageName) { 13758 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13759 } 13760 13761 @Override 13762 public List<PackageInfo> getPreferredPackages(int flags) { 13763 return new ArrayList<PackageInfo>(); 13764 } 13765 13766 private int getUidTargetSdkVersionLockedLPr(int uid) { 13767 Object obj = mSettings.getUserIdLPr(uid); 13768 if (obj instanceof SharedUserSetting) { 13769 final SharedUserSetting sus = (SharedUserSetting) obj; 13770 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13771 final Iterator<PackageSetting> it = sus.packages.iterator(); 13772 while (it.hasNext()) { 13773 final PackageSetting ps = it.next(); 13774 if (ps.pkg != null) { 13775 int v = ps.pkg.applicationInfo.targetSdkVersion; 13776 if (v < vers) vers = v; 13777 } 13778 } 13779 return vers; 13780 } else if (obj instanceof PackageSetting) { 13781 final PackageSetting ps = (PackageSetting) obj; 13782 if (ps.pkg != null) { 13783 return ps.pkg.applicationInfo.targetSdkVersion; 13784 } 13785 } 13786 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13787 } 13788 13789 @Override 13790 public void addPreferredActivity(IntentFilter filter, int match, 13791 ComponentName[] set, ComponentName activity, int userId) { 13792 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13793 "Adding preferred"); 13794 } 13795 13796 private void addPreferredActivityInternal(IntentFilter filter, int match, 13797 ComponentName[] set, ComponentName activity, boolean always, int userId, 13798 String opname) { 13799 // writer 13800 int callingUid = Binder.getCallingUid(); 13801 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13802 if (filter.countActions() == 0) { 13803 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13804 return; 13805 } 13806 synchronized (mPackages) { 13807 if (mContext.checkCallingOrSelfPermission( 13808 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13809 != PackageManager.PERMISSION_GRANTED) { 13810 if (getUidTargetSdkVersionLockedLPr(callingUid) 13811 < Build.VERSION_CODES.FROYO) { 13812 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13813 + callingUid); 13814 return; 13815 } 13816 mContext.enforceCallingOrSelfPermission( 13817 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13818 } 13819 13820 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13821 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13822 + userId + ":"); 13823 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13824 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13825 scheduleWritePackageRestrictionsLocked(userId); 13826 } 13827 } 13828 13829 @Override 13830 public void replacePreferredActivity(IntentFilter filter, int match, 13831 ComponentName[] set, ComponentName activity, int userId) { 13832 if (filter.countActions() != 1) { 13833 throw new IllegalArgumentException( 13834 "replacePreferredActivity expects filter to have only 1 action."); 13835 } 13836 if (filter.countDataAuthorities() != 0 13837 || filter.countDataPaths() != 0 13838 || filter.countDataSchemes() > 1 13839 || filter.countDataTypes() != 0) { 13840 throw new IllegalArgumentException( 13841 "replacePreferredActivity expects filter to have no data authorities, " + 13842 "paths, or types; and at most one scheme."); 13843 } 13844 13845 final int callingUid = Binder.getCallingUid(); 13846 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13847 synchronized (mPackages) { 13848 if (mContext.checkCallingOrSelfPermission( 13849 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13850 != PackageManager.PERMISSION_GRANTED) { 13851 if (getUidTargetSdkVersionLockedLPr(callingUid) 13852 < Build.VERSION_CODES.FROYO) { 13853 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13854 + Binder.getCallingUid()); 13855 return; 13856 } 13857 mContext.enforceCallingOrSelfPermission( 13858 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13859 } 13860 13861 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13862 if (pir != null) { 13863 // Get all of the existing entries that exactly match this filter. 13864 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13865 if (existing != null && existing.size() == 1) { 13866 PreferredActivity cur = existing.get(0); 13867 if (DEBUG_PREFERRED) { 13868 Slog.i(TAG, "Checking replace of preferred:"); 13869 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13870 if (!cur.mPref.mAlways) { 13871 Slog.i(TAG, " -- CUR; not mAlways!"); 13872 } else { 13873 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13874 Slog.i(TAG, " -- CUR: mSet=" 13875 + Arrays.toString(cur.mPref.mSetComponents)); 13876 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13877 Slog.i(TAG, " -- NEW: mMatch=" 13878 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13879 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13880 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13881 } 13882 } 13883 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13884 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13885 && cur.mPref.sameSet(set)) { 13886 // Setting the preferred activity to what it happens to be already 13887 if (DEBUG_PREFERRED) { 13888 Slog.i(TAG, "Replacing with same preferred activity " 13889 + cur.mPref.mShortComponent + " for user " 13890 + userId + ":"); 13891 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13892 } 13893 return; 13894 } 13895 } 13896 13897 if (existing != null) { 13898 if (DEBUG_PREFERRED) { 13899 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13900 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13901 } 13902 for (int i = 0; i < existing.size(); i++) { 13903 PreferredActivity pa = existing.get(i); 13904 if (DEBUG_PREFERRED) { 13905 Slog.i(TAG, "Removing existing preferred activity " 13906 + pa.mPref.mComponent + ":"); 13907 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13908 } 13909 pir.removeFilter(pa); 13910 } 13911 } 13912 } 13913 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13914 "Replacing preferred"); 13915 } 13916 } 13917 13918 @Override 13919 public void clearPackagePreferredActivities(String packageName) { 13920 final int uid = Binder.getCallingUid(); 13921 // writer 13922 synchronized (mPackages) { 13923 PackageParser.Package pkg = mPackages.get(packageName); 13924 if (pkg == null || pkg.applicationInfo.uid != uid) { 13925 if (mContext.checkCallingOrSelfPermission( 13926 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13927 != PackageManager.PERMISSION_GRANTED) { 13928 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13929 < Build.VERSION_CODES.FROYO) { 13930 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13931 + Binder.getCallingUid()); 13932 return; 13933 } 13934 mContext.enforceCallingOrSelfPermission( 13935 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13936 } 13937 } 13938 13939 int user = UserHandle.getCallingUserId(); 13940 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13941 scheduleWritePackageRestrictionsLocked(user); 13942 } 13943 } 13944 } 13945 13946 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13947 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13948 ArrayList<PreferredActivity> removed = null; 13949 boolean changed = false; 13950 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13951 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13952 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13953 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13954 continue; 13955 } 13956 Iterator<PreferredActivity> it = pir.filterIterator(); 13957 while (it.hasNext()) { 13958 PreferredActivity pa = it.next(); 13959 // Mark entry for removal only if it matches the package name 13960 // and the entry is of type "always". 13961 if (packageName == null || 13962 (pa.mPref.mComponent.getPackageName().equals(packageName) 13963 && pa.mPref.mAlways)) { 13964 if (removed == null) { 13965 removed = new ArrayList<PreferredActivity>(); 13966 } 13967 removed.add(pa); 13968 } 13969 } 13970 if (removed != null) { 13971 for (int j=0; j<removed.size(); j++) { 13972 PreferredActivity pa = removed.get(j); 13973 pir.removeFilter(pa); 13974 } 13975 changed = true; 13976 } 13977 } 13978 return changed; 13979 } 13980 13981 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13982 private void clearIntentFilterVerificationsLPw(int userId) { 13983 final int packageCount = mPackages.size(); 13984 for (int i = 0; i < packageCount; i++) { 13985 PackageParser.Package pkg = mPackages.valueAt(i); 13986 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13987 } 13988 } 13989 13990 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13991 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13992 if (userId == UserHandle.USER_ALL) { 13993 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13994 sUserManager.getUserIds())) { 13995 for (int oneUserId : sUserManager.getUserIds()) { 13996 scheduleWritePackageRestrictionsLocked(oneUserId); 13997 } 13998 } 13999 } else { 14000 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14001 scheduleWritePackageRestrictionsLocked(userId); 14002 } 14003 } 14004 } 14005 14006 void clearDefaultBrowserIfNeeded(String packageName) { 14007 for (int oneUserId : sUserManager.getUserIds()) { 14008 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14009 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14010 if (packageName.equals(defaultBrowserPackageName)) { 14011 setDefaultBrowserPackageName(null, oneUserId); 14012 } 14013 } 14014 } 14015 14016 @Override 14017 public void resetApplicationPreferences(int userId) { 14018 mContext.enforceCallingOrSelfPermission( 14019 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14020 // writer 14021 synchronized (mPackages) { 14022 final long identity = Binder.clearCallingIdentity(); 14023 try { 14024 clearPackagePreferredActivitiesLPw(null, userId); 14025 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14026 // TODO: We have to reset the default SMS and Phone. This requires 14027 // significant refactoring to keep all default apps in the package 14028 // manager (cleaner but more work) or have the services provide 14029 // callbacks to the package manager to request a default app reset. 14030 applyFactoryDefaultBrowserLPw(userId); 14031 clearIntentFilterVerificationsLPw(userId); 14032 primeDomainVerificationsLPw(userId); 14033 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14034 scheduleWritePackageRestrictionsLocked(userId); 14035 } finally { 14036 Binder.restoreCallingIdentity(identity); 14037 } 14038 } 14039 } 14040 14041 @Override 14042 public int getPreferredActivities(List<IntentFilter> outFilters, 14043 List<ComponentName> outActivities, String packageName) { 14044 14045 int num = 0; 14046 final int userId = UserHandle.getCallingUserId(); 14047 // reader 14048 synchronized (mPackages) { 14049 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14050 if (pir != null) { 14051 final Iterator<PreferredActivity> it = pir.filterIterator(); 14052 while (it.hasNext()) { 14053 final PreferredActivity pa = it.next(); 14054 if (packageName == null 14055 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14056 && pa.mPref.mAlways)) { 14057 if (outFilters != null) { 14058 outFilters.add(new IntentFilter(pa)); 14059 } 14060 if (outActivities != null) { 14061 outActivities.add(pa.mPref.mComponent); 14062 } 14063 } 14064 } 14065 } 14066 } 14067 14068 return num; 14069 } 14070 14071 @Override 14072 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14073 int userId) { 14074 int callingUid = Binder.getCallingUid(); 14075 if (callingUid != Process.SYSTEM_UID) { 14076 throw new SecurityException( 14077 "addPersistentPreferredActivity can only be run by the system"); 14078 } 14079 if (filter.countActions() == 0) { 14080 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14081 return; 14082 } 14083 synchronized (mPackages) { 14084 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14085 " :"); 14086 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14087 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14088 new PersistentPreferredActivity(filter, activity)); 14089 scheduleWritePackageRestrictionsLocked(userId); 14090 } 14091 } 14092 14093 @Override 14094 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14095 int callingUid = Binder.getCallingUid(); 14096 if (callingUid != Process.SYSTEM_UID) { 14097 throw new SecurityException( 14098 "clearPackagePersistentPreferredActivities can only be run by the system"); 14099 } 14100 ArrayList<PersistentPreferredActivity> removed = null; 14101 boolean changed = false; 14102 synchronized (mPackages) { 14103 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14104 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14105 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14106 .valueAt(i); 14107 if (userId != thisUserId) { 14108 continue; 14109 } 14110 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14111 while (it.hasNext()) { 14112 PersistentPreferredActivity ppa = it.next(); 14113 // Mark entry for removal only if it matches the package name. 14114 if (ppa.mComponent.getPackageName().equals(packageName)) { 14115 if (removed == null) { 14116 removed = new ArrayList<PersistentPreferredActivity>(); 14117 } 14118 removed.add(ppa); 14119 } 14120 } 14121 if (removed != null) { 14122 for (int j=0; j<removed.size(); j++) { 14123 PersistentPreferredActivity ppa = removed.get(j); 14124 ppir.removeFilter(ppa); 14125 } 14126 changed = true; 14127 } 14128 } 14129 14130 if (changed) { 14131 scheduleWritePackageRestrictionsLocked(userId); 14132 } 14133 } 14134 } 14135 14136 /** 14137 * Common machinery for picking apart a restored XML blob and passing 14138 * it to a caller-supplied functor to be applied to the running system. 14139 */ 14140 private void restoreFromXml(XmlPullParser parser, int userId, 14141 String expectedStartTag, BlobXmlRestorer functor) 14142 throws IOException, XmlPullParserException { 14143 int type; 14144 while ((type = parser.next()) != XmlPullParser.START_TAG 14145 && type != XmlPullParser.END_DOCUMENT) { 14146 } 14147 if (type != XmlPullParser.START_TAG) { 14148 // oops didn't find a start tag?! 14149 if (DEBUG_BACKUP) { 14150 Slog.e(TAG, "Didn't find start tag during restore"); 14151 } 14152 return; 14153 } 14154 14155 // this is supposed to be TAG_PREFERRED_BACKUP 14156 if (!expectedStartTag.equals(parser.getName())) { 14157 if (DEBUG_BACKUP) { 14158 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14159 } 14160 return; 14161 } 14162 14163 // skip interfering stuff, then we're aligned with the backing implementation 14164 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14165 functor.apply(parser, userId); 14166 } 14167 14168 private interface BlobXmlRestorer { 14169 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14170 } 14171 14172 /** 14173 * Non-Binder method, support for the backup/restore mechanism: write the 14174 * full set of preferred activities in its canonical XML format. Returns the 14175 * XML output as a byte array, or null if there is none. 14176 */ 14177 @Override 14178 public byte[] getPreferredActivityBackup(int userId) { 14179 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14180 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14181 } 14182 14183 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14184 try { 14185 final XmlSerializer serializer = new FastXmlSerializer(); 14186 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14187 serializer.startDocument(null, true); 14188 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14189 14190 synchronized (mPackages) { 14191 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14192 } 14193 14194 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14195 serializer.endDocument(); 14196 serializer.flush(); 14197 } catch (Exception e) { 14198 if (DEBUG_BACKUP) { 14199 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14200 } 14201 return null; 14202 } 14203 14204 return dataStream.toByteArray(); 14205 } 14206 14207 @Override 14208 public void restorePreferredActivities(byte[] backup, int userId) { 14209 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14210 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14211 } 14212 14213 try { 14214 final XmlPullParser parser = Xml.newPullParser(); 14215 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14216 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14217 new BlobXmlRestorer() { 14218 @Override 14219 public void apply(XmlPullParser parser, int userId) 14220 throws XmlPullParserException, IOException { 14221 synchronized (mPackages) { 14222 mSettings.readPreferredActivitiesLPw(parser, userId); 14223 } 14224 } 14225 } ); 14226 } catch (Exception e) { 14227 if (DEBUG_BACKUP) { 14228 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14229 } 14230 } 14231 } 14232 14233 /** 14234 * Non-Binder method, support for the backup/restore mechanism: write the 14235 * default browser (etc) settings in its canonical XML format. Returns the default 14236 * browser XML representation as a byte array, or null if there is none. 14237 */ 14238 @Override 14239 public byte[] getDefaultAppsBackup(int userId) { 14240 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14241 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14242 } 14243 14244 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14245 try { 14246 final XmlSerializer serializer = new FastXmlSerializer(); 14247 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14248 serializer.startDocument(null, true); 14249 serializer.startTag(null, TAG_DEFAULT_APPS); 14250 14251 synchronized (mPackages) { 14252 mSettings.writeDefaultAppsLPr(serializer, userId); 14253 } 14254 14255 serializer.endTag(null, TAG_DEFAULT_APPS); 14256 serializer.endDocument(); 14257 serializer.flush(); 14258 } catch (Exception e) { 14259 if (DEBUG_BACKUP) { 14260 Slog.e(TAG, "Unable to write default apps for backup", e); 14261 } 14262 return null; 14263 } 14264 14265 return dataStream.toByteArray(); 14266 } 14267 14268 @Override 14269 public void restoreDefaultApps(byte[] backup, int userId) { 14270 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14271 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14272 } 14273 14274 try { 14275 final XmlPullParser parser = Xml.newPullParser(); 14276 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14277 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14278 new BlobXmlRestorer() { 14279 @Override 14280 public void apply(XmlPullParser parser, int userId) 14281 throws XmlPullParserException, IOException { 14282 synchronized (mPackages) { 14283 mSettings.readDefaultAppsLPw(parser, userId); 14284 } 14285 } 14286 } ); 14287 } catch (Exception e) { 14288 if (DEBUG_BACKUP) { 14289 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14290 } 14291 } 14292 } 14293 14294 @Override 14295 public byte[] getIntentFilterVerificationBackup(int userId) { 14296 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14297 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14298 } 14299 14300 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14301 try { 14302 final XmlSerializer serializer = new FastXmlSerializer(); 14303 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14304 serializer.startDocument(null, true); 14305 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14306 14307 synchronized (mPackages) { 14308 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14309 } 14310 14311 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14312 serializer.endDocument(); 14313 serializer.flush(); 14314 } catch (Exception e) { 14315 if (DEBUG_BACKUP) { 14316 Slog.e(TAG, "Unable to write default apps for backup", e); 14317 } 14318 return null; 14319 } 14320 14321 return dataStream.toByteArray(); 14322 } 14323 14324 @Override 14325 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14326 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14327 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14328 } 14329 14330 try { 14331 final XmlPullParser parser = Xml.newPullParser(); 14332 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14333 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14334 new BlobXmlRestorer() { 14335 @Override 14336 public void apply(XmlPullParser parser, int userId) 14337 throws XmlPullParserException, IOException { 14338 synchronized (mPackages) { 14339 mSettings.readAllDomainVerificationsLPr(parser, userId); 14340 mSettings.writeLPr(); 14341 } 14342 } 14343 } ); 14344 } catch (Exception e) { 14345 if (DEBUG_BACKUP) { 14346 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14347 } 14348 } 14349 } 14350 14351 @Override 14352 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14353 int sourceUserId, int targetUserId, int flags) { 14354 mContext.enforceCallingOrSelfPermission( 14355 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14356 int callingUid = Binder.getCallingUid(); 14357 enforceOwnerRights(ownerPackage, callingUid); 14358 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14359 if (intentFilter.countActions() == 0) { 14360 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14361 return; 14362 } 14363 synchronized (mPackages) { 14364 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14365 ownerPackage, targetUserId, flags); 14366 CrossProfileIntentResolver resolver = 14367 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14368 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14369 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14370 if (existing != null) { 14371 int size = existing.size(); 14372 for (int i = 0; i < size; i++) { 14373 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14374 return; 14375 } 14376 } 14377 } 14378 resolver.addFilter(newFilter); 14379 scheduleWritePackageRestrictionsLocked(sourceUserId); 14380 } 14381 } 14382 14383 @Override 14384 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14385 mContext.enforceCallingOrSelfPermission( 14386 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14387 int callingUid = Binder.getCallingUid(); 14388 enforceOwnerRights(ownerPackage, callingUid); 14389 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14390 synchronized (mPackages) { 14391 CrossProfileIntentResolver resolver = 14392 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14393 ArraySet<CrossProfileIntentFilter> set = 14394 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14395 for (CrossProfileIntentFilter filter : set) { 14396 if (filter.getOwnerPackage().equals(ownerPackage)) { 14397 resolver.removeFilter(filter); 14398 } 14399 } 14400 scheduleWritePackageRestrictionsLocked(sourceUserId); 14401 } 14402 } 14403 14404 // Enforcing that callingUid is owning pkg on userId 14405 private void enforceOwnerRights(String pkg, int callingUid) { 14406 // The system owns everything. 14407 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14408 return; 14409 } 14410 int callingUserId = UserHandle.getUserId(callingUid); 14411 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14412 if (pi == null) { 14413 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14414 + callingUserId); 14415 } 14416 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14417 throw new SecurityException("Calling uid " + callingUid 14418 + " does not own package " + pkg); 14419 } 14420 } 14421 14422 @Override 14423 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14424 Intent intent = new Intent(Intent.ACTION_MAIN); 14425 intent.addCategory(Intent.CATEGORY_HOME); 14426 14427 final int callingUserId = UserHandle.getCallingUserId(); 14428 List<ResolveInfo> list = queryIntentActivities(intent, null, 14429 PackageManager.GET_META_DATA, callingUserId); 14430 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14431 true, false, false, callingUserId); 14432 14433 allHomeCandidates.clear(); 14434 if (list != null) { 14435 for (ResolveInfo ri : list) { 14436 allHomeCandidates.add(ri); 14437 } 14438 } 14439 return (preferred == null || preferred.activityInfo == null) 14440 ? null 14441 : new ComponentName(preferred.activityInfo.packageName, 14442 preferred.activityInfo.name); 14443 } 14444 14445 @Override 14446 public void setApplicationEnabledSetting(String appPackageName, 14447 int newState, int flags, int userId, String callingPackage) { 14448 if (!sUserManager.exists(userId)) return; 14449 if (callingPackage == null) { 14450 callingPackage = Integer.toString(Binder.getCallingUid()); 14451 } 14452 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14453 } 14454 14455 @Override 14456 public void setComponentEnabledSetting(ComponentName componentName, 14457 int newState, int flags, int userId) { 14458 if (!sUserManager.exists(userId)) return; 14459 setEnabledSetting(componentName.getPackageName(), 14460 componentName.getClassName(), newState, flags, userId, null); 14461 } 14462 14463 private void setEnabledSetting(final String packageName, String className, int newState, 14464 final int flags, int userId, String callingPackage) { 14465 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14466 || newState == COMPONENT_ENABLED_STATE_ENABLED 14467 || newState == COMPONENT_ENABLED_STATE_DISABLED 14468 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14469 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14470 throw new IllegalArgumentException("Invalid new component state: " 14471 + newState); 14472 } 14473 PackageSetting pkgSetting; 14474 final int uid = Binder.getCallingUid(); 14475 final int permission = mContext.checkCallingOrSelfPermission( 14476 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14477 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14478 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14479 boolean sendNow = false; 14480 boolean isApp = (className == null); 14481 String componentName = isApp ? packageName : className; 14482 int packageUid = -1; 14483 ArrayList<String> components; 14484 14485 // writer 14486 synchronized (mPackages) { 14487 pkgSetting = mSettings.mPackages.get(packageName); 14488 if (pkgSetting == null) { 14489 if (className == null) { 14490 throw new IllegalArgumentException( 14491 "Unknown package: " + packageName); 14492 } 14493 throw new IllegalArgumentException( 14494 "Unknown component: " + packageName 14495 + "/" + className); 14496 } 14497 // Allow root and verify that userId is not being specified by a different user 14498 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14499 throw new SecurityException( 14500 "Permission Denial: attempt to change component state from pid=" 14501 + Binder.getCallingPid() 14502 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14503 } 14504 if (className == null) { 14505 // We're dealing with an application/package level state change 14506 if (pkgSetting.getEnabled(userId) == newState) { 14507 // Nothing to do 14508 return; 14509 } 14510 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14511 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14512 // Don't care about who enables an app. 14513 callingPackage = null; 14514 } 14515 pkgSetting.setEnabled(newState, userId, callingPackage); 14516 // pkgSetting.pkg.mSetEnabled = newState; 14517 } else { 14518 // We're dealing with a component level state change 14519 // First, verify that this is a valid class name. 14520 PackageParser.Package pkg = pkgSetting.pkg; 14521 if (pkg == null || !pkg.hasComponentClassName(className)) { 14522 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14523 throw new IllegalArgumentException("Component class " + className 14524 + " does not exist in " + packageName); 14525 } else { 14526 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14527 + className + " does not exist in " + packageName); 14528 } 14529 } 14530 switch (newState) { 14531 case COMPONENT_ENABLED_STATE_ENABLED: 14532 if (!pkgSetting.enableComponentLPw(className, userId)) { 14533 return; 14534 } 14535 break; 14536 case COMPONENT_ENABLED_STATE_DISABLED: 14537 if (!pkgSetting.disableComponentLPw(className, userId)) { 14538 return; 14539 } 14540 break; 14541 case COMPONENT_ENABLED_STATE_DEFAULT: 14542 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14543 return; 14544 } 14545 break; 14546 default: 14547 Slog.e(TAG, "Invalid new component state: " + newState); 14548 return; 14549 } 14550 } 14551 scheduleWritePackageRestrictionsLocked(userId); 14552 components = mPendingBroadcasts.get(userId, packageName); 14553 final boolean newPackage = components == null; 14554 if (newPackage) { 14555 components = new ArrayList<String>(); 14556 } 14557 if (!components.contains(componentName)) { 14558 components.add(componentName); 14559 } 14560 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14561 sendNow = true; 14562 // Purge entry from pending broadcast list if another one exists already 14563 // since we are sending one right away. 14564 mPendingBroadcasts.remove(userId, packageName); 14565 } else { 14566 if (newPackage) { 14567 mPendingBroadcasts.put(userId, packageName, components); 14568 } 14569 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14570 // Schedule a message 14571 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14572 } 14573 } 14574 } 14575 14576 long callingId = Binder.clearCallingIdentity(); 14577 try { 14578 if (sendNow) { 14579 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14580 sendPackageChangedBroadcast(packageName, 14581 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14582 } 14583 } finally { 14584 Binder.restoreCallingIdentity(callingId); 14585 } 14586 } 14587 14588 private void sendPackageChangedBroadcast(String packageName, 14589 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14590 if (DEBUG_INSTALL) 14591 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14592 + componentNames); 14593 Bundle extras = new Bundle(4); 14594 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14595 String nameList[] = new String[componentNames.size()]; 14596 componentNames.toArray(nameList); 14597 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14598 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14599 extras.putInt(Intent.EXTRA_UID, packageUid); 14600 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14601 new int[] {UserHandle.getUserId(packageUid)}); 14602 } 14603 14604 @Override 14605 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14606 if (!sUserManager.exists(userId)) return; 14607 final int uid = Binder.getCallingUid(); 14608 final int permission = mContext.checkCallingOrSelfPermission( 14609 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14610 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14611 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14612 // writer 14613 synchronized (mPackages) { 14614 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14615 allowedByPermission, uid, userId)) { 14616 scheduleWritePackageRestrictionsLocked(userId); 14617 } 14618 } 14619 } 14620 14621 @Override 14622 public String getInstallerPackageName(String packageName) { 14623 // reader 14624 synchronized (mPackages) { 14625 return mSettings.getInstallerPackageNameLPr(packageName); 14626 } 14627 } 14628 14629 @Override 14630 public int getApplicationEnabledSetting(String packageName, int userId) { 14631 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14632 int uid = Binder.getCallingUid(); 14633 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14634 // reader 14635 synchronized (mPackages) { 14636 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14637 } 14638 } 14639 14640 @Override 14641 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14642 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14643 int uid = Binder.getCallingUid(); 14644 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14645 // reader 14646 synchronized (mPackages) { 14647 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14648 } 14649 } 14650 14651 @Override 14652 public void enterSafeMode() { 14653 enforceSystemOrRoot("Only the system can request entering safe mode"); 14654 14655 if (!mSystemReady) { 14656 mSafeMode = true; 14657 } 14658 } 14659 14660 @Override 14661 public void systemReady() { 14662 mSystemReady = true; 14663 14664 // Read the compatibilty setting when the system is ready. 14665 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14666 mContext.getContentResolver(), 14667 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14668 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14669 if (DEBUG_SETTINGS) { 14670 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14671 } 14672 14673 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14674 14675 synchronized (mPackages) { 14676 // Verify that all of the preferred activity components actually 14677 // exist. It is possible for applications to be updated and at 14678 // that point remove a previously declared activity component that 14679 // had been set as a preferred activity. We try to clean this up 14680 // the next time we encounter that preferred activity, but it is 14681 // possible for the user flow to never be able to return to that 14682 // situation so here we do a sanity check to make sure we haven't 14683 // left any junk around. 14684 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14685 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14686 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14687 removed.clear(); 14688 for (PreferredActivity pa : pir.filterSet()) { 14689 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14690 removed.add(pa); 14691 } 14692 } 14693 if (removed.size() > 0) { 14694 for (int r=0; r<removed.size(); r++) { 14695 PreferredActivity pa = removed.get(r); 14696 Slog.w(TAG, "Removing dangling preferred activity: " 14697 + pa.mPref.mComponent); 14698 pir.removeFilter(pa); 14699 } 14700 mSettings.writePackageRestrictionsLPr( 14701 mSettings.mPreferredActivities.keyAt(i)); 14702 } 14703 } 14704 14705 for (int userId : UserManagerService.getInstance().getUserIds()) { 14706 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14707 grantPermissionsUserIds = ArrayUtils.appendInt( 14708 grantPermissionsUserIds, userId); 14709 } 14710 } 14711 } 14712 sUserManager.systemReady(); 14713 14714 // If we upgraded grant all default permissions before kicking off. 14715 for (int userId : grantPermissionsUserIds) { 14716 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14717 } 14718 14719 // Kick off any messages waiting for system ready 14720 if (mPostSystemReadyMessages != null) { 14721 for (Message msg : mPostSystemReadyMessages) { 14722 msg.sendToTarget(); 14723 } 14724 mPostSystemReadyMessages = null; 14725 } 14726 14727 // Watch for external volumes that come and go over time 14728 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14729 storage.registerListener(mStorageListener); 14730 14731 mInstallerService.systemReady(); 14732 mPackageDexOptimizer.systemReady(); 14733 14734 MountServiceInternal mountServiceInternal = LocalServices.getService( 14735 MountServiceInternal.class); 14736 mountServiceInternal.addExternalStoragePolicy( 14737 new MountServiceInternal.ExternalStorageMountPolicy() { 14738 @Override 14739 public int getMountMode(int uid, String packageName) { 14740 if (Process.isIsolated(uid)) { 14741 return Zygote.MOUNT_EXTERNAL_NONE; 14742 } 14743 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14744 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14745 } 14746 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14747 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14748 } 14749 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14750 return Zygote.MOUNT_EXTERNAL_READ; 14751 } 14752 return Zygote.MOUNT_EXTERNAL_WRITE; 14753 } 14754 14755 @Override 14756 public boolean hasExternalStorage(int uid, String packageName) { 14757 return true; 14758 } 14759 }); 14760 } 14761 14762 @Override 14763 public boolean isSafeMode() { 14764 return mSafeMode; 14765 } 14766 14767 @Override 14768 public boolean hasSystemUidErrors() { 14769 return mHasSystemUidErrors; 14770 } 14771 14772 static String arrayToString(int[] array) { 14773 StringBuffer buf = new StringBuffer(128); 14774 buf.append('['); 14775 if (array != null) { 14776 for (int i=0; i<array.length; i++) { 14777 if (i > 0) buf.append(", "); 14778 buf.append(array[i]); 14779 } 14780 } 14781 buf.append(']'); 14782 return buf.toString(); 14783 } 14784 14785 static class DumpState { 14786 public static final int DUMP_LIBS = 1 << 0; 14787 public static final int DUMP_FEATURES = 1 << 1; 14788 public static final int DUMP_RESOLVERS = 1 << 2; 14789 public static final int DUMP_PERMISSIONS = 1 << 3; 14790 public static final int DUMP_PACKAGES = 1 << 4; 14791 public static final int DUMP_SHARED_USERS = 1 << 5; 14792 public static final int DUMP_MESSAGES = 1 << 6; 14793 public static final int DUMP_PROVIDERS = 1 << 7; 14794 public static final int DUMP_VERIFIERS = 1 << 8; 14795 public static final int DUMP_PREFERRED = 1 << 9; 14796 public static final int DUMP_PREFERRED_XML = 1 << 10; 14797 public static final int DUMP_KEYSETS = 1 << 11; 14798 public static final int DUMP_VERSION = 1 << 12; 14799 public static final int DUMP_INSTALLS = 1 << 13; 14800 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14801 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14802 14803 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14804 14805 private int mTypes; 14806 14807 private int mOptions; 14808 14809 private boolean mTitlePrinted; 14810 14811 private SharedUserSetting mSharedUser; 14812 14813 public boolean isDumping(int type) { 14814 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14815 return true; 14816 } 14817 14818 return (mTypes & type) != 0; 14819 } 14820 14821 public void setDump(int type) { 14822 mTypes |= type; 14823 } 14824 14825 public boolean isOptionEnabled(int option) { 14826 return (mOptions & option) != 0; 14827 } 14828 14829 public void setOptionEnabled(int option) { 14830 mOptions |= option; 14831 } 14832 14833 public boolean onTitlePrinted() { 14834 final boolean printed = mTitlePrinted; 14835 mTitlePrinted = true; 14836 return printed; 14837 } 14838 14839 public boolean getTitlePrinted() { 14840 return mTitlePrinted; 14841 } 14842 14843 public void setTitlePrinted(boolean enabled) { 14844 mTitlePrinted = enabled; 14845 } 14846 14847 public SharedUserSetting getSharedUser() { 14848 return mSharedUser; 14849 } 14850 14851 public void setSharedUser(SharedUserSetting user) { 14852 mSharedUser = user; 14853 } 14854 } 14855 14856 @Override 14857 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14858 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14859 != PackageManager.PERMISSION_GRANTED) { 14860 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14861 + Binder.getCallingPid() 14862 + ", uid=" + Binder.getCallingUid() 14863 + " without permission " 14864 + android.Manifest.permission.DUMP); 14865 return; 14866 } 14867 14868 DumpState dumpState = new DumpState(); 14869 boolean fullPreferred = false; 14870 boolean checkin = false; 14871 14872 String packageName = null; 14873 ArraySet<String> permissionNames = null; 14874 14875 int opti = 0; 14876 while (opti < args.length) { 14877 String opt = args[opti]; 14878 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14879 break; 14880 } 14881 opti++; 14882 14883 if ("-a".equals(opt)) { 14884 // Right now we only know how to print all. 14885 } else if ("-h".equals(opt)) { 14886 pw.println("Package manager dump options:"); 14887 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14888 pw.println(" --checkin: dump for a checkin"); 14889 pw.println(" -f: print details of intent filters"); 14890 pw.println(" -h: print this help"); 14891 pw.println(" cmd may be one of:"); 14892 pw.println(" l[ibraries]: list known shared libraries"); 14893 pw.println(" f[ibraries]: list device features"); 14894 pw.println(" k[eysets]: print known keysets"); 14895 pw.println(" r[esolvers]: dump intent resolvers"); 14896 pw.println(" perm[issions]: dump permissions"); 14897 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14898 pw.println(" pref[erred]: print preferred package settings"); 14899 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14900 pw.println(" prov[iders]: dump content providers"); 14901 pw.println(" p[ackages]: dump installed packages"); 14902 pw.println(" s[hared-users]: dump shared user IDs"); 14903 pw.println(" m[essages]: print collected runtime messages"); 14904 pw.println(" v[erifiers]: print package verifier info"); 14905 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14906 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14907 pw.println(" version: print database version info"); 14908 pw.println(" write: write current settings now"); 14909 pw.println(" installs: details about install sessions"); 14910 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 14911 pw.println(" <package.name>: info about given package"); 14912 return; 14913 } else if ("--checkin".equals(opt)) { 14914 checkin = true; 14915 } else if ("-f".equals(opt)) { 14916 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14917 } else { 14918 pw.println("Unknown argument: " + opt + "; use -h for help"); 14919 } 14920 } 14921 14922 // Is the caller requesting to dump a particular piece of data? 14923 if (opti < args.length) { 14924 String cmd = args[opti]; 14925 opti++; 14926 // Is this a package name? 14927 if ("android".equals(cmd) || cmd.contains(".")) { 14928 packageName = cmd; 14929 // When dumping a single package, we always dump all of its 14930 // filter information since the amount of data will be reasonable. 14931 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14932 } else if ("check-permission".equals(cmd)) { 14933 if (opti >= args.length) { 14934 pw.println("Error: check-permission missing permission argument"); 14935 return; 14936 } 14937 String perm = args[opti]; 14938 opti++; 14939 if (opti >= args.length) { 14940 pw.println("Error: check-permission missing package argument"); 14941 return; 14942 } 14943 String pkg = args[opti]; 14944 opti++; 14945 int user = UserHandle.getUserId(Binder.getCallingUid()); 14946 if (opti < args.length) { 14947 try { 14948 user = Integer.parseInt(args[opti]); 14949 } catch (NumberFormatException e) { 14950 pw.println("Error: check-permission user argument is not a number: " 14951 + args[opti]); 14952 return; 14953 } 14954 } 14955 pw.println(checkPermission(perm, pkg, user)); 14956 return; 14957 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14958 dumpState.setDump(DumpState.DUMP_LIBS); 14959 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14960 dumpState.setDump(DumpState.DUMP_FEATURES); 14961 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14962 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14963 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14964 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14965 } else if ("permission".equals(cmd)) { 14966 if (opti >= args.length) { 14967 pw.println("Error: permission requires permission name"); 14968 return; 14969 } 14970 permissionNames = new ArraySet<>(); 14971 while (opti < args.length) { 14972 permissionNames.add(args[opti]); 14973 opti++; 14974 } 14975 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14976 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14977 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14978 dumpState.setDump(DumpState.DUMP_PREFERRED); 14979 } else if ("preferred-xml".equals(cmd)) { 14980 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14981 if (opti < args.length && "--full".equals(args[opti])) { 14982 fullPreferred = true; 14983 opti++; 14984 } 14985 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14986 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14987 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14988 dumpState.setDump(DumpState.DUMP_PACKAGES); 14989 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14990 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14991 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14992 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14993 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14994 dumpState.setDump(DumpState.DUMP_MESSAGES); 14995 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14996 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14997 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14998 || "intent-filter-verifiers".equals(cmd)) { 14999 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15000 } else if ("version".equals(cmd)) { 15001 dumpState.setDump(DumpState.DUMP_VERSION); 15002 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15003 dumpState.setDump(DumpState.DUMP_KEYSETS); 15004 } else if ("installs".equals(cmd)) { 15005 dumpState.setDump(DumpState.DUMP_INSTALLS); 15006 } else if ("write".equals(cmd)) { 15007 synchronized (mPackages) { 15008 mSettings.writeLPr(); 15009 pw.println("Settings written."); 15010 return; 15011 } 15012 } 15013 } 15014 15015 if (checkin) { 15016 pw.println("vers,1"); 15017 } 15018 15019 // reader 15020 synchronized (mPackages) { 15021 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15022 if (!checkin) { 15023 if (dumpState.onTitlePrinted()) 15024 pw.println(); 15025 pw.println("Database versions:"); 15026 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15027 } 15028 } 15029 15030 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15031 if (!checkin) { 15032 if (dumpState.onTitlePrinted()) 15033 pw.println(); 15034 pw.println("Verifiers:"); 15035 pw.print(" Required: "); 15036 pw.print(mRequiredVerifierPackage); 15037 pw.print(" (uid="); 15038 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15039 pw.println(")"); 15040 } else if (mRequiredVerifierPackage != null) { 15041 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15042 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15043 } 15044 } 15045 15046 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15047 packageName == null) { 15048 if (mIntentFilterVerifierComponent != null) { 15049 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15050 if (!checkin) { 15051 if (dumpState.onTitlePrinted()) 15052 pw.println(); 15053 pw.println("Intent Filter Verifier:"); 15054 pw.print(" Using: "); 15055 pw.print(verifierPackageName); 15056 pw.print(" (uid="); 15057 pw.print(getPackageUid(verifierPackageName, 0)); 15058 pw.println(")"); 15059 } else if (verifierPackageName != null) { 15060 pw.print("ifv,"); pw.print(verifierPackageName); 15061 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15062 } 15063 } else { 15064 pw.println(); 15065 pw.println("No Intent Filter Verifier available!"); 15066 } 15067 } 15068 15069 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15070 boolean printedHeader = false; 15071 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15072 while (it.hasNext()) { 15073 String name = it.next(); 15074 SharedLibraryEntry ent = mSharedLibraries.get(name); 15075 if (!checkin) { 15076 if (!printedHeader) { 15077 if (dumpState.onTitlePrinted()) 15078 pw.println(); 15079 pw.println("Libraries:"); 15080 printedHeader = true; 15081 } 15082 pw.print(" "); 15083 } else { 15084 pw.print("lib,"); 15085 } 15086 pw.print(name); 15087 if (!checkin) { 15088 pw.print(" -> "); 15089 } 15090 if (ent.path != null) { 15091 if (!checkin) { 15092 pw.print("(jar) "); 15093 pw.print(ent.path); 15094 } else { 15095 pw.print(",jar,"); 15096 pw.print(ent.path); 15097 } 15098 } else { 15099 if (!checkin) { 15100 pw.print("(apk) "); 15101 pw.print(ent.apk); 15102 } else { 15103 pw.print(",apk,"); 15104 pw.print(ent.apk); 15105 } 15106 } 15107 pw.println(); 15108 } 15109 } 15110 15111 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15112 if (dumpState.onTitlePrinted()) 15113 pw.println(); 15114 if (!checkin) { 15115 pw.println("Features:"); 15116 } 15117 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15118 while (it.hasNext()) { 15119 String name = it.next(); 15120 if (!checkin) { 15121 pw.print(" "); 15122 } else { 15123 pw.print("feat,"); 15124 } 15125 pw.println(name); 15126 } 15127 } 15128 15129 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15130 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15131 : "Activity Resolver Table:", " ", packageName, 15132 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15133 dumpState.setTitlePrinted(true); 15134 } 15135 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15136 : "Receiver Resolver Table:", " ", packageName, 15137 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15138 dumpState.setTitlePrinted(true); 15139 } 15140 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15141 : "Service Resolver Table:", " ", packageName, 15142 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15143 dumpState.setTitlePrinted(true); 15144 } 15145 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15146 : "Provider Resolver Table:", " ", packageName, 15147 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15148 dumpState.setTitlePrinted(true); 15149 } 15150 } 15151 15152 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15153 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15154 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15155 int user = mSettings.mPreferredActivities.keyAt(i); 15156 if (pir.dump(pw, 15157 dumpState.getTitlePrinted() 15158 ? "\nPreferred Activities User " + user + ":" 15159 : "Preferred Activities User " + user + ":", " ", 15160 packageName, true, false)) { 15161 dumpState.setTitlePrinted(true); 15162 } 15163 } 15164 } 15165 15166 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15167 pw.flush(); 15168 FileOutputStream fout = new FileOutputStream(fd); 15169 BufferedOutputStream str = new BufferedOutputStream(fout); 15170 XmlSerializer serializer = new FastXmlSerializer(); 15171 try { 15172 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15173 serializer.startDocument(null, true); 15174 serializer.setFeature( 15175 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15176 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15177 serializer.endDocument(); 15178 serializer.flush(); 15179 } catch (IllegalArgumentException e) { 15180 pw.println("Failed writing: " + e); 15181 } catch (IllegalStateException e) { 15182 pw.println("Failed writing: " + e); 15183 } catch (IOException e) { 15184 pw.println("Failed writing: " + e); 15185 } 15186 } 15187 15188 if (!checkin 15189 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15190 && packageName == null) { 15191 pw.println(); 15192 int count = mSettings.mPackages.size(); 15193 if (count == 0) { 15194 pw.println("No applications!"); 15195 pw.println(); 15196 } else { 15197 final String prefix = " "; 15198 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15199 if (allPackageSettings.size() == 0) { 15200 pw.println("No domain preferred apps!"); 15201 pw.println(); 15202 } else { 15203 pw.println("App verification status:"); 15204 pw.println(); 15205 count = 0; 15206 for (PackageSetting ps : allPackageSettings) { 15207 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15208 if (ivi == null || ivi.getPackageName() == null) continue; 15209 pw.println(prefix + "Package: " + ivi.getPackageName()); 15210 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15211 pw.println(prefix + "Status: " + ivi.getStatusString()); 15212 pw.println(); 15213 count++; 15214 } 15215 if (count == 0) { 15216 pw.println(prefix + "No app verification established."); 15217 pw.println(); 15218 } 15219 for (int userId : sUserManager.getUserIds()) { 15220 pw.println("App linkages for user " + userId + ":"); 15221 pw.println(); 15222 count = 0; 15223 for (PackageSetting ps : allPackageSettings) { 15224 final long status = ps.getDomainVerificationStatusForUser(userId); 15225 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15226 continue; 15227 } 15228 pw.println(prefix + "Package: " + ps.name); 15229 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15230 String statusStr = IntentFilterVerificationInfo. 15231 getStatusStringFromValue(status); 15232 pw.println(prefix + "Status: " + statusStr); 15233 pw.println(); 15234 count++; 15235 } 15236 if (count == 0) { 15237 pw.println(prefix + "No configured app linkages."); 15238 pw.println(); 15239 } 15240 } 15241 } 15242 } 15243 } 15244 15245 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15246 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15247 if (packageName == null && permissionNames == null) { 15248 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15249 if (iperm == 0) { 15250 if (dumpState.onTitlePrinted()) 15251 pw.println(); 15252 pw.println("AppOp Permissions:"); 15253 } 15254 pw.print(" AppOp Permission "); 15255 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15256 pw.println(":"); 15257 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15258 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15259 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15260 } 15261 } 15262 } 15263 } 15264 15265 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15266 boolean printedSomething = false; 15267 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15268 if (packageName != null && !packageName.equals(p.info.packageName)) { 15269 continue; 15270 } 15271 if (!printedSomething) { 15272 if (dumpState.onTitlePrinted()) 15273 pw.println(); 15274 pw.println("Registered ContentProviders:"); 15275 printedSomething = true; 15276 } 15277 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15278 pw.print(" "); pw.println(p.toString()); 15279 } 15280 printedSomething = false; 15281 for (Map.Entry<String, PackageParser.Provider> entry : 15282 mProvidersByAuthority.entrySet()) { 15283 PackageParser.Provider p = entry.getValue(); 15284 if (packageName != null && !packageName.equals(p.info.packageName)) { 15285 continue; 15286 } 15287 if (!printedSomething) { 15288 if (dumpState.onTitlePrinted()) 15289 pw.println(); 15290 pw.println("ContentProvider Authorities:"); 15291 printedSomething = true; 15292 } 15293 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15294 pw.print(" "); pw.println(p.toString()); 15295 if (p.info != null && p.info.applicationInfo != null) { 15296 final String appInfo = p.info.applicationInfo.toString(); 15297 pw.print(" applicationInfo="); pw.println(appInfo); 15298 } 15299 } 15300 } 15301 15302 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15303 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15304 } 15305 15306 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15307 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15308 } 15309 15310 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15311 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15312 } 15313 15314 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15315 // XXX should handle packageName != null by dumping only install data that 15316 // the given package is involved with. 15317 if (dumpState.onTitlePrinted()) pw.println(); 15318 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15319 } 15320 15321 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15322 if (dumpState.onTitlePrinted()) pw.println(); 15323 mSettings.dumpReadMessagesLPr(pw, dumpState); 15324 15325 pw.println(); 15326 pw.println("Package warning messages:"); 15327 BufferedReader in = null; 15328 String line = null; 15329 try { 15330 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15331 while ((line = in.readLine()) != null) { 15332 if (line.contains("ignored: updated version")) continue; 15333 pw.println(line); 15334 } 15335 } catch (IOException ignored) { 15336 } finally { 15337 IoUtils.closeQuietly(in); 15338 } 15339 } 15340 15341 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15342 BufferedReader in = null; 15343 String line = null; 15344 try { 15345 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15346 while ((line = in.readLine()) != null) { 15347 if (line.contains("ignored: updated version")) continue; 15348 pw.print("msg,"); 15349 pw.println(line); 15350 } 15351 } catch (IOException ignored) { 15352 } finally { 15353 IoUtils.closeQuietly(in); 15354 } 15355 } 15356 } 15357 } 15358 15359 private String dumpDomainString(String packageName) { 15360 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15361 List<IntentFilter> filters = getAllIntentFilters(packageName); 15362 15363 ArraySet<String> result = new ArraySet<>(); 15364 if (iviList.size() > 0) { 15365 for (IntentFilterVerificationInfo ivi : iviList) { 15366 for (String host : ivi.getDomains()) { 15367 result.add(host); 15368 } 15369 } 15370 } 15371 if (filters != null && filters.size() > 0) { 15372 for (IntentFilter filter : filters) { 15373 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15374 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15375 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15376 result.addAll(filter.getHostsList()); 15377 } 15378 } 15379 } 15380 15381 StringBuilder sb = new StringBuilder(result.size() * 16); 15382 for (String domain : result) { 15383 if (sb.length() > 0) sb.append(" "); 15384 sb.append(domain); 15385 } 15386 return sb.toString(); 15387 } 15388 15389 // ------- apps on sdcard specific code ------- 15390 static final boolean DEBUG_SD_INSTALL = false; 15391 15392 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15393 15394 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15395 15396 private boolean mMediaMounted = false; 15397 15398 static String getEncryptKey() { 15399 try { 15400 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15401 SD_ENCRYPTION_KEYSTORE_NAME); 15402 if (sdEncKey == null) { 15403 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15404 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15405 if (sdEncKey == null) { 15406 Slog.e(TAG, "Failed to create encryption keys"); 15407 return null; 15408 } 15409 } 15410 return sdEncKey; 15411 } catch (NoSuchAlgorithmException nsae) { 15412 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15413 return null; 15414 } catch (IOException ioe) { 15415 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15416 return null; 15417 } 15418 } 15419 15420 /* 15421 * Update media status on PackageManager. 15422 */ 15423 @Override 15424 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15425 int callingUid = Binder.getCallingUid(); 15426 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15427 throw new SecurityException("Media status can only be updated by the system"); 15428 } 15429 // reader; this apparently protects mMediaMounted, but should probably 15430 // be a different lock in that case. 15431 synchronized (mPackages) { 15432 Log.i(TAG, "Updating external media status from " 15433 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15434 + (mediaStatus ? "mounted" : "unmounted")); 15435 if (DEBUG_SD_INSTALL) 15436 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15437 + ", mMediaMounted=" + mMediaMounted); 15438 if (mediaStatus == mMediaMounted) { 15439 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15440 : 0, -1); 15441 mHandler.sendMessage(msg); 15442 return; 15443 } 15444 mMediaMounted = mediaStatus; 15445 } 15446 // Queue up an async operation since the package installation may take a 15447 // little while. 15448 mHandler.post(new Runnable() { 15449 public void run() { 15450 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15451 } 15452 }); 15453 } 15454 15455 /** 15456 * Called by MountService when the initial ASECs to scan are available. 15457 * Should block until all the ASEC containers are finished being scanned. 15458 */ 15459 public void scanAvailableAsecs() { 15460 updateExternalMediaStatusInner(true, false, false); 15461 if (mShouldRestoreconData) { 15462 SELinuxMMAC.setRestoreconDone(); 15463 mShouldRestoreconData = false; 15464 } 15465 } 15466 15467 /* 15468 * Collect information of applications on external media, map them against 15469 * existing containers and update information based on current mount status. 15470 * Please note that we always have to report status if reportStatus has been 15471 * set to true especially when unloading packages. 15472 */ 15473 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15474 boolean externalStorage) { 15475 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15476 int[] uidArr = EmptyArray.INT; 15477 15478 final String[] list = PackageHelper.getSecureContainerList(); 15479 if (ArrayUtils.isEmpty(list)) { 15480 Log.i(TAG, "No secure containers found"); 15481 } else { 15482 // Process list of secure containers and categorize them 15483 // as active or stale based on their package internal state. 15484 15485 // reader 15486 synchronized (mPackages) { 15487 for (String cid : list) { 15488 // Leave stages untouched for now; installer service owns them 15489 if (PackageInstallerService.isStageName(cid)) continue; 15490 15491 if (DEBUG_SD_INSTALL) 15492 Log.i(TAG, "Processing container " + cid); 15493 String pkgName = getAsecPackageName(cid); 15494 if (pkgName == null) { 15495 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15496 continue; 15497 } 15498 if (DEBUG_SD_INSTALL) 15499 Log.i(TAG, "Looking for pkg : " + pkgName); 15500 15501 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15502 if (ps == null) { 15503 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15504 continue; 15505 } 15506 15507 /* 15508 * Skip packages that are not external if we're unmounting 15509 * external storage. 15510 */ 15511 if (externalStorage && !isMounted && !isExternal(ps)) { 15512 continue; 15513 } 15514 15515 final AsecInstallArgs args = new AsecInstallArgs(cid, 15516 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15517 // The package status is changed only if the code path 15518 // matches between settings and the container id. 15519 if (ps.codePathString != null 15520 && ps.codePathString.startsWith(args.getCodePath())) { 15521 if (DEBUG_SD_INSTALL) { 15522 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15523 + " at code path: " + ps.codePathString); 15524 } 15525 15526 // We do have a valid package installed on sdcard 15527 processCids.put(args, ps.codePathString); 15528 final int uid = ps.appId; 15529 if (uid != -1) { 15530 uidArr = ArrayUtils.appendInt(uidArr, uid); 15531 } 15532 } else { 15533 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15534 + ps.codePathString); 15535 } 15536 } 15537 } 15538 15539 Arrays.sort(uidArr); 15540 } 15541 15542 // Process packages with valid entries. 15543 if (isMounted) { 15544 if (DEBUG_SD_INSTALL) 15545 Log.i(TAG, "Loading packages"); 15546 loadMediaPackages(processCids, uidArr, externalStorage); 15547 startCleaningPackages(); 15548 mInstallerService.onSecureContainersAvailable(); 15549 } else { 15550 if (DEBUG_SD_INSTALL) 15551 Log.i(TAG, "Unloading packages"); 15552 unloadMediaPackages(processCids, uidArr, reportStatus); 15553 } 15554 } 15555 15556 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15557 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15558 final int size = infos.size(); 15559 final String[] packageNames = new String[size]; 15560 final int[] packageUids = new int[size]; 15561 for (int i = 0; i < size; i++) { 15562 final ApplicationInfo info = infos.get(i); 15563 packageNames[i] = info.packageName; 15564 packageUids[i] = info.uid; 15565 } 15566 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15567 finishedReceiver); 15568 } 15569 15570 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15571 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15572 sendResourcesChangedBroadcast(mediaStatus, replacing, 15573 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15574 } 15575 15576 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15577 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15578 int size = pkgList.length; 15579 if (size > 0) { 15580 // Send broadcasts here 15581 Bundle extras = new Bundle(); 15582 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15583 if (uidArr != null) { 15584 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15585 } 15586 if (replacing) { 15587 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15588 } 15589 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15590 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15591 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15592 } 15593 } 15594 15595 /* 15596 * Look at potentially valid container ids from processCids If package 15597 * information doesn't match the one on record or package scanning fails, 15598 * the cid is added to list of removeCids. We currently don't delete stale 15599 * containers. 15600 */ 15601 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 15602 boolean externalStorage) { 15603 ArrayList<String> pkgList = new ArrayList<String>(); 15604 Set<AsecInstallArgs> keys = processCids.keySet(); 15605 15606 for (AsecInstallArgs args : keys) { 15607 String codePath = processCids.get(args); 15608 if (DEBUG_SD_INSTALL) 15609 Log.i(TAG, "Loading container : " + args.cid); 15610 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15611 try { 15612 // Make sure there are no container errors first. 15613 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15614 Slog.e(TAG, "Failed to mount cid : " + args.cid 15615 + " when installing from sdcard"); 15616 continue; 15617 } 15618 // Check code path here. 15619 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15620 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15621 + " does not match one in settings " + codePath); 15622 continue; 15623 } 15624 // Parse package 15625 int parseFlags = mDefParseFlags; 15626 if (args.isExternalAsec()) { 15627 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15628 } 15629 if (args.isFwdLocked()) { 15630 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15631 } 15632 15633 synchronized (mInstallLock) { 15634 PackageParser.Package pkg = null; 15635 try { 15636 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15637 } catch (PackageManagerException e) { 15638 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15639 } 15640 // Scan the package 15641 if (pkg != null) { 15642 /* 15643 * TODO why is the lock being held? doPostInstall is 15644 * called in other places without the lock. This needs 15645 * to be straightened out. 15646 */ 15647 // writer 15648 synchronized (mPackages) { 15649 retCode = PackageManager.INSTALL_SUCCEEDED; 15650 pkgList.add(pkg.packageName); 15651 // Post process args 15652 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15653 pkg.applicationInfo.uid); 15654 } 15655 } else { 15656 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15657 } 15658 } 15659 15660 } finally { 15661 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15662 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15663 } 15664 } 15665 } 15666 // writer 15667 synchronized (mPackages) { 15668 // If the platform SDK has changed since the last time we booted, 15669 // we need to re-grant app permission to catch any new ones that 15670 // appear. This is really a hack, and means that apps can in some 15671 // cases get permissions that the user didn't initially explicitly 15672 // allow... it would be nice to have some better way to handle 15673 // this situation. 15674 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 15675 : mSettings.getInternalVersion(); 15676 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 15677 : StorageManager.UUID_PRIVATE_INTERNAL; 15678 15679 int updateFlags = UPDATE_PERMISSIONS_ALL; 15680 if (ver.sdkVersion != mSdkVersion) { 15681 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15682 + mSdkVersion + "; regranting permissions for external"); 15683 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15684 } 15685 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 15686 15687 // Yay, everything is now upgraded 15688 ver.forceCurrent(); 15689 15690 // can downgrade to reader 15691 // Persist settings 15692 mSettings.writeLPr(); 15693 } 15694 // Send a broadcast to let everyone know we are done processing 15695 if (pkgList.size() > 0) { 15696 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15697 } 15698 } 15699 15700 /* 15701 * Utility method to unload a list of specified containers 15702 */ 15703 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15704 // Just unmount all valid containers. 15705 for (AsecInstallArgs arg : cidArgs) { 15706 synchronized (mInstallLock) { 15707 arg.doPostDeleteLI(false); 15708 } 15709 } 15710 } 15711 15712 /* 15713 * Unload packages mounted on external media. This involves deleting package 15714 * data from internal structures, sending broadcasts about diabled packages, 15715 * gc'ing to free up references, unmounting all secure containers 15716 * corresponding to packages on external media, and posting a 15717 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15718 * that we always have to post this message if status has been requested no 15719 * matter what. 15720 */ 15721 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15722 final boolean reportStatus) { 15723 if (DEBUG_SD_INSTALL) 15724 Log.i(TAG, "unloading media packages"); 15725 ArrayList<String> pkgList = new ArrayList<String>(); 15726 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15727 final Set<AsecInstallArgs> keys = processCids.keySet(); 15728 for (AsecInstallArgs args : keys) { 15729 String pkgName = args.getPackageName(); 15730 if (DEBUG_SD_INSTALL) 15731 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15732 // Delete package internally 15733 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15734 synchronized (mInstallLock) { 15735 boolean res = deletePackageLI(pkgName, null, false, null, null, 15736 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15737 if (res) { 15738 pkgList.add(pkgName); 15739 } else { 15740 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15741 failedList.add(args); 15742 } 15743 } 15744 } 15745 15746 // reader 15747 synchronized (mPackages) { 15748 // We didn't update the settings after removing each package; 15749 // write them now for all packages. 15750 mSettings.writeLPr(); 15751 } 15752 15753 // We have to absolutely send UPDATED_MEDIA_STATUS only 15754 // after confirming that all the receivers processed the ordered 15755 // broadcast when packages get disabled, force a gc to clean things up. 15756 // and unload all the containers. 15757 if (pkgList.size() > 0) { 15758 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15759 new IIntentReceiver.Stub() { 15760 public void performReceive(Intent intent, int resultCode, String data, 15761 Bundle extras, boolean ordered, boolean sticky, 15762 int sendingUser) throws RemoteException { 15763 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15764 reportStatus ? 1 : 0, 1, keys); 15765 mHandler.sendMessage(msg); 15766 } 15767 }); 15768 } else { 15769 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15770 keys); 15771 mHandler.sendMessage(msg); 15772 } 15773 } 15774 15775 private void loadPrivatePackages(final VolumeInfo vol) { 15776 mHandler.post(new Runnable() { 15777 @Override 15778 public void run() { 15779 loadPrivatePackagesInner(vol); 15780 } 15781 }); 15782 } 15783 15784 private void loadPrivatePackagesInner(VolumeInfo vol) { 15785 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15786 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15787 15788 final VersionInfo ver; 15789 final List<PackageSetting> packages; 15790 synchronized (mPackages) { 15791 ver = mSettings.findOrCreateVersion(vol.fsUuid); 15792 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15793 } 15794 15795 for (PackageSetting ps : packages) { 15796 synchronized (mInstallLock) { 15797 final PackageParser.Package pkg; 15798 try { 15799 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15800 loaded.add(pkg.applicationInfo); 15801 } catch (PackageManagerException e) { 15802 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15803 } 15804 15805 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15806 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15807 } 15808 } 15809 } 15810 15811 synchronized (mPackages) { 15812 int updateFlags = UPDATE_PERMISSIONS_ALL; 15813 if (ver.sdkVersion != mSdkVersion) { 15814 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15815 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15816 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15817 } 15818 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 15819 15820 // Yay, everything is now upgraded 15821 ver.forceCurrent(); 15822 15823 mSettings.writeLPr(); 15824 } 15825 15826 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15827 sendResourcesChangedBroadcast(true, false, loaded, null); 15828 } 15829 15830 private void unloadPrivatePackages(final VolumeInfo vol) { 15831 mHandler.post(new Runnable() { 15832 @Override 15833 public void run() { 15834 unloadPrivatePackagesInner(vol); 15835 } 15836 }); 15837 } 15838 15839 private void unloadPrivatePackagesInner(VolumeInfo vol) { 15840 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15841 synchronized (mInstallLock) { 15842 synchronized (mPackages) { 15843 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15844 for (PackageSetting ps : packages) { 15845 if (ps.pkg == null) continue; 15846 15847 final ApplicationInfo info = ps.pkg.applicationInfo; 15848 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15849 if (deletePackageLI(ps.name, null, false, null, null, 15850 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15851 unloaded.add(info); 15852 } else { 15853 Slog.w(TAG, "Failed to unload " + ps.codePath); 15854 } 15855 } 15856 15857 mSettings.writeLPr(); 15858 } 15859 } 15860 15861 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15862 sendResourcesChangedBroadcast(false, false, unloaded, null); 15863 } 15864 15865 /** 15866 * Examine all users present on given mounted volume, and destroy data 15867 * belonging to users that are no longer valid, or whose user ID has been 15868 * recycled. 15869 */ 15870 private void reconcileUsers(String volumeUuid) { 15871 final File[] files = FileUtils 15872 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15873 for (File file : files) { 15874 if (!file.isDirectory()) continue; 15875 15876 final int userId; 15877 final UserInfo info; 15878 try { 15879 userId = Integer.parseInt(file.getName()); 15880 info = sUserManager.getUserInfo(userId); 15881 } catch (NumberFormatException e) { 15882 Slog.w(TAG, "Invalid user directory " + file); 15883 continue; 15884 } 15885 15886 boolean destroyUser = false; 15887 if (info == null) { 15888 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15889 + " because no matching user was found"); 15890 destroyUser = true; 15891 } else { 15892 try { 15893 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15894 } catch (IOException e) { 15895 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15896 + " because we failed to enforce serial number: " + e); 15897 destroyUser = true; 15898 } 15899 } 15900 15901 if (destroyUser) { 15902 synchronized (mInstallLock) { 15903 mInstaller.removeUserDataDirs(volumeUuid, userId); 15904 } 15905 } 15906 } 15907 15908 final UserManager um = mContext.getSystemService(UserManager.class); 15909 for (UserInfo user : um.getUsers()) { 15910 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15911 if (userDir.exists()) continue; 15912 15913 try { 15914 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15915 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15916 } catch (IOException e) { 15917 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15918 } 15919 } 15920 } 15921 15922 /** 15923 * Examine all apps present on given mounted volume, and destroy apps that 15924 * aren't expected, either due to uninstallation or reinstallation on 15925 * another volume. 15926 */ 15927 private void reconcileApps(String volumeUuid) { 15928 final File[] files = FileUtils 15929 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15930 for (File file : files) { 15931 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15932 && !PackageInstallerService.isStageName(file.getName()); 15933 if (!isPackage) { 15934 // Ignore entries which are not packages 15935 continue; 15936 } 15937 15938 boolean destroyApp = false; 15939 String packageName = null; 15940 try { 15941 final PackageLite pkg = PackageParser.parsePackageLite(file, 15942 PackageParser.PARSE_MUST_BE_APK); 15943 packageName = pkg.packageName; 15944 15945 synchronized (mPackages) { 15946 final PackageSetting ps = mSettings.mPackages.get(packageName); 15947 if (ps == null) { 15948 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15949 + volumeUuid + " because we found no install record"); 15950 destroyApp = true; 15951 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15952 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15953 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15954 destroyApp = true; 15955 } 15956 } 15957 15958 } catch (PackageParserException e) { 15959 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15960 destroyApp = true; 15961 } 15962 15963 if (destroyApp) { 15964 synchronized (mInstallLock) { 15965 if (packageName != null) { 15966 removeDataDirsLI(volumeUuid, packageName); 15967 } 15968 if (file.isDirectory()) { 15969 mInstaller.rmPackageDir(file.getAbsolutePath()); 15970 } else { 15971 file.delete(); 15972 } 15973 } 15974 } 15975 } 15976 } 15977 15978 private void unfreezePackage(String packageName) { 15979 synchronized (mPackages) { 15980 final PackageSetting ps = mSettings.mPackages.get(packageName); 15981 if (ps != null) { 15982 ps.frozen = false; 15983 } 15984 } 15985 } 15986 15987 @Override 15988 public int movePackage(final String packageName, final String volumeUuid) { 15989 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15990 15991 final int moveId = mNextMoveId.getAndIncrement(); 15992 try { 15993 movePackageInternal(packageName, volumeUuid, moveId); 15994 } catch (PackageManagerException e) { 15995 Slog.w(TAG, "Failed to move " + packageName, e); 15996 mMoveCallbacks.notifyStatusChanged(moveId, 15997 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15998 } 15999 return moveId; 16000 } 16001 16002 private void movePackageInternal(final String packageName, final String volumeUuid, 16003 final int moveId) throws PackageManagerException { 16004 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16005 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16006 final PackageManager pm = mContext.getPackageManager(); 16007 16008 final boolean currentAsec; 16009 final String currentVolumeUuid; 16010 final File codeFile; 16011 final String installerPackageName; 16012 final String packageAbiOverride; 16013 final int appId; 16014 final String seinfo; 16015 final String label; 16016 16017 // reader 16018 synchronized (mPackages) { 16019 final PackageParser.Package pkg = mPackages.get(packageName); 16020 final PackageSetting ps = mSettings.mPackages.get(packageName); 16021 if (pkg == null || ps == null) { 16022 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16023 } 16024 16025 if (pkg.applicationInfo.isSystemApp()) { 16026 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16027 "Cannot move system application"); 16028 } 16029 16030 if (pkg.applicationInfo.isExternalAsec()) { 16031 currentAsec = true; 16032 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16033 } else if (pkg.applicationInfo.isForwardLocked()) { 16034 currentAsec = true; 16035 currentVolumeUuid = "forward_locked"; 16036 } else { 16037 currentAsec = false; 16038 currentVolumeUuid = ps.volumeUuid; 16039 16040 final File probe = new File(pkg.codePath); 16041 final File probeOat = new File(probe, "oat"); 16042 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16043 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16044 "Move only supported for modern cluster style installs"); 16045 } 16046 } 16047 16048 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16049 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16050 "Package already moved to " + volumeUuid); 16051 } 16052 16053 if (ps.frozen) { 16054 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16055 "Failed to move already frozen package"); 16056 } 16057 ps.frozen = true; 16058 16059 codeFile = new File(pkg.codePath); 16060 installerPackageName = ps.installerPackageName; 16061 packageAbiOverride = ps.cpuAbiOverrideString; 16062 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16063 seinfo = pkg.applicationInfo.seinfo; 16064 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16065 } 16066 16067 // Now that we're guarded by frozen state, kill app during move 16068 final long token = Binder.clearCallingIdentity(); 16069 try { 16070 killApplication(packageName, appId, "move pkg"); 16071 } finally { 16072 Binder.restoreCallingIdentity(token); 16073 } 16074 16075 final Bundle extras = new Bundle(); 16076 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16077 extras.putString(Intent.EXTRA_TITLE, label); 16078 mMoveCallbacks.notifyCreated(moveId, extras); 16079 16080 int installFlags; 16081 final boolean moveCompleteApp; 16082 final File measurePath; 16083 16084 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16085 installFlags = INSTALL_INTERNAL; 16086 moveCompleteApp = !currentAsec; 16087 measurePath = Environment.getDataAppDirectory(volumeUuid); 16088 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16089 installFlags = INSTALL_EXTERNAL; 16090 moveCompleteApp = false; 16091 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16092 } else { 16093 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16094 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16095 || !volume.isMountedWritable()) { 16096 unfreezePackage(packageName); 16097 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16098 "Move location not mounted private volume"); 16099 } 16100 16101 Preconditions.checkState(!currentAsec); 16102 16103 installFlags = INSTALL_INTERNAL; 16104 moveCompleteApp = true; 16105 measurePath = Environment.getDataAppDirectory(volumeUuid); 16106 } 16107 16108 final PackageStats stats = new PackageStats(null, -1); 16109 synchronized (mInstaller) { 16110 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16111 unfreezePackage(packageName); 16112 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16113 "Failed to measure package size"); 16114 } 16115 } 16116 16117 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16118 + stats.dataSize); 16119 16120 final long startFreeBytes = measurePath.getFreeSpace(); 16121 final long sizeBytes; 16122 if (moveCompleteApp) { 16123 sizeBytes = stats.codeSize + stats.dataSize; 16124 } else { 16125 sizeBytes = stats.codeSize; 16126 } 16127 16128 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16129 unfreezePackage(packageName); 16130 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16131 "Not enough free space to move"); 16132 } 16133 16134 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16135 16136 final CountDownLatch installedLatch = new CountDownLatch(1); 16137 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16138 @Override 16139 public void onUserActionRequired(Intent intent) throws RemoteException { 16140 throw new IllegalStateException(); 16141 } 16142 16143 @Override 16144 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16145 Bundle extras) throws RemoteException { 16146 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16147 + PackageManager.installStatusToString(returnCode, msg)); 16148 16149 installedLatch.countDown(); 16150 16151 // Regardless of success or failure of the move operation, 16152 // always unfreeze the package 16153 unfreezePackage(packageName); 16154 16155 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16156 switch (status) { 16157 case PackageInstaller.STATUS_SUCCESS: 16158 mMoveCallbacks.notifyStatusChanged(moveId, 16159 PackageManager.MOVE_SUCCEEDED); 16160 break; 16161 case PackageInstaller.STATUS_FAILURE_STORAGE: 16162 mMoveCallbacks.notifyStatusChanged(moveId, 16163 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16164 break; 16165 default: 16166 mMoveCallbacks.notifyStatusChanged(moveId, 16167 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16168 break; 16169 } 16170 } 16171 }; 16172 16173 final MoveInfo move; 16174 if (moveCompleteApp) { 16175 // Kick off a thread to report progress estimates 16176 new Thread() { 16177 @Override 16178 public void run() { 16179 while (true) { 16180 try { 16181 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16182 break; 16183 } 16184 } catch (InterruptedException ignored) { 16185 } 16186 16187 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16188 final int progress = 10 + (int) MathUtils.constrain( 16189 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16190 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16191 } 16192 } 16193 }.start(); 16194 16195 final String dataAppName = codeFile.getName(); 16196 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16197 dataAppName, appId, seinfo); 16198 } else { 16199 move = null; 16200 } 16201 16202 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16203 16204 final Message msg = mHandler.obtainMessage(INIT_COPY); 16205 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16206 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 16207 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16208 mHandler.sendMessage(msg); 16209 } 16210 16211 @Override 16212 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16213 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16214 16215 final int realMoveId = mNextMoveId.getAndIncrement(); 16216 final Bundle extras = new Bundle(); 16217 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16218 mMoveCallbacks.notifyCreated(realMoveId, extras); 16219 16220 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16221 @Override 16222 public void onCreated(int moveId, Bundle extras) { 16223 // Ignored 16224 } 16225 16226 @Override 16227 public void onStatusChanged(int moveId, int status, long estMillis) { 16228 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16229 } 16230 }; 16231 16232 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16233 storage.setPrimaryStorageUuid(volumeUuid, callback); 16234 return realMoveId; 16235 } 16236 16237 @Override 16238 public int getMoveStatus(int moveId) { 16239 mContext.enforceCallingOrSelfPermission( 16240 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16241 return mMoveCallbacks.mLastStatus.get(moveId); 16242 } 16243 16244 @Override 16245 public void registerMoveCallback(IPackageMoveObserver callback) { 16246 mContext.enforceCallingOrSelfPermission( 16247 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16248 mMoveCallbacks.register(callback); 16249 } 16250 16251 @Override 16252 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16253 mContext.enforceCallingOrSelfPermission( 16254 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16255 mMoveCallbacks.unregister(callback); 16256 } 16257 16258 @Override 16259 public boolean setInstallLocation(int loc) { 16260 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16261 null); 16262 if (getInstallLocation() == loc) { 16263 return true; 16264 } 16265 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16266 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16267 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16268 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16269 return true; 16270 } 16271 return false; 16272 } 16273 16274 @Override 16275 public int getInstallLocation() { 16276 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16277 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16278 PackageHelper.APP_INSTALL_AUTO); 16279 } 16280 16281 /** Called by UserManagerService */ 16282 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16283 mDirtyUsers.remove(userHandle); 16284 mSettings.removeUserLPw(userHandle); 16285 mPendingBroadcasts.remove(userHandle); 16286 if (mInstaller != null) { 16287 // Technically, we shouldn't be doing this with the package lock 16288 // held. However, this is very rare, and there is already so much 16289 // other disk I/O going on, that we'll let it slide for now. 16290 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16291 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16292 final String volumeUuid = vol.getFsUuid(); 16293 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16294 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16295 } 16296 } 16297 mUserNeedsBadging.delete(userHandle); 16298 removeUnusedPackagesLILPw(userManager, userHandle); 16299 } 16300 16301 /** 16302 * We're removing userHandle and would like to remove any downloaded packages 16303 * that are no longer in use by any other user. 16304 * @param userHandle the user being removed 16305 */ 16306 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16307 final boolean DEBUG_CLEAN_APKS = false; 16308 int [] users = userManager.getUserIdsLPr(); 16309 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16310 while (psit.hasNext()) { 16311 PackageSetting ps = psit.next(); 16312 if (ps.pkg == null) { 16313 continue; 16314 } 16315 final String packageName = ps.pkg.packageName; 16316 // Skip over if system app 16317 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16318 continue; 16319 } 16320 if (DEBUG_CLEAN_APKS) { 16321 Slog.i(TAG, "Checking package " + packageName); 16322 } 16323 boolean keep = false; 16324 for (int i = 0; i < users.length; i++) { 16325 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16326 keep = true; 16327 if (DEBUG_CLEAN_APKS) { 16328 Slog.i(TAG, " Keeping package " + packageName + " for user " 16329 + users[i]); 16330 } 16331 break; 16332 } 16333 } 16334 if (!keep) { 16335 if (DEBUG_CLEAN_APKS) { 16336 Slog.i(TAG, " Removing package " + packageName); 16337 } 16338 mHandler.post(new Runnable() { 16339 public void run() { 16340 deletePackageX(packageName, userHandle, 0); 16341 } //end run 16342 }); 16343 } 16344 } 16345 } 16346 16347 /** Called by UserManagerService */ 16348 void createNewUserLILPw(int userHandle) { 16349 if (mInstaller != null) { 16350 mInstaller.createUserConfig(userHandle); 16351 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16352 applyFactoryDefaultBrowserLPw(userHandle); 16353 primeDomainVerificationsLPw(userHandle); 16354 } 16355 } 16356 16357 void newUserCreated(final int userHandle) { 16358 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16359 } 16360 16361 @Override 16362 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16363 mContext.enforceCallingOrSelfPermission( 16364 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16365 "Only package verification agents can read the verifier device identity"); 16366 16367 synchronized (mPackages) { 16368 return mSettings.getVerifierDeviceIdentityLPw(); 16369 } 16370 } 16371 16372 @Override 16373 public void setPermissionEnforced(String permission, boolean enforced) { 16374 // TODO: Now that we no longer change GID for storage, this should to away. 16375 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16376 "setPermissionEnforced"); 16377 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16378 synchronized (mPackages) { 16379 if (mSettings.mReadExternalStorageEnforced == null 16380 || mSettings.mReadExternalStorageEnforced != enforced) { 16381 mSettings.mReadExternalStorageEnforced = enforced; 16382 mSettings.writeLPr(); 16383 } 16384 } 16385 // kill any non-foreground processes so we restart them and 16386 // grant/revoke the GID. 16387 final IActivityManager am = ActivityManagerNative.getDefault(); 16388 if (am != null) { 16389 final long token = Binder.clearCallingIdentity(); 16390 try { 16391 am.killProcessesBelowForeground("setPermissionEnforcement"); 16392 } catch (RemoteException e) { 16393 } finally { 16394 Binder.restoreCallingIdentity(token); 16395 } 16396 } 16397 } else { 16398 throw new IllegalArgumentException("No selective enforcement for " + permission); 16399 } 16400 } 16401 16402 @Override 16403 @Deprecated 16404 public boolean isPermissionEnforced(String permission) { 16405 return true; 16406 } 16407 16408 @Override 16409 public boolean isStorageLow() { 16410 final long token = Binder.clearCallingIdentity(); 16411 try { 16412 final DeviceStorageMonitorInternal 16413 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16414 if (dsm != null) { 16415 return dsm.isMemoryLow(); 16416 } else { 16417 return false; 16418 } 16419 } finally { 16420 Binder.restoreCallingIdentity(token); 16421 } 16422 } 16423 16424 @Override 16425 public IPackageInstaller getPackageInstaller() { 16426 return mInstallerService; 16427 } 16428 16429 private boolean userNeedsBadging(int userId) { 16430 int index = mUserNeedsBadging.indexOfKey(userId); 16431 if (index < 0) { 16432 final UserInfo userInfo; 16433 final long token = Binder.clearCallingIdentity(); 16434 try { 16435 userInfo = sUserManager.getUserInfo(userId); 16436 } finally { 16437 Binder.restoreCallingIdentity(token); 16438 } 16439 final boolean b; 16440 if (userInfo != null && userInfo.isManagedProfile()) { 16441 b = true; 16442 } else { 16443 b = false; 16444 } 16445 mUserNeedsBadging.put(userId, b); 16446 return b; 16447 } 16448 return mUserNeedsBadging.valueAt(index); 16449 } 16450 16451 @Override 16452 public KeySet getKeySetByAlias(String packageName, String alias) { 16453 if (packageName == null || alias == null) { 16454 return null; 16455 } 16456 synchronized(mPackages) { 16457 final PackageParser.Package pkg = mPackages.get(packageName); 16458 if (pkg == null) { 16459 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16460 throw new IllegalArgumentException("Unknown package: " + packageName); 16461 } 16462 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16463 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16464 } 16465 } 16466 16467 @Override 16468 public KeySet getSigningKeySet(String packageName) { 16469 if (packageName == null) { 16470 return null; 16471 } 16472 synchronized(mPackages) { 16473 final PackageParser.Package pkg = mPackages.get(packageName); 16474 if (pkg == null) { 16475 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16476 throw new IllegalArgumentException("Unknown package: " + packageName); 16477 } 16478 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16479 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16480 throw new SecurityException("May not access signing KeySet of other apps."); 16481 } 16482 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16483 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16484 } 16485 } 16486 16487 @Override 16488 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16489 if (packageName == null || ks == null) { 16490 return false; 16491 } 16492 synchronized(mPackages) { 16493 final PackageParser.Package pkg = mPackages.get(packageName); 16494 if (pkg == null) { 16495 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16496 throw new IllegalArgumentException("Unknown package: " + packageName); 16497 } 16498 IBinder ksh = ks.getToken(); 16499 if (ksh instanceof KeySetHandle) { 16500 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16501 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16502 } 16503 return false; 16504 } 16505 } 16506 16507 @Override 16508 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16509 if (packageName == null || ks == null) { 16510 return false; 16511 } 16512 synchronized(mPackages) { 16513 final PackageParser.Package pkg = mPackages.get(packageName); 16514 if (pkg == null) { 16515 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16516 throw new IllegalArgumentException("Unknown package: " + packageName); 16517 } 16518 IBinder ksh = ks.getToken(); 16519 if (ksh instanceof KeySetHandle) { 16520 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16521 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16522 } 16523 return false; 16524 } 16525 } 16526 16527 public void getUsageStatsIfNoPackageUsageInfo() { 16528 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16529 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16530 if (usm == null) { 16531 throw new IllegalStateException("UsageStatsManager must be initialized"); 16532 } 16533 long now = System.currentTimeMillis(); 16534 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16535 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16536 String packageName = entry.getKey(); 16537 PackageParser.Package pkg = mPackages.get(packageName); 16538 if (pkg == null) { 16539 continue; 16540 } 16541 UsageStats usage = entry.getValue(); 16542 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16543 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16544 } 16545 } 16546 } 16547 16548 /** 16549 * Check and throw if the given before/after packages would be considered a 16550 * downgrade. 16551 */ 16552 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16553 throws PackageManagerException { 16554 if (after.versionCode < before.mVersionCode) { 16555 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16556 "Update version code " + after.versionCode + " is older than current " 16557 + before.mVersionCode); 16558 } else if (after.versionCode == before.mVersionCode) { 16559 if (after.baseRevisionCode < before.baseRevisionCode) { 16560 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16561 "Update base revision code " + after.baseRevisionCode 16562 + " is older than current " + before.baseRevisionCode); 16563 } 16564 16565 if (!ArrayUtils.isEmpty(after.splitNames)) { 16566 for (int i = 0; i < after.splitNames.length; i++) { 16567 final String splitName = after.splitNames[i]; 16568 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16569 if (j != -1) { 16570 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16571 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16572 "Update split " + splitName + " revision code " 16573 + after.splitRevisionCodes[i] + " is older than current " 16574 + before.splitRevisionCodes[j]); 16575 } 16576 } 16577 } 16578 } 16579 } 16580 } 16581 16582 private static class MoveCallbacks extends Handler { 16583 private static final int MSG_CREATED = 1; 16584 private static final int MSG_STATUS_CHANGED = 2; 16585 16586 private final RemoteCallbackList<IPackageMoveObserver> 16587 mCallbacks = new RemoteCallbackList<>(); 16588 16589 private final SparseIntArray mLastStatus = new SparseIntArray(); 16590 16591 public MoveCallbacks(Looper looper) { 16592 super(looper); 16593 } 16594 16595 public void register(IPackageMoveObserver callback) { 16596 mCallbacks.register(callback); 16597 } 16598 16599 public void unregister(IPackageMoveObserver callback) { 16600 mCallbacks.unregister(callback); 16601 } 16602 16603 @Override 16604 public void handleMessage(Message msg) { 16605 final SomeArgs args = (SomeArgs) msg.obj; 16606 final int n = mCallbacks.beginBroadcast(); 16607 for (int i = 0; i < n; i++) { 16608 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16609 try { 16610 invokeCallback(callback, msg.what, args); 16611 } catch (RemoteException ignored) { 16612 } 16613 } 16614 mCallbacks.finishBroadcast(); 16615 args.recycle(); 16616 } 16617 16618 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16619 throws RemoteException { 16620 switch (what) { 16621 case MSG_CREATED: { 16622 callback.onCreated(args.argi1, (Bundle) args.arg2); 16623 break; 16624 } 16625 case MSG_STATUS_CHANGED: { 16626 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16627 break; 16628 } 16629 } 16630 } 16631 16632 private void notifyCreated(int moveId, Bundle extras) { 16633 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16634 16635 final SomeArgs args = SomeArgs.obtain(); 16636 args.argi1 = moveId; 16637 args.arg2 = extras; 16638 obtainMessage(MSG_CREATED, args).sendToTarget(); 16639 } 16640 16641 private void notifyStatusChanged(int moveId, int status) { 16642 notifyStatusChanged(moveId, status, -1); 16643 } 16644 16645 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16646 Slog.v(TAG, "Move " + moveId + " status " + status); 16647 16648 final SomeArgs args = SomeArgs.obtain(); 16649 args.argi1 = moveId; 16650 args.argi2 = status; 16651 args.arg3 = estMillis; 16652 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16653 16654 synchronized (mLastStatus) { 16655 mLastStatus.put(moveId, status); 16656 } 16657 } 16658 } 16659 16660 private final class OnPermissionChangeListeners extends Handler { 16661 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16662 16663 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16664 new RemoteCallbackList<>(); 16665 16666 public OnPermissionChangeListeners(Looper looper) { 16667 super(looper); 16668 } 16669 16670 @Override 16671 public void handleMessage(Message msg) { 16672 switch (msg.what) { 16673 case MSG_ON_PERMISSIONS_CHANGED: { 16674 final int uid = msg.arg1; 16675 handleOnPermissionsChanged(uid); 16676 } break; 16677 } 16678 } 16679 16680 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16681 mPermissionListeners.register(listener); 16682 16683 } 16684 16685 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16686 mPermissionListeners.unregister(listener); 16687 } 16688 16689 public void onPermissionsChanged(int uid) { 16690 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16691 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16692 } 16693 } 16694 16695 private void handleOnPermissionsChanged(int uid) { 16696 final int count = mPermissionListeners.beginBroadcast(); 16697 try { 16698 for (int i = 0; i < count; i++) { 16699 IOnPermissionsChangeListener callback = mPermissionListeners 16700 .getBroadcastItem(i); 16701 try { 16702 callback.onPermissionsChanged(uid); 16703 } catch (RemoteException e) { 16704 Log.e(TAG, "Permission listener is dead", e); 16705 } 16706 } 16707 } finally { 16708 mPermissionListeners.finishBroadcast(); 16709 } 16710 } 16711 } 16712 16713 private class PackageManagerInternalImpl extends PackageManagerInternal { 16714 @Override 16715 public void setLocationPackagesProvider(PackagesProvider provider) { 16716 synchronized (mPackages) { 16717 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16718 } 16719 } 16720 16721 @Override 16722 public void setImePackagesProvider(PackagesProvider provider) { 16723 synchronized (mPackages) { 16724 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16725 } 16726 } 16727 16728 @Override 16729 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16730 synchronized (mPackages) { 16731 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16732 } 16733 } 16734 16735 @Override 16736 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16737 synchronized (mPackages) { 16738 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16739 } 16740 } 16741 16742 @Override 16743 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16744 synchronized (mPackages) { 16745 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16746 } 16747 } 16748 16749 @Override 16750 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16751 synchronized (mPackages) { 16752 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16753 } 16754 } 16755 16756 @Override 16757 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16758 synchronized (mPackages) { 16759 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16760 } 16761 } 16762 16763 @Override 16764 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16765 synchronized (mPackages) { 16766 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16767 packageName, userId); 16768 } 16769 } 16770 16771 @Override 16772 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16773 synchronized (mPackages) { 16774 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16775 packageName, userId); 16776 } 16777 } 16778 @Override 16779 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16780 synchronized (mPackages) { 16781 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16782 packageName, userId); 16783 } 16784 } 16785 } 16786 16787 @Override 16788 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16789 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16790 synchronized (mPackages) { 16791 final long identity = Binder.clearCallingIdentity(); 16792 try { 16793 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16794 packageNames, userId); 16795 } finally { 16796 Binder.restoreCallingIdentity(identity); 16797 } 16798 } 16799 } 16800 16801 private static void enforceSystemOrPhoneCaller(String tag) { 16802 int callingUid = Binder.getCallingUid(); 16803 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16804 throw new SecurityException( 16805 "Cannot call " + tag + " from UID " + callingUid); 16806 } 16807 } 16808} 16809