PackageManagerService.java revision f38c4ee9030b68c2f2b00d376c7d4a05a58a818a
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.MATCH_ALL; 60import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 61import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 62import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 63import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 64import static android.content.pm.PackageManager.PERMISSION_DENIED; 65import static android.content.pm.PackageManager.PERMISSION_GRANTED; 66import static android.content.pm.PackageParser.isApkFile; 67import static android.os.Process.PACKAGE_INFO_GID; 68import static android.os.Process.SYSTEM_UID; 69import static android.system.OsConstants.O_CREAT; 70import static android.system.OsConstants.O_RDWR; 71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 75import static com.android.internal.util.ArrayUtils.appendInt; 76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 84 85import android.Manifest; 86import android.app.ActivityManager; 87import android.app.ActivityManagerNative; 88import android.app.AppGlobals; 89import android.app.IActivityManager; 90import android.app.admin.IDevicePolicyManager; 91import android.app.backup.IBackupManager; 92import android.app.usage.UsageStats; 93import android.app.usage.UsageStatsManager; 94import android.content.BroadcastReceiver; 95import android.content.ComponentName; 96import android.content.Context; 97import android.content.IIntentReceiver; 98import android.content.Intent; 99import android.content.IntentFilter; 100import android.content.IntentSender; 101import android.content.IntentSender.SendIntentException; 102import android.content.ServiceConnection; 103import android.content.pm.ActivityInfo; 104import android.content.pm.ApplicationInfo; 105import android.content.pm.FeatureInfo; 106import android.content.pm.IOnPermissionsChangeListener; 107import android.content.pm.IPackageDataObserver; 108import android.content.pm.IPackageDeleteObserver; 109import android.content.pm.IPackageDeleteObserver2; 110import android.content.pm.IPackageInstallObserver2; 111import android.content.pm.IPackageInstaller; 112import android.content.pm.IPackageManager; 113import android.content.pm.IPackageMoveObserver; 114import android.content.pm.IPackageStatsObserver; 115import android.content.pm.InstrumentationInfo; 116import android.content.pm.IntentFilterVerificationInfo; 117import android.content.pm.KeySet; 118import android.content.pm.ManifestDigest; 119import android.content.pm.PackageCleanItem; 120import android.content.pm.PackageInfo; 121import android.content.pm.PackageInfoLite; 122import android.content.pm.PackageInstaller; 123import android.content.pm.PackageManager; 124import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 125import android.content.pm.PackageManagerInternal; 126import android.content.pm.PackageParser; 127import android.content.pm.PackageParser.ActivityIntentInfo; 128import android.content.pm.PackageParser.PackageLite; 129import android.content.pm.PackageParser.PackageParserException; 130import android.content.pm.PackageStats; 131import android.content.pm.PackageUserState; 132import android.content.pm.ParceledListSlice; 133import android.content.pm.PermissionGroupInfo; 134import android.content.pm.PermissionInfo; 135import android.content.pm.ProviderInfo; 136import android.content.pm.ResolveInfo; 137import android.content.pm.ServiceInfo; 138import android.content.pm.Signature; 139import android.content.pm.UserInfo; 140import android.content.pm.VerificationParams; 141import android.content.pm.VerifierDeviceIdentity; 142import android.content.pm.VerifierInfo; 143import android.content.res.Resources; 144import android.hardware.display.DisplayManager; 145import android.net.Uri; 146import android.os.Debug; 147import android.os.Binder; 148import android.os.Build; 149import android.os.Bundle; 150import android.os.Environment; 151import android.os.Environment.UserEnvironment; 152import android.os.FileUtils; 153import android.os.Handler; 154import android.os.IBinder; 155import android.os.Looper; 156import android.os.Message; 157import android.os.Parcel; 158import android.os.ParcelFileDescriptor; 159import android.os.Process; 160import android.os.RemoteCallbackList; 161import android.os.RemoteException; 162import android.os.SELinux; 163import android.os.ServiceManager; 164import android.os.SystemClock; 165import android.os.SystemProperties; 166import android.os.UserHandle; 167import android.os.UserManager; 168import android.os.storage.IMountService; 169import android.os.storage.MountServiceInternal; 170import android.os.storage.StorageEventListener; 171import android.os.storage.StorageManager; 172import android.os.storage.VolumeInfo; 173import android.os.storage.VolumeRecord; 174import android.security.KeyStore; 175import android.security.SystemKeyStore; 176import android.system.ErrnoException; 177import android.system.Os; 178import android.system.StructStat; 179import android.text.TextUtils; 180import android.text.format.DateUtils; 181import android.util.ArrayMap; 182import android.util.ArraySet; 183import android.util.AtomicFile; 184import android.util.DisplayMetrics; 185import android.util.EventLog; 186import android.util.ExceptionUtils; 187import android.util.Log; 188import android.util.LogPrinter; 189import android.util.MathUtils; 190import android.util.PrintStreamPrinter; 191import android.util.Slog; 192import android.util.SparseArray; 193import android.util.SparseBooleanArray; 194import android.util.SparseIntArray; 195import android.util.Xml; 196import android.view.Display; 197 198import dalvik.system.DexFile; 199import dalvik.system.VMRuntime; 200 201import libcore.io.IoUtils; 202import libcore.util.EmptyArray; 203 204import com.android.internal.R; 205import com.android.internal.annotations.GuardedBy; 206import com.android.internal.app.IMediaContainerService; 207import com.android.internal.app.ResolverActivity; 208import com.android.internal.content.NativeLibraryHelper; 209import com.android.internal.content.PackageHelper; 210import com.android.internal.os.IParcelFileDescriptorFactory; 211import com.android.internal.os.SomeArgs; 212import com.android.internal.os.Zygote; 213import com.android.internal.util.ArrayUtils; 214import com.android.internal.util.FastPrintWriter; 215import com.android.internal.util.FastXmlSerializer; 216import com.android.internal.util.IndentingPrintWriter; 217import com.android.internal.util.Preconditions; 218import com.android.server.EventLogTags; 219import com.android.server.FgThread; 220import com.android.server.IntentResolver; 221import com.android.server.LocalServices; 222import com.android.server.ServiceThread; 223import com.android.server.SystemConfig; 224import com.android.server.Watchdog; 225import com.android.server.pm.PermissionsState.PermissionState; 226import com.android.server.pm.Settings.DatabaseVersion; 227import com.android.server.storage.DeviceStorageMonitorInternal; 228 229import org.xmlpull.v1.XmlPullParser; 230import org.xmlpull.v1.XmlPullParserException; 231import org.xmlpull.v1.XmlSerializer; 232 233import java.io.BufferedInputStream; 234import java.io.BufferedOutputStream; 235import java.io.BufferedReader; 236import java.io.ByteArrayInputStream; 237import java.io.ByteArrayOutputStream; 238import java.io.File; 239import java.io.FileDescriptor; 240import java.io.FileNotFoundException; 241import java.io.FileOutputStream; 242import java.io.FileReader; 243import java.io.FilenameFilter; 244import java.io.IOException; 245import java.io.InputStream; 246import java.io.PrintWriter; 247import java.nio.charset.StandardCharsets; 248import java.security.NoSuchAlgorithmException; 249import java.security.PublicKey; 250import java.security.cert.CertificateEncodingException; 251import java.security.cert.CertificateException; 252import java.text.SimpleDateFormat; 253import java.util.ArrayList; 254import java.util.Arrays; 255import java.util.Collection; 256import java.util.Collections; 257import java.util.Comparator; 258import java.util.Date; 259import java.util.Iterator; 260import java.util.List; 261import java.util.Map; 262import java.util.Objects; 263import java.util.Set; 264import java.util.concurrent.CountDownLatch; 265import java.util.concurrent.TimeUnit; 266import java.util.concurrent.atomic.AtomicBoolean; 267import java.util.concurrent.atomic.AtomicInteger; 268import java.util.concurrent.atomic.AtomicLong; 269 270/** 271 * Keep track of all those .apks everywhere. 272 * 273 * This is very central to the platform's security; please run the unit 274 * tests whenever making modifications here: 275 * 276mmm frameworks/base/tests/AndroidTests 277adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 278adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 279 * 280 * {@hide} 281 */ 282public class PackageManagerService extends IPackageManager.Stub { 283 static final String TAG = "PackageManager"; 284 static final boolean DEBUG_SETTINGS = false; 285 static final boolean DEBUG_PREFERRED = false; 286 static final boolean DEBUG_UPGRADE = false; 287 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 288 private static final boolean DEBUG_BACKUP = false; 289 private static final boolean DEBUG_INSTALL = false; 290 private static final boolean DEBUG_REMOVE = false; 291 private static final boolean DEBUG_BROADCASTS = false; 292 private static final boolean DEBUG_SHOW_INFO = false; 293 private static final boolean DEBUG_PACKAGE_INFO = false; 294 private static final boolean DEBUG_INTENT_MATCHING = false; 295 private static final boolean DEBUG_PACKAGE_SCANNING = false; 296 private static final boolean DEBUG_VERIFY = false; 297 private static final boolean DEBUG_DEXOPT = false; 298 private static final boolean DEBUG_ABI_SELECTION = false; 299 300 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 301 302 private static final int RADIO_UID = Process.PHONE_UID; 303 private static final int LOG_UID = Process.LOG_UID; 304 private static final int NFC_UID = Process.NFC_UID; 305 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 306 private static final int SHELL_UID = Process.SHELL_UID; 307 308 // Cap the size of permission trees that 3rd party apps can define 309 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 310 311 // Suffix used during package installation when copying/moving 312 // package apks to install directory. 313 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 314 315 static final int SCAN_NO_DEX = 1<<1; 316 static final int SCAN_FORCE_DEX = 1<<2; 317 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 318 static final int SCAN_NEW_INSTALL = 1<<4; 319 static final int SCAN_NO_PATHS = 1<<5; 320 static final int SCAN_UPDATE_TIME = 1<<6; 321 static final int SCAN_DEFER_DEX = 1<<7; 322 static final int SCAN_BOOTING = 1<<8; 323 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 324 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 325 static final int SCAN_REQUIRE_KNOWN = 1<<12; 326 static final int SCAN_MOVE = 1<<13; 327 static final int SCAN_INITIAL = 1<<14; 328 329 static final int REMOVE_CHATTY = 1<<16; 330 331 private static final int[] EMPTY_INT_ARRAY = new int[0]; 332 333 /** 334 * Timeout (in milliseconds) after which the watchdog should declare that 335 * our handler thread is wedged. The usual default for such things is one 336 * minute but we sometimes do very lengthy I/O operations on this thread, 337 * such as installing multi-gigabyte applications, so ours needs to be longer. 338 */ 339 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 340 341 /** 342 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 343 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 344 * settings entry if available, otherwise we use the hardcoded default. If it's been 345 * more than this long since the last fstrim, we force one during the boot sequence. 346 * 347 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 348 * one gets run at the next available charging+idle time. This final mandatory 349 * no-fstrim check kicks in only of the other scheduling criteria is never met. 350 */ 351 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 352 353 /** 354 * Whether verification is enabled by default. 355 */ 356 private static final boolean DEFAULT_VERIFY_ENABLE = true; 357 358 /** 359 * The default maximum time to wait for the verification agent to return in 360 * milliseconds. 361 */ 362 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 363 364 /** 365 * The default response for package verification timeout. 366 * 367 * This can be either PackageManager.VERIFICATION_ALLOW or 368 * PackageManager.VERIFICATION_REJECT. 369 */ 370 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 371 372 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 373 374 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 375 DEFAULT_CONTAINER_PACKAGE, 376 "com.android.defcontainer.DefaultContainerService"); 377 378 private static final String KILL_APP_REASON_GIDS_CHANGED = 379 "permission grant or revoke changed gids"; 380 381 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 382 "permissions revoked"; 383 384 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 385 386 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 387 388 /** Permission grant: not grant the permission. */ 389 private static final int GRANT_DENIED = 1; 390 391 /** Permission grant: grant the permission as an install permission. */ 392 private static final int GRANT_INSTALL = 2; 393 394 /** Permission grant: grant the permission as an install permission for a legacy app. */ 395 private static final int GRANT_INSTALL_LEGACY = 3; 396 397 /** Permission grant: grant the permission as a runtime one. */ 398 private static final int GRANT_RUNTIME = 4; 399 400 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 401 private static final int GRANT_UPGRADE = 5; 402 403 /** Canonical intent used to identify what counts as a "web browser" app */ 404 private static final Intent sBrowserIntent; 405 static { 406 sBrowserIntent = new Intent(); 407 sBrowserIntent.setAction(Intent.ACTION_VIEW); 408 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 409 sBrowserIntent.setData(Uri.parse("http:")); 410 } 411 412 final ServiceThread mHandlerThread; 413 414 final PackageHandler mHandler; 415 416 /** 417 * Messages for {@link #mHandler} that need to wait for system ready before 418 * being dispatched. 419 */ 420 private ArrayList<Message> mPostSystemReadyMessages; 421 422 final int mSdkVersion = Build.VERSION.SDK_INT; 423 424 final Context mContext; 425 final boolean mFactoryTest; 426 final boolean mOnlyCore; 427 final boolean mLazyDexOpt; 428 final long mDexOptLRUThresholdInMills; 429 final DisplayMetrics mMetrics; 430 final int mDefParseFlags; 431 final String[] mSeparateProcesses; 432 final boolean mIsUpgrade; 433 434 // This is where all application persistent data goes. 435 final File mAppDataDir; 436 437 // This is where all application persistent data goes for secondary users. 438 final File mUserAppDataDir; 439 440 /** The location for ASEC container files on internal storage. */ 441 final String mAsecInternalPath; 442 443 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 444 // LOCK HELD. Can be called with mInstallLock held. 445 @GuardedBy("mInstallLock") 446 final Installer mInstaller; 447 448 /** Directory where installed third-party apps stored */ 449 final File mAppInstallDir; 450 451 /** 452 * Directory to which applications installed internally have their 453 * 32 bit native libraries copied. 454 */ 455 private File mAppLib32InstallDir; 456 457 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 458 // apps. 459 final File mDrmAppPrivateInstallDir; 460 461 // ---------------------------------------------------------------- 462 463 // Lock for state used when installing and doing other long running 464 // operations. Methods that must be called with this lock held have 465 // the suffix "LI". 466 final Object mInstallLock = new Object(); 467 468 // ---------------------------------------------------------------- 469 470 // Keys are String (package name), values are Package. This also serves 471 // as the lock for the global state. Methods that must be called with 472 // this lock held have the prefix "LP". 473 @GuardedBy("mPackages") 474 final ArrayMap<String, PackageParser.Package> mPackages = 475 new ArrayMap<String, PackageParser.Package>(); 476 477 // Tracks available target package names -> overlay package paths. 478 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 479 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 480 481 /** 482 * Tracks new system packages [receiving in an OTA] that we expect to 483 * find updated user-installed versions. Keys are package name, values 484 * are package location. 485 */ 486 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 487 488 final Settings mSettings; 489 boolean mRestoredSettings; 490 491 // System configuration read by SystemConfig. 492 final int[] mGlobalGids; 493 final SparseArray<ArraySet<String>> mSystemPermissions; 494 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 495 496 // If mac_permissions.xml was found for seinfo labeling. 497 boolean mFoundPolicyFile; 498 499 // If a recursive restorecon of /data/data/<pkg> is needed. 500 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 501 502 public static final class SharedLibraryEntry { 503 public final String path; 504 public final String apk; 505 506 SharedLibraryEntry(String _path, String _apk) { 507 path = _path; 508 apk = _apk; 509 } 510 } 511 512 // Currently known shared libraries. 513 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 514 new ArrayMap<String, SharedLibraryEntry>(); 515 516 // All available activities, for your resolving pleasure. 517 final ActivityIntentResolver mActivities = 518 new ActivityIntentResolver(); 519 520 // All available receivers, for your resolving pleasure. 521 final ActivityIntentResolver mReceivers = 522 new ActivityIntentResolver(); 523 524 // All available services, for your resolving pleasure. 525 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 526 527 // All available providers, for your resolving pleasure. 528 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 529 530 // Mapping from provider base names (first directory in content URI codePath) 531 // to the provider information. 532 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 533 new ArrayMap<String, PackageParser.Provider>(); 534 535 // Mapping from instrumentation class names to info about them. 536 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 537 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 538 539 // Mapping from permission names to info about them. 540 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 541 new ArrayMap<String, PackageParser.PermissionGroup>(); 542 543 // Packages whose data we have transfered into another package, thus 544 // should no longer exist. 545 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 546 547 // Broadcast actions that are only available to the system. 548 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 549 550 /** List of packages waiting for verification. */ 551 final SparseArray<PackageVerificationState> mPendingVerification 552 = new SparseArray<PackageVerificationState>(); 553 554 /** Set of packages associated with each app op permission. */ 555 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 556 557 final PackageInstallerService mInstallerService; 558 559 private final PackageDexOptimizer mPackageDexOptimizer; 560 561 private AtomicInteger mNextMoveId = new AtomicInteger(); 562 private final MoveCallbacks mMoveCallbacks; 563 564 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 565 566 // Cache of users who need badging. 567 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 568 569 /** Token for keys in mPendingVerification. */ 570 private int mPendingVerificationToken = 0; 571 572 volatile boolean mSystemReady; 573 volatile boolean mSafeMode; 574 volatile boolean mHasSystemUidErrors; 575 576 ApplicationInfo mAndroidApplication; 577 final ActivityInfo mResolveActivity = new ActivityInfo(); 578 final ResolveInfo mResolveInfo = new ResolveInfo(); 579 ComponentName mResolveComponentName; 580 PackageParser.Package mPlatformPackage; 581 ComponentName mCustomResolverComponentName; 582 583 boolean mResolverReplaced = false; 584 585 private final ComponentName mIntentFilterVerifierComponent; 586 private int mIntentFilterVerificationToken = 0; 587 588 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 589 = new SparseArray<IntentFilterVerificationState>(); 590 591 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 592 new DefaultPermissionGrantPolicy(this); 593 594 private static class IFVerificationParams { 595 PackageParser.Package pkg; 596 boolean replacing; 597 int userId; 598 int verifierUid; 599 600 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 601 int _userId, int _verifierUid) { 602 pkg = _pkg; 603 replacing = _replacing; 604 userId = _userId; 605 replacing = _replacing; 606 verifierUid = _verifierUid; 607 } 608 } 609 610 private interface IntentFilterVerifier<T extends IntentFilter> { 611 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 612 T filter, String packageName); 613 void startVerifications(int userId); 614 void receiveVerificationResponse(int verificationId); 615 } 616 617 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 618 private Context mContext; 619 private ComponentName mIntentFilterVerifierComponent; 620 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 621 622 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 623 mContext = context; 624 mIntentFilterVerifierComponent = verifierComponent; 625 } 626 627 private String getDefaultScheme() { 628 return IntentFilter.SCHEME_HTTPS; 629 } 630 631 @Override 632 public void startVerifications(int userId) { 633 // Launch verifications requests 634 int count = mCurrentIntentFilterVerifications.size(); 635 for (int n=0; n<count; n++) { 636 int verificationId = mCurrentIntentFilterVerifications.get(n); 637 final IntentFilterVerificationState ivs = 638 mIntentFilterVerificationStates.get(verificationId); 639 640 String packageName = ivs.getPackageName(); 641 642 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 643 final int filterCount = filters.size(); 644 ArraySet<String> domainsSet = new ArraySet<>(); 645 for (int m=0; m<filterCount; m++) { 646 PackageParser.ActivityIntentInfo filter = filters.get(m); 647 domainsSet.addAll(filter.getHostsList()); 648 } 649 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 650 synchronized (mPackages) { 651 if (mSettings.createIntentFilterVerificationIfNeededLPw( 652 packageName, domainsList) != null) { 653 scheduleWriteSettingsLocked(); 654 } 655 } 656 sendVerificationRequest(userId, verificationId, ivs); 657 } 658 mCurrentIntentFilterVerifications.clear(); 659 } 660 661 private void sendVerificationRequest(int userId, int verificationId, 662 IntentFilterVerificationState ivs) { 663 664 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 665 verificationIntent.putExtra( 666 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 667 verificationId); 668 verificationIntent.putExtra( 669 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 670 getDefaultScheme()); 671 verificationIntent.putExtra( 672 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 673 ivs.getHostsString()); 674 verificationIntent.putExtra( 675 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 676 ivs.getPackageName()); 677 verificationIntent.setComponent(mIntentFilterVerifierComponent); 678 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 679 680 UserHandle user = new UserHandle(userId); 681 mContext.sendBroadcastAsUser(verificationIntent, user); 682 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 683 "Sending IntentFilter verification broadcast"); 684 } 685 686 public void receiveVerificationResponse(int verificationId) { 687 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 688 689 final boolean verified = ivs.isVerified(); 690 691 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 692 final int count = filters.size(); 693 if (DEBUG_DOMAIN_VERIFICATION) { 694 Slog.i(TAG, "Received verification response " + verificationId 695 + " for " + count + " filters, verified=" + verified); 696 } 697 for (int n=0; n<count; n++) { 698 PackageParser.ActivityIntentInfo filter = filters.get(n); 699 filter.setVerified(verified); 700 701 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 702 + " verified with result:" + verified + " and hosts:" 703 + ivs.getHostsString()); 704 } 705 706 mIntentFilterVerificationStates.remove(verificationId); 707 708 final String packageName = ivs.getPackageName(); 709 IntentFilterVerificationInfo ivi = null; 710 711 synchronized (mPackages) { 712 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 713 } 714 if (ivi == null) { 715 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 716 + verificationId + " packageName:" + packageName); 717 return; 718 } 719 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 720 "Updating IntentFilterVerificationInfo for package " + packageName 721 +" verificationId:" + verificationId); 722 723 synchronized (mPackages) { 724 if (verified) { 725 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 726 } else { 727 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 728 } 729 scheduleWriteSettingsLocked(); 730 731 final int userId = ivs.getUserId(); 732 if (userId != UserHandle.USER_ALL) { 733 final int userStatus = 734 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 735 736 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 737 boolean needUpdate = false; 738 739 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 740 // already been set by the User thru the Disambiguation dialog 741 switch (userStatus) { 742 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 743 if (verified) { 744 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 745 } else { 746 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 747 } 748 needUpdate = true; 749 break; 750 751 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 752 if (verified) { 753 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 754 needUpdate = true; 755 } 756 break; 757 758 default: 759 // Nothing to do 760 } 761 762 if (needUpdate) { 763 mSettings.updateIntentFilterVerificationStatusLPw( 764 packageName, updatedStatus, userId); 765 scheduleWritePackageRestrictionsLocked(userId); 766 } 767 } 768 } 769 } 770 771 @Override 772 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 773 ActivityIntentInfo filter, String packageName) { 774 if (!hasValidDomains(filter)) { 775 return false; 776 } 777 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 778 if (ivs == null) { 779 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 780 packageName); 781 } 782 if (DEBUG_DOMAIN_VERIFICATION) { 783 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 784 } 785 ivs.addFilter(filter); 786 return true; 787 } 788 789 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 790 int userId, int verificationId, String packageName) { 791 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 792 verifierUid, userId, packageName); 793 ivs.setPendingState(); 794 synchronized (mPackages) { 795 mIntentFilterVerificationStates.append(verificationId, ivs); 796 mCurrentIntentFilterVerifications.add(verificationId); 797 } 798 return ivs; 799 } 800 } 801 802 private static boolean hasValidDomains(ActivityIntentInfo filter) { 803 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 804 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 805 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 806 } 807 808 private IntentFilterVerifier mIntentFilterVerifier; 809 810 // Set of pending broadcasts for aggregating enable/disable of components. 811 static class PendingPackageBroadcasts { 812 // for each user id, a map of <package name -> components within that package> 813 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 814 815 public PendingPackageBroadcasts() { 816 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 817 } 818 819 public ArrayList<String> get(int userId, String packageName) { 820 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 821 return packages.get(packageName); 822 } 823 824 public void put(int userId, String packageName, ArrayList<String> components) { 825 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 826 packages.put(packageName, components); 827 } 828 829 public void remove(int userId, String packageName) { 830 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 831 if (packages != null) { 832 packages.remove(packageName); 833 } 834 } 835 836 public void remove(int userId) { 837 mUidMap.remove(userId); 838 } 839 840 public int userIdCount() { 841 return mUidMap.size(); 842 } 843 844 public int userIdAt(int n) { 845 return mUidMap.keyAt(n); 846 } 847 848 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 849 return mUidMap.get(userId); 850 } 851 852 public int size() { 853 // total number of pending broadcast entries across all userIds 854 int num = 0; 855 for (int i = 0; i< mUidMap.size(); i++) { 856 num += mUidMap.valueAt(i).size(); 857 } 858 return num; 859 } 860 861 public void clear() { 862 mUidMap.clear(); 863 } 864 865 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 866 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 867 if (map == null) { 868 map = new ArrayMap<String, ArrayList<String>>(); 869 mUidMap.put(userId, map); 870 } 871 return map; 872 } 873 } 874 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 875 876 // Service Connection to remote media container service to copy 877 // package uri's from external media onto secure containers 878 // or internal storage. 879 private IMediaContainerService mContainerService = null; 880 881 static final int SEND_PENDING_BROADCAST = 1; 882 static final int MCS_BOUND = 3; 883 static final int END_COPY = 4; 884 static final int INIT_COPY = 5; 885 static final int MCS_UNBIND = 6; 886 static final int START_CLEANING_PACKAGE = 7; 887 static final int FIND_INSTALL_LOC = 8; 888 static final int POST_INSTALL = 9; 889 static final int MCS_RECONNECT = 10; 890 static final int MCS_GIVE_UP = 11; 891 static final int UPDATED_MEDIA_STATUS = 12; 892 static final int WRITE_SETTINGS = 13; 893 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 894 static final int PACKAGE_VERIFIED = 15; 895 static final int CHECK_PENDING_VERIFICATION = 16; 896 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 897 static final int INTENT_FILTER_VERIFIED = 18; 898 899 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 900 901 // Delay time in millisecs 902 static final int BROADCAST_DELAY = 10 * 1000; 903 904 static UserManagerService sUserManager; 905 906 // Stores a list of users whose package restrictions file needs to be updated 907 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 908 909 final private DefaultContainerConnection mDefContainerConn = 910 new DefaultContainerConnection(); 911 class DefaultContainerConnection implements ServiceConnection { 912 public void onServiceConnected(ComponentName name, IBinder service) { 913 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 914 IMediaContainerService imcs = 915 IMediaContainerService.Stub.asInterface(service); 916 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 917 } 918 919 public void onServiceDisconnected(ComponentName name) { 920 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 921 } 922 } 923 924 // Recordkeeping of restore-after-install operations that are currently in flight 925 // between the Package Manager and the Backup Manager 926 class PostInstallData { 927 public InstallArgs args; 928 public PackageInstalledInfo res; 929 930 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 931 args = _a; 932 res = _r; 933 } 934 } 935 936 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 937 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 938 939 // XML tags for backup/restore of various bits of state 940 private static final String TAG_PREFERRED_BACKUP = "pa"; 941 private static final String TAG_DEFAULT_APPS = "da"; 942 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 943 944 final String mRequiredVerifierPackage; 945 final String mRequiredInstallerPackage; 946 947 private final PackageUsage mPackageUsage = new PackageUsage(); 948 949 private class PackageUsage { 950 private static final int WRITE_INTERVAL 951 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 952 953 private final Object mFileLock = new Object(); 954 private final AtomicLong mLastWritten = new AtomicLong(0); 955 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 956 957 private boolean mIsHistoricalPackageUsageAvailable = true; 958 959 boolean isHistoricalPackageUsageAvailable() { 960 return mIsHistoricalPackageUsageAvailable; 961 } 962 963 void write(boolean force) { 964 if (force) { 965 writeInternal(); 966 return; 967 } 968 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 969 && !DEBUG_DEXOPT) { 970 return; 971 } 972 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 973 new Thread("PackageUsage_DiskWriter") { 974 @Override 975 public void run() { 976 try { 977 writeInternal(); 978 } finally { 979 mBackgroundWriteRunning.set(false); 980 } 981 } 982 }.start(); 983 } 984 } 985 986 private void writeInternal() { 987 synchronized (mPackages) { 988 synchronized (mFileLock) { 989 AtomicFile file = getFile(); 990 FileOutputStream f = null; 991 try { 992 f = file.startWrite(); 993 BufferedOutputStream out = new BufferedOutputStream(f); 994 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 995 StringBuilder sb = new StringBuilder(); 996 for (PackageParser.Package pkg : mPackages.values()) { 997 if (pkg.mLastPackageUsageTimeInMills == 0) { 998 continue; 999 } 1000 sb.setLength(0); 1001 sb.append(pkg.packageName); 1002 sb.append(' '); 1003 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1004 sb.append('\n'); 1005 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1006 } 1007 out.flush(); 1008 file.finishWrite(f); 1009 } catch (IOException e) { 1010 if (f != null) { 1011 file.failWrite(f); 1012 } 1013 Log.e(TAG, "Failed to write package usage times", e); 1014 } 1015 } 1016 } 1017 mLastWritten.set(SystemClock.elapsedRealtime()); 1018 } 1019 1020 void readLP() { 1021 synchronized (mFileLock) { 1022 AtomicFile file = getFile(); 1023 BufferedInputStream in = null; 1024 try { 1025 in = new BufferedInputStream(file.openRead()); 1026 StringBuffer sb = new StringBuffer(); 1027 while (true) { 1028 String packageName = readToken(in, sb, ' '); 1029 if (packageName == null) { 1030 break; 1031 } 1032 String timeInMillisString = readToken(in, sb, '\n'); 1033 if (timeInMillisString == null) { 1034 throw new IOException("Failed to find last usage time for package " 1035 + packageName); 1036 } 1037 PackageParser.Package pkg = mPackages.get(packageName); 1038 if (pkg == null) { 1039 continue; 1040 } 1041 long timeInMillis; 1042 try { 1043 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1044 } catch (NumberFormatException e) { 1045 throw new IOException("Failed to parse " + timeInMillisString 1046 + " as a long.", e); 1047 } 1048 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1049 } 1050 } catch (FileNotFoundException expected) { 1051 mIsHistoricalPackageUsageAvailable = false; 1052 } catch (IOException e) { 1053 Log.w(TAG, "Failed to read package usage times", e); 1054 } finally { 1055 IoUtils.closeQuietly(in); 1056 } 1057 } 1058 mLastWritten.set(SystemClock.elapsedRealtime()); 1059 } 1060 1061 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1062 throws IOException { 1063 sb.setLength(0); 1064 while (true) { 1065 int ch = in.read(); 1066 if (ch == -1) { 1067 if (sb.length() == 0) { 1068 return null; 1069 } 1070 throw new IOException("Unexpected EOF"); 1071 } 1072 if (ch == endOfToken) { 1073 return sb.toString(); 1074 } 1075 sb.append((char)ch); 1076 } 1077 } 1078 1079 private AtomicFile getFile() { 1080 File dataDir = Environment.getDataDirectory(); 1081 File systemDir = new File(dataDir, "system"); 1082 File fname = new File(systemDir, "package-usage.list"); 1083 return new AtomicFile(fname); 1084 } 1085 } 1086 1087 class PackageHandler extends Handler { 1088 private boolean mBound = false; 1089 final ArrayList<HandlerParams> mPendingInstalls = 1090 new ArrayList<HandlerParams>(); 1091 1092 private boolean connectToService() { 1093 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1094 " DefaultContainerService"); 1095 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1096 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1097 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1098 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1099 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1100 mBound = true; 1101 return true; 1102 } 1103 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1104 return false; 1105 } 1106 1107 private void disconnectService() { 1108 mContainerService = null; 1109 mBound = false; 1110 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1111 mContext.unbindService(mDefContainerConn); 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1113 } 1114 1115 PackageHandler(Looper looper) { 1116 super(looper); 1117 } 1118 1119 public void handleMessage(Message msg) { 1120 try { 1121 doHandleMessage(msg); 1122 } finally { 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1124 } 1125 } 1126 1127 void doHandleMessage(Message msg) { 1128 switch (msg.what) { 1129 case INIT_COPY: { 1130 HandlerParams params = (HandlerParams) msg.obj; 1131 int idx = mPendingInstalls.size(); 1132 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1133 // If a bind was already initiated we dont really 1134 // need to do anything. The pending install 1135 // will be processed later on. 1136 if (!mBound) { 1137 // If this is the only one pending we might 1138 // have to bind to the service again. 1139 if (!connectToService()) { 1140 Slog.e(TAG, "Failed to bind to media container service"); 1141 params.serviceError(); 1142 return; 1143 } else { 1144 // Once we bind to the service, the first 1145 // pending request will be processed. 1146 mPendingInstalls.add(idx, params); 1147 } 1148 } else { 1149 mPendingInstalls.add(idx, params); 1150 // Already bound to the service. Just make 1151 // sure we trigger off processing the first request. 1152 if (idx == 0) { 1153 mHandler.sendEmptyMessage(MCS_BOUND); 1154 } 1155 } 1156 break; 1157 } 1158 case MCS_BOUND: { 1159 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1160 if (msg.obj != null) { 1161 mContainerService = (IMediaContainerService) msg.obj; 1162 } 1163 if (mContainerService == null) { 1164 if (!mBound) { 1165 // Something seriously wrong since we are not bound and we are not 1166 // waiting for connection. Bail out. 1167 Slog.e(TAG, "Cannot bind to media container service"); 1168 for (HandlerParams params : mPendingInstalls) { 1169 // Indicate service bind error 1170 params.serviceError(); 1171 } 1172 mPendingInstalls.clear(); 1173 } else { 1174 Slog.w(TAG, "Waiting to connect to media container service"); 1175 } 1176 } else if (mPendingInstalls.size() > 0) { 1177 HandlerParams params = mPendingInstalls.get(0); 1178 if (params != null) { 1179 if (params.startCopy()) { 1180 // We are done... look for more work or to 1181 // go idle. 1182 if (DEBUG_SD_INSTALL) Log.i(TAG, 1183 "Checking for more work or unbind..."); 1184 // Delete pending install 1185 if (mPendingInstalls.size() > 0) { 1186 mPendingInstalls.remove(0); 1187 } 1188 if (mPendingInstalls.size() == 0) { 1189 if (mBound) { 1190 if (DEBUG_SD_INSTALL) Log.i(TAG, 1191 "Posting delayed MCS_UNBIND"); 1192 removeMessages(MCS_UNBIND); 1193 Message ubmsg = obtainMessage(MCS_UNBIND); 1194 // Unbind after a little delay, to avoid 1195 // continual thrashing. 1196 sendMessageDelayed(ubmsg, 10000); 1197 } 1198 } else { 1199 // There are more pending requests in queue. 1200 // Just post MCS_BOUND message to trigger processing 1201 // of next pending install. 1202 if (DEBUG_SD_INSTALL) Log.i(TAG, 1203 "Posting MCS_BOUND for next work"); 1204 mHandler.sendEmptyMessage(MCS_BOUND); 1205 } 1206 } 1207 } 1208 } else { 1209 // Should never happen ideally. 1210 Slog.w(TAG, "Empty queue"); 1211 } 1212 break; 1213 } 1214 case MCS_RECONNECT: { 1215 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1216 if (mPendingInstalls.size() > 0) { 1217 if (mBound) { 1218 disconnectService(); 1219 } 1220 if (!connectToService()) { 1221 Slog.e(TAG, "Failed to bind to media container service"); 1222 for (HandlerParams params : mPendingInstalls) { 1223 // Indicate service bind error 1224 params.serviceError(); 1225 } 1226 mPendingInstalls.clear(); 1227 } 1228 } 1229 break; 1230 } 1231 case MCS_UNBIND: { 1232 // If there is no actual work left, then time to unbind. 1233 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1234 1235 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1236 if (mBound) { 1237 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1238 1239 disconnectService(); 1240 } 1241 } else if (mPendingInstalls.size() > 0) { 1242 // There are more pending requests in queue. 1243 // Just post MCS_BOUND message to trigger processing 1244 // of next pending install. 1245 mHandler.sendEmptyMessage(MCS_BOUND); 1246 } 1247 1248 break; 1249 } 1250 case MCS_GIVE_UP: { 1251 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1252 mPendingInstalls.remove(0); 1253 break; 1254 } 1255 case SEND_PENDING_BROADCAST: { 1256 String packages[]; 1257 ArrayList<String> components[]; 1258 int size = 0; 1259 int uids[]; 1260 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1261 synchronized (mPackages) { 1262 if (mPendingBroadcasts == null) { 1263 return; 1264 } 1265 size = mPendingBroadcasts.size(); 1266 if (size <= 0) { 1267 // Nothing to be done. Just return 1268 return; 1269 } 1270 packages = new String[size]; 1271 components = new ArrayList[size]; 1272 uids = new int[size]; 1273 int i = 0; // filling out the above arrays 1274 1275 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1276 int packageUserId = mPendingBroadcasts.userIdAt(n); 1277 Iterator<Map.Entry<String, ArrayList<String>>> it 1278 = mPendingBroadcasts.packagesForUserId(packageUserId) 1279 .entrySet().iterator(); 1280 while (it.hasNext() && i < size) { 1281 Map.Entry<String, ArrayList<String>> ent = it.next(); 1282 packages[i] = ent.getKey(); 1283 components[i] = ent.getValue(); 1284 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1285 uids[i] = (ps != null) 1286 ? UserHandle.getUid(packageUserId, ps.appId) 1287 : -1; 1288 i++; 1289 } 1290 } 1291 size = i; 1292 mPendingBroadcasts.clear(); 1293 } 1294 // Send broadcasts 1295 for (int i = 0; i < size; i++) { 1296 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1297 } 1298 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1299 break; 1300 } 1301 case START_CLEANING_PACKAGE: { 1302 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1303 final String packageName = (String)msg.obj; 1304 final int userId = msg.arg1; 1305 final boolean andCode = msg.arg2 != 0; 1306 synchronized (mPackages) { 1307 if (userId == UserHandle.USER_ALL) { 1308 int[] users = sUserManager.getUserIds(); 1309 for (int user : users) { 1310 mSettings.addPackageToCleanLPw( 1311 new PackageCleanItem(user, packageName, andCode)); 1312 } 1313 } else { 1314 mSettings.addPackageToCleanLPw( 1315 new PackageCleanItem(userId, packageName, andCode)); 1316 } 1317 } 1318 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1319 startCleaningPackages(); 1320 } break; 1321 case POST_INSTALL: { 1322 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1323 PostInstallData data = mRunningInstalls.get(msg.arg1); 1324 mRunningInstalls.delete(msg.arg1); 1325 boolean deleteOld = false; 1326 1327 if (data != null) { 1328 InstallArgs args = data.args; 1329 PackageInstalledInfo res = data.res; 1330 1331 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1332 final String packageName = res.pkg.applicationInfo.packageName; 1333 res.removedInfo.sendBroadcast(false, true, false); 1334 Bundle extras = new Bundle(1); 1335 extras.putInt(Intent.EXTRA_UID, res.uid); 1336 1337 // Now that we successfully installed the package, grant runtime 1338 // permissions if requested before broadcasting the install. 1339 if ((args.installFlags 1340 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1341 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1342 args.installGrantPermissions); 1343 } 1344 1345 // Determine the set of users who are adding this 1346 // package for the first time vs. those who are seeing 1347 // an update. 1348 int[] firstUsers; 1349 int[] updateUsers = new int[0]; 1350 if (res.origUsers == null || res.origUsers.length == 0) { 1351 firstUsers = res.newUsers; 1352 } else { 1353 firstUsers = new int[0]; 1354 for (int i=0; i<res.newUsers.length; i++) { 1355 int user = res.newUsers[i]; 1356 boolean isNew = true; 1357 for (int j=0; j<res.origUsers.length; j++) { 1358 if (res.origUsers[j] == user) { 1359 isNew = false; 1360 break; 1361 } 1362 } 1363 if (isNew) { 1364 int[] newFirst = new int[firstUsers.length+1]; 1365 System.arraycopy(firstUsers, 0, newFirst, 0, 1366 firstUsers.length); 1367 newFirst[firstUsers.length] = user; 1368 firstUsers = newFirst; 1369 } else { 1370 int[] newUpdate = new int[updateUsers.length+1]; 1371 System.arraycopy(updateUsers, 0, newUpdate, 0, 1372 updateUsers.length); 1373 newUpdate[updateUsers.length] = user; 1374 updateUsers = newUpdate; 1375 } 1376 } 1377 } 1378 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1379 packageName, extras, null, null, firstUsers); 1380 final boolean update = res.removedInfo.removedPackage != null; 1381 if (update) { 1382 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1383 } 1384 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1385 packageName, extras, null, null, updateUsers); 1386 if (update) { 1387 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1388 packageName, extras, null, null, updateUsers); 1389 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1390 null, null, packageName, null, updateUsers); 1391 1392 // treat asec-hosted packages like removable media on upgrade 1393 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1394 if (DEBUG_INSTALL) { 1395 Slog.i(TAG, "upgrading pkg " + res.pkg 1396 + " is ASEC-hosted -> AVAILABLE"); 1397 } 1398 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1399 ArrayList<String> pkgList = new ArrayList<String>(1); 1400 pkgList.add(packageName); 1401 sendResourcesChangedBroadcast(true, true, 1402 pkgList,uidArray, null); 1403 } 1404 } 1405 if (res.removedInfo.args != null) { 1406 // Remove the replaced package's older resources safely now 1407 deleteOld = true; 1408 } 1409 1410 // If this app is a browser and it's newly-installed for some 1411 // users, clear any default-browser state in those users 1412 if (firstUsers.length > 0) { 1413 // the app's nature doesn't depend on the user, so we can just 1414 // check its browser nature in any user and generalize. 1415 if (packageIsBrowser(packageName, firstUsers[0])) { 1416 synchronized (mPackages) { 1417 for (int userId : firstUsers) { 1418 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1419 } 1420 } 1421 } 1422 } 1423 // Log current value of "unknown sources" setting 1424 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1425 getUnknownSourcesSettings()); 1426 } 1427 // Force a gc to clear up things 1428 Runtime.getRuntime().gc(); 1429 // We delete after a gc for applications on sdcard. 1430 if (deleteOld) { 1431 synchronized (mInstallLock) { 1432 res.removedInfo.args.doPostDeleteLI(true); 1433 } 1434 } 1435 if (args.observer != null) { 1436 try { 1437 Bundle extras = extrasForInstallResult(res); 1438 args.observer.onPackageInstalled(res.name, res.returnCode, 1439 res.returnMsg, extras); 1440 } catch (RemoteException e) { 1441 Slog.i(TAG, "Observer no longer exists."); 1442 } 1443 } 1444 } else { 1445 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1446 } 1447 } break; 1448 case UPDATED_MEDIA_STATUS: { 1449 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1450 boolean reportStatus = msg.arg1 == 1; 1451 boolean doGc = msg.arg2 == 1; 1452 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1453 if (doGc) { 1454 // Force a gc to clear up stale containers. 1455 Runtime.getRuntime().gc(); 1456 } 1457 if (msg.obj != null) { 1458 @SuppressWarnings("unchecked") 1459 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1460 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1461 // Unload containers 1462 unloadAllContainers(args); 1463 } 1464 if (reportStatus) { 1465 try { 1466 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1467 PackageHelper.getMountService().finishMediaUpdate(); 1468 } catch (RemoteException e) { 1469 Log.e(TAG, "MountService not running?"); 1470 } 1471 } 1472 } break; 1473 case WRITE_SETTINGS: { 1474 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1475 synchronized (mPackages) { 1476 removeMessages(WRITE_SETTINGS); 1477 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1478 mSettings.writeLPr(); 1479 mDirtyUsers.clear(); 1480 } 1481 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1482 } break; 1483 case WRITE_PACKAGE_RESTRICTIONS: { 1484 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1485 synchronized (mPackages) { 1486 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1487 for (int userId : mDirtyUsers) { 1488 mSettings.writePackageRestrictionsLPr(userId); 1489 } 1490 mDirtyUsers.clear(); 1491 } 1492 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1493 } break; 1494 case CHECK_PENDING_VERIFICATION: { 1495 final int verificationId = msg.arg1; 1496 final PackageVerificationState state = mPendingVerification.get(verificationId); 1497 1498 if ((state != null) && !state.timeoutExtended()) { 1499 final InstallArgs args = state.getInstallArgs(); 1500 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1501 1502 Slog.i(TAG, "Verification timed out for " + originUri); 1503 mPendingVerification.remove(verificationId); 1504 1505 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1506 1507 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1508 Slog.i(TAG, "Continuing with installation of " + originUri); 1509 state.setVerifierResponse(Binder.getCallingUid(), 1510 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1511 broadcastPackageVerified(verificationId, originUri, 1512 PackageManager.VERIFICATION_ALLOW, 1513 state.getInstallArgs().getUser()); 1514 try { 1515 ret = args.copyApk(mContainerService, true); 1516 } catch (RemoteException e) { 1517 Slog.e(TAG, "Could not contact the ContainerService"); 1518 } 1519 } else { 1520 broadcastPackageVerified(verificationId, originUri, 1521 PackageManager.VERIFICATION_REJECT, 1522 state.getInstallArgs().getUser()); 1523 } 1524 1525 processPendingInstall(args, ret); 1526 mHandler.sendEmptyMessage(MCS_UNBIND); 1527 } 1528 break; 1529 } 1530 case PACKAGE_VERIFIED: { 1531 final int verificationId = msg.arg1; 1532 1533 final PackageVerificationState state = mPendingVerification.get(verificationId); 1534 if (state == null) { 1535 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1536 break; 1537 } 1538 1539 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1540 1541 state.setVerifierResponse(response.callerUid, response.code); 1542 1543 if (state.isVerificationComplete()) { 1544 mPendingVerification.remove(verificationId); 1545 1546 final InstallArgs args = state.getInstallArgs(); 1547 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1548 1549 int ret; 1550 if (state.isInstallAllowed()) { 1551 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1552 broadcastPackageVerified(verificationId, originUri, 1553 response.code, state.getInstallArgs().getUser()); 1554 try { 1555 ret = args.copyApk(mContainerService, true); 1556 } catch (RemoteException e) { 1557 Slog.e(TAG, "Could not contact the ContainerService"); 1558 } 1559 } else { 1560 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1561 } 1562 1563 processPendingInstall(args, ret); 1564 1565 mHandler.sendEmptyMessage(MCS_UNBIND); 1566 } 1567 1568 break; 1569 } 1570 case START_INTENT_FILTER_VERIFICATIONS: { 1571 IFVerificationParams params = (IFVerificationParams) msg.obj; 1572 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1573 params.replacing, params.pkg); 1574 break; 1575 } 1576 case INTENT_FILTER_VERIFIED: { 1577 final int verificationId = msg.arg1; 1578 1579 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1580 verificationId); 1581 if (state == null) { 1582 Slog.w(TAG, "Invalid IntentFilter verification token " 1583 + verificationId + " received"); 1584 break; 1585 } 1586 1587 final int userId = state.getUserId(); 1588 1589 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1590 "Processing IntentFilter verification with token:" 1591 + verificationId + " and userId:" + userId); 1592 1593 final IntentFilterVerificationResponse response = 1594 (IntentFilterVerificationResponse) msg.obj; 1595 1596 state.setVerifierResponse(response.callerUid, response.code); 1597 1598 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1599 "IntentFilter verification with token:" + verificationId 1600 + " and userId:" + userId 1601 + " is settings verifier response with response code:" 1602 + response.code); 1603 1604 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1605 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1606 + response.getFailedDomainsString()); 1607 } 1608 1609 if (state.isVerificationComplete()) { 1610 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1611 } else { 1612 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1613 "IntentFilter verification with token:" + verificationId 1614 + " was not said to be complete"); 1615 } 1616 1617 break; 1618 } 1619 } 1620 } 1621 } 1622 1623 private StorageEventListener mStorageListener = new StorageEventListener() { 1624 @Override 1625 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1626 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1627 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1628 final String volumeUuid = vol.getFsUuid(); 1629 1630 // Clean up any users or apps that were removed or recreated 1631 // while this volume was missing 1632 reconcileUsers(volumeUuid); 1633 reconcileApps(volumeUuid); 1634 1635 // Clean up any install sessions that expired or were 1636 // cancelled while this volume was missing 1637 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1638 1639 loadPrivatePackages(vol); 1640 1641 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1642 unloadPrivatePackages(vol); 1643 } 1644 } 1645 1646 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1647 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1648 updateExternalMediaStatus(true, false); 1649 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1650 updateExternalMediaStatus(false, false); 1651 } 1652 } 1653 } 1654 1655 @Override 1656 public void onVolumeForgotten(String fsUuid) { 1657 // Remove any apps installed on the forgotten volume 1658 synchronized (mPackages) { 1659 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1660 for (PackageSetting ps : packages) { 1661 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1662 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1663 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1664 } 1665 1666 mSettings.writeLPr(); 1667 } 1668 } 1669 }; 1670 1671 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1672 String[] grantedPermissions) { 1673 if (userId >= UserHandle.USER_OWNER) { 1674 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1675 } else if (userId == UserHandle.USER_ALL) { 1676 final int[] userIds; 1677 synchronized (mPackages) { 1678 userIds = UserManagerService.getInstance().getUserIds(); 1679 } 1680 for (int someUserId : userIds) { 1681 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1682 } 1683 } 1684 1685 // We could have touched GID membership, so flush out packages.list 1686 synchronized (mPackages) { 1687 mSettings.writePackageListLPr(); 1688 } 1689 } 1690 1691 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1692 String[] grantedPermissions) { 1693 SettingBase sb = (SettingBase) pkg.mExtras; 1694 if (sb == null) { 1695 return; 1696 } 1697 1698 PermissionsState permissionsState = sb.getPermissionsState(); 1699 1700 for (String permission : pkg.requestedPermissions) { 1701 BasePermission bp = mSettings.mPermissions.get(permission); 1702 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1703 || ArrayUtils.contains(grantedPermissions, permission))) { 1704 permissionsState.grantRuntimePermission(bp, userId); 1705 } 1706 } 1707 } 1708 1709 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1710 Bundle extras = null; 1711 switch (res.returnCode) { 1712 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1713 extras = new Bundle(); 1714 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1715 res.origPermission); 1716 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1717 res.origPackage); 1718 break; 1719 } 1720 case PackageManager.INSTALL_SUCCEEDED: { 1721 extras = new Bundle(); 1722 extras.putBoolean(Intent.EXTRA_REPLACING, 1723 res.removedInfo != null && res.removedInfo.removedPackage != null); 1724 break; 1725 } 1726 } 1727 return extras; 1728 } 1729 1730 void scheduleWriteSettingsLocked() { 1731 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1732 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1733 } 1734 } 1735 1736 void scheduleWritePackageRestrictionsLocked(int userId) { 1737 if (!sUserManager.exists(userId)) return; 1738 mDirtyUsers.add(userId); 1739 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1740 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1741 } 1742 } 1743 1744 public static PackageManagerService main(Context context, Installer installer, 1745 boolean factoryTest, boolean onlyCore) { 1746 PackageManagerService m = new PackageManagerService(context, installer, 1747 factoryTest, onlyCore); 1748 ServiceManager.addService("package", m); 1749 return m; 1750 } 1751 1752 static String[] splitString(String str, char sep) { 1753 int count = 1; 1754 int i = 0; 1755 while ((i=str.indexOf(sep, i)) >= 0) { 1756 count++; 1757 i++; 1758 } 1759 1760 String[] res = new String[count]; 1761 i=0; 1762 count = 0; 1763 int lastI=0; 1764 while ((i=str.indexOf(sep, i)) >= 0) { 1765 res[count] = str.substring(lastI, i); 1766 count++; 1767 i++; 1768 lastI = i; 1769 } 1770 res[count] = str.substring(lastI, str.length()); 1771 return res; 1772 } 1773 1774 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1775 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1776 Context.DISPLAY_SERVICE); 1777 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1778 } 1779 1780 public PackageManagerService(Context context, Installer installer, 1781 boolean factoryTest, boolean onlyCore) { 1782 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1783 SystemClock.uptimeMillis()); 1784 1785 if (mSdkVersion <= 0) { 1786 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1787 } 1788 1789 mContext = context; 1790 mFactoryTest = factoryTest; 1791 mOnlyCore = onlyCore; 1792 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1793 mMetrics = new DisplayMetrics(); 1794 mSettings = new Settings(mPackages); 1795 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1796 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1797 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1798 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1799 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1800 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1801 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1802 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1803 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1804 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1805 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1806 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1807 1808 // TODO: add a property to control this? 1809 long dexOptLRUThresholdInMinutes; 1810 if (mLazyDexOpt) { 1811 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1812 } else { 1813 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1814 } 1815 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1816 1817 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1818 if (separateProcesses != null && separateProcesses.length() > 0) { 1819 if ("*".equals(separateProcesses)) { 1820 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1821 mSeparateProcesses = null; 1822 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1823 } else { 1824 mDefParseFlags = 0; 1825 mSeparateProcesses = separateProcesses.split(","); 1826 Slog.w(TAG, "Running with debug.separate_processes: " 1827 + separateProcesses); 1828 } 1829 } else { 1830 mDefParseFlags = 0; 1831 mSeparateProcesses = null; 1832 } 1833 1834 mInstaller = installer; 1835 mPackageDexOptimizer = new PackageDexOptimizer(this); 1836 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1837 1838 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1839 FgThread.get().getLooper()); 1840 1841 getDefaultDisplayMetrics(context, mMetrics); 1842 1843 SystemConfig systemConfig = SystemConfig.getInstance(); 1844 mGlobalGids = systemConfig.getGlobalGids(); 1845 mSystemPermissions = systemConfig.getSystemPermissions(); 1846 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1847 1848 synchronized (mInstallLock) { 1849 // writer 1850 synchronized (mPackages) { 1851 mHandlerThread = new ServiceThread(TAG, 1852 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1853 mHandlerThread.start(); 1854 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1855 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1856 1857 File dataDir = Environment.getDataDirectory(); 1858 mAppDataDir = new File(dataDir, "data"); 1859 mAppInstallDir = new File(dataDir, "app"); 1860 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1861 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1862 mUserAppDataDir = new File(dataDir, "user"); 1863 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1864 1865 sUserManager = new UserManagerService(context, this, 1866 mInstallLock, mPackages); 1867 1868 // Propagate permission configuration in to package manager. 1869 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1870 = systemConfig.getPermissions(); 1871 for (int i=0; i<permConfig.size(); i++) { 1872 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1873 BasePermission bp = mSettings.mPermissions.get(perm.name); 1874 if (bp == null) { 1875 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1876 mSettings.mPermissions.put(perm.name, bp); 1877 } 1878 if (perm.gids != null) { 1879 bp.setGids(perm.gids, perm.perUser); 1880 } 1881 } 1882 1883 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1884 for (int i=0; i<libConfig.size(); i++) { 1885 mSharedLibraries.put(libConfig.keyAt(i), 1886 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1887 } 1888 1889 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1890 1891 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1892 mSdkVersion, mOnlyCore); 1893 1894 String customResolverActivity = Resources.getSystem().getString( 1895 R.string.config_customResolverActivity); 1896 if (TextUtils.isEmpty(customResolverActivity)) { 1897 customResolverActivity = null; 1898 } else { 1899 mCustomResolverComponentName = ComponentName.unflattenFromString( 1900 customResolverActivity); 1901 } 1902 1903 long startTime = SystemClock.uptimeMillis(); 1904 1905 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1906 startTime); 1907 1908 // Set flag to monitor and not change apk file paths when 1909 // scanning install directories. 1910 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1911 1912 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1913 1914 /** 1915 * Add everything in the in the boot class path to the 1916 * list of process files because dexopt will have been run 1917 * if necessary during zygote startup. 1918 */ 1919 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1920 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1921 1922 if (bootClassPath != null) { 1923 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1924 for (String element : bootClassPathElements) { 1925 alreadyDexOpted.add(element); 1926 } 1927 } else { 1928 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1929 } 1930 1931 if (systemServerClassPath != null) { 1932 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1933 for (String element : systemServerClassPathElements) { 1934 alreadyDexOpted.add(element); 1935 } 1936 } else { 1937 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1938 } 1939 1940 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1941 final String[] dexCodeInstructionSets = 1942 getDexCodeInstructionSets( 1943 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1944 1945 /** 1946 * Ensure all external libraries have had dexopt run on them. 1947 */ 1948 if (mSharedLibraries.size() > 0) { 1949 // NOTE: For now, we're compiling these system "shared libraries" 1950 // (and framework jars) into all available architectures. It's possible 1951 // to compile them only when we come across an app that uses them (there's 1952 // already logic for that in scanPackageLI) but that adds some complexity. 1953 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1954 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1955 final String lib = libEntry.path; 1956 if (lib == null) { 1957 continue; 1958 } 1959 1960 try { 1961 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1962 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1963 alreadyDexOpted.add(lib); 1964 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1965 } 1966 } catch (FileNotFoundException e) { 1967 Slog.w(TAG, "Library not found: " + lib); 1968 } catch (IOException e) { 1969 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1970 + e.getMessage()); 1971 } 1972 } 1973 } 1974 } 1975 1976 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1977 1978 // Gross hack for now: we know this file doesn't contain any 1979 // code, so don't dexopt it to avoid the resulting log spew. 1980 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1981 1982 // Gross hack for now: we know this file is only part of 1983 // the boot class path for art, so don't dexopt it to 1984 // avoid the resulting log spew. 1985 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1986 1987 /** 1988 * There are a number of commands implemented in Java, which 1989 * we currently need to do the dexopt on so that they can be 1990 * run from a non-root shell. 1991 */ 1992 String[] frameworkFiles = frameworkDir.list(); 1993 if (frameworkFiles != null) { 1994 // TODO: We could compile these only for the most preferred ABI. We should 1995 // first double check that the dex files for these commands are not referenced 1996 // by other system apps. 1997 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1998 for (int i=0; i<frameworkFiles.length; i++) { 1999 File libPath = new File(frameworkDir, frameworkFiles[i]); 2000 String path = libPath.getPath(); 2001 // Skip the file if we already did it. 2002 if (alreadyDexOpted.contains(path)) { 2003 continue; 2004 } 2005 // Skip the file if it is not a type we want to dexopt. 2006 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2007 continue; 2008 } 2009 try { 2010 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2011 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2012 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2013 } 2014 } catch (FileNotFoundException e) { 2015 Slog.w(TAG, "Jar not found: " + path); 2016 } catch (IOException e) { 2017 Slog.w(TAG, "Exception reading jar: " + path, e); 2018 } 2019 } 2020 } 2021 } 2022 2023 // Collect vendor overlay packages. 2024 // (Do this before scanning any apps.) 2025 // For security and version matching reason, only consider 2026 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2027 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2028 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2029 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2030 2031 // Find base frameworks (resource packages without code). 2032 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2033 | PackageParser.PARSE_IS_SYSTEM_DIR 2034 | PackageParser.PARSE_IS_PRIVILEGED, 2035 scanFlags | SCAN_NO_DEX, 0); 2036 2037 // Collected privileged system packages. 2038 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2039 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2040 | PackageParser.PARSE_IS_SYSTEM_DIR 2041 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2042 2043 // Collect ordinary system packages. 2044 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2045 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2046 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2047 2048 // Collect all vendor packages. 2049 File vendorAppDir = new File("/vendor/app"); 2050 try { 2051 vendorAppDir = vendorAppDir.getCanonicalFile(); 2052 } catch (IOException e) { 2053 // failed to look up canonical path, continue with original one 2054 } 2055 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2056 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2057 2058 // Collect all OEM packages. 2059 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2060 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2061 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2062 2063 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2064 mInstaller.moveFiles(); 2065 2066 // Prune any system packages that no longer exist. 2067 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2068 if (!mOnlyCore) { 2069 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2070 while (psit.hasNext()) { 2071 PackageSetting ps = psit.next(); 2072 2073 /* 2074 * If this is not a system app, it can't be a 2075 * disable system app. 2076 */ 2077 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2078 continue; 2079 } 2080 2081 /* 2082 * If the package is scanned, it's not erased. 2083 */ 2084 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2085 if (scannedPkg != null) { 2086 /* 2087 * If the system app is both scanned and in the 2088 * disabled packages list, then it must have been 2089 * added via OTA. Remove it from the currently 2090 * scanned package so the previously user-installed 2091 * application can be scanned. 2092 */ 2093 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2094 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2095 + ps.name + "; removing system app. Last known codePath=" 2096 + ps.codePathString + ", installStatus=" + ps.installStatus 2097 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2098 + scannedPkg.mVersionCode); 2099 removePackageLI(ps, true); 2100 mExpectingBetter.put(ps.name, ps.codePath); 2101 } 2102 2103 continue; 2104 } 2105 2106 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2107 psit.remove(); 2108 logCriticalInfo(Log.WARN, "System package " + ps.name 2109 + " no longer exists; wiping its data"); 2110 removeDataDirsLI(null, ps.name); 2111 } else { 2112 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2113 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2114 possiblyDeletedUpdatedSystemApps.add(ps.name); 2115 } 2116 } 2117 } 2118 } 2119 2120 //look for any incomplete package installations 2121 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2122 //clean up list 2123 for(int i = 0; i < deletePkgsList.size(); i++) { 2124 //clean up here 2125 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2126 } 2127 //delete tmp files 2128 deleteTempPackageFiles(); 2129 2130 // Remove any shared userIDs that have no associated packages 2131 mSettings.pruneSharedUsersLPw(); 2132 2133 if (!mOnlyCore) { 2134 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2135 SystemClock.uptimeMillis()); 2136 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2137 2138 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2139 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2140 2141 /** 2142 * Remove disable package settings for any updated system 2143 * apps that were removed via an OTA. If they're not a 2144 * previously-updated app, remove them completely. 2145 * Otherwise, just revoke their system-level permissions. 2146 */ 2147 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2148 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2149 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2150 2151 String msg; 2152 if (deletedPkg == null) { 2153 msg = "Updated system package " + deletedAppName 2154 + " no longer exists; wiping its data"; 2155 removeDataDirsLI(null, deletedAppName); 2156 } else { 2157 msg = "Updated system app + " + deletedAppName 2158 + " no longer present; removing system privileges for " 2159 + deletedAppName; 2160 2161 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2162 2163 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2164 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2165 } 2166 logCriticalInfo(Log.WARN, msg); 2167 } 2168 2169 /** 2170 * Make sure all system apps that we expected to appear on 2171 * the userdata partition actually showed up. If they never 2172 * appeared, crawl back and revive the system version. 2173 */ 2174 for (int i = 0; i < mExpectingBetter.size(); i++) { 2175 final String packageName = mExpectingBetter.keyAt(i); 2176 if (!mPackages.containsKey(packageName)) { 2177 final File scanFile = mExpectingBetter.valueAt(i); 2178 2179 logCriticalInfo(Log.WARN, "Expected better " + packageName 2180 + " but never showed up; reverting to system"); 2181 2182 final int reparseFlags; 2183 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2184 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2185 | PackageParser.PARSE_IS_SYSTEM_DIR 2186 | PackageParser.PARSE_IS_PRIVILEGED; 2187 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2188 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2189 | PackageParser.PARSE_IS_SYSTEM_DIR; 2190 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2191 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2192 | PackageParser.PARSE_IS_SYSTEM_DIR; 2193 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2194 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2195 | PackageParser.PARSE_IS_SYSTEM_DIR; 2196 } else { 2197 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2198 continue; 2199 } 2200 2201 mSettings.enableSystemPackageLPw(packageName); 2202 2203 try { 2204 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2205 } catch (PackageManagerException e) { 2206 Slog.e(TAG, "Failed to parse original system package: " 2207 + e.getMessage()); 2208 } 2209 } 2210 } 2211 } 2212 mExpectingBetter.clear(); 2213 2214 // Now that we know all of the shared libraries, update all clients to have 2215 // the correct library paths. 2216 updateAllSharedLibrariesLPw(); 2217 2218 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2219 // NOTE: We ignore potential failures here during a system scan (like 2220 // the rest of the commands above) because there's precious little we 2221 // can do about it. A settings error is reported, though. 2222 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2223 false /* force dexopt */, false /* defer dexopt */); 2224 } 2225 2226 // Now that we know all the packages we are keeping, 2227 // read and update their last usage times. 2228 mPackageUsage.readLP(); 2229 2230 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2231 SystemClock.uptimeMillis()); 2232 Slog.i(TAG, "Time to scan packages: " 2233 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2234 + " seconds"); 2235 2236 // If the platform SDK has changed since the last time we booted, 2237 // we need to re-grant app permission to catch any new ones that 2238 // appear. This is really a hack, and means that apps can in some 2239 // cases get permissions that the user didn't initially explicitly 2240 // allow... it would be nice to have some better way to handle 2241 // this situation. 2242 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2243 != mSdkVersion; 2244 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2245 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2246 + "; regranting permissions for internal storage"); 2247 mSettings.mInternalSdkPlatform = mSdkVersion; 2248 2249 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2250 | (regrantPermissions 2251 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2252 : 0)); 2253 2254 // If this is the first boot, and it is a normal boot, then 2255 // we need to initialize the default preferred apps. 2256 if (!mRestoredSettings && !onlyCore) { 2257 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2258 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2259 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2260 } 2261 2262 // If this is first boot after an OTA, and a normal boot, then 2263 // we need to clear code cache directories. 2264 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2265 if (mIsUpgrade && !onlyCore) { 2266 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2267 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2268 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2269 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2270 } 2271 mSettings.mFingerprint = Build.FINGERPRINT; 2272 } 2273 2274 checkDefaultBrowser(); 2275 2276 // All the changes are done during package scanning. 2277 mSettings.updateInternalDatabaseVersion(); 2278 2279 // can downgrade to reader 2280 mSettings.writeLPr(); 2281 2282 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2283 SystemClock.uptimeMillis()); 2284 2285 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2286 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2287 2288 mInstallerService = new PackageInstallerService(context, this); 2289 2290 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2291 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2292 mIntentFilterVerifierComponent); 2293 2294 } // synchronized (mPackages) 2295 } // synchronized (mInstallLock) 2296 2297 // Now after opening every single application zip, make sure they 2298 // are all flushed. Not really needed, but keeps things nice and 2299 // tidy. 2300 Runtime.getRuntime().gc(); 2301 2302 // Expose private service for system components to use. 2303 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2304 } 2305 2306 @Override 2307 public boolean isFirstBoot() { 2308 return !mRestoredSettings; 2309 } 2310 2311 @Override 2312 public boolean isOnlyCoreApps() { 2313 return mOnlyCore; 2314 } 2315 2316 @Override 2317 public boolean isUpgrade() { 2318 return mIsUpgrade; 2319 } 2320 2321 private String getRequiredVerifierLPr() { 2322 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2323 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2324 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2325 2326 String requiredVerifier = null; 2327 2328 final int N = receivers.size(); 2329 for (int i = 0; i < N; i++) { 2330 final ResolveInfo info = receivers.get(i); 2331 2332 if (info.activityInfo == null) { 2333 continue; 2334 } 2335 2336 final String packageName = info.activityInfo.packageName; 2337 2338 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2339 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2340 continue; 2341 } 2342 2343 if (requiredVerifier != null) { 2344 throw new RuntimeException("There can be only one required verifier"); 2345 } 2346 2347 requiredVerifier = packageName; 2348 } 2349 2350 return requiredVerifier; 2351 } 2352 2353 private String getRequiredInstallerLPr() { 2354 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2355 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2356 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2357 2358 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2359 PACKAGE_MIME_TYPE, 0, 0); 2360 2361 String requiredInstaller = null; 2362 2363 final int N = installers.size(); 2364 for (int i = 0; i < N; i++) { 2365 final ResolveInfo info = installers.get(i); 2366 final String packageName = info.activityInfo.packageName; 2367 2368 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2369 continue; 2370 } 2371 2372 if (requiredInstaller != null) { 2373 throw new RuntimeException("There must be one required installer"); 2374 } 2375 2376 requiredInstaller = packageName; 2377 } 2378 2379 if (requiredInstaller == null) { 2380 throw new RuntimeException("There must be one required installer"); 2381 } 2382 2383 return requiredInstaller; 2384 } 2385 2386 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2387 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2388 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2389 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2390 2391 ComponentName verifierComponentName = null; 2392 2393 int priority = -1000; 2394 final int N = receivers.size(); 2395 for (int i = 0; i < N; i++) { 2396 final ResolveInfo info = receivers.get(i); 2397 2398 if (info.activityInfo == null) { 2399 continue; 2400 } 2401 2402 final String packageName = info.activityInfo.packageName; 2403 2404 final PackageSetting ps = mSettings.mPackages.get(packageName); 2405 if (ps == null) { 2406 continue; 2407 } 2408 2409 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2410 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2411 continue; 2412 } 2413 2414 // Select the IntentFilterVerifier with the highest priority 2415 if (priority < info.priority) { 2416 priority = info.priority; 2417 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2418 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2419 + verifierComponentName + " with priority: " + info.priority); 2420 } 2421 } 2422 2423 return verifierComponentName; 2424 } 2425 2426 private void primeDomainVerificationsLPw(int userId) { 2427 if (DEBUG_DOMAIN_VERIFICATION) { 2428 Slog.d(TAG, "Priming domain verifications in user " + userId); 2429 } 2430 2431 SystemConfig systemConfig = SystemConfig.getInstance(); 2432 ArraySet<String> packages = systemConfig.getLinkedApps(); 2433 ArraySet<String> domains = new ArraySet<String>(); 2434 2435 for (String packageName : packages) { 2436 PackageParser.Package pkg = mPackages.get(packageName); 2437 if (pkg != null) { 2438 if (!pkg.isSystemApp()) { 2439 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2440 continue; 2441 } 2442 2443 domains.clear(); 2444 for (PackageParser.Activity a : pkg.activities) { 2445 for (ActivityIntentInfo filter : a.intents) { 2446 if (hasValidDomains(filter)) { 2447 domains.addAll(filter.getHostsList()); 2448 } 2449 } 2450 } 2451 2452 if (domains.size() > 0) { 2453 if (DEBUG_DOMAIN_VERIFICATION) { 2454 Slog.v(TAG, " + " + packageName); 2455 } 2456 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2457 // state w.r.t. the formal app-linkage "no verification attempted" state; 2458 // and then 'always' in the per-user state actually used for intent resolution. 2459 final IntentFilterVerificationInfo ivi; 2460 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2461 new ArrayList<String>(domains)); 2462 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2463 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2464 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2465 } else { 2466 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2467 + "' does not handle web links"); 2468 } 2469 } else { 2470 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2471 } 2472 } 2473 2474 scheduleWritePackageRestrictionsLocked(userId); 2475 scheduleWriteSettingsLocked(); 2476 } 2477 2478 private void applyFactoryDefaultBrowserLPw(int userId) { 2479 // The default browser app's package name is stored in a string resource, 2480 // with a product-specific overlay used for vendor customization. 2481 String browserPkg = mContext.getResources().getString( 2482 com.android.internal.R.string.default_browser); 2483 if (!TextUtils.isEmpty(browserPkg)) { 2484 // non-empty string => required to be a known package 2485 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2486 if (ps == null) { 2487 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2488 browserPkg = null; 2489 } else { 2490 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2491 } 2492 } 2493 2494 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2495 // default. If there's more than one, just leave everything alone. 2496 if (browserPkg == null) { 2497 calculateDefaultBrowserLPw(userId); 2498 } 2499 } 2500 2501 private void calculateDefaultBrowserLPw(int userId) { 2502 List<String> allBrowsers = resolveAllBrowserApps(userId); 2503 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2504 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2505 } 2506 2507 private List<String> resolveAllBrowserApps(int userId) { 2508 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2509 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2510 PackageManager.MATCH_ALL, userId); 2511 2512 final int count = list.size(); 2513 List<String> result = new ArrayList<String>(count); 2514 for (int i=0; i<count; i++) { 2515 ResolveInfo info = list.get(i); 2516 if (info.activityInfo == null 2517 || !info.handleAllWebDataURI 2518 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2519 || result.contains(info.activityInfo.packageName)) { 2520 continue; 2521 } 2522 result.add(info.activityInfo.packageName); 2523 } 2524 2525 return result; 2526 } 2527 2528 private boolean packageIsBrowser(String packageName, int userId) { 2529 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2530 PackageManager.MATCH_ALL, userId); 2531 final int N = list.size(); 2532 for (int i = 0; i < N; i++) { 2533 ResolveInfo info = list.get(i); 2534 if (packageName.equals(info.activityInfo.packageName)) { 2535 return true; 2536 } 2537 } 2538 return false; 2539 } 2540 2541 private void checkDefaultBrowser() { 2542 final int myUserId = UserHandle.myUserId(); 2543 final String packageName = getDefaultBrowserPackageName(myUserId); 2544 if (packageName != null) { 2545 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2546 if (info == null) { 2547 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2548 synchronized (mPackages) { 2549 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2550 } 2551 } 2552 } 2553 } 2554 2555 @Override 2556 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2557 throws RemoteException { 2558 try { 2559 return super.onTransact(code, data, reply, flags); 2560 } catch (RuntimeException e) { 2561 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2562 Slog.wtf(TAG, "Package Manager Crash", e); 2563 } 2564 throw e; 2565 } 2566 } 2567 2568 void cleanupInstallFailedPackage(PackageSetting ps) { 2569 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2570 2571 removeDataDirsLI(ps.volumeUuid, ps.name); 2572 if (ps.codePath != null) { 2573 if (ps.codePath.isDirectory()) { 2574 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2575 } else { 2576 ps.codePath.delete(); 2577 } 2578 } 2579 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2580 if (ps.resourcePath.isDirectory()) { 2581 FileUtils.deleteContents(ps.resourcePath); 2582 } 2583 ps.resourcePath.delete(); 2584 } 2585 mSettings.removePackageLPw(ps.name); 2586 } 2587 2588 static int[] appendInts(int[] cur, int[] add) { 2589 if (add == null) return cur; 2590 if (cur == null) return add; 2591 final int N = add.length; 2592 for (int i=0; i<N; i++) { 2593 cur = appendInt(cur, add[i]); 2594 } 2595 return cur; 2596 } 2597 2598 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2599 if (!sUserManager.exists(userId)) return null; 2600 final PackageSetting ps = (PackageSetting) p.mExtras; 2601 if (ps == null) { 2602 return null; 2603 } 2604 2605 final PermissionsState permissionsState = ps.getPermissionsState(); 2606 2607 final int[] gids = permissionsState.computeGids(userId); 2608 final Set<String> permissions = permissionsState.getPermissions(userId); 2609 final PackageUserState state = ps.readUserState(userId); 2610 2611 return PackageParser.generatePackageInfo(p, gids, flags, 2612 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2613 } 2614 2615 @Override 2616 public boolean isPackageFrozen(String packageName) { 2617 synchronized (mPackages) { 2618 final PackageSetting ps = mSettings.mPackages.get(packageName); 2619 if (ps != null) { 2620 return ps.frozen; 2621 } 2622 } 2623 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2624 return true; 2625 } 2626 2627 @Override 2628 public boolean isPackageAvailable(String packageName, int userId) { 2629 if (!sUserManager.exists(userId)) return false; 2630 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2631 synchronized (mPackages) { 2632 PackageParser.Package p = mPackages.get(packageName); 2633 if (p != null) { 2634 final PackageSetting ps = (PackageSetting) p.mExtras; 2635 if (ps != null) { 2636 final PackageUserState state = ps.readUserState(userId); 2637 if (state != null) { 2638 return PackageParser.isAvailable(state); 2639 } 2640 } 2641 } 2642 } 2643 return false; 2644 } 2645 2646 @Override 2647 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2648 if (!sUserManager.exists(userId)) return null; 2649 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2650 // reader 2651 synchronized (mPackages) { 2652 PackageParser.Package p = mPackages.get(packageName); 2653 if (DEBUG_PACKAGE_INFO) 2654 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2655 if (p != null) { 2656 return generatePackageInfo(p, flags, userId); 2657 } 2658 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2659 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2660 } 2661 } 2662 return null; 2663 } 2664 2665 @Override 2666 public String[] currentToCanonicalPackageNames(String[] names) { 2667 String[] out = new String[names.length]; 2668 // reader 2669 synchronized (mPackages) { 2670 for (int i=names.length-1; i>=0; i--) { 2671 PackageSetting ps = mSettings.mPackages.get(names[i]); 2672 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2673 } 2674 } 2675 return out; 2676 } 2677 2678 @Override 2679 public String[] canonicalToCurrentPackageNames(String[] names) { 2680 String[] out = new String[names.length]; 2681 // reader 2682 synchronized (mPackages) { 2683 for (int i=names.length-1; i>=0; i--) { 2684 String cur = mSettings.mRenamedPackages.get(names[i]); 2685 out[i] = cur != null ? cur : names[i]; 2686 } 2687 } 2688 return out; 2689 } 2690 2691 @Override 2692 public int getPackageUid(String packageName, int userId) { 2693 if (!sUserManager.exists(userId)) return -1; 2694 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2695 2696 // reader 2697 synchronized (mPackages) { 2698 PackageParser.Package p = mPackages.get(packageName); 2699 if(p != null) { 2700 return UserHandle.getUid(userId, p.applicationInfo.uid); 2701 } 2702 PackageSetting ps = mSettings.mPackages.get(packageName); 2703 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2704 return -1; 2705 } 2706 p = ps.pkg; 2707 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2708 } 2709 } 2710 2711 @Override 2712 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2713 if (!sUserManager.exists(userId)) { 2714 return null; 2715 } 2716 2717 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2718 "getPackageGids"); 2719 2720 // reader 2721 synchronized (mPackages) { 2722 PackageParser.Package p = mPackages.get(packageName); 2723 if (DEBUG_PACKAGE_INFO) { 2724 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2725 } 2726 if (p != null) { 2727 PackageSetting ps = (PackageSetting) p.mExtras; 2728 return ps.getPermissionsState().computeGids(userId); 2729 } 2730 } 2731 2732 return null; 2733 } 2734 2735 static PermissionInfo generatePermissionInfo( 2736 BasePermission bp, int flags) { 2737 if (bp.perm != null) { 2738 return PackageParser.generatePermissionInfo(bp.perm, flags); 2739 } 2740 PermissionInfo pi = new PermissionInfo(); 2741 pi.name = bp.name; 2742 pi.packageName = bp.sourcePackage; 2743 pi.nonLocalizedLabel = bp.name; 2744 pi.protectionLevel = bp.protectionLevel; 2745 return pi; 2746 } 2747 2748 @Override 2749 public PermissionInfo getPermissionInfo(String name, int flags) { 2750 // reader 2751 synchronized (mPackages) { 2752 final BasePermission p = mSettings.mPermissions.get(name); 2753 if (p != null) { 2754 return generatePermissionInfo(p, flags); 2755 } 2756 return null; 2757 } 2758 } 2759 2760 @Override 2761 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2762 // reader 2763 synchronized (mPackages) { 2764 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2765 for (BasePermission p : mSettings.mPermissions.values()) { 2766 if (group == null) { 2767 if (p.perm == null || p.perm.info.group == null) { 2768 out.add(generatePermissionInfo(p, flags)); 2769 } 2770 } else { 2771 if (p.perm != null && group.equals(p.perm.info.group)) { 2772 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2773 } 2774 } 2775 } 2776 2777 if (out.size() > 0) { 2778 return out; 2779 } 2780 return mPermissionGroups.containsKey(group) ? out : null; 2781 } 2782 } 2783 2784 @Override 2785 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2786 // reader 2787 synchronized (mPackages) { 2788 return PackageParser.generatePermissionGroupInfo( 2789 mPermissionGroups.get(name), flags); 2790 } 2791 } 2792 2793 @Override 2794 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2795 // reader 2796 synchronized (mPackages) { 2797 final int N = mPermissionGroups.size(); 2798 ArrayList<PermissionGroupInfo> out 2799 = new ArrayList<PermissionGroupInfo>(N); 2800 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2801 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2802 } 2803 return out; 2804 } 2805 } 2806 2807 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2808 int userId) { 2809 if (!sUserManager.exists(userId)) return null; 2810 PackageSetting ps = mSettings.mPackages.get(packageName); 2811 if (ps != null) { 2812 if (ps.pkg == null) { 2813 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2814 flags, userId); 2815 if (pInfo != null) { 2816 return pInfo.applicationInfo; 2817 } 2818 return null; 2819 } 2820 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2821 ps.readUserState(userId), userId); 2822 } 2823 return null; 2824 } 2825 2826 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2827 int userId) { 2828 if (!sUserManager.exists(userId)) return null; 2829 PackageSetting ps = mSettings.mPackages.get(packageName); 2830 if (ps != null) { 2831 PackageParser.Package pkg = ps.pkg; 2832 if (pkg == null) { 2833 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2834 return null; 2835 } 2836 // Only data remains, so we aren't worried about code paths 2837 pkg = new PackageParser.Package(packageName); 2838 pkg.applicationInfo.packageName = packageName; 2839 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2840 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2841 pkg.applicationInfo.dataDir = Environment 2842 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2843 .getAbsolutePath(); 2844 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2845 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2846 } 2847 return generatePackageInfo(pkg, flags, userId); 2848 } 2849 return null; 2850 } 2851 2852 @Override 2853 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2854 if (!sUserManager.exists(userId)) return null; 2855 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2856 // writer 2857 synchronized (mPackages) { 2858 PackageParser.Package p = mPackages.get(packageName); 2859 if (DEBUG_PACKAGE_INFO) Log.v( 2860 TAG, "getApplicationInfo " + packageName 2861 + ": " + p); 2862 if (p != null) { 2863 PackageSetting ps = mSettings.mPackages.get(packageName); 2864 if (ps == null) return null; 2865 // Note: isEnabledLP() does not apply here - always return info 2866 return PackageParser.generateApplicationInfo( 2867 p, flags, ps.readUserState(userId), userId); 2868 } 2869 if ("android".equals(packageName)||"system".equals(packageName)) { 2870 return mAndroidApplication; 2871 } 2872 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2873 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2874 } 2875 } 2876 return null; 2877 } 2878 2879 @Override 2880 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2881 final IPackageDataObserver observer) { 2882 mContext.enforceCallingOrSelfPermission( 2883 android.Manifest.permission.CLEAR_APP_CACHE, null); 2884 // Queue up an async operation since clearing cache may take a little while. 2885 mHandler.post(new Runnable() { 2886 public void run() { 2887 mHandler.removeCallbacks(this); 2888 int retCode = -1; 2889 synchronized (mInstallLock) { 2890 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2891 if (retCode < 0) { 2892 Slog.w(TAG, "Couldn't clear application caches"); 2893 } 2894 } 2895 if (observer != null) { 2896 try { 2897 observer.onRemoveCompleted(null, (retCode >= 0)); 2898 } catch (RemoteException e) { 2899 Slog.w(TAG, "RemoveException when invoking call back"); 2900 } 2901 } 2902 } 2903 }); 2904 } 2905 2906 @Override 2907 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2908 final IntentSender pi) { 2909 mContext.enforceCallingOrSelfPermission( 2910 android.Manifest.permission.CLEAR_APP_CACHE, null); 2911 // Queue up an async operation since clearing cache may take a little while. 2912 mHandler.post(new Runnable() { 2913 public void run() { 2914 mHandler.removeCallbacks(this); 2915 int retCode = -1; 2916 synchronized (mInstallLock) { 2917 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2918 if (retCode < 0) { 2919 Slog.w(TAG, "Couldn't clear application caches"); 2920 } 2921 } 2922 if(pi != null) { 2923 try { 2924 // Callback via pending intent 2925 int code = (retCode >= 0) ? 1 : 0; 2926 pi.sendIntent(null, code, null, 2927 null, null); 2928 } catch (SendIntentException e1) { 2929 Slog.i(TAG, "Failed to send pending intent"); 2930 } 2931 } 2932 } 2933 }); 2934 } 2935 2936 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2937 synchronized (mInstallLock) { 2938 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2939 throw new IOException("Failed to free enough space"); 2940 } 2941 } 2942 } 2943 2944 @Override 2945 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2946 if (!sUserManager.exists(userId)) return null; 2947 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2948 synchronized (mPackages) { 2949 PackageParser.Activity a = mActivities.mActivities.get(component); 2950 2951 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2952 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2953 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2954 if (ps == null) return null; 2955 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2956 userId); 2957 } 2958 if (mResolveComponentName.equals(component)) { 2959 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2960 new PackageUserState(), userId); 2961 } 2962 } 2963 return null; 2964 } 2965 2966 @Override 2967 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2968 String resolvedType) { 2969 synchronized (mPackages) { 2970 if (component.equals(mResolveComponentName)) { 2971 // The resolver supports EVERYTHING! 2972 return true; 2973 } 2974 PackageParser.Activity a = mActivities.mActivities.get(component); 2975 if (a == null) { 2976 return false; 2977 } 2978 for (int i=0; i<a.intents.size(); i++) { 2979 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2980 intent.getData(), intent.getCategories(), TAG) >= 0) { 2981 return true; 2982 } 2983 } 2984 return false; 2985 } 2986 } 2987 2988 @Override 2989 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2990 if (!sUserManager.exists(userId)) return null; 2991 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2992 synchronized (mPackages) { 2993 PackageParser.Activity a = mReceivers.mActivities.get(component); 2994 if (DEBUG_PACKAGE_INFO) Log.v( 2995 TAG, "getReceiverInfo " + component + ": " + a); 2996 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2997 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2998 if (ps == null) return null; 2999 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3000 userId); 3001 } 3002 } 3003 return null; 3004 } 3005 3006 @Override 3007 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3008 if (!sUserManager.exists(userId)) return null; 3009 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3010 synchronized (mPackages) { 3011 PackageParser.Service s = mServices.mServices.get(component); 3012 if (DEBUG_PACKAGE_INFO) Log.v( 3013 TAG, "getServiceInfo " + component + ": " + s); 3014 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3015 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3016 if (ps == null) return null; 3017 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3018 userId); 3019 } 3020 } 3021 return null; 3022 } 3023 3024 @Override 3025 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3026 if (!sUserManager.exists(userId)) return null; 3027 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3028 synchronized (mPackages) { 3029 PackageParser.Provider p = mProviders.mProviders.get(component); 3030 if (DEBUG_PACKAGE_INFO) Log.v( 3031 TAG, "getProviderInfo " + component + ": " + p); 3032 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3033 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3034 if (ps == null) return null; 3035 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3036 userId); 3037 } 3038 } 3039 return null; 3040 } 3041 3042 @Override 3043 public String[] getSystemSharedLibraryNames() { 3044 Set<String> libSet; 3045 synchronized (mPackages) { 3046 libSet = mSharedLibraries.keySet(); 3047 int size = libSet.size(); 3048 if (size > 0) { 3049 String[] libs = new String[size]; 3050 libSet.toArray(libs); 3051 return libs; 3052 } 3053 } 3054 return null; 3055 } 3056 3057 /** 3058 * @hide 3059 */ 3060 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3061 synchronized (mPackages) { 3062 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3063 if (lib != null && lib.apk != null) { 3064 return mPackages.get(lib.apk); 3065 } 3066 } 3067 return null; 3068 } 3069 3070 @Override 3071 public FeatureInfo[] getSystemAvailableFeatures() { 3072 Collection<FeatureInfo> featSet; 3073 synchronized (mPackages) { 3074 featSet = mAvailableFeatures.values(); 3075 int size = featSet.size(); 3076 if (size > 0) { 3077 FeatureInfo[] features = new FeatureInfo[size+1]; 3078 featSet.toArray(features); 3079 FeatureInfo fi = new FeatureInfo(); 3080 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3081 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3082 features[size] = fi; 3083 return features; 3084 } 3085 } 3086 return null; 3087 } 3088 3089 @Override 3090 public boolean hasSystemFeature(String name) { 3091 synchronized (mPackages) { 3092 return mAvailableFeatures.containsKey(name); 3093 } 3094 } 3095 3096 private void checkValidCaller(int uid, int userId) { 3097 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3098 return; 3099 3100 throw new SecurityException("Caller uid=" + uid 3101 + " is not privileged to communicate with user=" + userId); 3102 } 3103 3104 @Override 3105 public int checkPermission(String permName, String pkgName, int userId) { 3106 if (!sUserManager.exists(userId)) { 3107 return PackageManager.PERMISSION_DENIED; 3108 } 3109 3110 synchronized (mPackages) { 3111 final PackageParser.Package p = mPackages.get(pkgName); 3112 if (p != null && p.mExtras != null) { 3113 final PackageSetting ps = (PackageSetting) p.mExtras; 3114 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3115 return PackageManager.PERMISSION_GRANTED; 3116 } 3117 } 3118 } 3119 3120 return PackageManager.PERMISSION_DENIED; 3121 } 3122 3123 @Override 3124 public int checkUidPermission(String permName, int uid) { 3125 final int userId = UserHandle.getUserId(uid); 3126 3127 if (!sUserManager.exists(userId)) { 3128 return PackageManager.PERMISSION_DENIED; 3129 } 3130 3131 synchronized (mPackages) { 3132 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3133 if (obj != null) { 3134 final SettingBase ps = (SettingBase) obj; 3135 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3136 return PackageManager.PERMISSION_GRANTED; 3137 } 3138 } else { 3139 ArraySet<String> perms = mSystemPermissions.get(uid); 3140 if (perms != null && perms.contains(permName)) { 3141 return PackageManager.PERMISSION_GRANTED; 3142 } 3143 } 3144 } 3145 3146 return PackageManager.PERMISSION_DENIED; 3147 } 3148 3149 @Override 3150 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3151 if (UserHandle.getCallingUserId() != userId) { 3152 mContext.enforceCallingPermission( 3153 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3154 "isPermissionRevokedByPolicy for user " + userId); 3155 } 3156 3157 if (checkPermission(permission, packageName, userId) 3158 == PackageManager.PERMISSION_GRANTED) { 3159 return false; 3160 } 3161 3162 final long identity = Binder.clearCallingIdentity(); 3163 try { 3164 final int flags = getPermissionFlags(permission, packageName, userId); 3165 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3166 } finally { 3167 Binder.restoreCallingIdentity(identity); 3168 } 3169 } 3170 3171 /** 3172 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3173 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3174 * @param checkShell TODO(yamasani): 3175 * @param message the message to log on security exception 3176 */ 3177 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3178 boolean checkShell, String message) { 3179 if (userId < 0) { 3180 throw new IllegalArgumentException("Invalid userId " + userId); 3181 } 3182 if (checkShell) { 3183 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3184 } 3185 if (userId == UserHandle.getUserId(callingUid)) return; 3186 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3187 if (requireFullPermission) { 3188 mContext.enforceCallingOrSelfPermission( 3189 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3190 } else { 3191 try { 3192 mContext.enforceCallingOrSelfPermission( 3193 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3194 } catch (SecurityException se) { 3195 mContext.enforceCallingOrSelfPermission( 3196 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3197 } 3198 } 3199 } 3200 } 3201 3202 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3203 if (callingUid == Process.SHELL_UID) { 3204 if (userHandle >= 0 3205 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3206 throw new SecurityException("Shell does not have permission to access user " 3207 + userHandle); 3208 } else if (userHandle < 0) { 3209 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3210 + Debug.getCallers(3)); 3211 } 3212 } 3213 } 3214 3215 private BasePermission findPermissionTreeLP(String permName) { 3216 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3217 if (permName.startsWith(bp.name) && 3218 permName.length() > bp.name.length() && 3219 permName.charAt(bp.name.length()) == '.') { 3220 return bp; 3221 } 3222 } 3223 return null; 3224 } 3225 3226 private BasePermission checkPermissionTreeLP(String permName) { 3227 if (permName != null) { 3228 BasePermission bp = findPermissionTreeLP(permName); 3229 if (bp != null) { 3230 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3231 return bp; 3232 } 3233 throw new SecurityException("Calling uid " 3234 + Binder.getCallingUid() 3235 + " is not allowed to add to permission tree " 3236 + bp.name + " owned by uid " + bp.uid); 3237 } 3238 } 3239 throw new SecurityException("No permission tree found for " + permName); 3240 } 3241 3242 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3243 if (s1 == null) { 3244 return s2 == null; 3245 } 3246 if (s2 == null) { 3247 return false; 3248 } 3249 if (s1.getClass() != s2.getClass()) { 3250 return false; 3251 } 3252 return s1.equals(s2); 3253 } 3254 3255 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3256 if (pi1.icon != pi2.icon) return false; 3257 if (pi1.logo != pi2.logo) return false; 3258 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3259 if (!compareStrings(pi1.name, pi2.name)) return false; 3260 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3261 // We'll take care of setting this one. 3262 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3263 // These are not currently stored in settings. 3264 //if (!compareStrings(pi1.group, pi2.group)) return false; 3265 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3266 //if (pi1.labelRes != pi2.labelRes) return false; 3267 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3268 return true; 3269 } 3270 3271 int permissionInfoFootprint(PermissionInfo info) { 3272 int size = info.name.length(); 3273 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3274 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3275 return size; 3276 } 3277 3278 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3279 int size = 0; 3280 for (BasePermission perm : mSettings.mPermissions.values()) { 3281 if (perm.uid == tree.uid) { 3282 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3283 } 3284 } 3285 return size; 3286 } 3287 3288 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3289 // We calculate the max size of permissions defined by this uid and throw 3290 // if that plus the size of 'info' would exceed our stated maximum. 3291 if (tree.uid != Process.SYSTEM_UID) { 3292 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3293 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3294 throw new SecurityException("Permission tree size cap exceeded"); 3295 } 3296 } 3297 } 3298 3299 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3300 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3301 throw new SecurityException("Label must be specified in permission"); 3302 } 3303 BasePermission tree = checkPermissionTreeLP(info.name); 3304 BasePermission bp = mSettings.mPermissions.get(info.name); 3305 boolean added = bp == null; 3306 boolean changed = true; 3307 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3308 if (added) { 3309 enforcePermissionCapLocked(info, tree); 3310 bp = new BasePermission(info.name, tree.sourcePackage, 3311 BasePermission.TYPE_DYNAMIC); 3312 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3313 throw new SecurityException( 3314 "Not allowed to modify non-dynamic permission " 3315 + info.name); 3316 } else { 3317 if (bp.protectionLevel == fixedLevel 3318 && bp.perm.owner.equals(tree.perm.owner) 3319 && bp.uid == tree.uid 3320 && comparePermissionInfos(bp.perm.info, info)) { 3321 changed = false; 3322 } 3323 } 3324 bp.protectionLevel = fixedLevel; 3325 info = new PermissionInfo(info); 3326 info.protectionLevel = fixedLevel; 3327 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3328 bp.perm.info.packageName = tree.perm.info.packageName; 3329 bp.uid = tree.uid; 3330 if (added) { 3331 mSettings.mPermissions.put(info.name, bp); 3332 } 3333 if (changed) { 3334 if (!async) { 3335 mSettings.writeLPr(); 3336 } else { 3337 scheduleWriteSettingsLocked(); 3338 } 3339 } 3340 return added; 3341 } 3342 3343 @Override 3344 public boolean addPermission(PermissionInfo info) { 3345 synchronized (mPackages) { 3346 return addPermissionLocked(info, false); 3347 } 3348 } 3349 3350 @Override 3351 public boolean addPermissionAsync(PermissionInfo info) { 3352 synchronized (mPackages) { 3353 return addPermissionLocked(info, true); 3354 } 3355 } 3356 3357 @Override 3358 public void removePermission(String name) { 3359 synchronized (mPackages) { 3360 checkPermissionTreeLP(name); 3361 BasePermission bp = mSettings.mPermissions.get(name); 3362 if (bp != null) { 3363 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3364 throw new SecurityException( 3365 "Not allowed to modify non-dynamic permission " 3366 + name); 3367 } 3368 mSettings.mPermissions.remove(name); 3369 mSettings.writeLPr(); 3370 } 3371 } 3372 } 3373 3374 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3375 BasePermission bp) { 3376 int index = pkg.requestedPermissions.indexOf(bp.name); 3377 if (index == -1) { 3378 throw new SecurityException("Package " + pkg.packageName 3379 + " has not requested permission " + bp.name); 3380 } 3381 if (!bp.isRuntime()) { 3382 throw new SecurityException("Permission " + bp.name 3383 + " is not a changeable permission type"); 3384 } 3385 } 3386 3387 @Override 3388 public void grantRuntimePermission(String packageName, String name, final int userId) { 3389 if (!sUserManager.exists(userId)) { 3390 Log.e(TAG, "No such user:" + userId); 3391 return; 3392 } 3393 3394 mContext.enforceCallingOrSelfPermission( 3395 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3396 "grantRuntimePermission"); 3397 3398 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3399 "grantRuntimePermission"); 3400 3401 final int uid; 3402 final SettingBase sb; 3403 3404 synchronized (mPackages) { 3405 final PackageParser.Package pkg = mPackages.get(packageName); 3406 if (pkg == null) { 3407 throw new IllegalArgumentException("Unknown package: " + packageName); 3408 } 3409 3410 final BasePermission bp = mSettings.mPermissions.get(name); 3411 if (bp == null) { 3412 throw new IllegalArgumentException("Unknown permission: " + name); 3413 } 3414 3415 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3416 3417 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3418 sb = (SettingBase) pkg.mExtras; 3419 if (sb == null) { 3420 throw new IllegalArgumentException("Unknown package: " + packageName); 3421 } 3422 3423 final PermissionsState permissionsState = sb.getPermissionsState(); 3424 3425 final int flags = permissionsState.getPermissionFlags(name, userId); 3426 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3427 throw new SecurityException("Cannot grant system fixed permission: " 3428 + name + " for package: " + packageName); 3429 } 3430 3431 final int result = permissionsState.grantRuntimePermission(bp, userId); 3432 switch (result) { 3433 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3434 return; 3435 } 3436 3437 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3438 mHandler.post(new Runnable() { 3439 @Override 3440 public void run() { 3441 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3442 } 3443 }); 3444 } break; 3445 } 3446 3447 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3448 3449 // Not critical if that is lost - app has to request again. 3450 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3451 } 3452 3453 // Only need to do this if user is initialized. Otherwise it's a new user 3454 // and there are no processes running as the user yet and there's no need 3455 // to make an expensive call to remount processes for the changed permissions. 3456 if (READ_EXTERNAL_STORAGE.equals(name) 3457 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3458 final long token = Binder.clearCallingIdentity(); 3459 try { 3460 if (sUserManager.isInitialized(userId)) { 3461 MountServiceInternal mountServiceInternal = LocalServices.getService( 3462 MountServiceInternal.class); 3463 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3464 } 3465 } finally { 3466 Binder.restoreCallingIdentity(token); 3467 } 3468 } 3469 } 3470 3471 @Override 3472 public void revokeRuntimePermission(String packageName, String name, int userId) { 3473 if (!sUserManager.exists(userId)) { 3474 Log.e(TAG, "No such user:" + userId); 3475 return; 3476 } 3477 3478 mContext.enforceCallingOrSelfPermission( 3479 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3480 "revokeRuntimePermission"); 3481 3482 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3483 "revokeRuntimePermission"); 3484 3485 final SettingBase sb; 3486 3487 synchronized (mPackages) { 3488 final PackageParser.Package pkg = mPackages.get(packageName); 3489 if (pkg == null) { 3490 throw new IllegalArgumentException("Unknown package: " + packageName); 3491 } 3492 3493 final BasePermission bp = mSettings.mPermissions.get(name); 3494 if (bp == null) { 3495 throw new IllegalArgumentException("Unknown permission: " + name); 3496 } 3497 3498 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3499 3500 sb = (SettingBase) pkg.mExtras; 3501 if (sb == null) { 3502 throw new IllegalArgumentException("Unknown package: " + packageName); 3503 } 3504 3505 final PermissionsState permissionsState = sb.getPermissionsState(); 3506 3507 final int flags = permissionsState.getPermissionFlags(name, userId); 3508 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3509 throw new SecurityException("Cannot revoke system fixed permission: " 3510 + name + " for package: " + packageName); 3511 } 3512 3513 if (permissionsState.revokeRuntimePermission(bp, userId) == 3514 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3515 return; 3516 } 3517 3518 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3519 3520 // Critical, after this call app should never have the permission. 3521 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3522 } 3523 3524 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3525 } 3526 3527 @Override 3528 public void resetRuntimePermissions() { 3529 mContext.enforceCallingOrSelfPermission( 3530 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3531 "revokeRuntimePermission"); 3532 3533 int callingUid = Binder.getCallingUid(); 3534 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3535 mContext.enforceCallingOrSelfPermission( 3536 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3537 "resetRuntimePermissions"); 3538 } 3539 3540 synchronized (mPackages) { 3541 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3542 for (int userId : UserManagerService.getInstance().getUserIds()) { 3543 final int packageCount = mPackages.size(); 3544 for (int i = 0; i < packageCount; i++) { 3545 PackageParser.Package pkg = mPackages.valueAt(i); 3546 if (!(pkg.mExtras instanceof PackageSetting)) { 3547 continue; 3548 } 3549 PackageSetting ps = (PackageSetting) pkg.mExtras; 3550 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 3551 } 3552 } 3553 } 3554 } 3555 3556 @Override 3557 public int getPermissionFlags(String name, String packageName, int userId) { 3558 if (!sUserManager.exists(userId)) { 3559 return 0; 3560 } 3561 3562 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3563 3564 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3565 "getPermissionFlags"); 3566 3567 synchronized (mPackages) { 3568 final PackageParser.Package pkg = mPackages.get(packageName); 3569 if (pkg == null) { 3570 throw new IllegalArgumentException("Unknown package: " + packageName); 3571 } 3572 3573 final BasePermission bp = mSettings.mPermissions.get(name); 3574 if (bp == null) { 3575 throw new IllegalArgumentException("Unknown permission: " + name); 3576 } 3577 3578 SettingBase sb = (SettingBase) pkg.mExtras; 3579 if (sb == null) { 3580 throw new IllegalArgumentException("Unknown package: " + packageName); 3581 } 3582 3583 PermissionsState permissionsState = sb.getPermissionsState(); 3584 return permissionsState.getPermissionFlags(name, userId); 3585 } 3586 } 3587 3588 @Override 3589 public void updatePermissionFlags(String name, String packageName, int flagMask, 3590 int flagValues, int userId) { 3591 if (!sUserManager.exists(userId)) { 3592 return; 3593 } 3594 3595 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3596 3597 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3598 "updatePermissionFlags"); 3599 3600 // Only the system can change system fixed flags. 3601 if (getCallingUid() != Process.SYSTEM_UID) { 3602 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3603 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3604 } 3605 3606 synchronized (mPackages) { 3607 final PackageParser.Package pkg = mPackages.get(packageName); 3608 if (pkg == null) { 3609 throw new IllegalArgumentException("Unknown package: " + packageName); 3610 } 3611 3612 final BasePermission bp = mSettings.mPermissions.get(name); 3613 if (bp == null) { 3614 throw new IllegalArgumentException("Unknown permission: " + name); 3615 } 3616 3617 SettingBase sb = (SettingBase) pkg.mExtras; 3618 if (sb == null) { 3619 throw new IllegalArgumentException("Unknown package: " + packageName); 3620 } 3621 3622 PermissionsState permissionsState = sb.getPermissionsState(); 3623 3624 // Only the package manager can change flags for system component permissions. 3625 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3626 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3627 return; 3628 } 3629 3630 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3631 3632 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3633 // Install and runtime permissions are stored in different places, 3634 // so figure out what permission changed and persist the change. 3635 if (permissionsState.getInstallPermissionState(name) != null) { 3636 scheduleWriteSettingsLocked(); 3637 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3638 || hadState) { 3639 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3640 } 3641 } 3642 } 3643 } 3644 3645 /** 3646 * Update the permission flags for all packages and runtime permissions of a user in order 3647 * to allow device or profile owner to remove POLICY_FIXED. 3648 */ 3649 @Override 3650 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3651 if (!sUserManager.exists(userId)) { 3652 return; 3653 } 3654 3655 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3656 3657 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3658 "updatePermissionFlagsForAllApps"); 3659 3660 // Only the system can change system fixed flags. 3661 if (getCallingUid() != Process.SYSTEM_UID) { 3662 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3663 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3664 } 3665 3666 synchronized (mPackages) { 3667 boolean changed = false; 3668 final int packageCount = mPackages.size(); 3669 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3670 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3671 SettingBase sb = (SettingBase) pkg.mExtras; 3672 if (sb == null) { 3673 continue; 3674 } 3675 PermissionsState permissionsState = sb.getPermissionsState(); 3676 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3677 userId, flagMask, flagValues); 3678 } 3679 if (changed) { 3680 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3681 } 3682 } 3683 } 3684 3685 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3686 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3687 != PackageManager.PERMISSION_GRANTED 3688 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3689 != PackageManager.PERMISSION_GRANTED) { 3690 throw new SecurityException(message + " requires " 3691 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3692 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3693 } 3694 } 3695 3696 @Override 3697 public boolean shouldShowRequestPermissionRationale(String permissionName, 3698 String packageName, int userId) { 3699 if (UserHandle.getCallingUserId() != userId) { 3700 mContext.enforceCallingPermission( 3701 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3702 "canShowRequestPermissionRationale for user " + userId); 3703 } 3704 3705 final int uid = getPackageUid(packageName, userId); 3706 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3707 return false; 3708 } 3709 3710 if (checkPermission(permissionName, packageName, userId) 3711 == PackageManager.PERMISSION_GRANTED) { 3712 return false; 3713 } 3714 3715 final int flags; 3716 3717 final long identity = Binder.clearCallingIdentity(); 3718 try { 3719 flags = getPermissionFlags(permissionName, 3720 packageName, userId); 3721 } finally { 3722 Binder.restoreCallingIdentity(identity); 3723 } 3724 3725 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3726 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3727 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3728 3729 if ((flags & fixedFlags) != 0) { 3730 return false; 3731 } 3732 3733 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3734 } 3735 3736 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3737 BasePermission bp = mSettings.mPermissions.get(permission); 3738 if (bp == null) { 3739 throw new SecurityException("Missing " + permission + " permission"); 3740 } 3741 3742 SettingBase sb = (SettingBase) pkg.mExtras; 3743 PermissionsState permissionsState = sb.getPermissionsState(); 3744 3745 if (permissionsState.grantInstallPermission(bp) != 3746 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3747 scheduleWriteSettingsLocked(); 3748 } 3749 } 3750 3751 @Override 3752 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3753 mContext.enforceCallingOrSelfPermission( 3754 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3755 "addOnPermissionsChangeListener"); 3756 3757 synchronized (mPackages) { 3758 mOnPermissionChangeListeners.addListenerLocked(listener); 3759 } 3760 } 3761 3762 @Override 3763 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3764 synchronized (mPackages) { 3765 mOnPermissionChangeListeners.removeListenerLocked(listener); 3766 } 3767 } 3768 3769 @Override 3770 public boolean isProtectedBroadcast(String actionName) { 3771 synchronized (mPackages) { 3772 return mProtectedBroadcasts.contains(actionName); 3773 } 3774 } 3775 3776 @Override 3777 public int checkSignatures(String pkg1, String pkg2) { 3778 synchronized (mPackages) { 3779 final PackageParser.Package p1 = mPackages.get(pkg1); 3780 final PackageParser.Package p2 = mPackages.get(pkg2); 3781 if (p1 == null || p1.mExtras == null 3782 || p2 == null || p2.mExtras == null) { 3783 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3784 } 3785 return compareSignatures(p1.mSignatures, p2.mSignatures); 3786 } 3787 } 3788 3789 @Override 3790 public int checkUidSignatures(int uid1, int uid2) { 3791 // Map to base uids. 3792 uid1 = UserHandle.getAppId(uid1); 3793 uid2 = UserHandle.getAppId(uid2); 3794 // reader 3795 synchronized (mPackages) { 3796 Signature[] s1; 3797 Signature[] s2; 3798 Object obj = mSettings.getUserIdLPr(uid1); 3799 if (obj != null) { 3800 if (obj instanceof SharedUserSetting) { 3801 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3802 } else if (obj instanceof PackageSetting) { 3803 s1 = ((PackageSetting)obj).signatures.mSignatures; 3804 } else { 3805 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3806 } 3807 } else { 3808 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3809 } 3810 obj = mSettings.getUserIdLPr(uid2); 3811 if (obj != null) { 3812 if (obj instanceof SharedUserSetting) { 3813 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3814 } else if (obj instanceof PackageSetting) { 3815 s2 = ((PackageSetting)obj).signatures.mSignatures; 3816 } else { 3817 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3818 } 3819 } else { 3820 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3821 } 3822 return compareSignatures(s1, s2); 3823 } 3824 } 3825 3826 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3827 final long identity = Binder.clearCallingIdentity(); 3828 try { 3829 if (sb instanceof SharedUserSetting) { 3830 SharedUserSetting sus = (SharedUserSetting) sb; 3831 final int packageCount = sus.packages.size(); 3832 for (int i = 0; i < packageCount; i++) { 3833 PackageSetting susPs = sus.packages.valueAt(i); 3834 if (userId == UserHandle.USER_ALL) { 3835 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3836 } else { 3837 final int uid = UserHandle.getUid(userId, susPs.appId); 3838 killUid(uid, reason); 3839 } 3840 } 3841 } else if (sb instanceof PackageSetting) { 3842 PackageSetting ps = (PackageSetting) sb; 3843 if (userId == UserHandle.USER_ALL) { 3844 killApplication(ps.pkg.packageName, ps.appId, reason); 3845 } else { 3846 final int uid = UserHandle.getUid(userId, ps.appId); 3847 killUid(uid, reason); 3848 } 3849 } 3850 } finally { 3851 Binder.restoreCallingIdentity(identity); 3852 } 3853 } 3854 3855 private static void killUid(int uid, String reason) { 3856 IActivityManager am = ActivityManagerNative.getDefault(); 3857 if (am != null) { 3858 try { 3859 am.killUid(uid, reason); 3860 } catch (RemoteException e) { 3861 /* ignore - same process */ 3862 } 3863 } 3864 } 3865 3866 /** 3867 * Compares two sets of signatures. Returns: 3868 * <br /> 3869 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3870 * <br /> 3871 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3872 * <br /> 3873 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3874 * <br /> 3875 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3876 * <br /> 3877 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3878 */ 3879 static int compareSignatures(Signature[] s1, Signature[] s2) { 3880 if (s1 == null) { 3881 return s2 == null 3882 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3883 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3884 } 3885 3886 if (s2 == null) { 3887 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3888 } 3889 3890 if (s1.length != s2.length) { 3891 return PackageManager.SIGNATURE_NO_MATCH; 3892 } 3893 3894 // Since both signature sets are of size 1, we can compare without HashSets. 3895 if (s1.length == 1) { 3896 return s1[0].equals(s2[0]) ? 3897 PackageManager.SIGNATURE_MATCH : 3898 PackageManager.SIGNATURE_NO_MATCH; 3899 } 3900 3901 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3902 for (Signature sig : s1) { 3903 set1.add(sig); 3904 } 3905 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3906 for (Signature sig : s2) { 3907 set2.add(sig); 3908 } 3909 // Make sure s2 contains all signatures in s1. 3910 if (set1.equals(set2)) { 3911 return PackageManager.SIGNATURE_MATCH; 3912 } 3913 return PackageManager.SIGNATURE_NO_MATCH; 3914 } 3915 3916 /** 3917 * If the database version for this type of package (internal storage or 3918 * external storage) is less than the version where package signatures 3919 * were updated, return true. 3920 */ 3921 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3922 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3923 DatabaseVersion.SIGNATURE_END_ENTITY)) 3924 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3925 DatabaseVersion.SIGNATURE_END_ENTITY)); 3926 } 3927 3928 /** 3929 * Used for backward compatibility to make sure any packages with 3930 * certificate chains get upgraded to the new style. {@code existingSigs} 3931 * will be in the old format (since they were stored on disk from before the 3932 * system upgrade) and {@code scannedSigs} will be in the newer format. 3933 */ 3934 private int compareSignaturesCompat(PackageSignatures existingSigs, 3935 PackageParser.Package scannedPkg) { 3936 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3937 return PackageManager.SIGNATURE_NO_MATCH; 3938 } 3939 3940 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3941 for (Signature sig : existingSigs.mSignatures) { 3942 existingSet.add(sig); 3943 } 3944 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3945 for (Signature sig : scannedPkg.mSignatures) { 3946 try { 3947 Signature[] chainSignatures = sig.getChainSignatures(); 3948 for (Signature chainSig : chainSignatures) { 3949 scannedCompatSet.add(chainSig); 3950 } 3951 } catch (CertificateEncodingException e) { 3952 scannedCompatSet.add(sig); 3953 } 3954 } 3955 /* 3956 * Make sure the expanded scanned set contains all signatures in the 3957 * existing one. 3958 */ 3959 if (scannedCompatSet.equals(existingSet)) { 3960 // Migrate the old signatures to the new scheme. 3961 existingSigs.assignSignatures(scannedPkg.mSignatures); 3962 // The new KeySets will be re-added later in the scanning process. 3963 synchronized (mPackages) { 3964 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3965 } 3966 return PackageManager.SIGNATURE_MATCH; 3967 } 3968 return PackageManager.SIGNATURE_NO_MATCH; 3969 } 3970 3971 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3972 if (isExternal(scannedPkg)) { 3973 return mSettings.isExternalDatabaseVersionOlderThan( 3974 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3975 } else { 3976 return mSettings.isInternalDatabaseVersionOlderThan( 3977 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3978 } 3979 } 3980 3981 private int compareSignaturesRecover(PackageSignatures existingSigs, 3982 PackageParser.Package scannedPkg) { 3983 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3984 return PackageManager.SIGNATURE_NO_MATCH; 3985 } 3986 3987 String msg = null; 3988 try { 3989 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3990 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3991 + scannedPkg.packageName); 3992 return PackageManager.SIGNATURE_MATCH; 3993 } 3994 } catch (CertificateException e) { 3995 msg = e.getMessage(); 3996 } 3997 3998 logCriticalInfo(Log.INFO, 3999 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4000 return PackageManager.SIGNATURE_NO_MATCH; 4001 } 4002 4003 @Override 4004 public String[] getPackagesForUid(int uid) { 4005 uid = UserHandle.getAppId(uid); 4006 // reader 4007 synchronized (mPackages) { 4008 Object obj = mSettings.getUserIdLPr(uid); 4009 if (obj instanceof SharedUserSetting) { 4010 final SharedUserSetting sus = (SharedUserSetting) obj; 4011 final int N = sus.packages.size(); 4012 final String[] res = new String[N]; 4013 final Iterator<PackageSetting> it = sus.packages.iterator(); 4014 int i = 0; 4015 while (it.hasNext()) { 4016 res[i++] = it.next().name; 4017 } 4018 return res; 4019 } else if (obj instanceof PackageSetting) { 4020 final PackageSetting ps = (PackageSetting) obj; 4021 return new String[] { ps.name }; 4022 } 4023 } 4024 return null; 4025 } 4026 4027 @Override 4028 public String getNameForUid(int uid) { 4029 // reader 4030 synchronized (mPackages) { 4031 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4032 if (obj instanceof SharedUserSetting) { 4033 final SharedUserSetting sus = (SharedUserSetting) obj; 4034 return sus.name + ":" + sus.userId; 4035 } else if (obj instanceof PackageSetting) { 4036 final PackageSetting ps = (PackageSetting) obj; 4037 return ps.name; 4038 } 4039 } 4040 return null; 4041 } 4042 4043 @Override 4044 public int getUidForSharedUser(String sharedUserName) { 4045 if(sharedUserName == null) { 4046 return -1; 4047 } 4048 // reader 4049 synchronized (mPackages) { 4050 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4051 if (suid == null) { 4052 return -1; 4053 } 4054 return suid.userId; 4055 } 4056 } 4057 4058 @Override 4059 public int getFlagsForUid(int uid) { 4060 synchronized (mPackages) { 4061 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4062 if (obj instanceof SharedUserSetting) { 4063 final SharedUserSetting sus = (SharedUserSetting) obj; 4064 return sus.pkgFlags; 4065 } else if (obj instanceof PackageSetting) { 4066 final PackageSetting ps = (PackageSetting) obj; 4067 return ps.pkgFlags; 4068 } 4069 } 4070 return 0; 4071 } 4072 4073 @Override 4074 public int getPrivateFlagsForUid(int uid) { 4075 synchronized (mPackages) { 4076 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4077 if (obj instanceof SharedUserSetting) { 4078 final SharedUserSetting sus = (SharedUserSetting) obj; 4079 return sus.pkgPrivateFlags; 4080 } else if (obj instanceof PackageSetting) { 4081 final PackageSetting ps = (PackageSetting) obj; 4082 return ps.pkgPrivateFlags; 4083 } 4084 } 4085 return 0; 4086 } 4087 4088 @Override 4089 public boolean isUidPrivileged(int uid) { 4090 uid = UserHandle.getAppId(uid); 4091 // reader 4092 synchronized (mPackages) { 4093 Object obj = mSettings.getUserIdLPr(uid); 4094 if (obj instanceof SharedUserSetting) { 4095 final SharedUserSetting sus = (SharedUserSetting) obj; 4096 final Iterator<PackageSetting> it = sus.packages.iterator(); 4097 while (it.hasNext()) { 4098 if (it.next().isPrivileged()) { 4099 return true; 4100 } 4101 } 4102 } else if (obj instanceof PackageSetting) { 4103 final PackageSetting ps = (PackageSetting) obj; 4104 return ps.isPrivileged(); 4105 } 4106 } 4107 return false; 4108 } 4109 4110 @Override 4111 public String[] getAppOpPermissionPackages(String permissionName) { 4112 synchronized (mPackages) { 4113 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4114 if (pkgs == null) { 4115 return null; 4116 } 4117 return pkgs.toArray(new String[pkgs.size()]); 4118 } 4119 } 4120 4121 @Override 4122 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4123 int flags, int userId) { 4124 if (!sUserManager.exists(userId)) return null; 4125 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4126 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4127 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4128 } 4129 4130 @Override 4131 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4132 IntentFilter filter, int match, ComponentName activity) { 4133 final int userId = UserHandle.getCallingUserId(); 4134 if (DEBUG_PREFERRED) { 4135 Log.v(TAG, "setLastChosenActivity intent=" + intent 4136 + " resolvedType=" + resolvedType 4137 + " flags=" + flags 4138 + " filter=" + filter 4139 + " match=" + match 4140 + " activity=" + activity); 4141 filter.dump(new PrintStreamPrinter(System.out), " "); 4142 } 4143 intent.setComponent(null); 4144 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4145 // Find any earlier preferred or last chosen entries and nuke them 4146 findPreferredActivity(intent, resolvedType, 4147 flags, query, 0, false, true, false, userId); 4148 // Add the new activity as the last chosen for this filter 4149 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4150 "Setting last chosen"); 4151 } 4152 4153 @Override 4154 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4155 final int userId = UserHandle.getCallingUserId(); 4156 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4157 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4158 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4159 false, false, false, userId); 4160 } 4161 4162 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4163 int flags, List<ResolveInfo> query, int userId) { 4164 if (query != null) { 4165 final int N = query.size(); 4166 if (N == 1) { 4167 return query.get(0); 4168 } else if (N > 1) { 4169 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4170 // If there is more than one activity with the same priority, 4171 // then let the user decide between them. 4172 ResolveInfo r0 = query.get(0); 4173 ResolveInfo r1 = query.get(1); 4174 if (DEBUG_INTENT_MATCHING || debug) { 4175 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4176 + r1.activityInfo.name + "=" + r1.priority); 4177 } 4178 // If the first activity has a higher priority, or a different 4179 // default, then it is always desireable to pick it. 4180 if (r0.priority != r1.priority 4181 || r0.preferredOrder != r1.preferredOrder 4182 || r0.isDefault != r1.isDefault) { 4183 return query.get(0); 4184 } 4185 // If we have saved a preference for a preferred activity for 4186 // this Intent, use that. 4187 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4188 flags, query, r0.priority, true, false, debug, userId); 4189 if (ri != null) { 4190 return ri; 4191 } 4192 if (userId != 0) { 4193 ri = new ResolveInfo(mResolveInfo); 4194 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4195 ri.activityInfo.applicationInfo = new ApplicationInfo( 4196 ri.activityInfo.applicationInfo); 4197 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4198 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4199 return ri; 4200 } 4201 return mResolveInfo; 4202 } 4203 } 4204 return null; 4205 } 4206 4207 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4208 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4209 final int N = query.size(); 4210 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4211 .get(userId); 4212 // Get the list of persistent preferred activities that handle the intent 4213 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4214 List<PersistentPreferredActivity> pprefs = ppir != null 4215 ? ppir.queryIntent(intent, resolvedType, 4216 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4217 : null; 4218 if (pprefs != null && pprefs.size() > 0) { 4219 final int M = pprefs.size(); 4220 for (int i=0; i<M; i++) { 4221 final PersistentPreferredActivity ppa = pprefs.get(i); 4222 if (DEBUG_PREFERRED || debug) { 4223 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4224 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4225 + "\n component=" + ppa.mComponent); 4226 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4227 } 4228 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4229 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4230 if (DEBUG_PREFERRED || debug) { 4231 Slog.v(TAG, "Found persistent preferred activity:"); 4232 if (ai != null) { 4233 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4234 } else { 4235 Slog.v(TAG, " null"); 4236 } 4237 } 4238 if (ai == null) { 4239 // This previously registered persistent preferred activity 4240 // component is no longer known. Ignore it and do NOT remove it. 4241 continue; 4242 } 4243 for (int j=0; j<N; j++) { 4244 final ResolveInfo ri = query.get(j); 4245 if (!ri.activityInfo.applicationInfo.packageName 4246 .equals(ai.applicationInfo.packageName)) { 4247 continue; 4248 } 4249 if (!ri.activityInfo.name.equals(ai.name)) { 4250 continue; 4251 } 4252 // Found a persistent preference that can handle the intent. 4253 if (DEBUG_PREFERRED || debug) { 4254 Slog.v(TAG, "Returning persistent preferred activity: " + 4255 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4256 } 4257 return ri; 4258 } 4259 } 4260 } 4261 return null; 4262 } 4263 4264 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4265 List<ResolveInfo> query, int priority, boolean always, 4266 boolean removeMatches, boolean debug, int userId) { 4267 if (!sUserManager.exists(userId)) return null; 4268 // writer 4269 synchronized (mPackages) { 4270 if (intent.getSelector() != null) { 4271 intent = intent.getSelector(); 4272 } 4273 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4274 4275 // Try to find a matching persistent preferred activity. 4276 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4277 debug, userId); 4278 4279 // If a persistent preferred activity matched, use it. 4280 if (pri != null) { 4281 return pri; 4282 } 4283 4284 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4285 // Get the list of preferred activities that handle the intent 4286 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4287 List<PreferredActivity> prefs = pir != null 4288 ? pir.queryIntent(intent, resolvedType, 4289 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4290 : null; 4291 if (prefs != null && prefs.size() > 0) { 4292 boolean changed = false; 4293 try { 4294 // First figure out how good the original match set is. 4295 // We will only allow preferred activities that came 4296 // from the same match quality. 4297 int match = 0; 4298 4299 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4300 4301 final int N = query.size(); 4302 for (int j=0; j<N; j++) { 4303 final ResolveInfo ri = query.get(j); 4304 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4305 + ": 0x" + Integer.toHexString(match)); 4306 if (ri.match > match) { 4307 match = ri.match; 4308 } 4309 } 4310 4311 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4312 + Integer.toHexString(match)); 4313 4314 match &= IntentFilter.MATCH_CATEGORY_MASK; 4315 final int M = prefs.size(); 4316 for (int i=0; i<M; i++) { 4317 final PreferredActivity pa = prefs.get(i); 4318 if (DEBUG_PREFERRED || debug) { 4319 Slog.v(TAG, "Checking PreferredActivity ds=" 4320 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4321 + "\n component=" + pa.mPref.mComponent); 4322 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4323 } 4324 if (pa.mPref.mMatch != match) { 4325 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4326 + Integer.toHexString(pa.mPref.mMatch)); 4327 continue; 4328 } 4329 // If it's not an "always" type preferred activity and that's what we're 4330 // looking for, skip it. 4331 if (always && !pa.mPref.mAlways) { 4332 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4333 continue; 4334 } 4335 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4336 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4337 if (DEBUG_PREFERRED || debug) { 4338 Slog.v(TAG, "Found preferred activity:"); 4339 if (ai != null) { 4340 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4341 } else { 4342 Slog.v(TAG, " null"); 4343 } 4344 } 4345 if (ai == null) { 4346 // This previously registered preferred activity 4347 // component is no longer known. Most likely an update 4348 // to the app was installed and in the new version this 4349 // component no longer exists. Clean it up by removing 4350 // it from the preferred activities list, and skip it. 4351 Slog.w(TAG, "Removing dangling preferred activity: " 4352 + pa.mPref.mComponent); 4353 pir.removeFilter(pa); 4354 changed = true; 4355 continue; 4356 } 4357 for (int j=0; j<N; j++) { 4358 final ResolveInfo ri = query.get(j); 4359 if (!ri.activityInfo.applicationInfo.packageName 4360 .equals(ai.applicationInfo.packageName)) { 4361 continue; 4362 } 4363 if (!ri.activityInfo.name.equals(ai.name)) { 4364 continue; 4365 } 4366 4367 if (removeMatches) { 4368 pir.removeFilter(pa); 4369 changed = true; 4370 if (DEBUG_PREFERRED) { 4371 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4372 } 4373 break; 4374 } 4375 4376 // Okay we found a previously set preferred or last chosen app. 4377 // If the result set is different from when this 4378 // was created, we need to clear it and re-ask the 4379 // user their preference, if we're looking for an "always" type entry. 4380 if (always && !pa.mPref.sameSet(query)) { 4381 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4382 + intent + " type " + resolvedType); 4383 if (DEBUG_PREFERRED) { 4384 Slog.v(TAG, "Removing preferred activity since set changed " 4385 + pa.mPref.mComponent); 4386 } 4387 pir.removeFilter(pa); 4388 // Re-add the filter as a "last chosen" entry (!always) 4389 PreferredActivity lastChosen = new PreferredActivity( 4390 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4391 pir.addFilter(lastChosen); 4392 changed = true; 4393 return null; 4394 } 4395 4396 // Yay! Either the set matched or we're looking for the last chosen 4397 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4398 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4399 return ri; 4400 } 4401 } 4402 } finally { 4403 if (changed) { 4404 if (DEBUG_PREFERRED) { 4405 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4406 } 4407 scheduleWritePackageRestrictionsLocked(userId); 4408 } 4409 } 4410 } 4411 } 4412 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4413 return null; 4414 } 4415 4416 /* 4417 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4418 */ 4419 @Override 4420 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4421 int targetUserId) { 4422 mContext.enforceCallingOrSelfPermission( 4423 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4424 List<CrossProfileIntentFilter> matches = 4425 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4426 if (matches != null) { 4427 int size = matches.size(); 4428 for (int i = 0; i < size; i++) { 4429 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4430 } 4431 } 4432 if (hasWebURI(intent)) { 4433 // cross-profile app linking works only towards the parent. 4434 final UserInfo parent = getProfileParent(sourceUserId); 4435 synchronized(mPackages) { 4436 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4437 intent, resolvedType, 0, sourceUserId, parent.id); 4438 return xpDomainInfo != null; 4439 } 4440 } 4441 return false; 4442 } 4443 4444 private UserInfo getProfileParent(int userId) { 4445 final long identity = Binder.clearCallingIdentity(); 4446 try { 4447 return sUserManager.getProfileParent(userId); 4448 } finally { 4449 Binder.restoreCallingIdentity(identity); 4450 } 4451 } 4452 4453 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4454 String resolvedType, int userId) { 4455 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4456 if (resolver != null) { 4457 return resolver.queryIntent(intent, resolvedType, false, userId); 4458 } 4459 return null; 4460 } 4461 4462 @Override 4463 public List<ResolveInfo> queryIntentActivities(Intent intent, 4464 String resolvedType, int flags, int userId) { 4465 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4466 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4467 ComponentName comp = intent.getComponent(); 4468 if (comp == null) { 4469 if (intent.getSelector() != null) { 4470 intent = intent.getSelector(); 4471 comp = intent.getComponent(); 4472 } 4473 } 4474 4475 if (comp != null) { 4476 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4477 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4478 if (ai != null) { 4479 final ResolveInfo ri = new ResolveInfo(); 4480 ri.activityInfo = ai; 4481 list.add(ri); 4482 } 4483 return list; 4484 } 4485 4486 // reader 4487 synchronized (mPackages) { 4488 final String pkgName = intent.getPackage(); 4489 if (pkgName == null) { 4490 List<CrossProfileIntentFilter> matchingFilters = 4491 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4492 // Check for results that need to skip the current profile. 4493 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4494 resolvedType, flags, userId); 4495 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4496 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4497 result.add(xpResolveInfo); 4498 return filterIfNotPrimaryUser(result, userId); 4499 } 4500 4501 // Check for results in the current profile. 4502 List<ResolveInfo> result = mActivities.queryIntent( 4503 intent, resolvedType, flags, userId); 4504 4505 // Check for cross profile results. 4506 xpResolveInfo = queryCrossProfileIntents( 4507 matchingFilters, intent, resolvedType, flags, userId); 4508 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4509 result.add(xpResolveInfo); 4510 Collections.sort(result, mResolvePrioritySorter); 4511 } 4512 result = filterIfNotPrimaryUser(result, userId); 4513 if (hasWebURI(intent)) { 4514 CrossProfileDomainInfo xpDomainInfo = null; 4515 final UserInfo parent = getProfileParent(userId); 4516 if (parent != null) { 4517 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4518 flags, userId, parent.id); 4519 } 4520 if (xpDomainInfo != null) { 4521 if (xpResolveInfo != null) { 4522 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4523 // in the result. 4524 result.remove(xpResolveInfo); 4525 } 4526 if (result.size() == 0) { 4527 result.add(xpDomainInfo.resolveInfo); 4528 return result; 4529 } 4530 } else if (result.size() <= 1) { 4531 return result; 4532 } 4533 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4534 xpDomainInfo, userId); 4535 Collections.sort(result, mResolvePrioritySorter); 4536 } 4537 return result; 4538 } 4539 final PackageParser.Package pkg = mPackages.get(pkgName); 4540 if (pkg != null) { 4541 return filterIfNotPrimaryUser( 4542 mActivities.queryIntentForPackage( 4543 intent, resolvedType, flags, pkg.activities, userId), 4544 userId); 4545 } 4546 return new ArrayList<ResolveInfo>(); 4547 } 4548 } 4549 4550 private static class CrossProfileDomainInfo { 4551 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4552 ResolveInfo resolveInfo; 4553 /* Best domain verification status of the activities found in the other profile */ 4554 int bestDomainVerificationStatus; 4555 } 4556 4557 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4558 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4559 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4560 sourceUserId)) { 4561 return null; 4562 } 4563 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4564 resolvedType, flags, parentUserId); 4565 4566 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4567 return null; 4568 } 4569 CrossProfileDomainInfo result = null; 4570 int size = resultTargetUser.size(); 4571 for (int i = 0; i < size; i++) { 4572 ResolveInfo riTargetUser = resultTargetUser.get(i); 4573 // Intent filter verification is only for filters that specify a host. So don't return 4574 // those that handle all web uris. 4575 if (riTargetUser.handleAllWebDataURI) { 4576 continue; 4577 } 4578 String packageName = riTargetUser.activityInfo.packageName; 4579 PackageSetting ps = mSettings.mPackages.get(packageName); 4580 if (ps == null) { 4581 continue; 4582 } 4583 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4584 int status = (int)(verificationState >> 32); 4585 if (result == null) { 4586 result = new CrossProfileDomainInfo(); 4587 result.resolveInfo = 4588 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4589 result.bestDomainVerificationStatus = status; 4590 } else { 4591 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4592 result.bestDomainVerificationStatus); 4593 } 4594 } 4595 // Don't consider matches with status NEVER across profiles. 4596 if (result != null && result.bestDomainVerificationStatus 4597 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4598 return null; 4599 } 4600 return result; 4601 } 4602 4603 /** 4604 * Verification statuses are ordered from the worse to the best, except for 4605 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4606 */ 4607 private int bestDomainVerificationStatus(int status1, int status2) { 4608 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4609 return status2; 4610 } 4611 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4612 return status1; 4613 } 4614 return (int) MathUtils.max(status1, status2); 4615 } 4616 4617 private boolean isUserEnabled(int userId) { 4618 long callingId = Binder.clearCallingIdentity(); 4619 try { 4620 UserInfo userInfo = sUserManager.getUserInfo(userId); 4621 return userInfo != null && userInfo.isEnabled(); 4622 } finally { 4623 Binder.restoreCallingIdentity(callingId); 4624 } 4625 } 4626 4627 /** 4628 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4629 * 4630 * @return filtered list 4631 */ 4632 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4633 if (userId == UserHandle.USER_OWNER) { 4634 return resolveInfos; 4635 } 4636 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4637 ResolveInfo info = resolveInfos.get(i); 4638 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4639 resolveInfos.remove(i); 4640 } 4641 } 4642 return resolveInfos; 4643 } 4644 4645 private static boolean hasWebURI(Intent intent) { 4646 if (intent.getData() == null) { 4647 return false; 4648 } 4649 final String scheme = intent.getScheme(); 4650 if (TextUtils.isEmpty(scheme)) { 4651 return false; 4652 } 4653 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4654 } 4655 4656 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4657 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4658 int userId) { 4659 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4660 4661 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4662 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4663 candidates.size()); 4664 } 4665 4666 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4667 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4668 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4669 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4670 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4671 4672 synchronized (mPackages) { 4673 final int count = candidates.size(); 4674 // First, try to use linked apps. Partition the candidates into four lists: 4675 // one for the final results, one for the "do not use ever", one for "undefined status" 4676 // and finally one for "browser app type". 4677 for (int n=0; n<count; n++) { 4678 ResolveInfo info = candidates.get(n); 4679 String packageName = info.activityInfo.packageName; 4680 PackageSetting ps = mSettings.mPackages.get(packageName); 4681 if (ps != null) { 4682 // Add to the special match all list (Browser use case) 4683 if (info.handleAllWebDataURI) { 4684 matchAllList.add(info); 4685 continue; 4686 } 4687 // Try to get the status from User settings first 4688 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4689 int status = (int)(packedStatus >> 32); 4690 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4691 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4692 if (DEBUG_DOMAIN_VERIFICATION) { 4693 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4694 + " : linkgen=" + linkGeneration); 4695 } 4696 // Use link-enabled generation as preferredOrder, i.e. 4697 // prefer newly-enabled over earlier-enabled. 4698 info.preferredOrder = linkGeneration; 4699 alwaysList.add(info); 4700 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4701 if (DEBUG_DOMAIN_VERIFICATION) { 4702 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4703 } 4704 neverList.add(info); 4705 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4706 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4707 if (DEBUG_DOMAIN_VERIFICATION) { 4708 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4709 } 4710 undefinedList.add(info); 4711 } 4712 } 4713 } 4714 // First try to add the "always" resolution(s) for the current user, if any 4715 if (alwaysList.size() > 0) { 4716 result.addAll(alwaysList); 4717 // if there is an "always" for the parent user, add it. 4718 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4719 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4720 result.add(xpDomainInfo.resolveInfo); 4721 } else { 4722 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4723 result.addAll(undefinedList); 4724 if (xpDomainInfo != null && ( 4725 xpDomainInfo.bestDomainVerificationStatus 4726 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4727 || xpDomainInfo.bestDomainVerificationStatus 4728 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4729 result.add(xpDomainInfo.resolveInfo); 4730 } 4731 // Also add Browsers (all of them or only the default one) 4732 if ((matchFlags & MATCH_ALL) != 0) { 4733 result.addAll(matchAllList); 4734 } else { 4735 // Browser/generic handling case. If there's a default browser, go straight 4736 // to that (but only if there is no other higher-priority match). 4737 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4738 int maxMatchPrio = 0; 4739 ResolveInfo defaultBrowserMatch = null; 4740 final int numCandidates = matchAllList.size(); 4741 for (int n = 0; n < numCandidates; n++) { 4742 ResolveInfo info = matchAllList.get(n); 4743 // track the highest overall match priority... 4744 if (info.priority > maxMatchPrio) { 4745 maxMatchPrio = info.priority; 4746 } 4747 // ...and the highest-priority default browser match 4748 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4749 if (defaultBrowserMatch == null 4750 || (defaultBrowserMatch.priority < info.priority)) { 4751 if (debug) { 4752 Slog.v(TAG, "Considering default browser match " + info); 4753 } 4754 defaultBrowserMatch = info; 4755 } 4756 } 4757 } 4758 if (defaultBrowserMatch != null 4759 && defaultBrowserMatch.priority >= maxMatchPrio 4760 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4761 { 4762 if (debug) { 4763 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4764 } 4765 result.add(defaultBrowserMatch); 4766 } else { 4767 result.addAll(matchAllList); 4768 } 4769 } 4770 4771 // If there is nothing selected, add all candidates and remove the ones that the user 4772 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4773 if (result.size() == 0) { 4774 result.addAll(candidates); 4775 result.removeAll(neverList); 4776 } 4777 } 4778 } 4779 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4780 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4781 result.size()); 4782 for (ResolveInfo info : result) { 4783 Slog.v(TAG, " + " + info.activityInfo); 4784 } 4785 } 4786 return result; 4787 } 4788 4789 // Returns a packed value as a long: 4790 // 4791 // high 'int'-sized word: link status: undefined/ask/never/always. 4792 // low 'int'-sized word: relative priority among 'always' results. 4793 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4794 long result = ps.getDomainVerificationStatusForUser(userId); 4795 // if none available, get the master status 4796 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4797 if (ps.getIntentFilterVerificationInfo() != null) { 4798 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4799 } 4800 } 4801 return result; 4802 } 4803 4804 private ResolveInfo querySkipCurrentProfileIntents( 4805 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4806 int flags, int sourceUserId) { 4807 if (matchingFilters != null) { 4808 int size = matchingFilters.size(); 4809 for (int i = 0; i < size; i ++) { 4810 CrossProfileIntentFilter filter = matchingFilters.get(i); 4811 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4812 // Checking if there are activities in the target user that can handle the 4813 // intent. 4814 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4815 flags, sourceUserId); 4816 if (resolveInfo != null) { 4817 return resolveInfo; 4818 } 4819 } 4820 } 4821 } 4822 return null; 4823 } 4824 4825 // Return matching ResolveInfo if any for skip current profile intent filters. 4826 private ResolveInfo queryCrossProfileIntents( 4827 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4828 int flags, int sourceUserId) { 4829 if (matchingFilters != null) { 4830 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4831 // match the same intent. For performance reasons, it is better not to 4832 // run queryIntent twice for the same userId 4833 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4834 int size = matchingFilters.size(); 4835 for (int i = 0; i < size; i++) { 4836 CrossProfileIntentFilter filter = matchingFilters.get(i); 4837 int targetUserId = filter.getTargetUserId(); 4838 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4839 && !alreadyTriedUserIds.get(targetUserId)) { 4840 // Checking if there are activities in the target user that can handle the 4841 // intent. 4842 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4843 flags, sourceUserId); 4844 if (resolveInfo != null) return resolveInfo; 4845 alreadyTriedUserIds.put(targetUserId, true); 4846 } 4847 } 4848 } 4849 return null; 4850 } 4851 4852 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4853 String resolvedType, int flags, int sourceUserId) { 4854 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4855 resolvedType, flags, filter.getTargetUserId()); 4856 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4857 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4858 } 4859 return null; 4860 } 4861 4862 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4863 int sourceUserId, int targetUserId) { 4864 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4865 String className; 4866 if (targetUserId == UserHandle.USER_OWNER) { 4867 className = FORWARD_INTENT_TO_USER_OWNER; 4868 } else { 4869 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4870 } 4871 ComponentName forwardingActivityComponentName = new ComponentName( 4872 mAndroidApplication.packageName, className); 4873 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4874 sourceUserId); 4875 if (targetUserId == UserHandle.USER_OWNER) { 4876 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4877 forwardingResolveInfo.noResourceId = true; 4878 } 4879 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4880 forwardingResolveInfo.priority = 0; 4881 forwardingResolveInfo.preferredOrder = 0; 4882 forwardingResolveInfo.match = 0; 4883 forwardingResolveInfo.isDefault = true; 4884 forwardingResolveInfo.filter = filter; 4885 forwardingResolveInfo.targetUserId = targetUserId; 4886 return forwardingResolveInfo; 4887 } 4888 4889 @Override 4890 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4891 Intent[] specifics, String[] specificTypes, Intent intent, 4892 String resolvedType, int flags, int userId) { 4893 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4894 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4895 false, "query intent activity options"); 4896 final String resultsAction = intent.getAction(); 4897 4898 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4899 | PackageManager.GET_RESOLVED_FILTER, userId); 4900 4901 if (DEBUG_INTENT_MATCHING) { 4902 Log.v(TAG, "Query " + intent + ": " + results); 4903 } 4904 4905 int specificsPos = 0; 4906 int N; 4907 4908 // todo: note that the algorithm used here is O(N^2). This 4909 // isn't a problem in our current environment, but if we start running 4910 // into situations where we have more than 5 or 10 matches then this 4911 // should probably be changed to something smarter... 4912 4913 // First we go through and resolve each of the specific items 4914 // that were supplied, taking care of removing any corresponding 4915 // duplicate items in the generic resolve list. 4916 if (specifics != null) { 4917 for (int i=0; i<specifics.length; i++) { 4918 final Intent sintent = specifics[i]; 4919 if (sintent == null) { 4920 continue; 4921 } 4922 4923 if (DEBUG_INTENT_MATCHING) { 4924 Log.v(TAG, "Specific #" + i + ": " + sintent); 4925 } 4926 4927 String action = sintent.getAction(); 4928 if (resultsAction != null && resultsAction.equals(action)) { 4929 // If this action was explicitly requested, then don't 4930 // remove things that have it. 4931 action = null; 4932 } 4933 4934 ResolveInfo ri = null; 4935 ActivityInfo ai = null; 4936 4937 ComponentName comp = sintent.getComponent(); 4938 if (comp == null) { 4939 ri = resolveIntent( 4940 sintent, 4941 specificTypes != null ? specificTypes[i] : null, 4942 flags, userId); 4943 if (ri == null) { 4944 continue; 4945 } 4946 if (ri == mResolveInfo) { 4947 // ACK! Must do something better with this. 4948 } 4949 ai = ri.activityInfo; 4950 comp = new ComponentName(ai.applicationInfo.packageName, 4951 ai.name); 4952 } else { 4953 ai = getActivityInfo(comp, flags, userId); 4954 if (ai == null) { 4955 continue; 4956 } 4957 } 4958 4959 // Look for any generic query activities that are duplicates 4960 // of this specific one, and remove them from the results. 4961 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4962 N = results.size(); 4963 int j; 4964 for (j=specificsPos; j<N; j++) { 4965 ResolveInfo sri = results.get(j); 4966 if ((sri.activityInfo.name.equals(comp.getClassName()) 4967 && sri.activityInfo.applicationInfo.packageName.equals( 4968 comp.getPackageName())) 4969 || (action != null && sri.filter.matchAction(action))) { 4970 results.remove(j); 4971 if (DEBUG_INTENT_MATCHING) Log.v( 4972 TAG, "Removing duplicate item from " + j 4973 + " due to specific " + specificsPos); 4974 if (ri == null) { 4975 ri = sri; 4976 } 4977 j--; 4978 N--; 4979 } 4980 } 4981 4982 // Add this specific item to its proper place. 4983 if (ri == null) { 4984 ri = new ResolveInfo(); 4985 ri.activityInfo = ai; 4986 } 4987 results.add(specificsPos, ri); 4988 ri.specificIndex = i; 4989 specificsPos++; 4990 } 4991 } 4992 4993 // Now we go through the remaining generic results and remove any 4994 // duplicate actions that are found here. 4995 N = results.size(); 4996 for (int i=specificsPos; i<N-1; i++) { 4997 final ResolveInfo rii = results.get(i); 4998 if (rii.filter == null) { 4999 continue; 5000 } 5001 5002 // Iterate over all of the actions of this result's intent 5003 // filter... typically this should be just one. 5004 final Iterator<String> it = rii.filter.actionsIterator(); 5005 if (it == null) { 5006 continue; 5007 } 5008 while (it.hasNext()) { 5009 final String action = it.next(); 5010 if (resultsAction != null && resultsAction.equals(action)) { 5011 // If this action was explicitly requested, then don't 5012 // remove things that have it. 5013 continue; 5014 } 5015 for (int j=i+1; j<N; j++) { 5016 final ResolveInfo rij = results.get(j); 5017 if (rij.filter != null && rij.filter.hasAction(action)) { 5018 results.remove(j); 5019 if (DEBUG_INTENT_MATCHING) Log.v( 5020 TAG, "Removing duplicate item from " + j 5021 + " due to action " + action + " at " + i); 5022 j--; 5023 N--; 5024 } 5025 } 5026 } 5027 5028 // If the caller didn't request filter information, drop it now 5029 // so we don't have to marshall/unmarshall it. 5030 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5031 rii.filter = null; 5032 } 5033 } 5034 5035 // Filter out the caller activity if so requested. 5036 if (caller != null) { 5037 N = results.size(); 5038 for (int i=0; i<N; i++) { 5039 ActivityInfo ainfo = results.get(i).activityInfo; 5040 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5041 && caller.getClassName().equals(ainfo.name)) { 5042 results.remove(i); 5043 break; 5044 } 5045 } 5046 } 5047 5048 // If the caller didn't request filter information, 5049 // drop them now so we don't have to 5050 // marshall/unmarshall it. 5051 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5052 N = results.size(); 5053 for (int i=0; i<N; i++) { 5054 results.get(i).filter = null; 5055 } 5056 } 5057 5058 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5059 return results; 5060 } 5061 5062 @Override 5063 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5064 int userId) { 5065 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5066 ComponentName comp = intent.getComponent(); 5067 if (comp == null) { 5068 if (intent.getSelector() != null) { 5069 intent = intent.getSelector(); 5070 comp = intent.getComponent(); 5071 } 5072 } 5073 if (comp != null) { 5074 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5075 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5076 if (ai != null) { 5077 ResolveInfo ri = new ResolveInfo(); 5078 ri.activityInfo = ai; 5079 list.add(ri); 5080 } 5081 return list; 5082 } 5083 5084 // reader 5085 synchronized (mPackages) { 5086 String pkgName = intent.getPackage(); 5087 if (pkgName == null) { 5088 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5089 } 5090 final PackageParser.Package pkg = mPackages.get(pkgName); 5091 if (pkg != null) { 5092 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5093 userId); 5094 } 5095 return null; 5096 } 5097 } 5098 5099 @Override 5100 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5101 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5102 if (!sUserManager.exists(userId)) return null; 5103 if (query != null) { 5104 if (query.size() >= 1) { 5105 // If there is more than one service with the same priority, 5106 // just arbitrarily pick the first one. 5107 return query.get(0); 5108 } 5109 } 5110 return null; 5111 } 5112 5113 @Override 5114 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5115 int userId) { 5116 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5117 ComponentName comp = intent.getComponent(); 5118 if (comp == null) { 5119 if (intent.getSelector() != null) { 5120 intent = intent.getSelector(); 5121 comp = intent.getComponent(); 5122 } 5123 } 5124 if (comp != null) { 5125 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5126 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5127 if (si != null) { 5128 final ResolveInfo ri = new ResolveInfo(); 5129 ri.serviceInfo = si; 5130 list.add(ri); 5131 } 5132 return list; 5133 } 5134 5135 // reader 5136 synchronized (mPackages) { 5137 String pkgName = intent.getPackage(); 5138 if (pkgName == null) { 5139 return mServices.queryIntent(intent, resolvedType, flags, userId); 5140 } 5141 final PackageParser.Package pkg = mPackages.get(pkgName); 5142 if (pkg != null) { 5143 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5144 userId); 5145 } 5146 return null; 5147 } 5148 } 5149 5150 @Override 5151 public List<ResolveInfo> queryIntentContentProviders( 5152 Intent intent, String resolvedType, int flags, int userId) { 5153 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5154 ComponentName comp = intent.getComponent(); 5155 if (comp == null) { 5156 if (intent.getSelector() != null) { 5157 intent = intent.getSelector(); 5158 comp = intent.getComponent(); 5159 } 5160 } 5161 if (comp != null) { 5162 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5163 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5164 if (pi != null) { 5165 final ResolveInfo ri = new ResolveInfo(); 5166 ri.providerInfo = pi; 5167 list.add(ri); 5168 } 5169 return list; 5170 } 5171 5172 // reader 5173 synchronized (mPackages) { 5174 String pkgName = intent.getPackage(); 5175 if (pkgName == null) { 5176 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5177 } 5178 final PackageParser.Package pkg = mPackages.get(pkgName); 5179 if (pkg != null) { 5180 return mProviders.queryIntentForPackage( 5181 intent, resolvedType, flags, pkg.providers, userId); 5182 } 5183 return null; 5184 } 5185 } 5186 5187 @Override 5188 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5189 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5190 5191 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5192 5193 // writer 5194 synchronized (mPackages) { 5195 ArrayList<PackageInfo> list; 5196 if (listUninstalled) { 5197 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5198 for (PackageSetting ps : mSettings.mPackages.values()) { 5199 PackageInfo pi; 5200 if (ps.pkg != null) { 5201 pi = generatePackageInfo(ps.pkg, flags, userId); 5202 } else { 5203 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5204 } 5205 if (pi != null) { 5206 list.add(pi); 5207 } 5208 } 5209 } else { 5210 list = new ArrayList<PackageInfo>(mPackages.size()); 5211 for (PackageParser.Package p : mPackages.values()) { 5212 PackageInfo pi = generatePackageInfo(p, flags, userId); 5213 if (pi != null) { 5214 list.add(pi); 5215 } 5216 } 5217 } 5218 5219 return new ParceledListSlice<PackageInfo>(list); 5220 } 5221 } 5222 5223 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5224 String[] permissions, boolean[] tmp, int flags, int userId) { 5225 int numMatch = 0; 5226 final PermissionsState permissionsState = ps.getPermissionsState(); 5227 for (int i=0; i<permissions.length; i++) { 5228 final String permission = permissions[i]; 5229 if (permissionsState.hasPermission(permission, userId)) { 5230 tmp[i] = true; 5231 numMatch++; 5232 } else { 5233 tmp[i] = false; 5234 } 5235 } 5236 if (numMatch == 0) { 5237 return; 5238 } 5239 PackageInfo pi; 5240 if (ps.pkg != null) { 5241 pi = generatePackageInfo(ps.pkg, flags, userId); 5242 } else { 5243 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5244 } 5245 // The above might return null in cases of uninstalled apps or install-state 5246 // skew across users/profiles. 5247 if (pi != null) { 5248 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5249 if (numMatch == permissions.length) { 5250 pi.requestedPermissions = permissions; 5251 } else { 5252 pi.requestedPermissions = new String[numMatch]; 5253 numMatch = 0; 5254 for (int i=0; i<permissions.length; i++) { 5255 if (tmp[i]) { 5256 pi.requestedPermissions[numMatch] = permissions[i]; 5257 numMatch++; 5258 } 5259 } 5260 } 5261 } 5262 list.add(pi); 5263 } 5264 } 5265 5266 @Override 5267 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5268 String[] permissions, int flags, int userId) { 5269 if (!sUserManager.exists(userId)) return null; 5270 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5271 5272 // writer 5273 synchronized (mPackages) { 5274 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5275 boolean[] tmpBools = new boolean[permissions.length]; 5276 if (listUninstalled) { 5277 for (PackageSetting ps : mSettings.mPackages.values()) { 5278 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5279 } 5280 } else { 5281 for (PackageParser.Package pkg : mPackages.values()) { 5282 PackageSetting ps = (PackageSetting)pkg.mExtras; 5283 if (ps != null) { 5284 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5285 userId); 5286 } 5287 } 5288 } 5289 5290 return new ParceledListSlice<PackageInfo>(list); 5291 } 5292 } 5293 5294 @Override 5295 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5296 if (!sUserManager.exists(userId)) return null; 5297 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5298 5299 // writer 5300 synchronized (mPackages) { 5301 ArrayList<ApplicationInfo> list; 5302 if (listUninstalled) { 5303 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5304 for (PackageSetting ps : mSettings.mPackages.values()) { 5305 ApplicationInfo ai; 5306 if (ps.pkg != null) { 5307 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5308 ps.readUserState(userId), userId); 5309 } else { 5310 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5311 } 5312 if (ai != null) { 5313 list.add(ai); 5314 } 5315 } 5316 } else { 5317 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5318 for (PackageParser.Package p : mPackages.values()) { 5319 if (p.mExtras != null) { 5320 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5321 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5322 if (ai != null) { 5323 list.add(ai); 5324 } 5325 } 5326 } 5327 } 5328 5329 return new ParceledListSlice<ApplicationInfo>(list); 5330 } 5331 } 5332 5333 public List<ApplicationInfo> getPersistentApplications(int flags) { 5334 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5335 5336 // reader 5337 synchronized (mPackages) { 5338 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5339 final int userId = UserHandle.getCallingUserId(); 5340 while (i.hasNext()) { 5341 final PackageParser.Package p = i.next(); 5342 if (p.applicationInfo != null 5343 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5344 && (!mSafeMode || isSystemApp(p))) { 5345 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5346 if (ps != null) { 5347 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5348 ps.readUserState(userId), userId); 5349 if (ai != null) { 5350 finalList.add(ai); 5351 } 5352 } 5353 } 5354 } 5355 } 5356 5357 return finalList; 5358 } 5359 5360 @Override 5361 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5362 if (!sUserManager.exists(userId)) return null; 5363 // reader 5364 synchronized (mPackages) { 5365 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5366 PackageSetting ps = provider != null 5367 ? mSettings.mPackages.get(provider.owner.packageName) 5368 : null; 5369 return ps != null 5370 && mSettings.isEnabledLPr(provider.info, flags, userId) 5371 && (!mSafeMode || (provider.info.applicationInfo.flags 5372 &ApplicationInfo.FLAG_SYSTEM) != 0) 5373 ? PackageParser.generateProviderInfo(provider, flags, 5374 ps.readUserState(userId), userId) 5375 : null; 5376 } 5377 } 5378 5379 /** 5380 * @deprecated 5381 */ 5382 @Deprecated 5383 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5384 // reader 5385 synchronized (mPackages) { 5386 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5387 .entrySet().iterator(); 5388 final int userId = UserHandle.getCallingUserId(); 5389 while (i.hasNext()) { 5390 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5391 PackageParser.Provider p = entry.getValue(); 5392 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5393 5394 if (ps != null && p.syncable 5395 && (!mSafeMode || (p.info.applicationInfo.flags 5396 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5397 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5398 ps.readUserState(userId), userId); 5399 if (info != null) { 5400 outNames.add(entry.getKey()); 5401 outInfo.add(info); 5402 } 5403 } 5404 } 5405 } 5406 } 5407 5408 @Override 5409 public List<ProviderInfo> queryContentProviders(String processName, 5410 int uid, int flags) { 5411 ArrayList<ProviderInfo> finalList = null; 5412 // reader 5413 synchronized (mPackages) { 5414 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5415 final int userId = processName != null ? 5416 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5417 while (i.hasNext()) { 5418 final PackageParser.Provider p = i.next(); 5419 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5420 if (ps != null && p.info.authority != null 5421 && (processName == null 5422 || (p.info.processName.equals(processName) 5423 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5424 && mSettings.isEnabledLPr(p.info, flags, userId) 5425 && (!mSafeMode 5426 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5427 if (finalList == null) { 5428 finalList = new ArrayList<ProviderInfo>(3); 5429 } 5430 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5431 ps.readUserState(userId), userId); 5432 if (info != null) { 5433 finalList.add(info); 5434 } 5435 } 5436 } 5437 } 5438 5439 if (finalList != null) { 5440 Collections.sort(finalList, mProviderInitOrderSorter); 5441 } 5442 5443 return finalList; 5444 } 5445 5446 @Override 5447 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5448 int flags) { 5449 // reader 5450 synchronized (mPackages) { 5451 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5452 return PackageParser.generateInstrumentationInfo(i, flags); 5453 } 5454 } 5455 5456 @Override 5457 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5458 int flags) { 5459 ArrayList<InstrumentationInfo> finalList = 5460 new ArrayList<InstrumentationInfo>(); 5461 5462 // reader 5463 synchronized (mPackages) { 5464 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5465 while (i.hasNext()) { 5466 final PackageParser.Instrumentation p = i.next(); 5467 if (targetPackage == null 5468 || targetPackage.equals(p.info.targetPackage)) { 5469 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5470 flags); 5471 if (ii != null) { 5472 finalList.add(ii); 5473 } 5474 } 5475 } 5476 } 5477 5478 return finalList; 5479 } 5480 5481 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5482 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5483 if (overlays == null) { 5484 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5485 return; 5486 } 5487 for (PackageParser.Package opkg : overlays.values()) { 5488 // Not much to do if idmap fails: we already logged the error 5489 // and we certainly don't want to abort installation of pkg simply 5490 // because an overlay didn't fit properly. For these reasons, 5491 // ignore the return value of createIdmapForPackagePairLI. 5492 createIdmapForPackagePairLI(pkg, opkg); 5493 } 5494 } 5495 5496 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5497 PackageParser.Package opkg) { 5498 if (!opkg.mTrustedOverlay) { 5499 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5500 opkg.baseCodePath + ": overlay not trusted"); 5501 return false; 5502 } 5503 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5504 if (overlaySet == null) { 5505 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5506 opkg.baseCodePath + " but target package has no known overlays"); 5507 return false; 5508 } 5509 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5510 // TODO: generate idmap for split APKs 5511 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5512 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5513 + opkg.baseCodePath); 5514 return false; 5515 } 5516 PackageParser.Package[] overlayArray = 5517 overlaySet.values().toArray(new PackageParser.Package[0]); 5518 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5519 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5520 return p1.mOverlayPriority - p2.mOverlayPriority; 5521 } 5522 }; 5523 Arrays.sort(overlayArray, cmp); 5524 5525 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5526 int i = 0; 5527 for (PackageParser.Package p : overlayArray) { 5528 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5529 } 5530 return true; 5531 } 5532 5533 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5534 final File[] files = dir.listFiles(); 5535 if (ArrayUtils.isEmpty(files)) { 5536 Log.d(TAG, "No files in app dir " + dir); 5537 return; 5538 } 5539 5540 if (DEBUG_PACKAGE_SCANNING) { 5541 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5542 + " flags=0x" + Integer.toHexString(parseFlags)); 5543 } 5544 5545 for (File file : files) { 5546 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5547 && !PackageInstallerService.isStageName(file.getName()); 5548 if (!isPackage) { 5549 // Ignore entries which are not packages 5550 continue; 5551 } 5552 try { 5553 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5554 scanFlags, currentTime, null); 5555 } catch (PackageManagerException e) { 5556 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5557 5558 // Delete invalid userdata apps 5559 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5560 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5561 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5562 if (file.isDirectory()) { 5563 mInstaller.rmPackageDir(file.getAbsolutePath()); 5564 } else { 5565 file.delete(); 5566 } 5567 } 5568 } 5569 } 5570 } 5571 5572 private static File getSettingsProblemFile() { 5573 File dataDir = Environment.getDataDirectory(); 5574 File systemDir = new File(dataDir, "system"); 5575 File fname = new File(systemDir, "uiderrors.txt"); 5576 return fname; 5577 } 5578 5579 static void reportSettingsProblem(int priority, String msg) { 5580 logCriticalInfo(priority, msg); 5581 } 5582 5583 static void logCriticalInfo(int priority, String msg) { 5584 Slog.println(priority, TAG, msg); 5585 EventLogTags.writePmCriticalInfo(msg); 5586 try { 5587 File fname = getSettingsProblemFile(); 5588 FileOutputStream out = new FileOutputStream(fname, true); 5589 PrintWriter pw = new FastPrintWriter(out); 5590 SimpleDateFormat formatter = new SimpleDateFormat(); 5591 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5592 pw.println(dateString + ": " + msg); 5593 pw.close(); 5594 FileUtils.setPermissions( 5595 fname.toString(), 5596 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5597 -1, -1); 5598 } catch (java.io.IOException e) { 5599 } 5600 } 5601 5602 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5603 PackageParser.Package pkg, File srcFile, int parseFlags) 5604 throws PackageManagerException { 5605 if (ps != null 5606 && ps.codePath.equals(srcFile) 5607 && ps.timeStamp == srcFile.lastModified() 5608 && !isCompatSignatureUpdateNeeded(pkg) 5609 && !isRecoverSignatureUpdateNeeded(pkg)) { 5610 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5611 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5612 ArraySet<PublicKey> signingKs; 5613 synchronized (mPackages) { 5614 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5615 } 5616 if (ps.signatures.mSignatures != null 5617 && ps.signatures.mSignatures.length != 0 5618 && signingKs != null) { 5619 // Optimization: reuse the existing cached certificates 5620 // if the package appears to be unchanged. 5621 pkg.mSignatures = ps.signatures.mSignatures; 5622 pkg.mSigningKeys = signingKs; 5623 return; 5624 } 5625 5626 Slog.w(TAG, "PackageSetting for " + ps.name 5627 + " is missing signatures. Collecting certs again to recover them."); 5628 } else { 5629 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5630 } 5631 5632 try { 5633 pp.collectCertificates(pkg, parseFlags); 5634 pp.collectManifestDigest(pkg); 5635 } catch (PackageParserException e) { 5636 throw PackageManagerException.from(e); 5637 } 5638 } 5639 5640 /* 5641 * Scan a package and return the newly parsed package. 5642 * Returns null in case of errors and the error code is stored in mLastScanError 5643 */ 5644 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5645 long currentTime, UserHandle user) throws PackageManagerException { 5646 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5647 parseFlags |= mDefParseFlags; 5648 PackageParser pp = new PackageParser(); 5649 pp.setSeparateProcesses(mSeparateProcesses); 5650 pp.setOnlyCoreApps(mOnlyCore); 5651 pp.setDisplayMetrics(mMetrics); 5652 5653 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5654 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5655 } 5656 5657 final PackageParser.Package pkg; 5658 try { 5659 pkg = pp.parsePackage(scanFile, parseFlags); 5660 } catch (PackageParserException e) { 5661 throw PackageManagerException.from(e); 5662 } 5663 5664 PackageSetting ps = null; 5665 PackageSetting updatedPkg; 5666 // reader 5667 synchronized (mPackages) { 5668 // Look to see if we already know about this package. 5669 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5670 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5671 // This package has been renamed to its original name. Let's 5672 // use that. 5673 ps = mSettings.peekPackageLPr(oldName); 5674 } 5675 // If there was no original package, see one for the real package name. 5676 if (ps == null) { 5677 ps = mSettings.peekPackageLPr(pkg.packageName); 5678 } 5679 // Check to see if this package could be hiding/updating a system 5680 // package. Must look for it either under the original or real 5681 // package name depending on our state. 5682 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5683 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5684 } 5685 boolean updatedPkgBetter = false; 5686 // First check if this is a system package that may involve an update 5687 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5688 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5689 // it needs to drop FLAG_PRIVILEGED. 5690 if (locationIsPrivileged(scanFile)) { 5691 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5692 } else { 5693 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5694 } 5695 5696 if (ps != null && !ps.codePath.equals(scanFile)) { 5697 // The path has changed from what was last scanned... check the 5698 // version of the new path against what we have stored to determine 5699 // what to do. 5700 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5701 if (pkg.mVersionCode <= ps.versionCode) { 5702 // The system package has been updated and the code path does not match 5703 // Ignore entry. Skip it. 5704 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5705 + " ignored: updated version " + ps.versionCode 5706 + " better than this " + pkg.mVersionCode); 5707 if (!updatedPkg.codePath.equals(scanFile)) { 5708 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5709 + ps.name + " changing from " + updatedPkg.codePathString 5710 + " to " + scanFile); 5711 updatedPkg.codePath = scanFile; 5712 updatedPkg.codePathString = scanFile.toString(); 5713 updatedPkg.resourcePath = scanFile; 5714 updatedPkg.resourcePathString = scanFile.toString(); 5715 } 5716 updatedPkg.pkg = pkg; 5717 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5718 "Package " + ps.name + " at " + scanFile 5719 + " ignored: updated version " + ps.versionCode 5720 + " better than this " + pkg.mVersionCode); 5721 } else { 5722 // The current app on the system partition is better than 5723 // what we have updated to on the data partition; switch 5724 // back to the system partition version. 5725 // At this point, its safely assumed that package installation for 5726 // apps in system partition will go through. If not there won't be a working 5727 // version of the app 5728 // writer 5729 synchronized (mPackages) { 5730 // Just remove the loaded entries from package lists. 5731 mPackages.remove(ps.name); 5732 } 5733 5734 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5735 + " reverting from " + ps.codePathString 5736 + ": new version " + pkg.mVersionCode 5737 + " better than installed " + ps.versionCode); 5738 5739 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5740 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5741 synchronized (mInstallLock) { 5742 args.cleanUpResourcesLI(); 5743 } 5744 synchronized (mPackages) { 5745 mSettings.enableSystemPackageLPw(ps.name); 5746 } 5747 updatedPkgBetter = true; 5748 } 5749 } 5750 } 5751 5752 if (updatedPkg != null) { 5753 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5754 // initially 5755 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5756 5757 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5758 // flag set initially 5759 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5760 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5761 } 5762 } 5763 5764 // Verify certificates against what was last scanned 5765 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5766 5767 /* 5768 * A new system app appeared, but we already had a non-system one of the 5769 * same name installed earlier. 5770 */ 5771 boolean shouldHideSystemApp = false; 5772 if (updatedPkg == null && ps != null 5773 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5774 /* 5775 * Check to make sure the signatures match first. If they don't, 5776 * wipe the installed application and its data. 5777 */ 5778 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5779 != PackageManager.SIGNATURE_MATCH) { 5780 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5781 + " signatures don't match existing userdata copy; removing"); 5782 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5783 ps = null; 5784 } else { 5785 /* 5786 * If the newly-added system app is an older version than the 5787 * already installed version, hide it. It will be scanned later 5788 * and re-added like an update. 5789 */ 5790 if (pkg.mVersionCode <= ps.versionCode) { 5791 shouldHideSystemApp = true; 5792 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5793 + " but new version " + pkg.mVersionCode + " better than installed " 5794 + ps.versionCode + "; hiding system"); 5795 } else { 5796 /* 5797 * The newly found system app is a newer version that the 5798 * one previously installed. Simply remove the 5799 * already-installed application and replace it with our own 5800 * while keeping the application data. 5801 */ 5802 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5803 + " reverting from " + ps.codePathString + ": new version " 5804 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5805 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5806 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5807 synchronized (mInstallLock) { 5808 args.cleanUpResourcesLI(); 5809 } 5810 } 5811 } 5812 } 5813 5814 // The apk is forward locked (not public) if its code and resources 5815 // are kept in different files. (except for app in either system or 5816 // vendor path). 5817 // TODO grab this value from PackageSettings 5818 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5819 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5820 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5821 } 5822 } 5823 5824 // TODO: extend to support forward-locked splits 5825 String resourcePath = null; 5826 String baseResourcePath = null; 5827 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5828 if (ps != null && ps.resourcePathString != null) { 5829 resourcePath = ps.resourcePathString; 5830 baseResourcePath = ps.resourcePathString; 5831 } else { 5832 // Should not happen at all. Just log an error. 5833 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5834 } 5835 } else { 5836 resourcePath = pkg.codePath; 5837 baseResourcePath = pkg.baseCodePath; 5838 } 5839 5840 // Set application objects path explicitly. 5841 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5842 pkg.applicationInfo.setCodePath(pkg.codePath); 5843 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5844 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5845 pkg.applicationInfo.setResourcePath(resourcePath); 5846 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5847 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5848 5849 // Note that we invoke the following method only if we are about to unpack an application 5850 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5851 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5852 5853 /* 5854 * If the system app should be overridden by a previously installed 5855 * data, hide the system app now and let the /data/app scan pick it up 5856 * again. 5857 */ 5858 if (shouldHideSystemApp) { 5859 synchronized (mPackages) { 5860 /* 5861 * We have to grant systems permissions before we hide, because 5862 * grantPermissions will assume the package update is trying to 5863 * expand its permissions. 5864 */ 5865 grantPermissionsLPw(pkg, true, pkg.packageName); 5866 mSettings.disableSystemPackageLPw(pkg.packageName); 5867 } 5868 } 5869 5870 return scannedPkg; 5871 } 5872 5873 private static String fixProcessName(String defProcessName, 5874 String processName, int uid) { 5875 if (processName == null) { 5876 return defProcessName; 5877 } 5878 return processName; 5879 } 5880 5881 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5882 throws PackageManagerException { 5883 if (pkgSetting.signatures.mSignatures != null) { 5884 // Already existing package. Make sure signatures match 5885 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5886 == PackageManager.SIGNATURE_MATCH; 5887 if (!match) { 5888 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5889 == PackageManager.SIGNATURE_MATCH; 5890 } 5891 if (!match) { 5892 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5893 == PackageManager.SIGNATURE_MATCH; 5894 } 5895 if (!match) { 5896 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5897 + pkg.packageName + " signatures do not match the " 5898 + "previously installed version; ignoring!"); 5899 } 5900 } 5901 5902 // Check for shared user signatures 5903 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5904 // Already existing package. Make sure signatures match 5905 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5906 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5907 if (!match) { 5908 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5909 == PackageManager.SIGNATURE_MATCH; 5910 } 5911 if (!match) { 5912 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5913 == PackageManager.SIGNATURE_MATCH; 5914 } 5915 if (!match) { 5916 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5917 "Package " + pkg.packageName 5918 + " has no signatures that match those in shared user " 5919 + pkgSetting.sharedUser.name + "; ignoring!"); 5920 } 5921 } 5922 } 5923 5924 /** 5925 * Enforces that only the system UID or root's UID can call a method exposed 5926 * via Binder. 5927 * 5928 * @param message used as message if SecurityException is thrown 5929 * @throws SecurityException if the caller is not system or root 5930 */ 5931 private static final void enforceSystemOrRoot(String message) { 5932 final int uid = Binder.getCallingUid(); 5933 if (uid != Process.SYSTEM_UID && uid != 0) { 5934 throw new SecurityException(message); 5935 } 5936 } 5937 5938 @Override 5939 public void performBootDexOpt() { 5940 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5941 5942 // Before everything else, see whether we need to fstrim. 5943 try { 5944 IMountService ms = PackageHelper.getMountService(); 5945 if (ms != null) { 5946 final boolean isUpgrade = isUpgrade(); 5947 boolean doTrim = isUpgrade; 5948 if (doTrim) { 5949 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5950 } else { 5951 final long interval = android.provider.Settings.Global.getLong( 5952 mContext.getContentResolver(), 5953 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5954 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5955 if (interval > 0) { 5956 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5957 if (timeSinceLast > interval) { 5958 doTrim = true; 5959 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5960 + "; running immediately"); 5961 } 5962 } 5963 } 5964 if (doTrim) { 5965 if (!isFirstBoot()) { 5966 try { 5967 ActivityManagerNative.getDefault().showBootMessage( 5968 mContext.getResources().getString( 5969 R.string.android_upgrading_fstrim), true); 5970 } catch (RemoteException e) { 5971 } 5972 } 5973 ms.runMaintenance(); 5974 } 5975 } else { 5976 Slog.e(TAG, "Mount service unavailable!"); 5977 } 5978 } catch (RemoteException e) { 5979 // Can't happen; MountService is local 5980 } 5981 5982 final ArraySet<PackageParser.Package> pkgs; 5983 synchronized (mPackages) { 5984 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5985 } 5986 5987 if (pkgs != null) { 5988 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5989 // in case the device runs out of space. 5990 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5991 // Give priority to core apps. 5992 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5993 PackageParser.Package pkg = it.next(); 5994 if (pkg.coreApp) { 5995 if (DEBUG_DEXOPT) { 5996 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5997 } 5998 sortedPkgs.add(pkg); 5999 it.remove(); 6000 } 6001 } 6002 // Give priority to system apps that listen for pre boot complete. 6003 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6004 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6005 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6006 PackageParser.Package pkg = it.next(); 6007 if (pkgNames.contains(pkg.packageName)) { 6008 if (DEBUG_DEXOPT) { 6009 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6010 } 6011 sortedPkgs.add(pkg); 6012 it.remove(); 6013 } 6014 } 6015 // Give priority to system apps. 6016 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6017 PackageParser.Package pkg = it.next(); 6018 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6019 if (DEBUG_DEXOPT) { 6020 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6021 } 6022 sortedPkgs.add(pkg); 6023 it.remove(); 6024 } 6025 } 6026 // Give priority to updated system apps. 6027 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6028 PackageParser.Package pkg = it.next(); 6029 if (pkg.isUpdatedSystemApp()) { 6030 if (DEBUG_DEXOPT) { 6031 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6032 } 6033 sortedPkgs.add(pkg); 6034 it.remove(); 6035 } 6036 } 6037 // Give priority to apps that listen for boot complete. 6038 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6039 pkgNames = getPackageNamesForIntent(intent); 6040 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6041 PackageParser.Package pkg = it.next(); 6042 if (pkgNames.contains(pkg.packageName)) { 6043 if (DEBUG_DEXOPT) { 6044 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6045 } 6046 sortedPkgs.add(pkg); 6047 it.remove(); 6048 } 6049 } 6050 // Filter out packages that aren't recently used. 6051 filterRecentlyUsedApps(pkgs); 6052 // Add all remaining apps. 6053 for (PackageParser.Package pkg : pkgs) { 6054 if (DEBUG_DEXOPT) { 6055 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6056 } 6057 sortedPkgs.add(pkg); 6058 } 6059 6060 // If we want to be lazy, filter everything that wasn't recently used. 6061 if (mLazyDexOpt) { 6062 filterRecentlyUsedApps(sortedPkgs); 6063 } 6064 6065 int i = 0; 6066 int total = sortedPkgs.size(); 6067 File dataDir = Environment.getDataDirectory(); 6068 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6069 if (lowThreshold == 0) { 6070 throw new IllegalStateException("Invalid low memory threshold"); 6071 } 6072 for (PackageParser.Package pkg : sortedPkgs) { 6073 long usableSpace = dataDir.getUsableSpace(); 6074 if (usableSpace < lowThreshold) { 6075 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6076 break; 6077 } 6078 performBootDexOpt(pkg, ++i, total); 6079 } 6080 } 6081 } 6082 6083 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6084 // Filter out packages that aren't recently used. 6085 // 6086 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6087 // should do a full dexopt. 6088 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6089 int total = pkgs.size(); 6090 int skipped = 0; 6091 long now = System.currentTimeMillis(); 6092 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6093 PackageParser.Package pkg = i.next(); 6094 long then = pkg.mLastPackageUsageTimeInMills; 6095 if (then + mDexOptLRUThresholdInMills < now) { 6096 if (DEBUG_DEXOPT) { 6097 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6098 ((then == 0) ? "never" : new Date(then))); 6099 } 6100 i.remove(); 6101 skipped++; 6102 } 6103 } 6104 if (DEBUG_DEXOPT) { 6105 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6106 } 6107 } 6108 } 6109 6110 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6111 List<ResolveInfo> ris = null; 6112 try { 6113 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6114 intent, null, 0, UserHandle.USER_OWNER); 6115 } catch (RemoteException e) { 6116 } 6117 ArraySet<String> pkgNames = new ArraySet<String>(); 6118 if (ris != null) { 6119 for (ResolveInfo ri : ris) { 6120 pkgNames.add(ri.activityInfo.packageName); 6121 } 6122 } 6123 return pkgNames; 6124 } 6125 6126 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6127 if (DEBUG_DEXOPT) { 6128 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6129 } 6130 if (!isFirstBoot()) { 6131 try { 6132 ActivityManagerNative.getDefault().showBootMessage( 6133 mContext.getResources().getString(R.string.android_upgrading_apk, 6134 curr, total), true); 6135 } catch (RemoteException e) { 6136 } 6137 } 6138 PackageParser.Package p = pkg; 6139 synchronized (mInstallLock) { 6140 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6141 false /* force dex */, false /* defer */, true /* include dependencies */); 6142 } 6143 } 6144 6145 @Override 6146 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6147 return performDexOpt(packageName, instructionSet, false); 6148 } 6149 6150 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6151 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6152 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6153 if (!dexopt && !updateUsage) { 6154 // We aren't going to dexopt or update usage, so bail early. 6155 return false; 6156 } 6157 PackageParser.Package p; 6158 final String targetInstructionSet; 6159 synchronized (mPackages) { 6160 p = mPackages.get(packageName); 6161 if (p == null) { 6162 return false; 6163 } 6164 if (updateUsage) { 6165 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6166 } 6167 mPackageUsage.write(false); 6168 if (!dexopt) { 6169 // We aren't going to dexopt, so bail early. 6170 return false; 6171 } 6172 6173 targetInstructionSet = instructionSet != null ? instructionSet : 6174 getPrimaryInstructionSet(p.applicationInfo); 6175 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6176 return false; 6177 } 6178 } 6179 6180 synchronized (mInstallLock) { 6181 final String[] instructionSets = new String[] { targetInstructionSet }; 6182 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6183 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6184 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6185 } 6186 } 6187 6188 public ArraySet<String> getPackagesThatNeedDexOpt() { 6189 ArraySet<String> pkgs = null; 6190 synchronized (mPackages) { 6191 for (PackageParser.Package p : mPackages.values()) { 6192 if (DEBUG_DEXOPT) { 6193 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6194 } 6195 if (!p.mDexOptPerformed.isEmpty()) { 6196 continue; 6197 } 6198 if (pkgs == null) { 6199 pkgs = new ArraySet<String>(); 6200 } 6201 pkgs.add(p.packageName); 6202 } 6203 } 6204 return pkgs; 6205 } 6206 6207 public void shutdown() { 6208 mPackageUsage.write(true); 6209 } 6210 6211 @Override 6212 public void forceDexOpt(String packageName) { 6213 enforceSystemOrRoot("forceDexOpt"); 6214 6215 PackageParser.Package pkg; 6216 synchronized (mPackages) { 6217 pkg = mPackages.get(packageName); 6218 if (pkg == null) { 6219 throw new IllegalArgumentException("Missing package: " + packageName); 6220 } 6221 } 6222 6223 synchronized (mInstallLock) { 6224 final String[] instructionSets = new String[] { 6225 getPrimaryInstructionSet(pkg.applicationInfo) }; 6226 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6227 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6228 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6229 throw new IllegalStateException("Failed to dexopt: " + res); 6230 } 6231 } 6232 } 6233 6234 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6235 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6236 Slog.w(TAG, "Unable to update from " + oldPkg.name 6237 + " to " + newPkg.packageName 6238 + ": old package not in system partition"); 6239 return false; 6240 } else if (mPackages.get(oldPkg.name) != null) { 6241 Slog.w(TAG, "Unable to update from " + oldPkg.name 6242 + " to " + newPkg.packageName 6243 + ": old package still exists"); 6244 return false; 6245 } 6246 return true; 6247 } 6248 6249 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6250 int[] users = sUserManager.getUserIds(); 6251 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6252 if (res < 0) { 6253 return res; 6254 } 6255 for (int user : users) { 6256 if (user != 0) { 6257 res = mInstaller.createUserData(volumeUuid, packageName, 6258 UserHandle.getUid(user, uid), user, seinfo); 6259 if (res < 0) { 6260 return res; 6261 } 6262 } 6263 } 6264 return res; 6265 } 6266 6267 private int removeDataDirsLI(String volumeUuid, String packageName) { 6268 int[] users = sUserManager.getUserIds(); 6269 int res = 0; 6270 for (int user : users) { 6271 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6272 if (resInner < 0) { 6273 res = resInner; 6274 } 6275 } 6276 6277 return res; 6278 } 6279 6280 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6281 int[] users = sUserManager.getUserIds(); 6282 int res = 0; 6283 for (int user : users) { 6284 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6285 if (resInner < 0) { 6286 res = resInner; 6287 } 6288 } 6289 return res; 6290 } 6291 6292 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6293 PackageParser.Package changingLib) { 6294 if (file.path != null) { 6295 usesLibraryFiles.add(file.path); 6296 return; 6297 } 6298 PackageParser.Package p = mPackages.get(file.apk); 6299 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6300 // If we are doing this while in the middle of updating a library apk, 6301 // then we need to make sure to use that new apk for determining the 6302 // dependencies here. (We haven't yet finished committing the new apk 6303 // to the package manager state.) 6304 if (p == null || p.packageName.equals(changingLib.packageName)) { 6305 p = changingLib; 6306 } 6307 } 6308 if (p != null) { 6309 usesLibraryFiles.addAll(p.getAllCodePaths()); 6310 } 6311 } 6312 6313 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6314 PackageParser.Package changingLib) throws PackageManagerException { 6315 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6316 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6317 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6318 for (int i=0; i<N; i++) { 6319 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6320 if (file == null) { 6321 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6322 "Package " + pkg.packageName + " requires unavailable shared library " 6323 + pkg.usesLibraries.get(i) + "; failing!"); 6324 } 6325 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6326 } 6327 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6328 for (int i=0; i<N; i++) { 6329 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6330 if (file == null) { 6331 Slog.w(TAG, "Package " + pkg.packageName 6332 + " desires unavailable shared library " 6333 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6334 } else { 6335 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6336 } 6337 } 6338 N = usesLibraryFiles.size(); 6339 if (N > 0) { 6340 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6341 } else { 6342 pkg.usesLibraryFiles = null; 6343 } 6344 } 6345 } 6346 6347 private static boolean hasString(List<String> list, List<String> which) { 6348 if (list == null) { 6349 return false; 6350 } 6351 for (int i=list.size()-1; i>=0; i--) { 6352 for (int j=which.size()-1; j>=0; j--) { 6353 if (which.get(j).equals(list.get(i))) { 6354 return true; 6355 } 6356 } 6357 } 6358 return false; 6359 } 6360 6361 private void updateAllSharedLibrariesLPw() { 6362 for (PackageParser.Package pkg : mPackages.values()) { 6363 try { 6364 updateSharedLibrariesLPw(pkg, null); 6365 } catch (PackageManagerException e) { 6366 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6367 } 6368 } 6369 } 6370 6371 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6372 PackageParser.Package changingPkg) { 6373 ArrayList<PackageParser.Package> res = null; 6374 for (PackageParser.Package pkg : mPackages.values()) { 6375 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6376 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6377 if (res == null) { 6378 res = new ArrayList<PackageParser.Package>(); 6379 } 6380 res.add(pkg); 6381 try { 6382 updateSharedLibrariesLPw(pkg, changingPkg); 6383 } catch (PackageManagerException e) { 6384 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6385 } 6386 } 6387 } 6388 return res; 6389 } 6390 6391 /** 6392 * Derive the value of the {@code cpuAbiOverride} based on the provided 6393 * value and an optional stored value from the package settings. 6394 */ 6395 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6396 String cpuAbiOverride = null; 6397 6398 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6399 cpuAbiOverride = null; 6400 } else if (abiOverride != null) { 6401 cpuAbiOverride = abiOverride; 6402 } else if (settings != null) { 6403 cpuAbiOverride = settings.cpuAbiOverrideString; 6404 } 6405 6406 return cpuAbiOverride; 6407 } 6408 6409 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6410 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6411 boolean success = false; 6412 try { 6413 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6414 currentTime, user); 6415 success = true; 6416 return res; 6417 } finally { 6418 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6419 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6420 } 6421 } 6422 } 6423 6424 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6425 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6426 final File scanFile = new File(pkg.codePath); 6427 if (pkg.applicationInfo.getCodePath() == null || 6428 pkg.applicationInfo.getResourcePath() == null) { 6429 // Bail out. The resource and code paths haven't been set. 6430 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6431 "Code and resource paths haven't been set correctly"); 6432 } 6433 6434 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6435 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6436 } else { 6437 // Only allow system apps to be flagged as core apps. 6438 pkg.coreApp = false; 6439 } 6440 6441 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6442 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6443 } 6444 6445 if (mCustomResolverComponentName != null && 6446 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6447 setUpCustomResolverActivity(pkg); 6448 } 6449 6450 if (pkg.packageName.equals("android")) { 6451 synchronized (mPackages) { 6452 if (mAndroidApplication != null) { 6453 Slog.w(TAG, "*************************************************"); 6454 Slog.w(TAG, "Core android package being redefined. Skipping."); 6455 Slog.w(TAG, " file=" + scanFile); 6456 Slog.w(TAG, "*************************************************"); 6457 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6458 "Core android package being redefined. Skipping."); 6459 } 6460 6461 // Set up information for our fall-back user intent resolution activity. 6462 mPlatformPackage = pkg; 6463 pkg.mVersionCode = mSdkVersion; 6464 mAndroidApplication = pkg.applicationInfo; 6465 6466 if (!mResolverReplaced) { 6467 mResolveActivity.applicationInfo = mAndroidApplication; 6468 mResolveActivity.name = ResolverActivity.class.getName(); 6469 mResolveActivity.packageName = mAndroidApplication.packageName; 6470 mResolveActivity.processName = "system:ui"; 6471 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6472 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6473 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6474 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6475 mResolveActivity.exported = true; 6476 mResolveActivity.enabled = true; 6477 mResolveInfo.activityInfo = mResolveActivity; 6478 mResolveInfo.priority = 0; 6479 mResolveInfo.preferredOrder = 0; 6480 mResolveInfo.match = 0; 6481 mResolveComponentName = new ComponentName( 6482 mAndroidApplication.packageName, mResolveActivity.name); 6483 } 6484 } 6485 } 6486 6487 if (DEBUG_PACKAGE_SCANNING) { 6488 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6489 Log.d(TAG, "Scanning package " + pkg.packageName); 6490 } 6491 6492 if (mPackages.containsKey(pkg.packageName) 6493 || mSharedLibraries.containsKey(pkg.packageName)) { 6494 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6495 "Application package " + pkg.packageName 6496 + " already installed. Skipping duplicate."); 6497 } 6498 6499 // If we're only installing presumed-existing packages, require that the 6500 // scanned APK is both already known and at the path previously established 6501 // for it. Previously unknown packages we pick up normally, but if we have an 6502 // a priori expectation about this package's install presence, enforce it. 6503 // With a singular exception for new system packages. When an OTA contains 6504 // a new system package, we allow the codepath to change from a system location 6505 // to the user-installed location. If we don't allow this change, any newer, 6506 // user-installed version of the application will be ignored. 6507 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6508 if (mExpectingBetter.containsKey(pkg.packageName)) { 6509 logCriticalInfo(Log.WARN, 6510 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6511 } else { 6512 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6513 if (known != null) { 6514 if (DEBUG_PACKAGE_SCANNING) { 6515 Log.d(TAG, "Examining " + pkg.codePath 6516 + " and requiring known paths " + known.codePathString 6517 + " & " + known.resourcePathString); 6518 } 6519 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6520 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6521 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6522 "Application package " + pkg.packageName 6523 + " found at " + pkg.applicationInfo.getCodePath() 6524 + " but expected at " + known.codePathString + "; ignoring."); 6525 } 6526 } 6527 } 6528 } 6529 6530 // Initialize package source and resource directories 6531 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6532 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6533 6534 SharedUserSetting suid = null; 6535 PackageSetting pkgSetting = null; 6536 6537 if (!isSystemApp(pkg)) { 6538 // Only system apps can use these features. 6539 pkg.mOriginalPackages = null; 6540 pkg.mRealPackage = null; 6541 pkg.mAdoptPermissions = null; 6542 } 6543 6544 // writer 6545 synchronized (mPackages) { 6546 if (pkg.mSharedUserId != null) { 6547 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6548 if (suid == null) { 6549 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6550 "Creating application package " + pkg.packageName 6551 + " for shared user failed"); 6552 } 6553 if (DEBUG_PACKAGE_SCANNING) { 6554 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6555 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6556 + "): packages=" + suid.packages); 6557 } 6558 } 6559 6560 // Check if we are renaming from an original package name. 6561 PackageSetting origPackage = null; 6562 String realName = null; 6563 if (pkg.mOriginalPackages != null) { 6564 // This package may need to be renamed to a previously 6565 // installed name. Let's check on that... 6566 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6567 if (pkg.mOriginalPackages.contains(renamed)) { 6568 // This package had originally been installed as the 6569 // original name, and we have already taken care of 6570 // transitioning to the new one. Just update the new 6571 // one to continue using the old name. 6572 realName = pkg.mRealPackage; 6573 if (!pkg.packageName.equals(renamed)) { 6574 // Callers into this function may have already taken 6575 // care of renaming the package; only do it here if 6576 // it is not already done. 6577 pkg.setPackageName(renamed); 6578 } 6579 6580 } else { 6581 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6582 if ((origPackage = mSettings.peekPackageLPr( 6583 pkg.mOriginalPackages.get(i))) != null) { 6584 // We do have the package already installed under its 6585 // original name... should we use it? 6586 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6587 // New package is not compatible with original. 6588 origPackage = null; 6589 continue; 6590 } else if (origPackage.sharedUser != null) { 6591 // Make sure uid is compatible between packages. 6592 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6593 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6594 + " to " + pkg.packageName + ": old uid " 6595 + origPackage.sharedUser.name 6596 + " differs from " + pkg.mSharedUserId); 6597 origPackage = null; 6598 continue; 6599 } 6600 } else { 6601 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6602 + pkg.packageName + " to old name " + origPackage.name); 6603 } 6604 break; 6605 } 6606 } 6607 } 6608 } 6609 6610 if (mTransferedPackages.contains(pkg.packageName)) { 6611 Slog.w(TAG, "Package " + pkg.packageName 6612 + " was transferred to another, but its .apk remains"); 6613 } 6614 6615 // Just create the setting, don't add it yet. For already existing packages 6616 // the PkgSetting exists already and doesn't have to be created. 6617 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6618 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6619 pkg.applicationInfo.primaryCpuAbi, 6620 pkg.applicationInfo.secondaryCpuAbi, 6621 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6622 user, false); 6623 if (pkgSetting == null) { 6624 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6625 "Creating application package " + pkg.packageName + " failed"); 6626 } 6627 6628 if (pkgSetting.origPackage != null) { 6629 // If we are first transitioning from an original package, 6630 // fix up the new package's name now. We need to do this after 6631 // looking up the package under its new name, so getPackageLP 6632 // can take care of fiddling things correctly. 6633 pkg.setPackageName(origPackage.name); 6634 6635 // File a report about this. 6636 String msg = "New package " + pkgSetting.realName 6637 + " renamed to replace old package " + pkgSetting.name; 6638 reportSettingsProblem(Log.WARN, msg); 6639 6640 // Make a note of it. 6641 mTransferedPackages.add(origPackage.name); 6642 6643 // No longer need to retain this. 6644 pkgSetting.origPackage = null; 6645 } 6646 6647 if (realName != null) { 6648 // Make a note of it. 6649 mTransferedPackages.add(pkg.packageName); 6650 } 6651 6652 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6653 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6654 } 6655 6656 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6657 // Check all shared libraries and map to their actual file path. 6658 // We only do this here for apps not on a system dir, because those 6659 // are the only ones that can fail an install due to this. We 6660 // will take care of the system apps by updating all of their 6661 // library paths after the scan is done. 6662 updateSharedLibrariesLPw(pkg, null); 6663 } 6664 6665 if (mFoundPolicyFile) { 6666 SELinuxMMAC.assignSeinfoValue(pkg); 6667 } 6668 6669 pkg.applicationInfo.uid = pkgSetting.appId; 6670 pkg.mExtras = pkgSetting; 6671 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6672 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6673 // We just determined the app is signed correctly, so bring 6674 // over the latest parsed certs. 6675 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6676 } else { 6677 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6678 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6679 "Package " + pkg.packageName + " upgrade keys do not match the " 6680 + "previously installed version"); 6681 } else { 6682 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6683 String msg = "System package " + pkg.packageName 6684 + " signature changed; retaining data."; 6685 reportSettingsProblem(Log.WARN, msg); 6686 } 6687 } 6688 } else { 6689 try { 6690 verifySignaturesLP(pkgSetting, pkg); 6691 // We just determined the app is signed correctly, so bring 6692 // over the latest parsed certs. 6693 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6694 } catch (PackageManagerException e) { 6695 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6696 throw e; 6697 } 6698 // The signature has changed, but this package is in the system 6699 // image... let's recover! 6700 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6701 // However... if this package is part of a shared user, but it 6702 // doesn't match the signature of the shared user, let's fail. 6703 // What this means is that you can't change the signatures 6704 // associated with an overall shared user, which doesn't seem all 6705 // that unreasonable. 6706 if (pkgSetting.sharedUser != null) { 6707 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6708 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6709 throw new PackageManagerException( 6710 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6711 "Signature mismatch for shared user : " 6712 + pkgSetting.sharedUser); 6713 } 6714 } 6715 // File a report about this. 6716 String msg = "System package " + pkg.packageName 6717 + " signature changed; retaining data."; 6718 reportSettingsProblem(Log.WARN, msg); 6719 } 6720 } 6721 // Verify that this new package doesn't have any content providers 6722 // that conflict with existing packages. Only do this if the 6723 // package isn't already installed, since we don't want to break 6724 // things that are installed. 6725 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6726 final int N = pkg.providers.size(); 6727 int i; 6728 for (i=0; i<N; i++) { 6729 PackageParser.Provider p = pkg.providers.get(i); 6730 if (p.info.authority != null) { 6731 String names[] = p.info.authority.split(";"); 6732 for (int j = 0; j < names.length; j++) { 6733 if (mProvidersByAuthority.containsKey(names[j])) { 6734 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6735 final String otherPackageName = 6736 ((other != null && other.getComponentName() != null) ? 6737 other.getComponentName().getPackageName() : "?"); 6738 throw new PackageManagerException( 6739 INSTALL_FAILED_CONFLICTING_PROVIDER, 6740 "Can't install because provider name " + names[j] 6741 + " (in package " + pkg.applicationInfo.packageName 6742 + ") is already used by " + otherPackageName); 6743 } 6744 } 6745 } 6746 } 6747 } 6748 6749 if (pkg.mAdoptPermissions != null) { 6750 // This package wants to adopt ownership of permissions from 6751 // another package. 6752 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6753 final String origName = pkg.mAdoptPermissions.get(i); 6754 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6755 if (orig != null) { 6756 if (verifyPackageUpdateLPr(orig, pkg)) { 6757 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6758 + pkg.packageName); 6759 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6760 } 6761 } 6762 } 6763 } 6764 } 6765 6766 final String pkgName = pkg.packageName; 6767 6768 final long scanFileTime = scanFile.lastModified(); 6769 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6770 pkg.applicationInfo.processName = fixProcessName( 6771 pkg.applicationInfo.packageName, 6772 pkg.applicationInfo.processName, 6773 pkg.applicationInfo.uid); 6774 6775 File dataPath; 6776 if (mPlatformPackage == pkg) { 6777 // The system package is special. 6778 dataPath = new File(Environment.getDataDirectory(), "system"); 6779 6780 pkg.applicationInfo.dataDir = dataPath.getPath(); 6781 6782 } else { 6783 // This is a normal package, need to make its data directory. 6784 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6785 UserHandle.USER_OWNER, pkg.packageName); 6786 6787 boolean uidError = false; 6788 if (dataPath.exists()) { 6789 int currentUid = 0; 6790 try { 6791 StructStat stat = Os.stat(dataPath.getPath()); 6792 currentUid = stat.st_uid; 6793 } catch (ErrnoException e) { 6794 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6795 } 6796 6797 // If we have mismatched owners for the data path, we have a problem. 6798 if (currentUid != pkg.applicationInfo.uid) { 6799 boolean recovered = false; 6800 if (currentUid == 0) { 6801 // The directory somehow became owned by root. Wow. 6802 // This is probably because the system was stopped while 6803 // installd was in the middle of messing with its libs 6804 // directory. Ask installd to fix that. 6805 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6806 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6807 if (ret >= 0) { 6808 recovered = true; 6809 String msg = "Package " + pkg.packageName 6810 + " unexpectedly changed to uid 0; recovered to " + 6811 + pkg.applicationInfo.uid; 6812 reportSettingsProblem(Log.WARN, msg); 6813 } 6814 } 6815 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6816 || (scanFlags&SCAN_BOOTING) != 0)) { 6817 // If this is a system app, we can at least delete its 6818 // current data so the application will still work. 6819 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6820 if (ret >= 0) { 6821 // TODO: Kill the processes first 6822 // Old data gone! 6823 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6824 ? "System package " : "Third party package "; 6825 String msg = prefix + pkg.packageName 6826 + " has changed from uid: " 6827 + currentUid + " to " 6828 + pkg.applicationInfo.uid + "; old data erased"; 6829 reportSettingsProblem(Log.WARN, msg); 6830 recovered = true; 6831 6832 // And now re-install the app. 6833 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6834 pkg.applicationInfo.seinfo); 6835 if (ret == -1) { 6836 // Ack should not happen! 6837 msg = prefix + pkg.packageName 6838 + " could not have data directory re-created after delete."; 6839 reportSettingsProblem(Log.WARN, msg); 6840 throw new PackageManagerException( 6841 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6842 } 6843 } 6844 if (!recovered) { 6845 mHasSystemUidErrors = true; 6846 } 6847 } else if (!recovered) { 6848 // If we allow this install to proceed, we will be broken. 6849 // Abort, abort! 6850 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6851 "scanPackageLI"); 6852 } 6853 if (!recovered) { 6854 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6855 + pkg.applicationInfo.uid + "/fs_" 6856 + currentUid; 6857 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6858 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6859 String msg = "Package " + pkg.packageName 6860 + " has mismatched uid: " 6861 + currentUid + " on disk, " 6862 + pkg.applicationInfo.uid + " in settings"; 6863 // writer 6864 synchronized (mPackages) { 6865 mSettings.mReadMessages.append(msg); 6866 mSettings.mReadMessages.append('\n'); 6867 uidError = true; 6868 if (!pkgSetting.uidError) { 6869 reportSettingsProblem(Log.ERROR, msg); 6870 } 6871 } 6872 } 6873 } 6874 pkg.applicationInfo.dataDir = dataPath.getPath(); 6875 if (mShouldRestoreconData) { 6876 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6877 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6878 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6879 } 6880 } else { 6881 if (DEBUG_PACKAGE_SCANNING) { 6882 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6883 Log.v(TAG, "Want this data dir: " + dataPath); 6884 } 6885 //invoke installer to do the actual installation 6886 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6887 pkg.applicationInfo.seinfo); 6888 if (ret < 0) { 6889 // Error from installer 6890 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6891 "Unable to create data dirs [errorCode=" + ret + "]"); 6892 } 6893 6894 if (dataPath.exists()) { 6895 pkg.applicationInfo.dataDir = dataPath.getPath(); 6896 } else { 6897 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6898 pkg.applicationInfo.dataDir = null; 6899 } 6900 } 6901 6902 pkgSetting.uidError = uidError; 6903 } 6904 6905 final String path = scanFile.getPath(); 6906 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6907 6908 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6909 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6910 6911 // Some system apps still use directory structure for native libraries 6912 // in which case we might end up not detecting abi solely based on apk 6913 // structure. Try to detect abi based on directory structure. 6914 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6915 pkg.applicationInfo.primaryCpuAbi == null) { 6916 setBundledAppAbisAndRoots(pkg, pkgSetting); 6917 setNativeLibraryPaths(pkg); 6918 } 6919 6920 } else { 6921 if ((scanFlags & SCAN_MOVE) != 0) { 6922 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6923 // but we already have this packages package info in the PackageSetting. We just 6924 // use that and derive the native library path based on the new codepath. 6925 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6926 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6927 } 6928 6929 // Set native library paths again. For moves, the path will be updated based on the 6930 // ABIs we've determined above. For non-moves, the path will be updated based on the 6931 // ABIs we determined during compilation, but the path will depend on the final 6932 // package path (after the rename away from the stage path). 6933 setNativeLibraryPaths(pkg); 6934 } 6935 6936 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6937 final int[] userIds = sUserManager.getUserIds(); 6938 synchronized (mInstallLock) { 6939 // Make sure all user data directories are ready to roll; we're okay 6940 // if they already exist 6941 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6942 for (int userId : userIds) { 6943 if (userId != 0) { 6944 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6945 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6946 pkg.applicationInfo.seinfo); 6947 } 6948 } 6949 } 6950 6951 // Create a native library symlink only if we have native libraries 6952 // and if the native libraries are 32 bit libraries. We do not provide 6953 // this symlink for 64 bit libraries. 6954 if (pkg.applicationInfo.primaryCpuAbi != null && 6955 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6956 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6957 for (int userId : userIds) { 6958 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6959 nativeLibPath, userId) < 0) { 6960 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6961 "Failed linking native library dir (user=" + userId + ")"); 6962 } 6963 } 6964 } 6965 } 6966 6967 // This is a special case for the "system" package, where the ABI is 6968 // dictated by the zygote configuration (and init.rc). We should keep track 6969 // of this ABI so that we can deal with "normal" applications that run under 6970 // the same UID correctly. 6971 if (mPlatformPackage == pkg) { 6972 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6973 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6974 } 6975 6976 // If there's a mismatch between the abi-override in the package setting 6977 // and the abiOverride specified for the install. Warn about this because we 6978 // would've already compiled the app without taking the package setting into 6979 // account. 6980 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6981 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6982 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6983 " for package: " + pkg.packageName); 6984 } 6985 } 6986 6987 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6988 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6989 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6990 6991 // Copy the derived override back to the parsed package, so that we can 6992 // update the package settings accordingly. 6993 pkg.cpuAbiOverride = cpuAbiOverride; 6994 6995 if (DEBUG_ABI_SELECTION) { 6996 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6997 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6998 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6999 } 7000 7001 // Push the derived path down into PackageSettings so we know what to 7002 // clean up at uninstall time. 7003 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7004 7005 if (DEBUG_ABI_SELECTION) { 7006 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7007 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7008 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7009 } 7010 7011 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7012 // We don't do this here during boot because we can do it all 7013 // at once after scanning all existing packages. 7014 // 7015 // We also do this *before* we perform dexopt on this package, so that 7016 // we can avoid redundant dexopts, and also to make sure we've got the 7017 // code and package path correct. 7018 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7019 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7020 } 7021 7022 if ((scanFlags & SCAN_NO_DEX) == 0) { 7023 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7024 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7025 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7026 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7027 } 7028 } 7029 if (mFactoryTest && pkg.requestedPermissions.contains( 7030 android.Manifest.permission.FACTORY_TEST)) { 7031 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7032 } 7033 7034 ArrayList<PackageParser.Package> clientLibPkgs = null; 7035 7036 // writer 7037 synchronized (mPackages) { 7038 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7039 // Only system apps can add new shared libraries. 7040 if (pkg.libraryNames != null) { 7041 for (int i=0; i<pkg.libraryNames.size(); i++) { 7042 String name = pkg.libraryNames.get(i); 7043 boolean allowed = false; 7044 if (pkg.isUpdatedSystemApp()) { 7045 // New library entries can only be added through the 7046 // system image. This is important to get rid of a lot 7047 // of nasty edge cases: for example if we allowed a non- 7048 // system update of the app to add a library, then uninstalling 7049 // the update would make the library go away, and assumptions 7050 // we made such as through app install filtering would now 7051 // have allowed apps on the device which aren't compatible 7052 // with it. Better to just have the restriction here, be 7053 // conservative, and create many fewer cases that can negatively 7054 // impact the user experience. 7055 final PackageSetting sysPs = mSettings 7056 .getDisabledSystemPkgLPr(pkg.packageName); 7057 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7058 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7059 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7060 allowed = true; 7061 allowed = true; 7062 break; 7063 } 7064 } 7065 } 7066 } else { 7067 allowed = true; 7068 } 7069 if (allowed) { 7070 if (!mSharedLibraries.containsKey(name)) { 7071 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7072 } else if (!name.equals(pkg.packageName)) { 7073 Slog.w(TAG, "Package " + pkg.packageName + " library " 7074 + name + " already exists; skipping"); 7075 } 7076 } else { 7077 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7078 + name + " that is not declared on system image; skipping"); 7079 } 7080 } 7081 if ((scanFlags&SCAN_BOOTING) == 0) { 7082 // If we are not booting, we need to update any applications 7083 // that are clients of our shared library. If we are booting, 7084 // this will all be done once the scan is complete. 7085 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7086 } 7087 } 7088 } 7089 } 7090 7091 // We also need to dexopt any apps that are dependent on this library. Note that 7092 // if these fail, we should abort the install since installing the library will 7093 // result in some apps being broken. 7094 if (clientLibPkgs != null) { 7095 if ((scanFlags & SCAN_NO_DEX) == 0) { 7096 for (int i = 0; i < clientLibPkgs.size(); i++) { 7097 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7098 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7099 null /* instruction sets */, forceDex, 7100 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7101 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7102 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7103 "scanPackageLI failed to dexopt clientLibPkgs"); 7104 } 7105 } 7106 } 7107 } 7108 7109 // Also need to kill any apps that are dependent on the library. 7110 if (clientLibPkgs != null) { 7111 for (int i=0; i<clientLibPkgs.size(); i++) { 7112 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7113 killApplication(clientPkg.applicationInfo.packageName, 7114 clientPkg.applicationInfo.uid, "update lib"); 7115 } 7116 } 7117 7118 // Make sure we're not adding any bogus keyset info 7119 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7120 ksms.assertScannedPackageValid(pkg); 7121 7122 // writer 7123 synchronized (mPackages) { 7124 // We don't expect installation to fail beyond this point 7125 7126 // Add the new setting to mSettings 7127 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7128 // Add the new setting to mPackages 7129 mPackages.put(pkg.applicationInfo.packageName, pkg); 7130 // Make sure we don't accidentally delete its data. 7131 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7132 while (iter.hasNext()) { 7133 PackageCleanItem item = iter.next(); 7134 if (pkgName.equals(item.packageName)) { 7135 iter.remove(); 7136 } 7137 } 7138 7139 // Take care of first install / last update times. 7140 if (currentTime != 0) { 7141 if (pkgSetting.firstInstallTime == 0) { 7142 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7143 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7144 pkgSetting.lastUpdateTime = currentTime; 7145 } 7146 } else if (pkgSetting.firstInstallTime == 0) { 7147 // We need *something*. Take time time stamp of the file. 7148 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7149 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7150 if (scanFileTime != pkgSetting.timeStamp) { 7151 // A package on the system image has changed; consider this 7152 // to be an update. 7153 pkgSetting.lastUpdateTime = scanFileTime; 7154 } 7155 } 7156 7157 // Add the package's KeySets to the global KeySetManagerService 7158 ksms.addScannedPackageLPw(pkg); 7159 7160 int N = pkg.providers.size(); 7161 StringBuilder r = null; 7162 int i; 7163 for (i=0; i<N; i++) { 7164 PackageParser.Provider p = pkg.providers.get(i); 7165 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7166 p.info.processName, pkg.applicationInfo.uid); 7167 mProviders.addProvider(p); 7168 p.syncable = p.info.isSyncable; 7169 if (p.info.authority != null) { 7170 String names[] = p.info.authority.split(";"); 7171 p.info.authority = null; 7172 for (int j = 0; j < names.length; j++) { 7173 if (j == 1 && p.syncable) { 7174 // We only want the first authority for a provider to possibly be 7175 // syncable, so if we already added this provider using a different 7176 // authority clear the syncable flag. We copy the provider before 7177 // changing it because the mProviders object contains a reference 7178 // to a provider that we don't want to change. 7179 // Only do this for the second authority since the resulting provider 7180 // object can be the same for all future authorities for this provider. 7181 p = new PackageParser.Provider(p); 7182 p.syncable = false; 7183 } 7184 if (!mProvidersByAuthority.containsKey(names[j])) { 7185 mProvidersByAuthority.put(names[j], p); 7186 if (p.info.authority == null) { 7187 p.info.authority = names[j]; 7188 } else { 7189 p.info.authority = p.info.authority + ";" + names[j]; 7190 } 7191 if (DEBUG_PACKAGE_SCANNING) { 7192 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7193 Log.d(TAG, "Registered content provider: " + names[j] 7194 + ", className = " + p.info.name + ", isSyncable = " 7195 + p.info.isSyncable); 7196 } 7197 } else { 7198 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7199 Slog.w(TAG, "Skipping provider name " + names[j] + 7200 " (in package " + pkg.applicationInfo.packageName + 7201 "): name already used by " 7202 + ((other != null && other.getComponentName() != null) 7203 ? other.getComponentName().getPackageName() : "?")); 7204 } 7205 } 7206 } 7207 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7208 if (r == null) { 7209 r = new StringBuilder(256); 7210 } else { 7211 r.append(' '); 7212 } 7213 r.append(p.info.name); 7214 } 7215 } 7216 if (r != null) { 7217 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7218 } 7219 7220 N = pkg.services.size(); 7221 r = null; 7222 for (i=0; i<N; i++) { 7223 PackageParser.Service s = pkg.services.get(i); 7224 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7225 s.info.processName, pkg.applicationInfo.uid); 7226 mServices.addService(s); 7227 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7228 if (r == null) { 7229 r = new StringBuilder(256); 7230 } else { 7231 r.append(' '); 7232 } 7233 r.append(s.info.name); 7234 } 7235 } 7236 if (r != null) { 7237 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7238 } 7239 7240 N = pkg.receivers.size(); 7241 r = null; 7242 for (i=0; i<N; i++) { 7243 PackageParser.Activity a = pkg.receivers.get(i); 7244 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7245 a.info.processName, pkg.applicationInfo.uid); 7246 mReceivers.addActivity(a, "receiver"); 7247 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7248 if (r == null) { 7249 r = new StringBuilder(256); 7250 } else { 7251 r.append(' '); 7252 } 7253 r.append(a.info.name); 7254 } 7255 } 7256 if (r != null) { 7257 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7258 } 7259 7260 N = pkg.activities.size(); 7261 r = null; 7262 for (i=0; i<N; i++) { 7263 PackageParser.Activity a = pkg.activities.get(i); 7264 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7265 a.info.processName, pkg.applicationInfo.uid); 7266 mActivities.addActivity(a, "activity"); 7267 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7268 if (r == null) { 7269 r = new StringBuilder(256); 7270 } else { 7271 r.append(' '); 7272 } 7273 r.append(a.info.name); 7274 } 7275 } 7276 if (r != null) { 7277 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7278 } 7279 7280 N = pkg.permissionGroups.size(); 7281 r = null; 7282 for (i=0; i<N; i++) { 7283 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7284 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7285 if (cur == null) { 7286 mPermissionGroups.put(pg.info.name, pg); 7287 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7288 if (r == null) { 7289 r = new StringBuilder(256); 7290 } else { 7291 r.append(' '); 7292 } 7293 r.append(pg.info.name); 7294 } 7295 } else { 7296 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7297 + pg.info.packageName + " ignored: original from " 7298 + cur.info.packageName); 7299 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7300 if (r == null) { 7301 r = new StringBuilder(256); 7302 } else { 7303 r.append(' '); 7304 } 7305 r.append("DUP:"); 7306 r.append(pg.info.name); 7307 } 7308 } 7309 } 7310 if (r != null) { 7311 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7312 } 7313 7314 N = pkg.permissions.size(); 7315 r = null; 7316 for (i=0; i<N; i++) { 7317 PackageParser.Permission p = pkg.permissions.get(i); 7318 7319 // Now that permission groups have a special meaning, we ignore permission 7320 // groups for legacy apps to prevent unexpected behavior. In particular, 7321 // permissions for one app being granted to someone just becuase they happen 7322 // to be in a group defined by another app (before this had no implications). 7323 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7324 p.group = mPermissionGroups.get(p.info.group); 7325 // Warn for a permission in an unknown group. 7326 if (p.info.group != null && p.group == null) { 7327 Slog.w(TAG, "Permission " + p.info.name + " from package " 7328 + p.info.packageName + " in an unknown group " + p.info.group); 7329 } 7330 } 7331 7332 ArrayMap<String, BasePermission> permissionMap = 7333 p.tree ? mSettings.mPermissionTrees 7334 : mSettings.mPermissions; 7335 BasePermission bp = permissionMap.get(p.info.name); 7336 7337 // Allow system apps to redefine non-system permissions 7338 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7339 final boolean currentOwnerIsSystem = (bp.perm != null 7340 && isSystemApp(bp.perm.owner)); 7341 if (isSystemApp(p.owner)) { 7342 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7343 // It's a built-in permission and no owner, take ownership now 7344 bp.packageSetting = pkgSetting; 7345 bp.perm = p; 7346 bp.uid = pkg.applicationInfo.uid; 7347 bp.sourcePackage = p.info.packageName; 7348 } else if (!currentOwnerIsSystem) { 7349 String msg = "New decl " + p.owner + " of permission " 7350 + p.info.name + " is system; overriding " + bp.sourcePackage; 7351 reportSettingsProblem(Log.WARN, msg); 7352 bp = null; 7353 } 7354 } 7355 } 7356 7357 if (bp == null) { 7358 bp = new BasePermission(p.info.name, p.info.packageName, 7359 BasePermission.TYPE_NORMAL); 7360 permissionMap.put(p.info.name, bp); 7361 } 7362 7363 if (bp.perm == null) { 7364 if (bp.sourcePackage == null 7365 || bp.sourcePackage.equals(p.info.packageName)) { 7366 BasePermission tree = findPermissionTreeLP(p.info.name); 7367 if (tree == null 7368 || tree.sourcePackage.equals(p.info.packageName)) { 7369 bp.packageSetting = pkgSetting; 7370 bp.perm = p; 7371 bp.uid = pkg.applicationInfo.uid; 7372 bp.sourcePackage = p.info.packageName; 7373 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7374 if (r == null) { 7375 r = new StringBuilder(256); 7376 } else { 7377 r.append(' '); 7378 } 7379 r.append(p.info.name); 7380 } 7381 } else { 7382 Slog.w(TAG, "Permission " + p.info.name + " from package " 7383 + p.info.packageName + " ignored: base tree " 7384 + tree.name + " is from package " 7385 + tree.sourcePackage); 7386 } 7387 } else { 7388 Slog.w(TAG, "Permission " + p.info.name + " from package " 7389 + p.info.packageName + " ignored: original from " 7390 + bp.sourcePackage); 7391 } 7392 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7393 if (r == null) { 7394 r = new StringBuilder(256); 7395 } else { 7396 r.append(' '); 7397 } 7398 r.append("DUP:"); 7399 r.append(p.info.name); 7400 } 7401 if (bp.perm == p) { 7402 bp.protectionLevel = p.info.protectionLevel; 7403 } 7404 } 7405 7406 if (r != null) { 7407 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7408 } 7409 7410 N = pkg.instrumentation.size(); 7411 r = null; 7412 for (i=0; i<N; i++) { 7413 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7414 a.info.packageName = pkg.applicationInfo.packageName; 7415 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7416 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7417 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7418 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7419 a.info.dataDir = pkg.applicationInfo.dataDir; 7420 7421 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7422 // need other information about the application, like the ABI and what not ? 7423 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7424 mInstrumentation.put(a.getComponentName(), a); 7425 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7426 if (r == null) { 7427 r = new StringBuilder(256); 7428 } else { 7429 r.append(' '); 7430 } 7431 r.append(a.info.name); 7432 } 7433 } 7434 if (r != null) { 7435 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7436 } 7437 7438 if (pkg.protectedBroadcasts != null) { 7439 N = pkg.protectedBroadcasts.size(); 7440 for (i=0; i<N; i++) { 7441 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7442 } 7443 } 7444 7445 pkgSetting.setTimeStamp(scanFileTime); 7446 7447 // Create idmap files for pairs of (packages, overlay packages). 7448 // Note: "android", ie framework-res.apk, is handled by native layers. 7449 if (pkg.mOverlayTarget != null) { 7450 // This is an overlay package. 7451 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7452 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7453 mOverlays.put(pkg.mOverlayTarget, 7454 new ArrayMap<String, PackageParser.Package>()); 7455 } 7456 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7457 map.put(pkg.packageName, pkg); 7458 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7459 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7460 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7461 "scanPackageLI failed to createIdmap"); 7462 } 7463 } 7464 } else if (mOverlays.containsKey(pkg.packageName) && 7465 !pkg.packageName.equals("android")) { 7466 // This is a regular package, with one or more known overlay packages. 7467 createIdmapsForPackageLI(pkg); 7468 } 7469 } 7470 7471 return pkg; 7472 } 7473 7474 /** 7475 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7476 * is derived purely on the basis of the contents of {@code scanFile} and 7477 * {@code cpuAbiOverride}. 7478 * 7479 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7480 */ 7481 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7482 String cpuAbiOverride, boolean extractLibs) 7483 throws PackageManagerException { 7484 // TODO: We can probably be smarter about this stuff. For installed apps, 7485 // we can calculate this information at install time once and for all. For 7486 // system apps, we can probably assume that this information doesn't change 7487 // after the first boot scan. As things stand, we do lots of unnecessary work. 7488 7489 // Give ourselves some initial paths; we'll come back for another 7490 // pass once we've determined ABI below. 7491 setNativeLibraryPaths(pkg); 7492 7493 // We would never need to extract libs for forward-locked and external packages, 7494 // since the container service will do it for us. We shouldn't attempt to 7495 // extract libs from system app when it was not updated. 7496 if (pkg.isForwardLocked() || isExternal(pkg) || 7497 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7498 extractLibs = false; 7499 } 7500 7501 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7502 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7503 7504 NativeLibraryHelper.Handle handle = null; 7505 try { 7506 handle = NativeLibraryHelper.Handle.create(scanFile); 7507 // TODO(multiArch): This can be null for apps that didn't go through the 7508 // usual installation process. We can calculate it again, like we 7509 // do during install time. 7510 // 7511 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7512 // unnecessary. 7513 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7514 7515 // Null out the abis so that they can be recalculated. 7516 pkg.applicationInfo.primaryCpuAbi = null; 7517 pkg.applicationInfo.secondaryCpuAbi = null; 7518 if (isMultiArch(pkg.applicationInfo)) { 7519 // Warn if we've set an abiOverride for multi-lib packages.. 7520 // By definition, we need to copy both 32 and 64 bit libraries for 7521 // such packages. 7522 if (pkg.cpuAbiOverride != null 7523 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7524 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7525 } 7526 7527 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7528 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7529 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7530 if (extractLibs) { 7531 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7532 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7533 useIsaSpecificSubdirs); 7534 } else { 7535 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7536 } 7537 } 7538 7539 maybeThrowExceptionForMultiArchCopy( 7540 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7541 7542 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7543 if (extractLibs) { 7544 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7545 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7546 useIsaSpecificSubdirs); 7547 } else { 7548 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7549 } 7550 } 7551 7552 maybeThrowExceptionForMultiArchCopy( 7553 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7554 7555 if (abi64 >= 0) { 7556 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7557 } 7558 7559 if (abi32 >= 0) { 7560 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7561 if (abi64 >= 0) { 7562 pkg.applicationInfo.secondaryCpuAbi = abi; 7563 } else { 7564 pkg.applicationInfo.primaryCpuAbi = abi; 7565 } 7566 } 7567 } else { 7568 String[] abiList = (cpuAbiOverride != null) ? 7569 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7570 7571 // Enable gross and lame hacks for apps that are built with old 7572 // SDK tools. We must scan their APKs for renderscript bitcode and 7573 // not launch them if it's present. Don't bother checking on devices 7574 // that don't have 64 bit support. 7575 boolean needsRenderScriptOverride = false; 7576 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7577 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7578 abiList = Build.SUPPORTED_32_BIT_ABIS; 7579 needsRenderScriptOverride = true; 7580 } 7581 7582 final int copyRet; 7583 if (extractLibs) { 7584 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7585 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7586 } else { 7587 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7588 } 7589 7590 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7591 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7592 "Error unpackaging native libs for app, errorCode=" + copyRet); 7593 } 7594 7595 if (copyRet >= 0) { 7596 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7597 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7598 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7599 } else if (needsRenderScriptOverride) { 7600 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7601 } 7602 } 7603 } catch (IOException ioe) { 7604 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7605 } finally { 7606 IoUtils.closeQuietly(handle); 7607 } 7608 7609 // Now that we've calculated the ABIs and determined if it's an internal app, 7610 // we will go ahead and populate the nativeLibraryPath. 7611 setNativeLibraryPaths(pkg); 7612 } 7613 7614 /** 7615 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7616 * i.e, so that all packages can be run inside a single process if required. 7617 * 7618 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7619 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7620 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7621 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7622 * updating a package that belongs to a shared user. 7623 * 7624 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7625 * adds unnecessary complexity. 7626 */ 7627 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7628 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7629 String requiredInstructionSet = null; 7630 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7631 requiredInstructionSet = VMRuntime.getInstructionSet( 7632 scannedPackage.applicationInfo.primaryCpuAbi); 7633 } 7634 7635 PackageSetting requirer = null; 7636 for (PackageSetting ps : packagesForUser) { 7637 // If packagesForUser contains scannedPackage, we skip it. This will happen 7638 // when scannedPackage is an update of an existing package. Without this check, 7639 // we will never be able to change the ABI of any package belonging to a shared 7640 // user, even if it's compatible with other packages. 7641 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7642 if (ps.primaryCpuAbiString == null) { 7643 continue; 7644 } 7645 7646 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7647 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7648 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7649 // this but there's not much we can do. 7650 String errorMessage = "Instruction set mismatch, " 7651 + ((requirer == null) ? "[caller]" : requirer) 7652 + " requires " + requiredInstructionSet + " whereas " + ps 7653 + " requires " + instructionSet; 7654 Slog.w(TAG, errorMessage); 7655 } 7656 7657 if (requiredInstructionSet == null) { 7658 requiredInstructionSet = instructionSet; 7659 requirer = ps; 7660 } 7661 } 7662 } 7663 7664 if (requiredInstructionSet != null) { 7665 String adjustedAbi; 7666 if (requirer != null) { 7667 // requirer != null implies that either scannedPackage was null or that scannedPackage 7668 // did not require an ABI, in which case we have to adjust scannedPackage to match 7669 // the ABI of the set (which is the same as requirer's ABI) 7670 adjustedAbi = requirer.primaryCpuAbiString; 7671 if (scannedPackage != null) { 7672 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7673 } 7674 } else { 7675 // requirer == null implies that we're updating all ABIs in the set to 7676 // match scannedPackage. 7677 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7678 } 7679 7680 for (PackageSetting ps : packagesForUser) { 7681 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7682 if (ps.primaryCpuAbiString != null) { 7683 continue; 7684 } 7685 7686 ps.primaryCpuAbiString = adjustedAbi; 7687 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7688 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7689 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7690 7691 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7692 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7693 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7694 ps.primaryCpuAbiString = null; 7695 ps.pkg.applicationInfo.primaryCpuAbi = null; 7696 return; 7697 } else { 7698 mInstaller.rmdex(ps.codePathString, 7699 getDexCodeInstructionSet(getPreferredInstructionSet())); 7700 } 7701 } 7702 } 7703 } 7704 } 7705 } 7706 7707 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7708 synchronized (mPackages) { 7709 mResolverReplaced = true; 7710 // Set up information for custom user intent resolution activity. 7711 mResolveActivity.applicationInfo = pkg.applicationInfo; 7712 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7713 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7714 mResolveActivity.processName = pkg.applicationInfo.packageName; 7715 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7716 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7717 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7718 mResolveActivity.theme = 0; 7719 mResolveActivity.exported = true; 7720 mResolveActivity.enabled = true; 7721 mResolveInfo.activityInfo = mResolveActivity; 7722 mResolveInfo.priority = 0; 7723 mResolveInfo.preferredOrder = 0; 7724 mResolveInfo.match = 0; 7725 mResolveComponentName = mCustomResolverComponentName; 7726 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7727 mResolveComponentName); 7728 } 7729 } 7730 7731 private static String calculateBundledApkRoot(final String codePathString) { 7732 final File codePath = new File(codePathString); 7733 final File codeRoot; 7734 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7735 codeRoot = Environment.getRootDirectory(); 7736 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7737 codeRoot = Environment.getOemDirectory(); 7738 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7739 codeRoot = Environment.getVendorDirectory(); 7740 } else { 7741 // Unrecognized code path; take its top real segment as the apk root: 7742 // e.g. /something/app/blah.apk => /something 7743 try { 7744 File f = codePath.getCanonicalFile(); 7745 File parent = f.getParentFile(); // non-null because codePath is a file 7746 File tmp; 7747 while ((tmp = parent.getParentFile()) != null) { 7748 f = parent; 7749 parent = tmp; 7750 } 7751 codeRoot = f; 7752 Slog.w(TAG, "Unrecognized code path " 7753 + codePath + " - using " + codeRoot); 7754 } catch (IOException e) { 7755 // Can't canonicalize the code path -- shenanigans? 7756 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7757 return Environment.getRootDirectory().getPath(); 7758 } 7759 } 7760 return codeRoot.getPath(); 7761 } 7762 7763 /** 7764 * Derive and set the location of native libraries for the given package, 7765 * which varies depending on where and how the package was installed. 7766 */ 7767 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7768 final ApplicationInfo info = pkg.applicationInfo; 7769 final String codePath = pkg.codePath; 7770 final File codeFile = new File(codePath); 7771 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7772 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7773 7774 info.nativeLibraryRootDir = null; 7775 info.nativeLibraryRootRequiresIsa = false; 7776 info.nativeLibraryDir = null; 7777 info.secondaryNativeLibraryDir = null; 7778 7779 if (isApkFile(codeFile)) { 7780 // Monolithic install 7781 if (bundledApp) { 7782 // If "/system/lib64/apkname" exists, assume that is the per-package 7783 // native library directory to use; otherwise use "/system/lib/apkname". 7784 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7785 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7786 getPrimaryInstructionSet(info)); 7787 7788 // This is a bundled system app so choose the path based on the ABI. 7789 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7790 // is just the default path. 7791 final String apkName = deriveCodePathName(codePath); 7792 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7793 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7794 apkName).getAbsolutePath(); 7795 7796 if (info.secondaryCpuAbi != null) { 7797 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7798 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7799 secondaryLibDir, apkName).getAbsolutePath(); 7800 } 7801 } else if (asecApp) { 7802 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7803 .getAbsolutePath(); 7804 } else { 7805 final String apkName = deriveCodePathName(codePath); 7806 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7807 .getAbsolutePath(); 7808 } 7809 7810 info.nativeLibraryRootRequiresIsa = false; 7811 info.nativeLibraryDir = info.nativeLibraryRootDir; 7812 } else { 7813 // Cluster install 7814 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7815 info.nativeLibraryRootRequiresIsa = true; 7816 7817 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7818 getPrimaryInstructionSet(info)).getAbsolutePath(); 7819 7820 if (info.secondaryCpuAbi != null) { 7821 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7822 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7823 } 7824 } 7825 } 7826 7827 /** 7828 * Calculate the abis and roots for a bundled app. These can uniquely 7829 * be determined from the contents of the system partition, i.e whether 7830 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7831 * of this information, and instead assume that the system was built 7832 * sensibly. 7833 */ 7834 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7835 PackageSetting pkgSetting) { 7836 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7837 7838 // If "/system/lib64/apkname" exists, assume that is the per-package 7839 // native library directory to use; otherwise use "/system/lib/apkname". 7840 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7841 setBundledAppAbi(pkg, apkRoot, apkName); 7842 // pkgSetting might be null during rescan following uninstall of updates 7843 // to a bundled app, so accommodate that possibility. The settings in 7844 // that case will be established later from the parsed package. 7845 // 7846 // If the settings aren't null, sync them up with what we've just derived. 7847 // note that apkRoot isn't stored in the package settings. 7848 if (pkgSetting != null) { 7849 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7850 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7851 } 7852 } 7853 7854 /** 7855 * Deduces the ABI of a bundled app and sets the relevant fields on the 7856 * parsed pkg object. 7857 * 7858 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7859 * under which system libraries are installed. 7860 * @param apkName the name of the installed package. 7861 */ 7862 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7863 final File codeFile = new File(pkg.codePath); 7864 7865 final boolean has64BitLibs; 7866 final boolean has32BitLibs; 7867 if (isApkFile(codeFile)) { 7868 // Monolithic install 7869 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7870 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7871 } else { 7872 // Cluster install 7873 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7874 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7875 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7876 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7877 has64BitLibs = (new File(rootDir, isa)).exists(); 7878 } else { 7879 has64BitLibs = false; 7880 } 7881 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7882 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7883 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7884 has32BitLibs = (new File(rootDir, isa)).exists(); 7885 } else { 7886 has32BitLibs = false; 7887 } 7888 } 7889 7890 if (has64BitLibs && !has32BitLibs) { 7891 // The package has 64 bit libs, but not 32 bit libs. Its primary 7892 // ABI should be 64 bit. We can safely assume here that the bundled 7893 // native libraries correspond to the most preferred ABI in the list. 7894 7895 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7896 pkg.applicationInfo.secondaryCpuAbi = null; 7897 } else if (has32BitLibs && !has64BitLibs) { 7898 // The package has 32 bit libs but not 64 bit libs. Its primary 7899 // ABI should be 32 bit. 7900 7901 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7902 pkg.applicationInfo.secondaryCpuAbi = null; 7903 } else if (has32BitLibs && has64BitLibs) { 7904 // The application has both 64 and 32 bit bundled libraries. We check 7905 // here that the app declares multiArch support, and warn if it doesn't. 7906 // 7907 // We will be lenient here and record both ABIs. The primary will be the 7908 // ABI that's higher on the list, i.e, a device that's configured to prefer 7909 // 64 bit apps will see a 64 bit primary ABI, 7910 7911 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7912 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7913 } 7914 7915 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7916 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7917 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7918 } else { 7919 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7920 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7921 } 7922 } else { 7923 pkg.applicationInfo.primaryCpuAbi = null; 7924 pkg.applicationInfo.secondaryCpuAbi = null; 7925 } 7926 } 7927 7928 private void killApplication(String pkgName, int appId, String reason) { 7929 // Request the ActivityManager to kill the process(only for existing packages) 7930 // so that we do not end up in a confused state while the user is still using the older 7931 // version of the application while the new one gets installed. 7932 IActivityManager am = ActivityManagerNative.getDefault(); 7933 if (am != null) { 7934 try { 7935 am.killApplicationWithAppId(pkgName, appId, reason); 7936 } catch (RemoteException e) { 7937 } 7938 } 7939 } 7940 7941 void removePackageLI(PackageSetting ps, boolean chatty) { 7942 if (DEBUG_INSTALL) { 7943 if (chatty) 7944 Log.d(TAG, "Removing package " + ps.name); 7945 } 7946 7947 // writer 7948 synchronized (mPackages) { 7949 mPackages.remove(ps.name); 7950 final PackageParser.Package pkg = ps.pkg; 7951 if (pkg != null) { 7952 cleanPackageDataStructuresLILPw(pkg, chatty); 7953 } 7954 } 7955 } 7956 7957 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7958 if (DEBUG_INSTALL) { 7959 if (chatty) 7960 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7961 } 7962 7963 // writer 7964 synchronized (mPackages) { 7965 mPackages.remove(pkg.applicationInfo.packageName); 7966 cleanPackageDataStructuresLILPw(pkg, chatty); 7967 } 7968 } 7969 7970 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7971 int N = pkg.providers.size(); 7972 StringBuilder r = null; 7973 int i; 7974 for (i=0; i<N; i++) { 7975 PackageParser.Provider p = pkg.providers.get(i); 7976 mProviders.removeProvider(p); 7977 if (p.info.authority == null) { 7978 7979 /* There was another ContentProvider with this authority when 7980 * this app was installed so this authority is null, 7981 * Ignore it as we don't have to unregister the provider. 7982 */ 7983 continue; 7984 } 7985 String names[] = p.info.authority.split(";"); 7986 for (int j = 0; j < names.length; j++) { 7987 if (mProvidersByAuthority.get(names[j]) == p) { 7988 mProvidersByAuthority.remove(names[j]); 7989 if (DEBUG_REMOVE) { 7990 if (chatty) 7991 Log.d(TAG, "Unregistered content provider: " + names[j] 7992 + ", className = " + p.info.name + ", isSyncable = " 7993 + p.info.isSyncable); 7994 } 7995 } 7996 } 7997 if (DEBUG_REMOVE && chatty) { 7998 if (r == null) { 7999 r = new StringBuilder(256); 8000 } else { 8001 r.append(' '); 8002 } 8003 r.append(p.info.name); 8004 } 8005 } 8006 if (r != null) { 8007 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8008 } 8009 8010 N = pkg.services.size(); 8011 r = null; 8012 for (i=0; i<N; i++) { 8013 PackageParser.Service s = pkg.services.get(i); 8014 mServices.removeService(s); 8015 if (chatty) { 8016 if (r == null) { 8017 r = new StringBuilder(256); 8018 } else { 8019 r.append(' '); 8020 } 8021 r.append(s.info.name); 8022 } 8023 } 8024 if (r != null) { 8025 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8026 } 8027 8028 N = pkg.receivers.size(); 8029 r = null; 8030 for (i=0; i<N; i++) { 8031 PackageParser.Activity a = pkg.receivers.get(i); 8032 mReceivers.removeActivity(a, "receiver"); 8033 if (DEBUG_REMOVE && chatty) { 8034 if (r == null) { 8035 r = new StringBuilder(256); 8036 } else { 8037 r.append(' '); 8038 } 8039 r.append(a.info.name); 8040 } 8041 } 8042 if (r != null) { 8043 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8044 } 8045 8046 N = pkg.activities.size(); 8047 r = null; 8048 for (i=0; i<N; i++) { 8049 PackageParser.Activity a = pkg.activities.get(i); 8050 mActivities.removeActivity(a, "activity"); 8051 if (DEBUG_REMOVE && chatty) { 8052 if (r == null) { 8053 r = new StringBuilder(256); 8054 } else { 8055 r.append(' '); 8056 } 8057 r.append(a.info.name); 8058 } 8059 } 8060 if (r != null) { 8061 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8062 } 8063 8064 N = pkg.permissions.size(); 8065 r = null; 8066 for (i=0; i<N; i++) { 8067 PackageParser.Permission p = pkg.permissions.get(i); 8068 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8069 if (bp == null) { 8070 bp = mSettings.mPermissionTrees.get(p.info.name); 8071 } 8072 if (bp != null && bp.perm == p) { 8073 bp.perm = null; 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 ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8084 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8085 if (appOpPerms != null) { 8086 appOpPerms.remove(pkg.packageName); 8087 } 8088 } 8089 } 8090 if (r != null) { 8091 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8092 } 8093 8094 N = pkg.requestedPermissions.size(); 8095 r = null; 8096 for (i=0; i<N; i++) { 8097 String perm = pkg.requestedPermissions.get(i); 8098 BasePermission bp = mSettings.mPermissions.get(perm); 8099 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8100 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8101 if (appOpPerms != null) { 8102 appOpPerms.remove(pkg.packageName); 8103 if (appOpPerms.isEmpty()) { 8104 mAppOpPermissionPackages.remove(perm); 8105 } 8106 } 8107 } 8108 } 8109 if (r != null) { 8110 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8111 } 8112 8113 N = pkg.instrumentation.size(); 8114 r = null; 8115 for (i=0; i<N; i++) { 8116 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8117 mInstrumentation.remove(a.getComponentName()); 8118 if (DEBUG_REMOVE && chatty) { 8119 if (r == null) { 8120 r = new StringBuilder(256); 8121 } else { 8122 r.append(' '); 8123 } 8124 r.append(a.info.name); 8125 } 8126 } 8127 if (r != null) { 8128 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8129 } 8130 8131 r = null; 8132 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8133 // Only system apps can hold shared libraries. 8134 if (pkg.libraryNames != null) { 8135 for (i=0; i<pkg.libraryNames.size(); i++) { 8136 String name = pkg.libraryNames.get(i); 8137 SharedLibraryEntry cur = mSharedLibraries.get(name); 8138 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8139 mSharedLibraries.remove(name); 8140 if (DEBUG_REMOVE && chatty) { 8141 if (r == null) { 8142 r = new StringBuilder(256); 8143 } else { 8144 r.append(' '); 8145 } 8146 r.append(name); 8147 } 8148 } 8149 } 8150 } 8151 } 8152 if (r != null) { 8153 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8154 } 8155 } 8156 8157 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8158 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8159 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8160 return true; 8161 } 8162 } 8163 return false; 8164 } 8165 8166 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8167 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8168 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8169 8170 private void updatePermissionsLPw(String changingPkg, 8171 PackageParser.Package pkgInfo, int flags) { 8172 // Make sure there are no dangling permission trees. 8173 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8174 while (it.hasNext()) { 8175 final BasePermission bp = it.next(); 8176 if (bp.packageSetting == null) { 8177 // We may not yet have parsed the package, so just see if 8178 // we still know about its settings. 8179 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8180 } 8181 if (bp.packageSetting == null) { 8182 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8183 + " from package " + bp.sourcePackage); 8184 it.remove(); 8185 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8186 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8187 Slog.i(TAG, "Removing old permission tree: " + bp.name 8188 + " from package " + bp.sourcePackage); 8189 flags |= UPDATE_PERMISSIONS_ALL; 8190 it.remove(); 8191 } 8192 } 8193 } 8194 8195 // Make sure all dynamic permissions have been assigned to a package, 8196 // and make sure there are no dangling permissions. 8197 it = mSettings.mPermissions.values().iterator(); 8198 while (it.hasNext()) { 8199 final BasePermission bp = it.next(); 8200 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8201 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8202 + bp.name + " pkg=" + bp.sourcePackage 8203 + " info=" + bp.pendingInfo); 8204 if (bp.packageSetting == null && bp.pendingInfo != null) { 8205 final BasePermission tree = findPermissionTreeLP(bp.name); 8206 if (tree != null && tree.perm != null) { 8207 bp.packageSetting = tree.packageSetting; 8208 bp.perm = new PackageParser.Permission(tree.perm.owner, 8209 new PermissionInfo(bp.pendingInfo)); 8210 bp.perm.info.packageName = tree.perm.info.packageName; 8211 bp.perm.info.name = bp.name; 8212 bp.uid = tree.uid; 8213 } 8214 } 8215 } 8216 if (bp.packageSetting == null) { 8217 // We may not yet have parsed the package, so just see if 8218 // we still know about its settings. 8219 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8220 } 8221 if (bp.packageSetting == null) { 8222 Slog.w(TAG, "Removing dangling permission: " + bp.name 8223 + " from package " + bp.sourcePackage); 8224 it.remove(); 8225 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8226 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8227 Slog.i(TAG, "Removing old permission: " + bp.name 8228 + " from package " + bp.sourcePackage); 8229 flags |= UPDATE_PERMISSIONS_ALL; 8230 it.remove(); 8231 } 8232 } 8233 } 8234 8235 // Now update the permissions for all packages, in particular 8236 // replace the granted permissions of the system packages. 8237 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8238 for (PackageParser.Package pkg : mPackages.values()) { 8239 if (pkg != pkgInfo) { 8240 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8241 changingPkg); 8242 } 8243 } 8244 } 8245 8246 if (pkgInfo != null) { 8247 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8248 } 8249 } 8250 8251 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8252 String packageOfInterest) { 8253 // IMPORTANT: There are two types of permissions: install and runtime. 8254 // Install time permissions are granted when the app is installed to 8255 // all device users and users added in the future. Runtime permissions 8256 // are granted at runtime explicitly to specific users. Normal and signature 8257 // protected permissions are install time permissions. Dangerous permissions 8258 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8259 // otherwise they are runtime permissions. This function does not manage 8260 // runtime permissions except for the case an app targeting Lollipop MR1 8261 // being upgraded to target a newer SDK, in which case dangerous permissions 8262 // are transformed from install time to runtime ones. 8263 8264 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8265 if (ps == null) { 8266 return; 8267 } 8268 8269 PermissionsState permissionsState = ps.getPermissionsState(); 8270 PermissionsState origPermissions = permissionsState; 8271 8272 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8273 8274 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8275 8276 boolean changedInstallPermission = false; 8277 8278 if (replace) { 8279 ps.installPermissionsFixed = false; 8280 if (!ps.isSharedUser()) { 8281 origPermissions = new PermissionsState(permissionsState); 8282 permissionsState.reset(); 8283 } 8284 } 8285 8286 permissionsState.setGlobalGids(mGlobalGids); 8287 8288 final int N = pkg.requestedPermissions.size(); 8289 for (int i=0; i<N; i++) { 8290 final String name = pkg.requestedPermissions.get(i); 8291 final BasePermission bp = mSettings.mPermissions.get(name); 8292 8293 if (DEBUG_INSTALL) { 8294 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8295 } 8296 8297 if (bp == null || bp.packageSetting == null) { 8298 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8299 Slog.w(TAG, "Unknown permission " + name 8300 + " in package " + pkg.packageName); 8301 } 8302 continue; 8303 } 8304 8305 final String perm = bp.name; 8306 boolean allowedSig = false; 8307 int grant = GRANT_DENIED; 8308 8309 // Keep track of app op permissions. 8310 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8311 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8312 if (pkgs == null) { 8313 pkgs = new ArraySet<>(); 8314 mAppOpPermissionPackages.put(bp.name, pkgs); 8315 } 8316 pkgs.add(pkg.packageName); 8317 } 8318 8319 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8320 switch (level) { 8321 case PermissionInfo.PROTECTION_NORMAL: { 8322 // For all apps normal permissions are install time ones. 8323 grant = GRANT_INSTALL; 8324 } break; 8325 8326 case PermissionInfo.PROTECTION_DANGEROUS: { 8327 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8328 // For legacy apps dangerous permissions are install time ones. 8329 grant = GRANT_INSTALL_LEGACY; 8330 } else if (origPermissions.hasInstallPermission(bp.name)) { 8331 // For legacy apps that became modern, install becomes runtime. 8332 grant = GRANT_UPGRADE; 8333 } else { 8334 // For modern apps keep runtime permissions unchanged. 8335 grant = GRANT_RUNTIME; 8336 } 8337 } break; 8338 8339 case PermissionInfo.PROTECTION_SIGNATURE: { 8340 // For all apps signature permissions are install time ones. 8341 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8342 if (allowedSig) { 8343 grant = GRANT_INSTALL; 8344 } 8345 } break; 8346 } 8347 8348 if (DEBUG_INSTALL) { 8349 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8350 } 8351 8352 if (grant != GRANT_DENIED) { 8353 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8354 // If this is an existing, non-system package, then 8355 // we can't add any new permissions to it. 8356 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8357 // Except... if this is a permission that was added 8358 // to the platform (note: need to only do this when 8359 // updating the platform). 8360 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8361 grant = GRANT_DENIED; 8362 } 8363 } 8364 } 8365 8366 switch (grant) { 8367 case GRANT_INSTALL: { 8368 // Revoke this as runtime permission to handle the case of 8369 // a runtime permission being downgraded to an install one. 8370 for (int userId : UserManagerService.getInstance().getUserIds()) { 8371 if (origPermissions.getRuntimePermissionState( 8372 bp.name, userId) != null) { 8373 // Revoke the runtime permission and clear the flags. 8374 origPermissions.revokeRuntimePermission(bp, userId); 8375 origPermissions.updatePermissionFlags(bp, userId, 8376 PackageManager.MASK_PERMISSION_FLAGS, 0); 8377 // If we revoked a permission permission, we have to write. 8378 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8379 changedRuntimePermissionUserIds, userId); 8380 } 8381 } 8382 // Grant an install permission. 8383 if (permissionsState.grantInstallPermission(bp) != 8384 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8385 changedInstallPermission = true; 8386 } 8387 } break; 8388 8389 case GRANT_INSTALL_LEGACY: { 8390 // Grant an install permission. 8391 if (permissionsState.grantInstallPermission(bp) != 8392 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8393 changedInstallPermission = true; 8394 } 8395 } break; 8396 8397 case GRANT_RUNTIME: { 8398 // Grant previously granted runtime permissions. 8399 for (int userId : UserManagerService.getInstance().getUserIds()) { 8400 PermissionState permissionState = origPermissions 8401 .getRuntimePermissionState(bp.name, userId); 8402 final int flags = permissionState != null 8403 ? permissionState.getFlags() : 0; 8404 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8405 if (permissionsState.grantRuntimePermission(bp, userId) == 8406 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8407 // If we cannot put the permission as it was, we have to write. 8408 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8409 changedRuntimePermissionUserIds, userId); 8410 } 8411 } 8412 // Propagate the permission flags. 8413 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8414 } 8415 } break; 8416 8417 case GRANT_UPGRADE: { 8418 // Grant runtime permissions for a previously held install permission. 8419 PermissionState permissionState = origPermissions 8420 .getInstallPermissionState(bp.name); 8421 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8422 8423 if (origPermissions.revokeInstallPermission(bp) 8424 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8425 // We will be transferring the permission flags, so clear them. 8426 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8427 PackageManager.MASK_PERMISSION_FLAGS, 0); 8428 changedInstallPermission = true; 8429 } 8430 8431 // If the permission is not to be promoted to runtime we ignore it and 8432 // also its other flags as they are not applicable to install permissions. 8433 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8434 for (int userId : currentUserIds) { 8435 if (permissionsState.grantRuntimePermission(bp, userId) != 8436 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8437 // Transfer the permission flags. 8438 permissionsState.updatePermissionFlags(bp, userId, 8439 flags, flags); 8440 // If we granted the permission, we have to write. 8441 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8442 changedRuntimePermissionUserIds, userId); 8443 } 8444 } 8445 } 8446 } break; 8447 8448 default: { 8449 if (packageOfInterest == null 8450 || packageOfInterest.equals(pkg.packageName)) { 8451 Slog.w(TAG, "Not granting permission " + perm 8452 + " to package " + pkg.packageName 8453 + " because it was previously installed without"); 8454 } 8455 } break; 8456 } 8457 } else { 8458 if (permissionsState.revokeInstallPermission(bp) != 8459 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8460 // Also drop the permission flags. 8461 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8462 PackageManager.MASK_PERMISSION_FLAGS, 0); 8463 changedInstallPermission = true; 8464 Slog.i(TAG, "Un-granting permission " + perm 8465 + " from package " + pkg.packageName 8466 + " (protectionLevel=" + bp.protectionLevel 8467 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8468 + ")"); 8469 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8470 // Don't print warning for app op permissions, since it is fine for them 8471 // not to be granted, there is a UI for the user to decide. 8472 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8473 Slog.w(TAG, "Not granting permission " + perm 8474 + " to package " + pkg.packageName 8475 + " (protectionLevel=" + bp.protectionLevel 8476 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8477 + ")"); 8478 } 8479 } 8480 } 8481 } 8482 8483 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8484 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8485 // This is the first that we have heard about this package, so the 8486 // permissions we have now selected are fixed until explicitly 8487 // changed. 8488 ps.installPermissionsFixed = true; 8489 } 8490 8491 // Persist the runtime permissions state for users with changes. 8492 for (int userId : changedRuntimePermissionUserIds) { 8493 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8494 } 8495 } 8496 8497 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8498 boolean allowed = false; 8499 final int NP = PackageParser.NEW_PERMISSIONS.length; 8500 for (int ip=0; ip<NP; ip++) { 8501 final PackageParser.NewPermissionInfo npi 8502 = PackageParser.NEW_PERMISSIONS[ip]; 8503 if (npi.name.equals(perm) 8504 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8505 allowed = true; 8506 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8507 + pkg.packageName); 8508 break; 8509 } 8510 } 8511 return allowed; 8512 } 8513 8514 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8515 BasePermission bp, PermissionsState origPermissions) { 8516 boolean allowed; 8517 allowed = (compareSignatures( 8518 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8519 == PackageManager.SIGNATURE_MATCH) 8520 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8521 == PackageManager.SIGNATURE_MATCH); 8522 if (!allowed && (bp.protectionLevel 8523 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8524 if (isSystemApp(pkg)) { 8525 // For updated system applications, a system permission 8526 // is granted only if it had been defined by the original application. 8527 if (pkg.isUpdatedSystemApp()) { 8528 final PackageSetting sysPs = mSettings 8529 .getDisabledSystemPkgLPr(pkg.packageName); 8530 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8531 // If the original was granted this permission, we take 8532 // that grant decision as read and propagate it to the 8533 // update. 8534 if (sysPs.isPrivileged()) { 8535 allowed = true; 8536 } 8537 } else { 8538 // The system apk may have been updated with an older 8539 // version of the one on the data partition, but which 8540 // granted a new system permission that it didn't have 8541 // before. In this case we do want to allow the app to 8542 // now get the new permission if the ancestral apk is 8543 // privileged to get it. 8544 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8545 for (int j=0; 8546 j<sysPs.pkg.requestedPermissions.size(); j++) { 8547 if (perm.equals( 8548 sysPs.pkg.requestedPermissions.get(j))) { 8549 allowed = true; 8550 break; 8551 } 8552 } 8553 } 8554 } 8555 } else { 8556 allowed = isPrivilegedApp(pkg); 8557 } 8558 } 8559 } 8560 if (!allowed) { 8561 if (!allowed && (bp.protectionLevel 8562 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8563 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8564 // If this was a previously normal/dangerous permission that got moved 8565 // to a system permission as part of the runtime permission redesign, then 8566 // we still want to blindly grant it to old apps. 8567 allowed = true; 8568 } 8569 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8570 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8571 // If this permission is to be granted to the system installer and 8572 // this app is an installer, then it gets the permission. 8573 allowed = true; 8574 } 8575 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8576 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8577 // If this permission is to be granted to the system verifier and 8578 // this app is a verifier, then it gets the permission. 8579 allowed = true; 8580 } 8581 if (!allowed && (bp.protectionLevel 8582 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8583 && isSystemApp(pkg)) { 8584 // Any pre-installed system app is allowed to get this permission. 8585 allowed = true; 8586 } 8587 if (!allowed && (bp.protectionLevel 8588 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8589 // For development permissions, a development permission 8590 // is granted only if it was already granted. 8591 allowed = origPermissions.hasInstallPermission(perm); 8592 } 8593 } 8594 return allowed; 8595 } 8596 8597 final class ActivityIntentResolver 8598 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8599 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8600 boolean defaultOnly, int userId) { 8601 if (!sUserManager.exists(userId)) return null; 8602 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8603 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8604 } 8605 8606 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8607 int userId) { 8608 if (!sUserManager.exists(userId)) return null; 8609 mFlags = flags; 8610 return super.queryIntent(intent, resolvedType, 8611 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8612 } 8613 8614 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8615 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8616 if (!sUserManager.exists(userId)) return null; 8617 if (packageActivities == null) { 8618 return null; 8619 } 8620 mFlags = flags; 8621 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8622 final int N = packageActivities.size(); 8623 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8624 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8625 8626 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8627 for (int i = 0; i < N; ++i) { 8628 intentFilters = packageActivities.get(i).intents; 8629 if (intentFilters != null && intentFilters.size() > 0) { 8630 PackageParser.ActivityIntentInfo[] array = 8631 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8632 intentFilters.toArray(array); 8633 listCut.add(array); 8634 } 8635 } 8636 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8637 } 8638 8639 public final void addActivity(PackageParser.Activity a, String type) { 8640 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8641 mActivities.put(a.getComponentName(), a); 8642 if (DEBUG_SHOW_INFO) 8643 Log.v( 8644 TAG, " " + type + " " + 8645 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8646 if (DEBUG_SHOW_INFO) 8647 Log.v(TAG, " Class=" + a.info.name); 8648 final int NI = a.intents.size(); 8649 for (int j=0; j<NI; j++) { 8650 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8651 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8652 intent.setPriority(0); 8653 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8654 + a.className + " with priority > 0, forcing to 0"); 8655 } 8656 if (DEBUG_SHOW_INFO) { 8657 Log.v(TAG, " IntentFilter:"); 8658 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8659 } 8660 if (!intent.debugCheck()) { 8661 Log.w(TAG, "==> For Activity " + a.info.name); 8662 } 8663 addFilter(intent); 8664 } 8665 } 8666 8667 public final void removeActivity(PackageParser.Activity a, String type) { 8668 mActivities.remove(a.getComponentName()); 8669 if (DEBUG_SHOW_INFO) { 8670 Log.v(TAG, " " + type + " " 8671 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8672 : a.info.name) + ":"); 8673 Log.v(TAG, " Class=" + a.info.name); 8674 } 8675 final int NI = a.intents.size(); 8676 for (int j=0; j<NI; j++) { 8677 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8678 if (DEBUG_SHOW_INFO) { 8679 Log.v(TAG, " IntentFilter:"); 8680 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8681 } 8682 removeFilter(intent); 8683 } 8684 } 8685 8686 @Override 8687 protected boolean allowFilterResult( 8688 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8689 ActivityInfo filterAi = filter.activity.info; 8690 for (int i=dest.size()-1; i>=0; i--) { 8691 ActivityInfo destAi = dest.get(i).activityInfo; 8692 if (destAi.name == filterAi.name 8693 && destAi.packageName == filterAi.packageName) { 8694 return false; 8695 } 8696 } 8697 return true; 8698 } 8699 8700 @Override 8701 protected ActivityIntentInfo[] newArray(int size) { 8702 return new ActivityIntentInfo[size]; 8703 } 8704 8705 @Override 8706 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8707 if (!sUserManager.exists(userId)) return true; 8708 PackageParser.Package p = filter.activity.owner; 8709 if (p != null) { 8710 PackageSetting ps = (PackageSetting)p.mExtras; 8711 if (ps != null) { 8712 // System apps are never considered stopped for purposes of 8713 // filtering, because there may be no way for the user to 8714 // actually re-launch them. 8715 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8716 && ps.getStopped(userId); 8717 } 8718 } 8719 return false; 8720 } 8721 8722 @Override 8723 protected boolean isPackageForFilter(String packageName, 8724 PackageParser.ActivityIntentInfo info) { 8725 return packageName.equals(info.activity.owner.packageName); 8726 } 8727 8728 @Override 8729 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8730 int match, int userId) { 8731 if (!sUserManager.exists(userId)) return null; 8732 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8733 return null; 8734 } 8735 final PackageParser.Activity activity = info.activity; 8736 if (mSafeMode && (activity.info.applicationInfo.flags 8737 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8738 return null; 8739 } 8740 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8741 if (ps == null) { 8742 return null; 8743 } 8744 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8745 ps.readUserState(userId), userId); 8746 if (ai == null) { 8747 return null; 8748 } 8749 final ResolveInfo res = new ResolveInfo(); 8750 res.activityInfo = ai; 8751 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8752 res.filter = info; 8753 } 8754 if (info != null) { 8755 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8756 } 8757 res.priority = info.getPriority(); 8758 res.preferredOrder = activity.owner.mPreferredOrder; 8759 //System.out.println("Result: " + res.activityInfo.className + 8760 // " = " + res.priority); 8761 res.match = match; 8762 res.isDefault = info.hasDefault; 8763 res.labelRes = info.labelRes; 8764 res.nonLocalizedLabel = info.nonLocalizedLabel; 8765 if (userNeedsBadging(userId)) { 8766 res.noResourceId = true; 8767 } else { 8768 res.icon = info.icon; 8769 } 8770 res.iconResourceId = info.icon; 8771 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8772 return res; 8773 } 8774 8775 @Override 8776 protected void sortResults(List<ResolveInfo> results) { 8777 Collections.sort(results, mResolvePrioritySorter); 8778 } 8779 8780 @Override 8781 protected void dumpFilter(PrintWriter out, String prefix, 8782 PackageParser.ActivityIntentInfo filter) { 8783 out.print(prefix); out.print( 8784 Integer.toHexString(System.identityHashCode(filter.activity))); 8785 out.print(' '); 8786 filter.activity.printComponentShortName(out); 8787 out.print(" filter "); 8788 out.println(Integer.toHexString(System.identityHashCode(filter))); 8789 } 8790 8791 @Override 8792 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8793 return filter.activity; 8794 } 8795 8796 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8797 PackageParser.Activity activity = (PackageParser.Activity)label; 8798 out.print(prefix); out.print( 8799 Integer.toHexString(System.identityHashCode(activity))); 8800 out.print(' '); 8801 activity.printComponentShortName(out); 8802 if (count > 1) { 8803 out.print(" ("); out.print(count); out.print(" filters)"); 8804 } 8805 out.println(); 8806 } 8807 8808// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8809// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8810// final List<ResolveInfo> retList = Lists.newArrayList(); 8811// while (i.hasNext()) { 8812// final ResolveInfo resolveInfo = i.next(); 8813// if (isEnabledLP(resolveInfo.activityInfo)) { 8814// retList.add(resolveInfo); 8815// } 8816// } 8817// return retList; 8818// } 8819 8820 // Keys are String (activity class name), values are Activity. 8821 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8822 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8823 private int mFlags; 8824 } 8825 8826 private final class ServiceIntentResolver 8827 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8828 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8829 boolean defaultOnly, int userId) { 8830 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8831 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8832 } 8833 8834 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8835 int userId) { 8836 if (!sUserManager.exists(userId)) return null; 8837 mFlags = flags; 8838 return super.queryIntent(intent, resolvedType, 8839 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8840 } 8841 8842 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8843 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8844 if (!sUserManager.exists(userId)) return null; 8845 if (packageServices == null) { 8846 return null; 8847 } 8848 mFlags = flags; 8849 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8850 final int N = packageServices.size(); 8851 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8852 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8853 8854 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8855 for (int i = 0; i < N; ++i) { 8856 intentFilters = packageServices.get(i).intents; 8857 if (intentFilters != null && intentFilters.size() > 0) { 8858 PackageParser.ServiceIntentInfo[] array = 8859 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8860 intentFilters.toArray(array); 8861 listCut.add(array); 8862 } 8863 } 8864 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8865 } 8866 8867 public final void addService(PackageParser.Service s) { 8868 mServices.put(s.getComponentName(), s); 8869 if (DEBUG_SHOW_INFO) { 8870 Log.v(TAG, " " 8871 + (s.info.nonLocalizedLabel != null 8872 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8873 Log.v(TAG, " Class=" + s.info.name); 8874 } 8875 final int NI = s.intents.size(); 8876 int j; 8877 for (j=0; j<NI; j++) { 8878 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8879 if (DEBUG_SHOW_INFO) { 8880 Log.v(TAG, " IntentFilter:"); 8881 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8882 } 8883 if (!intent.debugCheck()) { 8884 Log.w(TAG, "==> For Service " + s.info.name); 8885 } 8886 addFilter(intent); 8887 } 8888 } 8889 8890 public final void removeService(PackageParser.Service s) { 8891 mServices.remove(s.getComponentName()); 8892 if (DEBUG_SHOW_INFO) { 8893 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8894 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8895 Log.v(TAG, " Class=" + s.info.name); 8896 } 8897 final int NI = s.intents.size(); 8898 int j; 8899 for (j=0; j<NI; j++) { 8900 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8901 if (DEBUG_SHOW_INFO) { 8902 Log.v(TAG, " IntentFilter:"); 8903 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8904 } 8905 removeFilter(intent); 8906 } 8907 } 8908 8909 @Override 8910 protected boolean allowFilterResult( 8911 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8912 ServiceInfo filterSi = filter.service.info; 8913 for (int i=dest.size()-1; i>=0; i--) { 8914 ServiceInfo destAi = dest.get(i).serviceInfo; 8915 if (destAi.name == filterSi.name 8916 && destAi.packageName == filterSi.packageName) { 8917 return false; 8918 } 8919 } 8920 return true; 8921 } 8922 8923 @Override 8924 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8925 return new PackageParser.ServiceIntentInfo[size]; 8926 } 8927 8928 @Override 8929 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8930 if (!sUserManager.exists(userId)) return true; 8931 PackageParser.Package p = filter.service.owner; 8932 if (p != null) { 8933 PackageSetting ps = (PackageSetting)p.mExtras; 8934 if (ps != null) { 8935 // System apps are never considered stopped for purposes of 8936 // filtering, because there may be no way for the user to 8937 // actually re-launch them. 8938 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8939 && ps.getStopped(userId); 8940 } 8941 } 8942 return false; 8943 } 8944 8945 @Override 8946 protected boolean isPackageForFilter(String packageName, 8947 PackageParser.ServiceIntentInfo info) { 8948 return packageName.equals(info.service.owner.packageName); 8949 } 8950 8951 @Override 8952 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8953 int match, int userId) { 8954 if (!sUserManager.exists(userId)) return null; 8955 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8956 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8957 return null; 8958 } 8959 final PackageParser.Service service = info.service; 8960 if (mSafeMode && (service.info.applicationInfo.flags 8961 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8962 return null; 8963 } 8964 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8965 if (ps == null) { 8966 return null; 8967 } 8968 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8969 ps.readUserState(userId), userId); 8970 if (si == null) { 8971 return null; 8972 } 8973 final ResolveInfo res = new ResolveInfo(); 8974 res.serviceInfo = si; 8975 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8976 res.filter = filter; 8977 } 8978 res.priority = info.getPriority(); 8979 res.preferredOrder = service.owner.mPreferredOrder; 8980 res.match = match; 8981 res.isDefault = info.hasDefault; 8982 res.labelRes = info.labelRes; 8983 res.nonLocalizedLabel = info.nonLocalizedLabel; 8984 res.icon = info.icon; 8985 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8986 return res; 8987 } 8988 8989 @Override 8990 protected void sortResults(List<ResolveInfo> results) { 8991 Collections.sort(results, mResolvePrioritySorter); 8992 } 8993 8994 @Override 8995 protected void dumpFilter(PrintWriter out, String prefix, 8996 PackageParser.ServiceIntentInfo filter) { 8997 out.print(prefix); out.print( 8998 Integer.toHexString(System.identityHashCode(filter.service))); 8999 out.print(' '); 9000 filter.service.printComponentShortName(out); 9001 out.print(" filter "); 9002 out.println(Integer.toHexString(System.identityHashCode(filter))); 9003 } 9004 9005 @Override 9006 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9007 return filter.service; 9008 } 9009 9010 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9011 PackageParser.Service service = (PackageParser.Service)label; 9012 out.print(prefix); out.print( 9013 Integer.toHexString(System.identityHashCode(service))); 9014 out.print(' '); 9015 service.printComponentShortName(out); 9016 if (count > 1) { 9017 out.print(" ("); out.print(count); out.print(" filters)"); 9018 } 9019 out.println(); 9020 } 9021 9022// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9023// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9024// final List<ResolveInfo> retList = Lists.newArrayList(); 9025// while (i.hasNext()) { 9026// final ResolveInfo resolveInfo = (ResolveInfo) i; 9027// if (isEnabledLP(resolveInfo.serviceInfo)) { 9028// retList.add(resolveInfo); 9029// } 9030// } 9031// return retList; 9032// } 9033 9034 // Keys are String (activity class name), values are Activity. 9035 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9036 = new ArrayMap<ComponentName, PackageParser.Service>(); 9037 private int mFlags; 9038 }; 9039 9040 private final class ProviderIntentResolver 9041 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9042 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9043 boolean defaultOnly, int userId) { 9044 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9045 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9046 } 9047 9048 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9049 int userId) { 9050 if (!sUserManager.exists(userId)) 9051 return null; 9052 mFlags = flags; 9053 return super.queryIntent(intent, resolvedType, 9054 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9055 } 9056 9057 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9058 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9059 if (!sUserManager.exists(userId)) 9060 return null; 9061 if (packageProviders == null) { 9062 return null; 9063 } 9064 mFlags = flags; 9065 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9066 final int N = packageProviders.size(); 9067 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9068 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9069 9070 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9071 for (int i = 0; i < N; ++i) { 9072 intentFilters = packageProviders.get(i).intents; 9073 if (intentFilters != null && intentFilters.size() > 0) { 9074 PackageParser.ProviderIntentInfo[] array = 9075 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9076 intentFilters.toArray(array); 9077 listCut.add(array); 9078 } 9079 } 9080 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9081 } 9082 9083 public final void addProvider(PackageParser.Provider p) { 9084 if (mProviders.containsKey(p.getComponentName())) { 9085 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9086 return; 9087 } 9088 9089 mProviders.put(p.getComponentName(), p); 9090 if (DEBUG_SHOW_INFO) { 9091 Log.v(TAG, " " 9092 + (p.info.nonLocalizedLabel != null 9093 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9094 Log.v(TAG, " Class=" + p.info.name); 9095 } 9096 final int NI = p.intents.size(); 9097 int j; 9098 for (j = 0; j < NI; j++) { 9099 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9100 if (DEBUG_SHOW_INFO) { 9101 Log.v(TAG, " IntentFilter:"); 9102 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9103 } 9104 if (!intent.debugCheck()) { 9105 Log.w(TAG, "==> For Provider " + p.info.name); 9106 } 9107 addFilter(intent); 9108 } 9109 } 9110 9111 public final void removeProvider(PackageParser.Provider p) { 9112 mProviders.remove(p.getComponentName()); 9113 if (DEBUG_SHOW_INFO) { 9114 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9115 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9116 Log.v(TAG, " Class=" + p.info.name); 9117 } 9118 final int NI = p.intents.size(); 9119 int j; 9120 for (j = 0; j < NI; j++) { 9121 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9122 if (DEBUG_SHOW_INFO) { 9123 Log.v(TAG, " IntentFilter:"); 9124 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9125 } 9126 removeFilter(intent); 9127 } 9128 } 9129 9130 @Override 9131 protected boolean allowFilterResult( 9132 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9133 ProviderInfo filterPi = filter.provider.info; 9134 for (int i = dest.size() - 1; i >= 0; i--) { 9135 ProviderInfo destPi = dest.get(i).providerInfo; 9136 if (destPi.name == filterPi.name 9137 && destPi.packageName == filterPi.packageName) { 9138 return false; 9139 } 9140 } 9141 return true; 9142 } 9143 9144 @Override 9145 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9146 return new PackageParser.ProviderIntentInfo[size]; 9147 } 9148 9149 @Override 9150 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9151 if (!sUserManager.exists(userId)) 9152 return true; 9153 PackageParser.Package p = filter.provider.owner; 9154 if (p != null) { 9155 PackageSetting ps = (PackageSetting) p.mExtras; 9156 if (ps != null) { 9157 // System apps are never considered stopped for purposes of 9158 // filtering, because there may be no way for the user to 9159 // actually re-launch them. 9160 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9161 && ps.getStopped(userId); 9162 } 9163 } 9164 return false; 9165 } 9166 9167 @Override 9168 protected boolean isPackageForFilter(String packageName, 9169 PackageParser.ProviderIntentInfo info) { 9170 return packageName.equals(info.provider.owner.packageName); 9171 } 9172 9173 @Override 9174 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9175 int match, int userId) { 9176 if (!sUserManager.exists(userId)) 9177 return null; 9178 final PackageParser.ProviderIntentInfo info = filter; 9179 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9180 return null; 9181 } 9182 final PackageParser.Provider provider = info.provider; 9183 if (mSafeMode && (provider.info.applicationInfo.flags 9184 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9185 return null; 9186 } 9187 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9188 if (ps == null) { 9189 return null; 9190 } 9191 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9192 ps.readUserState(userId), userId); 9193 if (pi == null) { 9194 return null; 9195 } 9196 final ResolveInfo res = new ResolveInfo(); 9197 res.providerInfo = pi; 9198 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9199 res.filter = filter; 9200 } 9201 res.priority = info.getPriority(); 9202 res.preferredOrder = provider.owner.mPreferredOrder; 9203 res.match = match; 9204 res.isDefault = info.hasDefault; 9205 res.labelRes = info.labelRes; 9206 res.nonLocalizedLabel = info.nonLocalizedLabel; 9207 res.icon = info.icon; 9208 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9209 return res; 9210 } 9211 9212 @Override 9213 protected void sortResults(List<ResolveInfo> results) { 9214 Collections.sort(results, mResolvePrioritySorter); 9215 } 9216 9217 @Override 9218 protected void dumpFilter(PrintWriter out, String prefix, 9219 PackageParser.ProviderIntentInfo filter) { 9220 out.print(prefix); 9221 out.print( 9222 Integer.toHexString(System.identityHashCode(filter.provider))); 9223 out.print(' '); 9224 filter.provider.printComponentShortName(out); 9225 out.print(" filter "); 9226 out.println(Integer.toHexString(System.identityHashCode(filter))); 9227 } 9228 9229 @Override 9230 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9231 return filter.provider; 9232 } 9233 9234 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9235 PackageParser.Provider provider = (PackageParser.Provider)label; 9236 out.print(prefix); out.print( 9237 Integer.toHexString(System.identityHashCode(provider))); 9238 out.print(' '); 9239 provider.printComponentShortName(out); 9240 if (count > 1) { 9241 out.print(" ("); out.print(count); out.print(" filters)"); 9242 } 9243 out.println(); 9244 } 9245 9246 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9247 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9248 private int mFlags; 9249 }; 9250 9251 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9252 new Comparator<ResolveInfo>() { 9253 public int compare(ResolveInfo r1, ResolveInfo r2) { 9254 int v1 = r1.priority; 9255 int v2 = r2.priority; 9256 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9257 if (v1 != v2) { 9258 return (v1 > v2) ? -1 : 1; 9259 } 9260 v1 = r1.preferredOrder; 9261 v2 = r2.preferredOrder; 9262 if (v1 != v2) { 9263 return (v1 > v2) ? -1 : 1; 9264 } 9265 if (r1.isDefault != r2.isDefault) { 9266 return r1.isDefault ? -1 : 1; 9267 } 9268 v1 = r1.match; 9269 v2 = r2.match; 9270 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9271 if (v1 != v2) { 9272 return (v1 > v2) ? -1 : 1; 9273 } 9274 if (r1.system != r2.system) { 9275 return r1.system ? -1 : 1; 9276 } 9277 return 0; 9278 } 9279 }; 9280 9281 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9282 new Comparator<ProviderInfo>() { 9283 public int compare(ProviderInfo p1, ProviderInfo p2) { 9284 final int v1 = p1.initOrder; 9285 final int v2 = p2.initOrder; 9286 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9287 } 9288 }; 9289 9290 final void sendPackageBroadcast(final String action, final String pkg, 9291 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9292 final int[] userIds) { 9293 mHandler.post(new Runnable() { 9294 @Override 9295 public void run() { 9296 try { 9297 final IActivityManager am = ActivityManagerNative.getDefault(); 9298 if (am == null) return; 9299 final int[] resolvedUserIds; 9300 if (userIds == null) { 9301 resolvedUserIds = am.getRunningUserIds(); 9302 } else { 9303 resolvedUserIds = userIds; 9304 } 9305 for (int id : resolvedUserIds) { 9306 final Intent intent = new Intent(action, 9307 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9308 if (extras != null) { 9309 intent.putExtras(extras); 9310 } 9311 if (targetPkg != null) { 9312 intent.setPackage(targetPkg); 9313 } 9314 // Modify the UID when posting to other users 9315 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9316 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9317 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9318 intent.putExtra(Intent.EXTRA_UID, uid); 9319 } 9320 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9321 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9322 if (DEBUG_BROADCASTS) { 9323 RuntimeException here = new RuntimeException("here"); 9324 here.fillInStackTrace(); 9325 Slog.d(TAG, "Sending to user " + id + ": " 9326 + intent.toShortString(false, true, false, false) 9327 + " " + intent.getExtras(), here); 9328 } 9329 am.broadcastIntent(null, intent, null, finishedReceiver, 9330 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9331 null, finishedReceiver != null, false, id); 9332 } 9333 } catch (RemoteException ex) { 9334 } 9335 } 9336 }); 9337 } 9338 9339 /** 9340 * Check if the external storage media is available. This is true if there 9341 * is a mounted external storage medium or if the external storage is 9342 * emulated. 9343 */ 9344 private boolean isExternalMediaAvailable() { 9345 return mMediaMounted || Environment.isExternalStorageEmulated(); 9346 } 9347 9348 @Override 9349 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9350 // writer 9351 synchronized (mPackages) { 9352 if (!isExternalMediaAvailable()) { 9353 // If the external storage is no longer mounted at this point, 9354 // the caller may not have been able to delete all of this 9355 // packages files and can not delete any more. Bail. 9356 return null; 9357 } 9358 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9359 if (lastPackage != null) { 9360 pkgs.remove(lastPackage); 9361 } 9362 if (pkgs.size() > 0) { 9363 return pkgs.get(0); 9364 } 9365 } 9366 return null; 9367 } 9368 9369 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9370 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9371 userId, andCode ? 1 : 0, packageName); 9372 if (mSystemReady) { 9373 msg.sendToTarget(); 9374 } else { 9375 if (mPostSystemReadyMessages == null) { 9376 mPostSystemReadyMessages = new ArrayList<>(); 9377 } 9378 mPostSystemReadyMessages.add(msg); 9379 } 9380 } 9381 9382 void startCleaningPackages() { 9383 // reader 9384 synchronized (mPackages) { 9385 if (!isExternalMediaAvailable()) { 9386 return; 9387 } 9388 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9389 return; 9390 } 9391 } 9392 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9393 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9394 IActivityManager am = ActivityManagerNative.getDefault(); 9395 if (am != null) { 9396 try { 9397 am.startService(null, intent, null, mContext.getOpPackageName(), 9398 UserHandle.USER_OWNER); 9399 } catch (RemoteException e) { 9400 } 9401 } 9402 } 9403 9404 @Override 9405 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9406 int installFlags, String installerPackageName, VerificationParams verificationParams, 9407 String packageAbiOverride) { 9408 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9409 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9410 } 9411 9412 @Override 9413 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9414 int installFlags, String installerPackageName, VerificationParams verificationParams, 9415 String packageAbiOverride, int userId) { 9416 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9417 9418 final int callingUid = Binder.getCallingUid(); 9419 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9420 9421 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9422 try { 9423 if (observer != null) { 9424 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9425 } 9426 } catch (RemoteException re) { 9427 } 9428 return; 9429 } 9430 9431 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9432 installFlags |= PackageManager.INSTALL_FROM_ADB; 9433 9434 } else { 9435 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9436 // about installerPackageName. 9437 9438 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9439 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9440 } 9441 9442 UserHandle user; 9443 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9444 user = UserHandle.ALL; 9445 } else { 9446 user = new UserHandle(userId); 9447 } 9448 9449 // Only system components can circumvent runtime permissions when installing. 9450 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9451 && mContext.checkCallingOrSelfPermission(Manifest.permission 9452 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9453 throw new SecurityException("You need the " 9454 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9455 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9456 } 9457 9458 verificationParams.setInstallerUid(callingUid); 9459 9460 final File originFile = new File(originPath); 9461 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9462 9463 final Message msg = mHandler.obtainMessage(INIT_COPY); 9464 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9465 null, verificationParams, user, packageAbiOverride, null); 9466 mHandler.sendMessage(msg); 9467 } 9468 9469 void installStage(String packageName, File stagedDir, String stagedCid, 9470 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9471 String installerPackageName, int installerUid, UserHandle user) { 9472 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9473 params.referrerUri, installerUid, null); 9474 verifParams.setInstallerUid(installerUid); 9475 9476 final OriginInfo origin; 9477 if (stagedDir != null) { 9478 origin = OriginInfo.fromStagedFile(stagedDir); 9479 } else { 9480 origin = OriginInfo.fromStagedContainer(stagedCid); 9481 } 9482 9483 final Message msg = mHandler.obtainMessage(INIT_COPY); 9484 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9485 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9486 params.grantedRuntimePermissions); 9487 mHandler.sendMessage(msg); 9488 } 9489 9490 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9491 Bundle extras = new Bundle(1); 9492 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9493 9494 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9495 packageName, extras, null, null, new int[] {userId}); 9496 try { 9497 IActivityManager am = ActivityManagerNative.getDefault(); 9498 final boolean isSystem = 9499 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9500 if (isSystem && am.isUserRunning(userId, false)) { 9501 // The just-installed/enabled app is bundled on the system, so presumed 9502 // to be able to run automatically without needing an explicit launch. 9503 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9504 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9505 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9506 .setPackage(packageName); 9507 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9508 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9509 } 9510 } catch (RemoteException e) { 9511 // shouldn't happen 9512 Slog.w(TAG, "Unable to bootstrap installed package", e); 9513 } 9514 } 9515 9516 @Override 9517 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9518 int userId) { 9519 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9520 PackageSetting pkgSetting; 9521 final int uid = Binder.getCallingUid(); 9522 enforceCrossUserPermission(uid, userId, true, true, 9523 "setApplicationHiddenSetting for user " + userId); 9524 9525 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9526 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9527 return false; 9528 } 9529 9530 long callingId = Binder.clearCallingIdentity(); 9531 try { 9532 boolean sendAdded = false; 9533 boolean sendRemoved = false; 9534 // writer 9535 synchronized (mPackages) { 9536 pkgSetting = mSettings.mPackages.get(packageName); 9537 if (pkgSetting == null) { 9538 return false; 9539 } 9540 if (pkgSetting.getHidden(userId) != hidden) { 9541 pkgSetting.setHidden(hidden, userId); 9542 mSettings.writePackageRestrictionsLPr(userId); 9543 if (hidden) { 9544 sendRemoved = true; 9545 } else { 9546 sendAdded = true; 9547 } 9548 } 9549 } 9550 if (sendAdded) { 9551 sendPackageAddedForUser(packageName, pkgSetting, userId); 9552 return true; 9553 } 9554 if (sendRemoved) { 9555 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9556 "hiding pkg"); 9557 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9558 } 9559 } finally { 9560 Binder.restoreCallingIdentity(callingId); 9561 } 9562 return false; 9563 } 9564 9565 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9566 int userId) { 9567 final PackageRemovedInfo info = new PackageRemovedInfo(); 9568 info.removedPackage = packageName; 9569 info.removedUsers = new int[] {userId}; 9570 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9571 info.sendBroadcast(false, false, false); 9572 } 9573 9574 /** 9575 * Returns true if application is not found or there was an error. Otherwise it returns 9576 * the hidden state of the package for the given user. 9577 */ 9578 @Override 9579 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9580 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9581 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9582 false, "getApplicationHidden for user " + userId); 9583 PackageSetting pkgSetting; 9584 long callingId = Binder.clearCallingIdentity(); 9585 try { 9586 // writer 9587 synchronized (mPackages) { 9588 pkgSetting = mSettings.mPackages.get(packageName); 9589 if (pkgSetting == null) { 9590 return true; 9591 } 9592 return pkgSetting.getHidden(userId); 9593 } 9594 } finally { 9595 Binder.restoreCallingIdentity(callingId); 9596 } 9597 } 9598 9599 /** 9600 * @hide 9601 */ 9602 @Override 9603 public int installExistingPackageAsUser(String packageName, int userId) { 9604 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9605 null); 9606 PackageSetting pkgSetting; 9607 final int uid = Binder.getCallingUid(); 9608 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9609 + userId); 9610 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9611 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9612 } 9613 9614 long callingId = Binder.clearCallingIdentity(); 9615 try { 9616 boolean sendAdded = false; 9617 9618 // writer 9619 synchronized (mPackages) { 9620 pkgSetting = mSettings.mPackages.get(packageName); 9621 if (pkgSetting == null) { 9622 return PackageManager.INSTALL_FAILED_INVALID_URI; 9623 } 9624 if (!pkgSetting.getInstalled(userId)) { 9625 pkgSetting.setInstalled(true, userId); 9626 pkgSetting.setHidden(false, userId); 9627 mSettings.writePackageRestrictionsLPr(userId); 9628 sendAdded = true; 9629 } 9630 } 9631 9632 if (sendAdded) { 9633 sendPackageAddedForUser(packageName, pkgSetting, userId); 9634 } 9635 } finally { 9636 Binder.restoreCallingIdentity(callingId); 9637 } 9638 9639 return PackageManager.INSTALL_SUCCEEDED; 9640 } 9641 9642 boolean isUserRestricted(int userId, String restrictionKey) { 9643 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9644 if (restrictions.getBoolean(restrictionKey, false)) { 9645 Log.w(TAG, "User is restricted: " + restrictionKey); 9646 return true; 9647 } 9648 return false; 9649 } 9650 9651 @Override 9652 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9653 mContext.enforceCallingOrSelfPermission( 9654 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9655 "Only package verification agents can verify applications"); 9656 9657 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9658 final PackageVerificationResponse response = new PackageVerificationResponse( 9659 verificationCode, Binder.getCallingUid()); 9660 msg.arg1 = id; 9661 msg.obj = response; 9662 mHandler.sendMessage(msg); 9663 } 9664 9665 @Override 9666 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9667 long millisecondsToDelay) { 9668 mContext.enforceCallingOrSelfPermission( 9669 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9670 "Only package verification agents can extend verification timeouts"); 9671 9672 final PackageVerificationState state = mPendingVerification.get(id); 9673 final PackageVerificationResponse response = new PackageVerificationResponse( 9674 verificationCodeAtTimeout, Binder.getCallingUid()); 9675 9676 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9677 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9678 } 9679 if (millisecondsToDelay < 0) { 9680 millisecondsToDelay = 0; 9681 } 9682 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9683 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9684 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9685 } 9686 9687 if ((state != null) && !state.timeoutExtended()) { 9688 state.extendTimeout(); 9689 9690 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9691 msg.arg1 = id; 9692 msg.obj = response; 9693 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9694 } 9695 } 9696 9697 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9698 int verificationCode, UserHandle user) { 9699 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9700 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9701 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9702 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9703 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9704 9705 mContext.sendBroadcastAsUser(intent, user, 9706 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9707 } 9708 9709 private ComponentName matchComponentForVerifier(String packageName, 9710 List<ResolveInfo> receivers) { 9711 ActivityInfo targetReceiver = null; 9712 9713 final int NR = receivers.size(); 9714 for (int i = 0; i < NR; i++) { 9715 final ResolveInfo info = receivers.get(i); 9716 if (info.activityInfo == null) { 9717 continue; 9718 } 9719 9720 if (packageName.equals(info.activityInfo.packageName)) { 9721 targetReceiver = info.activityInfo; 9722 break; 9723 } 9724 } 9725 9726 if (targetReceiver == null) { 9727 return null; 9728 } 9729 9730 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9731 } 9732 9733 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9734 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9735 if (pkgInfo.verifiers.length == 0) { 9736 return null; 9737 } 9738 9739 final int N = pkgInfo.verifiers.length; 9740 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9741 for (int i = 0; i < N; i++) { 9742 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9743 9744 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9745 receivers); 9746 if (comp == null) { 9747 continue; 9748 } 9749 9750 final int verifierUid = getUidForVerifier(verifierInfo); 9751 if (verifierUid == -1) { 9752 continue; 9753 } 9754 9755 if (DEBUG_VERIFY) { 9756 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9757 + " with the correct signature"); 9758 } 9759 sufficientVerifiers.add(comp); 9760 verificationState.addSufficientVerifier(verifierUid); 9761 } 9762 9763 return sufficientVerifiers; 9764 } 9765 9766 private int getUidForVerifier(VerifierInfo verifierInfo) { 9767 synchronized (mPackages) { 9768 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9769 if (pkg == null) { 9770 return -1; 9771 } else if (pkg.mSignatures.length != 1) { 9772 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9773 + " has more than one signature; ignoring"); 9774 return -1; 9775 } 9776 9777 /* 9778 * If the public key of the package's signature does not match 9779 * our expected public key, then this is a different package and 9780 * we should skip. 9781 */ 9782 9783 final byte[] expectedPublicKey; 9784 try { 9785 final Signature verifierSig = pkg.mSignatures[0]; 9786 final PublicKey publicKey = verifierSig.getPublicKey(); 9787 expectedPublicKey = publicKey.getEncoded(); 9788 } catch (CertificateException e) { 9789 return -1; 9790 } 9791 9792 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9793 9794 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9795 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9796 + " does not have the expected public key; ignoring"); 9797 return -1; 9798 } 9799 9800 return pkg.applicationInfo.uid; 9801 } 9802 } 9803 9804 @Override 9805 public void finishPackageInstall(int token) { 9806 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9807 9808 if (DEBUG_INSTALL) { 9809 Slog.v(TAG, "BM finishing package install for " + token); 9810 } 9811 9812 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9813 mHandler.sendMessage(msg); 9814 } 9815 9816 /** 9817 * Get the verification agent timeout. 9818 * 9819 * @return verification timeout in milliseconds 9820 */ 9821 private long getVerificationTimeout() { 9822 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9823 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9824 DEFAULT_VERIFICATION_TIMEOUT); 9825 } 9826 9827 /** 9828 * Get the default verification agent response code. 9829 * 9830 * @return default verification response code 9831 */ 9832 private int getDefaultVerificationResponse() { 9833 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9834 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9835 DEFAULT_VERIFICATION_RESPONSE); 9836 } 9837 9838 /** 9839 * Check whether or not package verification has been enabled. 9840 * 9841 * @return true if verification should be performed 9842 */ 9843 private boolean isVerificationEnabled(int userId, int installFlags) { 9844 if (!DEFAULT_VERIFY_ENABLE) { 9845 return false; 9846 } 9847 9848 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9849 9850 // Check if installing from ADB 9851 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9852 // Do not run verification in a test harness environment 9853 if (ActivityManager.isRunningInTestHarness()) { 9854 return false; 9855 } 9856 if (ensureVerifyAppsEnabled) { 9857 return true; 9858 } 9859 // Check if the developer does not want package verification for ADB installs 9860 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9861 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9862 return false; 9863 } 9864 } 9865 9866 if (ensureVerifyAppsEnabled) { 9867 return true; 9868 } 9869 9870 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9871 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9872 } 9873 9874 @Override 9875 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9876 throws RemoteException { 9877 mContext.enforceCallingOrSelfPermission( 9878 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9879 "Only intentfilter verification agents can verify applications"); 9880 9881 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9882 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9883 Binder.getCallingUid(), verificationCode, failedDomains); 9884 msg.arg1 = id; 9885 msg.obj = response; 9886 mHandler.sendMessage(msg); 9887 } 9888 9889 @Override 9890 public int getIntentVerificationStatus(String packageName, int userId) { 9891 synchronized (mPackages) { 9892 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9893 } 9894 } 9895 9896 @Override 9897 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9898 mContext.enforceCallingOrSelfPermission( 9899 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9900 9901 boolean result = false; 9902 synchronized (mPackages) { 9903 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9904 } 9905 if (result) { 9906 scheduleWritePackageRestrictionsLocked(userId); 9907 } 9908 return result; 9909 } 9910 9911 @Override 9912 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9913 synchronized (mPackages) { 9914 return mSettings.getIntentFilterVerificationsLPr(packageName); 9915 } 9916 } 9917 9918 @Override 9919 public List<IntentFilter> getAllIntentFilters(String packageName) { 9920 if (TextUtils.isEmpty(packageName)) { 9921 return Collections.<IntentFilter>emptyList(); 9922 } 9923 synchronized (mPackages) { 9924 PackageParser.Package pkg = mPackages.get(packageName); 9925 if (pkg == null || pkg.activities == null) { 9926 return Collections.<IntentFilter>emptyList(); 9927 } 9928 final int count = pkg.activities.size(); 9929 ArrayList<IntentFilter> result = new ArrayList<>(); 9930 for (int n=0; n<count; n++) { 9931 PackageParser.Activity activity = pkg.activities.get(n); 9932 if (activity.intents != null || activity.intents.size() > 0) { 9933 result.addAll(activity.intents); 9934 } 9935 } 9936 return result; 9937 } 9938 } 9939 9940 @Override 9941 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9942 mContext.enforceCallingOrSelfPermission( 9943 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9944 9945 synchronized (mPackages) { 9946 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9947 if (packageName != null) { 9948 result |= updateIntentVerificationStatus(packageName, 9949 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9950 userId); 9951 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9952 packageName, userId); 9953 } 9954 return result; 9955 } 9956 } 9957 9958 @Override 9959 public String getDefaultBrowserPackageName(int userId) { 9960 synchronized (mPackages) { 9961 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9962 } 9963 } 9964 9965 /** 9966 * Get the "allow unknown sources" setting. 9967 * 9968 * @return the current "allow unknown sources" setting 9969 */ 9970 private int getUnknownSourcesSettings() { 9971 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9972 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9973 -1); 9974 } 9975 9976 @Override 9977 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9978 final int uid = Binder.getCallingUid(); 9979 // writer 9980 synchronized (mPackages) { 9981 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9982 if (targetPackageSetting == null) { 9983 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9984 } 9985 9986 PackageSetting installerPackageSetting; 9987 if (installerPackageName != null) { 9988 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9989 if (installerPackageSetting == null) { 9990 throw new IllegalArgumentException("Unknown installer package: " 9991 + installerPackageName); 9992 } 9993 } else { 9994 installerPackageSetting = null; 9995 } 9996 9997 Signature[] callerSignature; 9998 Object obj = mSettings.getUserIdLPr(uid); 9999 if (obj != null) { 10000 if (obj instanceof SharedUserSetting) { 10001 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10002 } else if (obj instanceof PackageSetting) { 10003 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10004 } else { 10005 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10006 } 10007 } else { 10008 throw new SecurityException("Unknown calling uid " + uid); 10009 } 10010 10011 // Verify: can't set installerPackageName to a package that is 10012 // not signed with the same cert as the caller. 10013 if (installerPackageSetting != null) { 10014 if (compareSignatures(callerSignature, 10015 installerPackageSetting.signatures.mSignatures) 10016 != PackageManager.SIGNATURE_MATCH) { 10017 throw new SecurityException( 10018 "Caller does not have same cert as new installer package " 10019 + installerPackageName); 10020 } 10021 } 10022 10023 // Verify: if target already has an installer package, it must 10024 // be signed with the same cert as the caller. 10025 if (targetPackageSetting.installerPackageName != null) { 10026 PackageSetting setting = mSettings.mPackages.get( 10027 targetPackageSetting.installerPackageName); 10028 // If the currently set package isn't valid, then it's always 10029 // okay to change it. 10030 if (setting != null) { 10031 if (compareSignatures(callerSignature, 10032 setting.signatures.mSignatures) 10033 != PackageManager.SIGNATURE_MATCH) { 10034 throw new SecurityException( 10035 "Caller does not have same cert as old installer package " 10036 + targetPackageSetting.installerPackageName); 10037 } 10038 } 10039 } 10040 10041 // Okay! 10042 targetPackageSetting.installerPackageName = installerPackageName; 10043 scheduleWriteSettingsLocked(); 10044 } 10045 } 10046 10047 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10048 // Queue up an async operation since the package installation may take a little while. 10049 mHandler.post(new Runnable() { 10050 public void run() { 10051 mHandler.removeCallbacks(this); 10052 // Result object to be returned 10053 PackageInstalledInfo res = new PackageInstalledInfo(); 10054 res.returnCode = currentStatus; 10055 res.uid = -1; 10056 res.pkg = null; 10057 res.removedInfo = new PackageRemovedInfo(); 10058 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10059 args.doPreInstall(res.returnCode); 10060 synchronized (mInstallLock) { 10061 installPackageLI(args, res); 10062 } 10063 args.doPostInstall(res.returnCode, res.uid); 10064 } 10065 10066 // A restore should be performed at this point if (a) the install 10067 // succeeded, (b) the operation is not an update, and (c) the new 10068 // package has not opted out of backup participation. 10069 final boolean update = res.removedInfo.removedPackage != null; 10070 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10071 boolean doRestore = !update 10072 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10073 10074 // Set up the post-install work request bookkeeping. This will be used 10075 // and cleaned up by the post-install event handling regardless of whether 10076 // there's a restore pass performed. Token values are >= 1. 10077 int token; 10078 if (mNextInstallToken < 0) mNextInstallToken = 1; 10079 token = mNextInstallToken++; 10080 10081 PostInstallData data = new PostInstallData(args, res); 10082 mRunningInstalls.put(token, data); 10083 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10084 10085 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10086 // Pass responsibility to the Backup Manager. It will perform a 10087 // restore if appropriate, then pass responsibility back to the 10088 // Package Manager to run the post-install observer callbacks 10089 // and broadcasts. 10090 IBackupManager bm = IBackupManager.Stub.asInterface( 10091 ServiceManager.getService(Context.BACKUP_SERVICE)); 10092 if (bm != null) { 10093 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10094 + " to BM for possible restore"); 10095 try { 10096 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10097 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10098 } else { 10099 doRestore = false; 10100 } 10101 } catch (RemoteException e) { 10102 // can't happen; the backup manager is local 10103 } catch (Exception e) { 10104 Slog.e(TAG, "Exception trying to enqueue restore", e); 10105 doRestore = false; 10106 } 10107 } else { 10108 Slog.e(TAG, "Backup Manager not found!"); 10109 doRestore = false; 10110 } 10111 } 10112 10113 if (!doRestore) { 10114 // No restore possible, or the Backup Manager was mysteriously not 10115 // available -- just fire the post-install work request directly. 10116 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10117 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10118 mHandler.sendMessage(msg); 10119 } 10120 } 10121 }); 10122 } 10123 10124 private abstract class HandlerParams { 10125 private static final int MAX_RETRIES = 4; 10126 10127 /** 10128 * Number of times startCopy() has been attempted and had a non-fatal 10129 * error. 10130 */ 10131 private int mRetries = 0; 10132 10133 /** User handle for the user requesting the information or installation. */ 10134 private final UserHandle mUser; 10135 10136 HandlerParams(UserHandle user) { 10137 mUser = user; 10138 } 10139 10140 UserHandle getUser() { 10141 return mUser; 10142 } 10143 10144 final boolean startCopy() { 10145 boolean res; 10146 try { 10147 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10148 10149 if (++mRetries > MAX_RETRIES) { 10150 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10151 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10152 handleServiceError(); 10153 return false; 10154 } else { 10155 handleStartCopy(); 10156 res = true; 10157 } 10158 } catch (RemoteException e) { 10159 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10160 mHandler.sendEmptyMessage(MCS_RECONNECT); 10161 res = false; 10162 } 10163 handleReturnCode(); 10164 return res; 10165 } 10166 10167 final void serviceError() { 10168 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10169 handleServiceError(); 10170 handleReturnCode(); 10171 } 10172 10173 abstract void handleStartCopy() throws RemoteException; 10174 abstract void handleServiceError(); 10175 abstract void handleReturnCode(); 10176 } 10177 10178 class MeasureParams extends HandlerParams { 10179 private final PackageStats mStats; 10180 private boolean mSuccess; 10181 10182 private final IPackageStatsObserver mObserver; 10183 10184 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10185 super(new UserHandle(stats.userHandle)); 10186 mObserver = observer; 10187 mStats = stats; 10188 } 10189 10190 @Override 10191 public String toString() { 10192 return "MeasureParams{" 10193 + Integer.toHexString(System.identityHashCode(this)) 10194 + " " + mStats.packageName + "}"; 10195 } 10196 10197 @Override 10198 void handleStartCopy() throws RemoteException { 10199 synchronized (mInstallLock) { 10200 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10201 } 10202 10203 if (mSuccess) { 10204 final boolean mounted; 10205 if (Environment.isExternalStorageEmulated()) { 10206 mounted = true; 10207 } else { 10208 final String status = Environment.getExternalStorageState(); 10209 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10210 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10211 } 10212 10213 if (mounted) { 10214 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10215 10216 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10217 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10218 10219 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10220 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10221 10222 // Always subtract cache size, since it's a subdirectory 10223 mStats.externalDataSize -= mStats.externalCacheSize; 10224 10225 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10226 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10227 10228 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10229 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10230 } 10231 } 10232 } 10233 10234 @Override 10235 void handleReturnCode() { 10236 if (mObserver != null) { 10237 try { 10238 mObserver.onGetStatsCompleted(mStats, mSuccess); 10239 } catch (RemoteException e) { 10240 Slog.i(TAG, "Observer no longer exists."); 10241 } 10242 } 10243 } 10244 10245 @Override 10246 void handleServiceError() { 10247 Slog.e(TAG, "Could not measure application " + mStats.packageName 10248 + " external storage"); 10249 } 10250 } 10251 10252 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10253 throws RemoteException { 10254 long result = 0; 10255 for (File path : paths) { 10256 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10257 } 10258 return result; 10259 } 10260 10261 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10262 for (File path : paths) { 10263 try { 10264 mcs.clearDirectory(path.getAbsolutePath()); 10265 } catch (RemoteException e) { 10266 } 10267 } 10268 } 10269 10270 static class OriginInfo { 10271 /** 10272 * Location where install is coming from, before it has been 10273 * copied/renamed into place. This could be a single monolithic APK 10274 * file, or a cluster directory. This location may be untrusted. 10275 */ 10276 final File file; 10277 final String cid; 10278 10279 /** 10280 * Flag indicating that {@link #file} or {@link #cid} has already been 10281 * staged, meaning downstream users don't need to defensively copy the 10282 * contents. 10283 */ 10284 final boolean staged; 10285 10286 /** 10287 * Flag indicating that {@link #file} or {@link #cid} is an already 10288 * installed app that is being moved. 10289 */ 10290 final boolean existing; 10291 10292 final String resolvedPath; 10293 final File resolvedFile; 10294 10295 static OriginInfo fromNothing() { 10296 return new OriginInfo(null, null, false, false); 10297 } 10298 10299 static OriginInfo fromUntrustedFile(File file) { 10300 return new OriginInfo(file, null, false, false); 10301 } 10302 10303 static OriginInfo fromExistingFile(File file) { 10304 return new OriginInfo(file, null, false, true); 10305 } 10306 10307 static OriginInfo fromStagedFile(File file) { 10308 return new OriginInfo(file, null, true, false); 10309 } 10310 10311 static OriginInfo fromStagedContainer(String cid) { 10312 return new OriginInfo(null, cid, true, false); 10313 } 10314 10315 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10316 this.file = file; 10317 this.cid = cid; 10318 this.staged = staged; 10319 this.existing = existing; 10320 10321 if (cid != null) { 10322 resolvedPath = PackageHelper.getSdDir(cid); 10323 resolvedFile = new File(resolvedPath); 10324 } else if (file != null) { 10325 resolvedPath = file.getAbsolutePath(); 10326 resolvedFile = file; 10327 } else { 10328 resolvedPath = null; 10329 resolvedFile = null; 10330 } 10331 } 10332 } 10333 10334 class MoveInfo { 10335 final int moveId; 10336 final String fromUuid; 10337 final String toUuid; 10338 final String packageName; 10339 final String dataAppName; 10340 final int appId; 10341 final String seinfo; 10342 10343 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10344 String dataAppName, int appId, String seinfo) { 10345 this.moveId = moveId; 10346 this.fromUuid = fromUuid; 10347 this.toUuid = toUuid; 10348 this.packageName = packageName; 10349 this.dataAppName = dataAppName; 10350 this.appId = appId; 10351 this.seinfo = seinfo; 10352 } 10353 } 10354 10355 class InstallParams extends HandlerParams { 10356 final OriginInfo origin; 10357 final MoveInfo move; 10358 final IPackageInstallObserver2 observer; 10359 int installFlags; 10360 final String installerPackageName; 10361 final String volumeUuid; 10362 final VerificationParams verificationParams; 10363 private InstallArgs mArgs; 10364 private int mRet; 10365 final String packageAbiOverride; 10366 final String[] grantedRuntimePermissions; 10367 10368 10369 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10370 int installFlags, String installerPackageName, String volumeUuid, 10371 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10372 String[] grantedPermissions) { 10373 super(user); 10374 this.origin = origin; 10375 this.move = move; 10376 this.observer = observer; 10377 this.installFlags = installFlags; 10378 this.installerPackageName = installerPackageName; 10379 this.volumeUuid = volumeUuid; 10380 this.verificationParams = verificationParams; 10381 this.packageAbiOverride = packageAbiOverride; 10382 this.grantedRuntimePermissions = grantedPermissions; 10383 } 10384 10385 @Override 10386 public String toString() { 10387 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10388 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10389 } 10390 10391 public ManifestDigest getManifestDigest() { 10392 if (verificationParams == null) { 10393 return null; 10394 } 10395 return verificationParams.getManifestDigest(); 10396 } 10397 10398 private int installLocationPolicy(PackageInfoLite pkgLite) { 10399 String packageName = pkgLite.packageName; 10400 int installLocation = pkgLite.installLocation; 10401 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10402 // reader 10403 synchronized (mPackages) { 10404 PackageParser.Package pkg = mPackages.get(packageName); 10405 if (pkg != null) { 10406 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10407 // Check for downgrading. 10408 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10409 try { 10410 checkDowngrade(pkg, pkgLite); 10411 } catch (PackageManagerException e) { 10412 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10413 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10414 } 10415 } 10416 // Check for updated system application. 10417 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10418 if (onSd) { 10419 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10420 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10421 } 10422 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10423 } else { 10424 if (onSd) { 10425 // Install flag overrides everything. 10426 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10427 } 10428 // If current upgrade specifies particular preference 10429 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10430 // Application explicitly specified internal. 10431 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10432 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10433 // App explictly prefers external. Let policy decide 10434 } else { 10435 // Prefer previous location 10436 if (isExternal(pkg)) { 10437 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10438 } 10439 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10440 } 10441 } 10442 } else { 10443 // Invalid install. Return error code 10444 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10445 } 10446 } 10447 } 10448 // All the special cases have been taken care of. 10449 // Return result based on recommended install location. 10450 if (onSd) { 10451 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10452 } 10453 return pkgLite.recommendedInstallLocation; 10454 } 10455 10456 /* 10457 * Invoke remote method to get package information and install 10458 * location values. Override install location based on default 10459 * policy if needed and then create install arguments based 10460 * on the install location. 10461 */ 10462 public void handleStartCopy() throws RemoteException { 10463 int ret = PackageManager.INSTALL_SUCCEEDED; 10464 10465 // If we're already staged, we've firmly committed to an install location 10466 if (origin.staged) { 10467 if (origin.file != null) { 10468 installFlags |= PackageManager.INSTALL_INTERNAL; 10469 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10470 } else if (origin.cid != null) { 10471 installFlags |= PackageManager.INSTALL_EXTERNAL; 10472 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10473 } else { 10474 throw new IllegalStateException("Invalid stage location"); 10475 } 10476 } 10477 10478 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10479 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10480 10481 PackageInfoLite pkgLite = null; 10482 10483 if (onInt && onSd) { 10484 // Check if both bits are set. 10485 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10486 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10487 } else { 10488 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10489 packageAbiOverride); 10490 10491 /* 10492 * If we have too little free space, try to free cache 10493 * before giving up. 10494 */ 10495 if (!origin.staged && pkgLite.recommendedInstallLocation 10496 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10497 // TODO: focus freeing disk space on the target device 10498 final StorageManager storage = StorageManager.from(mContext); 10499 final long lowThreshold = storage.getStorageLowBytes( 10500 Environment.getDataDirectory()); 10501 10502 final long sizeBytes = mContainerService.calculateInstalledSize( 10503 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10504 10505 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10506 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10507 installFlags, packageAbiOverride); 10508 } 10509 10510 /* 10511 * The cache free must have deleted the file we 10512 * downloaded to install. 10513 * 10514 * TODO: fix the "freeCache" call to not delete 10515 * the file we care about. 10516 */ 10517 if (pkgLite.recommendedInstallLocation 10518 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10519 pkgLite.recommendedInstallLocation 10520 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10521 } 10522 } 10523 } 10524 10525 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10526 int loc = pkgLite.recommendedInstallLocation; 10527 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10528 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10529 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10530 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10531 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10532 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10533 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10534 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10535 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10536 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10537 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10538 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10539 } else { 10540 // Override with defaults if needed. 10541 loc = installLocationPolicy(pkgLite); 10542 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10543 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10544 } else if (!onSd && !onInt) { 10545 // Override install location with flags 10546 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10547 // Set the flag to install on external media. 10548 installFlags |= PackageManager.INSTALL_EXTERNAL; 10549 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10550 } else { 10551 // Make sure the flag for installing on external 10552 // media is unset 10553 installFlags |= PackageManager.INSTALL_INTERNAL; 10554 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10555 } 10556 } 10557 } 10558 } 10559 10560 final InstallArgs args = createInstallArgs(this); 10561 mArgs = args; 10562 10563 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10564 /* 10565 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10566 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10567 */ 10568 int userIdentifier = getUser().getIdentifier(); 10569 if (userIdentifier == UserHandle.USER_ALL 10570 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10571 userIdentifier = UserHandle.USER_OWNER; 10572 } 10573 10574 /* 10575 * Determine if we have any installed package verifiers. If we 10576 * do, then we'll defer to them to verify the packages. 10577 */ 10578 final int requiredUid = mRequiredVerifierPackage == null ? -1 10579 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10580 if (!origin.existing && requiredUid != -1 10581 && isVerificationEnabled(userIdentifier, installFlags)) { 10582 final Intent verification = new Intent( 10583 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10584 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10585 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10586 PACKAGE_MIME_TYPE); 10587 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10588 10589 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10590 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10591 0 /* TODO: Which userId? */); 10592 10593 if (DEBUG_VERIFY) { 10594 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10595 + verification.toString() + " with " + pkgLite.verifiers.length 10596 + " optional verifiers"); 10597 } 10598 10599 final int verificationId = mPendingVerificationToken++; 10600 10601 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10602 10603 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10604 installerPackageName); 10605 10606 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10607 installFlags); 10608 10609 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10610 pkgLite.packageName); 10611 10612 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10613 pkgLite.versionCode); 10614 10615 if (verificationParams != null) { 10616 if (verificationParams.getVerificationURI() != null) { 10617 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10618 verificationParams.getVerificationURI()); 10619 } 10620 if (verificationParams.getOriginatingURI() != null) { 10621 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10622 verificationParams.getOriginatingURI()); 10623 } 10624 if (verificationParams.getReferrer() != null) { 10625 verification.putExtra(Intent.EXTRA_REFERRER, 10626 verificationParams.getReferrer()); 10627 } 10628 if (verificationParams.getOriginatingUid() >= 0) { 10629 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10630 verificationParams.getOriginatingUid()); 10631 } 10632 if (verificationParams.getInstallerUid() >= 0) { 10633 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10634 verificationParams.getInstallerUid()); 10635 } 10636 } 10637 10638 final PackageVerificationState verificationState = new PackageVerificationState( 10639 requiredUid, args); 10640 10641 mPendingVerification.append(verificationId, verificationState); 10642 10643 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10644 receivers, verificationState); 10645 10646 // Apps installed for "all" users use the device owner to verify the app 10647 UserHandle verifierUser = getUser(); 10648 if (verifierUser == UserHandle.ALL) { 10649 verifierUser = UserHandle.OWNER; 10650 } 10651 10652 /* 10653 * If any sufficient verifiers were listed in the package 10654 * manifest, attempt to ask them. 10655 */ 10656 if (sufficientVerifiers != null) { 10657 final int N = sufficientVerifiers.size(); 10658 if (N == 0) { 10659 Slog.i(TAG, "Additional verifiers required, but none installed."); 10660 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10661 } else { 10662 for (int i = 0; i < N; i++) { 10663 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10664 10665 final Intent sufficientIntent = new Intent(verification); 10666 sufficientIntent.setComponent(verifierComponent); 10667 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10668 } 10669 } 10670 } 10671 10672 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10673 mRequiredVerifierPackage, receivers); 10674 if (ret == PackageManager.INSTALL_SUCCEEDED 10675 && mRequiredVerifierPackage != null) { 10676 /* 10677 * Send the intent to the required verification agent, 10678 * but only start the verification timeout after the 10679 * target BroadcastReceivers have run. 10680 */ 10681 verification.setComponent(requiredVerifierComponent); 10682 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10683 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10684 new BroadcastReceiver() { 10685 @Override 10686 public void onReceive(Context context, Intent intent) { 10687 final Message msg = mHandler 10688 .obtainMessage(CHECK_PENDING_VERIFICATION); 10689 msg.arg1 = verificationId; 10690 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10691 } 10692 }, null, 0, null, null); 10693 10694 /* 10695 * We don't want the copy to proceed until verification 10696 * succeeds, so null out this field. 10697 */ 10698 mArgs = null; 10699 } 10700 } else { 10701 /* 10702 * No package verification is enabled, so immediately start 10703 * the remote call to initiate copy using temporary file. 10704 */ 10705 ret = args.copyApk(mContainerService, true); 10706 } 10707 } 10708 10709 mRet = ret; 10710 } 10711 10712 @Override 10713 void handleReturnCode() { 10714 // If mArgs is null, then MCS couldn't be reached. When it 10715 // reconnects, it will try again to install. At that point, this 10716 // will succeed. 10717 if (mArgs != null) { 10718 processPendingInstall(mArgs, mRet); 10719 } 10720 } 10721 10722 @Override 10723 void handleServiceError() { 10724 mArgs = createInstallArgs(this); 10725 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10726 } 10727 10728 public boolean isForwardLocked() { 10729 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10730 } 10731 } 10732 10733 /** 10734 * Used during creation of InstallArgs 10735 * 10736 * @param installFlags package installation flags 10737 * @return true if should be installed on external storage 10738 */ 10739 private static boolean installOnExternalAsec(int installFlags) { 10740 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10741 return false; 10742 } 10743 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10744 return true; 10745 } 10746 return false; 10747 } 10748 10749 /** 10750 * Used during creation of InstallArgs 10751 * 10752 * @param installFlags package installation flags 10753 * @return true if should be installed as forward locked 10754 */ 10755 private static boolean installForwardLocked(int installFlags) { 10756 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10757 } 10758 10759 private InstallArgs createInstallArgs(InstallParams params) { 10760 if (params.move != null) { 10761 return new MoveInstallArgs(params); 10762 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10763 return new AsecInstallArgs(params); 10764 } else { 10765 return new FileInstallArgs(params); 10766 } 10767 } 10768 10769 /** 10770 * Create args that describe an existing installed package. Typically used 10771 * when cleaning up old installs, or used as a move source. 10772 */ 10773 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10774 String resourcePath, String[] instructionSets) { 10775 final boolean isInAsec; 10776 if (installOnExternalAsec(installFlags)) { 10777 /* Apps on SD card are always in ASEC containers. */ 10778 isInAsec = true; 10779 } else if (installForwardLocked(installFlags) 10780 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10781 /* 10782 * Forward-locked apps are only in ASEC containers if they're the 10783 * new style 10784 */ 10785 isInAsec = true; 10786 } else { 10787 isInAsec = false; 10788 } 10789 10790 if (isInAsec) { 10791 return new AsecInstallArgs(codePath, instructionSets, 10792 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10793 } else { 10794 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10795 } 10796 } 10797 10798 static abstract class InstallArgs { 10799 /** @see InstallParams#origin */ 10800 final OriginInfo origin; 10801 /** @see InstallParams#move */ 10802 final MoveInfo move; 10803 10804 final IPackageInstallObserver2 observer; 10805 // Always refers to PackageManager flags only 10806 final int installFlags; 10807 final String installerPackageName; 10808 final String volumeUuid; 10809 final ManifestDigest manifestDigest; 10810 final UserHandle user; 10811 final String abiOverride; 10812 final String[] installGrantPermissions; 10813 10814 // The list of instruction sets supported by this app. This is currently 10815 // only used during the rmdex() phase to clean up resources. We can get rid of this 10816 // if we move dex files under the common app path. 10817 /* nullable */ String[] instructionSets; 10818 10819 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10820 int installFlags, String installerPackageName, String volumeUuid, 10821 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10822 String abiOverride, String[] installGrantPermissions) { 10823 this.origin = origin; 10824 this.move = move; 10825 this.installFlags = installFlags; 10826 this.observer = observer; 10827 this.installerPackageName = installerPackageName; 10828 this.volumeUuid = volumeUuid; 10829 this.manifestDigest = manifestDigest; 10830 this.user = user; 10831 this.instructionSets = instructionSets; 10832 this.abiOverride = abiOverride; 10833 this.installGrantPermissions = installGrantPermissions; 10834 } 10835 10836 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10837 abstract int doPreInstall(int status); 10838 10839 /** 10840 * Rename package into final resting place. All paths on the given 10841 * scanned package should be updated to reflect the rename. 10842 */ 10843 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10844 abstract int doPostInstall(int status, int uid); 10845 10846 /** @see PackageSettingBase#codePathString */ 10847 abstract String getCodePath(); 10848 /** @see PackageSettingBase#resourcePathString */ 10849 abstract String getResourcePath(); 10850 10851 // Need installer lock especially for dex file removal. 10852 abstract void cleanUpResourcesLI(); 10853 abstract boolean doPostDeleteLI(boolean delete); 10854 10855 /** 10856 * Called before the source arguments are copied. This is used mostly 10857 * for MoveParams when it needs to read the source file to put it in the 10858 * destination. 10859 */ 10860 int doPreCopy() { 10861 return PackageManager.INSTALL_SUCCEEDED; 10862 } 10863 10864 /** 10865 * Called after the source arguments are copied. This is used mostly for 10866 * MoveParams when it needs to read the source file to put it in the 10867 * destination. 10868 * 10869 * @return 10870 */ 10871 int doPostCopy(int uid) { 10872 return PackageManager.INSTALL_SUCCEEDED; 10873 } 10874 10875 protected boolean isFwdLocked() { 10876 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10877 } 10878 10879 protected boolean isExternalAsec() { 10880 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10881 } 10882 10883 UserHandle getUser() { 10884 return user; 10885 } 10886 } 10887 10888 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10889 if (!allCodePaths.isEmpty()) { 10890 if (instructionSets == null) { 10891 throw new IllegalStateException("instructionSet == null"); 10892 } 10893 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10894 for (String codePath : allCodePaths) { 10895 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10896 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10897 if (retCode < 0) { 10898 Slog.w(TAG, "Couldn't remove dex file for package: " 10899 + " at location " + codePath + ", retcode=" + retCode); 10900 // we don't consider this to be a failure of the core package deletion 10901 } 10902 } 10903 } 10904 } 10905 } 10906 10907 /** 10908 * Logic to handle installation of non-ASEC applications, including copying 10909 * and renaming logic. 10910 */ 10911 class FileInstallArgs extends InstallArgs { 10912 private File codeFile; 10913 private File resourceFile; 10914 10915 // Example topology: 10916 // /data/app/com.example/base.apk 10917 // /data/app/com.example/split_foo.apk 10918 // /data/app/com.example/lib/arm/libfoo.so 10919 // /data/app/com.example/lib/arm64/libfoo.so 10920 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10921 10922 /** New install */ 10923 FileInstallArgs(InstallParams params) { 10924 super(params.origin, params.move, params.observer, params.installFlags, 10925 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10926 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 10927 params.grantedRuntimePermissions); 10928 if (isFwdLocked()) { 10929 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10930 } 10931 } 10932 10933 /** Existing install */ 10934 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10935 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10936 null, null); 10937 this.codeFile = (codePath != null) ? new File(codePath) : null; 10938 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10939 } 10940 10941 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10942 if (origin.staged) { 10943 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10944 codeFile = origin.file; 10945 resourceFile = origin.file; 10946 return PackageManager.INSTALL_SUCCEEDED; 10947 } 10948 10949 try { 10950 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10951 codeFile = tempDir; 10952 resourceFile = tempDir; 10953 } catch (IOException e) { 10954 Slog.w(TAG, "Failed to create copy file: " + e); 10955 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10956 } 10957 10958 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10959 @Override 10960 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10961 if (!FileUtils.isValidExtFilename(name)) { 10962 throw new IllegalArgumentException("Invalid filename: " + name); 10963 } 10964 try { 10965 final File file = new File(codeFile, name); 10966 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10967 O_RDWR | O_CREAT, 0644); 10968 Os.chmod(file.getAbsolutePath(), 0644); 10969 return new ParcelFileDescriptor(fd); 10970 } catch (ErrnoException e) { 10971 throw new RemoteException("Failed to open: " + e.getMessage()); 10972 } 10973 } 10974 }; 10975 10976 int ret = PackageManager.INSTALL_SUCCEEDED; 10977 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10978 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10979 Slog.e(TAG, "Failed to copy package"); 10980 return ret; 10981 } 10982 10983 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10984 NativeLibraryHelper.Handle handle = null; 10985 try { 10986 handle = NativeLibraryHelper.Handle.create(codeFile); 10987 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10988 abiOverride); 10989 } catch (IOException e) { 10990 Slog.e(TAG, "Copying native libraries failed", e); 10991 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10992 } finally { 10993 IoUtils.closeQuietly(handle); 10994 } 10995 10996 return ret; 10997 } 10998 10999 int doPreInstall(int status) { 11000 if (status != PackageManager.INSTALL_SUCCEEDED) { 11001 cleanUp(); 11002 } 11003 return status; 11004 } 11005 11006 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11007 if (status != PackageManager.INSTALL_SUCCEEDED) { 11008 cleanUp(); 11009 return false; 11010 } 11011 11012 final File targetDir = codeFile.getParentFile(); 11013 final File beforeCodeFile = codeFile; 11014 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11015 11016 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11017 try { 11018 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11019 } catch (ErrnoException e) { 11020 Slog.w(TAG, "Failed to rename", e); 11021 return false; 11022 } 11023 11024 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11025 Slog.w(TAG, "Failed to restorecon"); 11026 return false; 11027 } 11028 11029 // Reflect the rename internally 11030 codeFile = afterCodeFile; 11031 resourceFile = afterCodeFile; 11032 11033 // Reflect the rename in scanned details 11034 pkg.codePath = afterCodeFile.getAbsolutePath(); 11035 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11036 pkg.baseCodePath); 11037 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11038 pkg.splitCodePaths); 11039 11040 // Reflect the rename in app info 11041 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11042 pkg.applicationInfo.setCodePath(pkg.codePath); 11043 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11044 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11045 pkg.applicationInfo.setResourcePath(pkg.codePath); 11046 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11047 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11048 11049 return true; 11050 } 11051 11052 int doPostInstall(int status, int uid) { 11053 if (status != PackageManager.INSTALL_SUCCEEDED) { 11054 cleanUp(); 11055 } 11056 return status; 11057 } 11058 11059 @Override 11060 String getCodePath() { 11061 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11062 } 11063 11064 @Override 11065 String getResourcePath() { 11066 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11067 } 11068 11069 private boolean cleanUp() { 11070 if (codeFile == null || !codeFile.exists()) { 11071 return false; 11072 } 11073 11074 if (codeFile.isDirectory()) { 11075 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11076 } else { 11077 codeFile.delete(); 11078 } 11079 11080 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11081 resourceFile.delete(); 11082 } 11083 11084 return true; 11085 } 11086 11087 void cleanUpResourcesLI() { 11088 // Try enumerating all code paths before deleting 11089 List<String> allCodePaths = Collections.EMPTY_LIST; 11090 if (codeFile != null && codeFile.exists()) { 11091 try { 11092 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11093 allCodePaths = pkg.getAllCodePaths(); 11094 } catch (PackageParserException e) { 11095 // Ignored; we tried our best 11096 } 11097 } 11098 11099 cleanUp(); 11100 removeDexFiles(allCodePaths, instructionSets); 11101 } 11102 11103 boolean doPostDeleteLI(boolean delete) { 11104 // XXX err, shouldn't we respect the delete flag? 11105 cleanUpResourcesLI(); 11106 return true; 11107 } 11108 } 11109 11110 private boolean isAsecExternal(String cid) { 11111 final String asecPath = PackageHelper.getSdFilesystem(cid); 11112 return !asecPath.startsWith(mAsecInternalPath); 11113 } 11114 11115 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11116 PackageManagerException { 11117 if (copyRet < 0) { 11118 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11119 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11120 throw new PackageManagerException(copyRet, message); 11121 } 11122 } 11123 } 11124 11125 /** 11126 * Extract the MountService "container ID" from the full code path of an 11127 * .apk. 11128 */ 11129 static String cidFromCodePath(String fullCodePath) { 11130 int eidx = fullCodePath.lastIndexOf("/"); 11131 String subStr1 = fullCodePath.substring(0, eidx); 11132 int sidx = subStr1.lastIndexOf("/"); 11133 return subStr1.substring(sidx+1, eidx); 11134 } 11135 11136 /** 11137 * Logic to handle installation of ASEC applications, including copying and 11138 * renaming logic. 11139 */ 11140 class AsecInstallArgs extends InstallArgs { 11141 static final String RES_FILE_NAME = "pkg.apk"; 11142 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11143 11144 String cid; 11145 String packagePath; 11146 String resourcePath; 11147 11148 /** New install */ 11149 AsecInstallArgs(InstallParams params) { 11150 super(params.origin, params.move, params.observer, params.installFlags, 11151 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11152 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11153 params.grantedRuntimePermissions); 11154 } 11155 11156 /** Existing install */ 11157 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11158 boolean isExternal, boolean isForwardLocked) { 11159 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11160 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11161 instructionSets, null, null); 11162 // Hackily pretend we're still looking at a full code path 11163 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11164 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11165 } 11166 11167 // Extract cid from fullCodePath 11168 int eidx = fullCodePath.lastIndexOf("/"); 11169 String subStr1 = fullCodePath.substring(0, eidx); 11170 int sidx = subStr1.lastIndexOf("/"); 11171 cid = subStr1.substring(sidx+1, eidx); 11172 setMountPath(subStr1); 11173 } 11174 11175 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11176 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11177 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11178 instructionSets, null, null); 11179 this.cid = cid; 11180 setMountPath(PackageHelper.getSdDir(cid)); 11181 } 11182 11183 void createCopyFile() { 11184 cid = mInstallerService.allocateExternalStageCidLegacy(); 11185 } 11186 11187 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11188 if (origin.staged) { 11189 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11190 cid = origin.cid; 11191 setMountPath(PackageHelper.getSdDir(cid)); 11192 return PackageManager.INSTALL_SUCCEEDED; 11193 } 11194 11195 if (temp) { 11196 createCopyFile(); 11197 } else { 11198 /* 11199 * Pre-emptively destroy the container since it's destroyed if 11200 * copying fails due to it existing anyway. 11201 */ 11202 PackageHelper.destroySdDir(cid); 11203 } 11204 11205 final String newMountPath = imcs.copyPackageToContainer( 11206 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11207 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11208 11209 if (newMountPath != null) { 11210 setMountPath(newMountPath); 11211 return PackageManager.INSTALL_SUCCEEDED; 11212 } else { 11213 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11214 } 11215 } 11216 11217 @Override 11218 String getCodePath() { 11219 return packagePath; 11220 } 11221 11222 @Override 11223 String getResourcePath() { 11224 return resourcePath; 11225 } 11226 11227 int doPreInstall(int status) { 11228 if (status != PackageManager.INSTALL_SUCCEEDED) { 11229 // Destroy container 11230 PackageHelper.destroySdDir(cid); 11231 } else { 11232 boolean mounted = PackageHelper.isContainerMounted(cid); 11233 if (!mounted) { 11234 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11235 Process.SYSTEM_UID); 11236 if (newMountPath != null) { 11237 setMountPath(newMountPath); 11238 } else { 11239 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11240 } 11241 } 11242 } 11243 return status; 11244 } 11245 11246 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11247 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11248 String newMountPath = null; 11249 if (PackageHelper.isContainerMounted(cid)) { 11250 // Unmount the container 11251 if (!PackageHelper.unMountSdDir(cid)) { 11252 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11253 return false; 11254 } 11255 } 11256 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11257 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11258 " which might be stale. Will try to clean up."); 11259 // Clean up the stale container and proceed to recreate. 11260 if (!PackageHelper.destroySdDir(newCacheId)) { 11261 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11262 return false; 11263 } 11264 // Successfully cleaned up stale container. Try to rename again. 11265 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11266 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11267 + " inspite of cleaning it up."); 11268 return false; 11269 } 11270 } 11271 if (!PackageHelper.isContainerMounted(newCacheId)) { 11272 Slog.w(TAG, "Mounting container " + newCacheId); 11273 newMountPath = PackageHelper.mountSdDir(newCacheId, 11274 getEncryptKey(), Process.SYSTEM_UID); 11275 } else { 11276 newMountPath = PackageHelper.getSdDir(newCacheId); 11277 } 11278 if (newMountPath == null) { 11279 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11280 return false; 11281 } 11282 Log.i(TAG, "Succesfully renamed " + cid + 11283 " to " + newCacheId + 11284 " at new path: " + newMountPath); 11285 cid = newCacheId; 11286 11287 final File beforeCodeFile = new File(packagePath); 11288 setMountPath(newMountPath); 11289 final File afterCodeFile = new File(packagePath); 11290 11291 // Reflect the rename in scanned details 11292 pkg.codePath = afterCodeFile.getAbsolutePath(); 11293 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11294 pkg.baseCodePath); 11295 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11296 pkg.splitCodePaths); 11297 11298 // Reflect the rename in app info 11299 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11300 pkg.applicationInfo.setCodePath(pkg.codePath); 11301 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11302 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11303 pkg.applicationInfo.setResourcePath(pkg.codePath); 11304 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11305 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11306 11307 return true; 11308 } 11309 11310 private void setMountPath(String mountPath) { 11311 final File mountFile = new File(mountPath); 11312 11313 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11314 if (monolithicFile.exists()) { 11315 packagePath = monolithicFile.getAbsolutePath(); 11316 if (isFwdLocked()) { 11317 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11318 } else { 11319 resourcePath = packagePath; 11320 } 11321 } else { 11322 packagePath = mountFile.getAbsolutePath(); 11323 resourcePath = packagePath; 11324 } 11325 } 11326 11327 int doPostInstall(int status, int uid) { 11328 if (status != PackageManager.INSTALL_SUCCEEDED) { 11329 cleanUp(); 11330 } else { 11331 final int groupOwner; 11332 final String protectedFile; 11333 if (isFwdLocked()) { 11334 groupOwner = UserHandle.getSharedAppGid(uid); 11335 protectedFile = RES_FILE_NAME; 11336 } else { 11337 groupOwner = -1; 11338 protectedFile = null; 11339 } 11340 11341 if (uid < Process.FIRST_APPLICATION_UID 11342 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11343 Slog.e(TAG, "Failed to finalize " + cid); 11344 PackageHelper.destroySdDir(cid); 11345 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11346 } 11347 11348 boolean mounted = PackageHelper.isContainerMounted(cid); 11349 if (!mounted) { 11350 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11351 } 11352 } 11353 return status; 11354 } 11355 11356 private void cleanUp() { 11357 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11358 11359 // Destroy secure container 11360 PackageHelper.destroySdDir(cid); 11361 } 11362 11363 private List<String> getAllCodePaths() { 11364 final File codeFile = new File(getCodePath()); 11365 if (codeFile != null && codeFile.exists()) { 11366 try { 11367 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11368 return pkg.getAllCodePaths(); 11369 } catch (PackageParserException e) { 11370 // Ignored; we tried our best 11371 } 11372 } 11373 return Collections.EMPTY_LIST; 11374 } 11375 11376 void cleanUpResourcesLI() { 11377 // Enumerate all code paths before deleting 11378 cleanUpResourcesLI(getAllCodePaths()); 11379 } 11380 11381 private void cleanUpResourcesLI(List<String> allCodePaths) { 11382 cleanUp(); 11383 removeDexFiles(allCodePaths, instructionSets); 11384 } 11385 11386 String getPackageName() { 11387 return getAsecPackageName(cid); 11388 } 11389 11390 boolean doPostDeleteLI(boolean delete) { 11391 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11392 final List<String> allCodePaths = getAllCodePaths(); 11393 boolean mounted = PackageHelper.isContainerMounted(cid); 11394 if (mounted) { 11395 // Unmount first 11396 if (PackageHelper.unMountSdDir(cid)) { 11397 mounted = false; 11398 } 11399 } 11400 if (!mounted && delete) { 11401 cleanUpResourcesLI(allCodePaths); 11402 } 11403 return !mounted; 11404 } 11405 11406 @Override 11407 int doPreCopy() { 11408 if (isFwdLocked()) { 11409 if (!PackageHelper.fixSdPermissions(cid, 11410 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11411 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11412 } 11413 } 11414 11415 return PackageManager.INSTALL_SUCCEEDED; 11416 } 11417 11418 @Override 11419 int doPostCopy(int uid) { 11420 if (isFwdLocked()) { 11421 if (uid < Process.FIRST_APPLICATION_UID 11422 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11423 RES_FILE_NAME)) { 11424 Slog.e(TAG, "Failed to finalize " + cid); 11425 PackageHelper.destroySdDir(cid); 11426 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11427 } 11428 } 11429 11430 return PackageManager.INSTALL_SUCCEEDED; 11431 } 11432 } 11433 11434 /** 11435 * Logic to handle movement of existing installed applications. 11436 */ 11437 class MoveInstallArgs extends InstallArgs { 11438 private File codeFile; 11439 private File resourceFile; 11440 11441 /** New install */ 11442 MoveInstallArgs(InstallParams params) { 11443 super(params.origin, params.move, params.observer, params.installFlags, 11444 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11445 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11446 params.grantedRuntimePermissions); 11447 } 11448 11449 int copyApk(IMediaContainerService imcs, boolean temp) { 11450 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11451 + move.fromUuid + " to " + move.toUuid); 11452 synchronized (mInstaller) { 11453 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11454 move.dataAppName, move.appId, move.seinfo) != 0) { 11455 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11456 } 11457 } 11458 11459 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11460 resourceFile = codeFile; 11461 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11462 11463 return PackageManager.INSTALL_SUCCEEDED; 11464 } 11465 11466 int doPreInstall(int status) { 11467 if (status != PackageManager.INSTALL_SUCCEEDED) { 11468 cleanUp(move.toUuid); 11469 } 11470 return status; 11471 } 11472 11473 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11474 if (status != PackageManager.INSTALL_SUCCEEDED) { 11475 cleanUp(move.toUuid); 11476 return false; 11477 } 11478 11479 // Reflect the move in app info 11480 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11481 pkg.applicationInfo.setCodePath(pkg.codePath); 11482 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11483 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11484 pkg.applicationInfo.setResourcePath(pkg.codePath); 11485 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11486 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11487 11488 return true; 11489 } 11490 11491 int doPostInstall(int status, int uid) { 11492 if (status == PackageManager.INSTALL_SUCCEEDED) { 11493 cleanUp(move.fromUuid); 11494 } else { 11495 cleanUp(move.toUuid); 11496 } 11497 return status; 11498 } 11499 11500 @Override 11501 String getCodePath() { 11502 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11503 } 11504 11505 @Override 11506 String getResourcePath() { 11507 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11508 } 11509 11510 private boolean cleanUp(String volumeUuid) { 11511 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11512 move.dataAppName); 11513 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11514 synchronized (mInstallLock) { 11515 // Clean up both app data and code 11516 removeDataDirsLI(volumeUuid, move.packageName); 11517 if (codeFile.isDirectory()) { 11518 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11519 } else { 11520 codeFile.delete(); 11521 } 11522 } 11523 return true; 11524 } 11525 11526 void cleanUpResourcesLI() { 11527 throw new UnsupportedOperationException(); 11528 } 11529 11530 boolean doPostDeleteLI(boolean delete) { 11531 throw new UnsupportedOperationException(); 11532 } 11533 } 11534 11535 static String getAsecPackageName(String packageCid) { 11536 int idx = packageCid.lastIndexOf("-"); 11537 if (idx == -1) { 11538 return packageCid; 11539 } 11540 return packageCid.substring(0, idx); 11541 } 11542 11543 // Utility method used to create code paths based on package name and available index. 11544 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11545 String idxStr = ""; 11546 int idx = 1; 11547 // Fall back to default value of idx=1 if prefix is not 11548 // part of oldCodePath 11549 if (oldCodePath != null) { 11550 String subStr = oldCodePath; 11551 // Drop the suffix right away 11552 if (suffix != null && subStr.endsWith(suffix)) { 11553 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11554 } 11555 // If oldCodePath already contains prefix find out the 11556 // ending index to either increment or decrement. 11557 int sidx = subStr.lastIndexOf(prefix); 11558 if (sidx != -1) { 11559 subStr = subStr.substring(sidx + prefix.length()); 11560 if (subStr != null) { 11561 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11562 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11563 } 11564 try { 11565 idx = Integer.parseInt(subStr); 11566 if (idx <= 1) { 11567 idx++; 11568 } else { 11569 idx--; 11570 } 11571 } catch(NumberFormatException e) { 11572 } 11573 } 11574 } 11575 } 11576 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11577 return prefix + idxStr; 11578 } 11579 11580 private File getNextCodePath(File targetDir, String packageName) { 11581 int suffix = 1; 11582 File result; 11583 do { 11584 result = new File(targetDir, packageName + "-" + suffix); 11585 suffix++; 11586 } while (result.exists()); 11587 return result; 11588 } 11589 11590 // Utility method that returns the relative package path with respect 11591 // to the installation directory. Like say for /data/data/com.test-1.apk 11592 // string com.test-1 is returned. 11593 static String deriveCodePathName(String codePath) { 11594 if (codePath == null) { 11595 return null; 11596 } 11597 final File codeFile = new File(codePath); 11598 final String name = codeFile.getName(); 11599 if (codeFile.isDirectory()) { 11600 return name; 11601 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11602 final int lastDot = name.lastIndexOf('.'); 11603 return name.substring(0, lastDot); 11604 } else { 11605 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11606 return null; 11607 } 11608 } 11609 11610 class PackageInstalledInfo { 11611 String name; 11612 int uid; 11613 // The set of users that originally had this package installed. 11614 int[] origUsers; 11615 // The set of users that now have this package installed. 11616 int[] newUsers; 11617 PackageParser.Package pkg; 11618 int returnCode; 11619 String returnMsg; 11620 PackageRemovedInfo removedInfo; 11621 11622 public void setError(int code, String msg) { 11623 returnCode = code; 11624 returnMsg = msg; 11625 Slog.w(TAG, msg); 11626 } 11627 11628 public void setError(String msg, PackageParserException e) { 11629 returnCode = e.error; 11630 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11631 Slog.w(TAG, msg, e); 11632 } 11633 11634 public void setError(String msg, PackageManagerException e) { 11635 returnCode = e.error; 11636 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11637 Slog.w(TAG, msg, e); 11638 } 11639 11640 // In some error cases we want to convey more info back to the observer 11641 String origPackage; 11642 String origPermission; 11643 } 11644 11645 /* 11646 * Install a non-existing package. 11647 */ 11648 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11649 UserHandle user, String installerPackageName, String volumeUuid, 11650 PackageInstalledInfo res) { 11651 // Remember this for later, in case we need to rollback this install 11652 String pkgName = pkg.packageName; 11653 11654 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11655 final boolean dataDirExists = Environment 11656 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11657 synchronized(mPackages) { 11658 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11659 // A package with the same name is already installed, though 11660 // it has been renamed to an older name. The package we 11661 // are trying to install should be installed as an update to 11662 // the existing one, but that has not been requested, so bail. 11663 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11664 + " without first uninstalling package running as " 11665 + mSettings.mRenamedPackages.get(pkgName)); 11666 return; 11667 } 11668 if (mPackages.containsKey(pkgName)) { 11669 // Don't allow installation over an existing package with the same name. 11670 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11671 + " without first uninstalling."); 11672 return; 11673 } 11674 } 11675 11676 try { 11677 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11678 System.currentTimeMillis(), user); 11679 11680 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11681 // delete the partially installed application. the data directory will have to be 11682 // restored if it was already existing 11683 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11684 // remove package from internal structures. Note that we want deletePackageX to 11685 // delete the package data and cache directories that it created in 11686 // scanPackageLocked, unless those directories existed before we even tried to 11687 // install. 11688 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11689 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11690 res.removedInfo, true); 11691 } 11692 11693 } catch (PackageManagerException e) { 11694 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11695 } 11696 } 11697 11698 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11699 // Can't rotate keys during boot or if sharedUser. 11700 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11701 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11702 return false; 11703 } 11704 // app is using upgradeKeySets; make sure all are valid 11705 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11706 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11707 for (int i = 0; i < upgradeKeySets.length; i++) { 11708 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11709 Slog.wtf(TAG, "Package " 11710 + (oldPs.name != null ? oldPs.name : "<null>") 11711 + " contains upgrade-key-set reference to unknown key-set: " 11712 + upgradeKeySets[i] 11713 + " reverting to signatures check."); 11714 return false; 11715 } 11716 } 11717 return true; 11718 } 11719 11720 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11721 // Upgrade keysets are being used. Determine if new package has a superset of the 11722 // required keys. 11723 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11724 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11725 for (int i = 0; i < upgradeKeySets.length; i++) { 11726 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11727 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11728 return true; 11729 } 11730 } 11731 return false; 11732 } 11733 11734 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11735 UserHandle user, String installerPackageName, String volumeUuid, 11736 PackageInstalledInfo res) { 11737 final PackageParser.Package oldPackage; 11738 final String pkgName = pkg.packageName; 11739 final int[] allUsers; 11740 final boolean[] perUserInstalled; 11741 final boolean weFroze; 11742 11743 // First find the old package info and check signatures 11744 synchronized(mPackages) { 11745 oldPackage = mPackages.get(pkgName); 11746 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11747 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11748 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11749 if(!checkUpgradeKeySetLP(ps, pkg)) { 11750 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11751 "New package not signed by keys specified by upgrade-keysets: " 11752 + pkgName); 11753 return; 11754 } 11755 } else { 11756 // default to original signature matching 11757 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11758 != PackageManager.SIGNATURE_MATCH) { 11759 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11760 "New package has a different signature: " + pkgName); 11761 return; 11762 } 11763 } 11764 11765 // In case of rollback, remember per-user/profile install state 11766 allUsers = sUserManager.getUserIds(); 11767 perUserInstalled = new boolean[allUsers.length]; 11768 for (int i = 0; i < allUsers.length; i++) { 11769 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11770 } 11771 11772 // Mark the app as frozen to prevent launching during the upgrade 11773 // process, and then kill all running instances 11774 if (!ps.frozen) { 11775 ps.frozen = true; 11776 weFroze = true; 11777 } else { 11778 weFroze = false; 11779 } 11780 } 11781 11782 // Now that we're guarded by frozen state, kill app during upgrade 11783 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11784 11785 try { 11786 boolean sysPkg = (isSystemApp(oldPackage)); 11787 if (sysPkg) { 11788 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11789 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11790 } else { 11791 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11792 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11793 } 11794 } finally { 11795 // Regardless of success or failure of upgrade steps above, always 11796 // unfreeze the package if we froze it 11797 if (weFroze) { 11798 unfreezePackage(pkgName); 11799 } 11800 } 11801 } 11802 11803 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11804 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11805 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11806 String volumeUuid, PackageInstalledInfo res) { 11807 String pkgName = deletedPackage.packageName; 11808 boolean deletedPkg = true; 11809 boolean updatedSettings = false; 11810 11811 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11812 + deletedPackage); 11813 long origUpdateTime; 11814 if (pkg.mExtras != null) { 11815 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11816 } else { 11817 origUpdateTime = 0; 11818 } 11819 11820 // First delete the existing package while retaining the data directory 11821 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11822 res.removedInfo, true)) { 11823 // If the existing package wasn't successfully deleted 11824 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11825 deletedPkg = false; 11826 } else { 11827 // Successfully deleted the old package; proceed with replace. 11828 11829 // If deleted package lived in a container, give users a chance to 11830 // relinquish resources before killing. 11831 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11832 if (DEBUG_INSTALL) { 11833 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11834 } 11835 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11836 final ArrayList<String> pkgList = new ArrayList<String>(1); 11837 pkgList.add(deletedPackage.applicationInfo.packageName); 11838 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11839 } 11840 11841 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11842 try { 11843 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11844 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11845 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11846 perUserInstalled, res, user); 11847 updatedSettings = true; 11848 } catch (PackageManagerException e) { 11849 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11850 } 11851 } 11852 11853 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11854 // remove package from internal structures. Note that we want deletePackageX to 11855 // delete the package data and cache directories that it created in 11856 // scanPackageLocked, unless those directories existed before we even tried to 11857 // install. 11858 if(updatedSettings) { 11859 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11860 deletePackageLI( 11861 pkgName, null, true, allUsers, perUserInstalled, 11862 PackageManager.DELETE_KEEP_DATA, 11863 res.removedInfo, true); 11864 } 11865 // Since we failed to install the new package we need to restore the old 11866 // package that we deleted. 11867 if (deletedPkg) { 11868 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11869 File restoreFile = new File(deletedPackage.codePath); 11870 // Parse old package 11871 boolean oldExternal = isExternal(deletedPackage); 11872 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11873 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11874 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11875 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11876 try { 11877 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11878 } catch (PackageManagerException e) { 11879 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11880 + e.getMessage()); 11881 return; 11882 } 11883 // Restore of old package succeeded. Update permissions. 11884 // writer 11885 synchronized (mPackages) { 11886 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11887 UPDATE_PERMISSIONS_ALL); 11888 // can downgrade to reader 11889 mSettings.writeLPr(); 11890 } 11891 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11892 } 11893 } 11894 } 11895 11896 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11897 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11898 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11899 String volumeUuid, PackageInstalledInfo res) { 11900 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11901 + ", old=" + deletedPackage); 11902 boolean disabledSystem = false; 11903 boolean updatedSettings = false; 11904 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11905 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11906 != 0) { 11907 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11908 } 11909 String packageName = deletedPackage.packageName; 11910 if (packageName == null) { 11911 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11912 "Attempt to delete null packageName."); 11913 return; 11914 } 11915 PackageParser.Package oldPkg; 11916 PackageSetting oldPkgSetting; 11917 // reader 11918 synchronized (mPackages) { 11919 oldPkg = mPackages.get(packageName); 11920 oldPkgSetting = mSettings.mPackages.get(packageName); 11921 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11922 (oldPkgSetting == null)) { 11923 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11924 "Couldn't find package:" + packageName + " information"); 11925 return; 11926 } 11927 } 11928 11929 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11930 res.removedInfo.removedPackage = packageName; 11931 // Remove existing system package 11932 removePackageLI(oldPkgSetting, true); 11933 // writer 11934 synchronized (mPackages) { 11935 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11936 if (!disabledSystem && deletedPackage != null) { 11937 // We didn't need to disable the .apk as a current system package, 11938 // which means we are replacing another update that is already 11939 // installed. We need to make sure to delete the older one's .apk. 11940 res.removedInfo.args = createInstallArgsForExisting(0, 11941 deletedPackage.applicationInfo.getCodePath(), 11942 deletedPackage.applicationInfo.getResourcePath(), 11943 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11944 } else { 11945 res.removedInfo.args = null; 11946 } 11947 } 11948 11949 // Successfully disabled the old package. Now proceed with re-installation 11950 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11951 11952 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11953 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11954 11955 PackageParser.Package newPackage = null; 11956 try { 11957 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11958 if (newPackage.mExtras != null) { 11959 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11960 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11961 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11962 11963 // is the update attempting to change shared user? that isn't going to work... 11964 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11965 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11966 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11967 + " to " + newPkgSetting.sharedUser); 11968 updatedSettings = true; 11969 } 11970 } 11971 11972 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11973 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11974 perUserInstalled, res, user); 11975 updatedSettings = true; 11976 } 11977 11978 } catch (PackageManagerException e) { 11979 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11980 } 11981 11982 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11983 // Re installation failed. Restore old information 11984 // Remove new pkg information 11985 if (newPackage != null) { 11986 removeInstalledPackageLI(newPackage, true); 11987 } 11988 // Add back the old system package 11989 try { 11990 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11991 } catch (PackageManagerException e) { 11992 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11993 } 11994 // Restore the old system information in Settings 11995 synchronized (mPackages) { 11996 if (disabledSystem) { 11997 mSettings.enableSystemPackageLPw(packageName); 11998 } 11999 if (updatedSettings) { 12000 mSettings.setInstallerPackageName(packageName, 12001 oldPkgSetting.installerPackageName); 12002 } 12003 mSettings.writeLPr(); 12004 } 12005 } 12006 } 12007 12008 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12009 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12010 UserHandle user) { 12011 String pkgName = newPackage.packageName; 12012 synchronized (mPackages) { 12013 //write settings. the installStatus will be incomplete at this stage. 12014 //note that the new package setting would have already been 12015 //added to mPackages. It hasn't been persisted yet. 12016 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12017 mSettings.writeLPr(); 12018 } 12019 12020 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12021 12022 synchronized (mPackages) { 12023 updatePermissionsLPw(newPackage.packageName, newPackage, 12024 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12025 ? UPDATE_PERMISSIONS_ALL : 0)); 12026 // For system-bundled packages, we assume that installing an upgraded version 12027 // of the package implies that the user actually wants to run that new code, 12028 // so we enable the package. 12029 PackageSetting ps = mSettings.mPackages.get(pkgName); 12030 if (ps != null) { 12031 if (isSystemApp(newPackage)) { 12032 // NB: implicit assumption that system package upgrades apply to all users 12033 if (DEBUG_INSTALL) { 12034 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12035 } 12036 if (res.origUsers != null) { 12037 for (int userHandle : res.origUsers) { 12038 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12039 userHandle, installerPackageName); 12040 } 12041 } 12042 // Also convey the prior install/uninstall state 12043 if (allUsers != null && perUserInstalled != null) { 12044 for (int i = 0; i < allUsers.length; i++) { 12045 if (DEBUG_INSTALL) { 12046 Slog.d(TAG, " user " + allUsers[i] 12047 + " => " + perUserInstalled[i]); 12048 } 12049 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12050 } 12051 // these install state changes will be persisted in the 12052 // upcoming call to mSettings.writeLPr(). 12053 } 12054 } 12055 // It's implied that when a user requests installation, they want the app to be 12056 // installed and enabled. 12057 int userId = user.getIdentifier(); 12058 if (userId != UserHandle.USER_ALL) { 12059 ps.setInstalled(true, userId); 12060 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12061 } 12062 } 12063 res.name = pkgName; 12064 res.uid = newPackage.applicationInfo.uid; 12065 res.pkg = newPackage; 12066 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12067 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12068 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12069 //to update install status 12070 mSettings.writeLPr(); 12071 } 12072 } 12073 12074 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12075 final int installFlags = args.installFlags; 12076 final String installerPackageName = args.installerPackageName; 12077 final String volumeUuid = args.volumeUuid; 12078 final File tmpPackageFile = new File(args.getCodePath()); 12079 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12080 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12081 || (args.volumeUuid != null)); 12082 boolean replace = false; 12083 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12084 if (args.move != null) { 12085 // moving a complete application; perfom an initial scan on the new install location 12086 scanFlags |= SCAN_INITIAL; 12087 } 12088 // Result object to be returned 12089 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12090 12091 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12092 // Retrieve PackageSettings and parse package 12093 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12094 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12095 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12096 PackageParser pp = new PackageParser(); 12097 pp.setSeparateProcesses(mSeparateProcesses); 12098 pp.setDisplayMetrics(mMetrics); 12099 12100 final PackageParser.Package pkg; 12101 try { 12102 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12103 } catch (PackageParserException e) { 12104 res.setError("Failed parse during installPackageLI", e); 12105 return; 12106 } 12107 12108 // Mark that we have an install time CPU ABI override. 12109 pkg.cpuAbiOverride = args.abiOverride; 12110 12111 String pkgName = res.name = pkg.packageName; 12112 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12113 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12114 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12115 return; 12116 } 12117 } 12118 12119 try { 12120 pp.collectCertificates(pkg, parseFlags); 12121 pp.collectManifestDigest(pkg); 12122 } catch (PackageParserException e) { 12123 res.setError("Failed collect during installPackageLI", e); 12124 return; 12125 } 12126 12127 /* If the installer passed in a manifest digest, compare it now. */ 12128 if (args.manifestDigest != null) { 12129 if (DEBUG_INSTALL) { 12130 final String parsedManifest = pkg.manifestDigest == null ? "null" 12131 : pkg.manifestDigest.toString(); 12132 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12133 + parsedManifest); 12134 } 12135 12136 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12137 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12138 return; 12139 } 12140 } else if (DEBUG_INSTALL) { 12141 final String parsedManifest = pkg.manifestDigest == null 12142 ? "null" : pkg.manifestDigest.toString(); 12143 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12144 } 12145 12146 // Get rid of all references to package scan path via parser. 12147 pp = null; 12148 String oldCodePath = null; 12149 boolean systemApp = false; 12150 synchronized (mPackages) { 12151 // Check if installing already existing package 12152 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12153 String oldName = mSettings.mRenamedPackages.get(pkgName); 12154 if (pkg.mOriginalPackages != null 12155 && pkg.mOriginalPackages.contains(oldName) 12156 && mPackages.containsKey(oldName)) { 12157 // This package is derived from an original package, 12158 // and this device has been updating from that original 12159 // name. We must continue using the original name, so 12160 // rename the new package here. 12161 pkg.setPackageName(oldName); 12162 pkgName = pkg.packageName; 12163 replace = true; 12164 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12165 + oldName + " pkgName=" + pkgName); 12166 } else if (mPackages.containsKey(pkgName)) { 12167 // This package, under its official name, already exists 12168 // on the device; we should replace it. 12169 replace = true; 12170 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12171 } 12172 12173 // Prevent apps opting out from runtime permissions 12174 if (replace) { 12175 PackageParser.Package oldPackage = mPackages.get(pkgName); 12176 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12177 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12178 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12179 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12180 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12181 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12182 + " doesn't support runtime permissions but the old" 12183 + " target SDK " + oldTargetSdk + " does."); 12184 return; 12185 } 12186 } 12187 } 12188 12189 PackageSetting ps = mSettings.mPackages.get(pkgName); 12190 if (ps != null) { 12191 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12192 12193 // Quick sanity check that we're signed correctly if updating; 12194 // we'll check this again later when scanning, but we want to 12195 // bail early here before tripping over redefined permissions. 12196 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12197 if (!checkUpgradeKeySetLP(ps, pkg)) { 12198 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12199 + pkg.packageName + " upgrade keys do not match the " 12200 + "previously installed version"); 12201 return; 12202 } 12203 } else { 12204 try { 12205 verifySignaturesLP(ps, pkg); 12206 } catch (PackageManagerException e) { 12207 res.setError(e.error, e.getMessage()); 12208 return; 12209 } 12210 } 12211 12212 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12213 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12214 systemApp = (ps.pkg.applicationInfo.flags & 12215 ApplicationInfo.FLAG_SYSTEM) != 0; 12216 } 12217 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12218 } 12219 12220 // Check whether the newly-scanned package wants to define an already-defined perm 12221 int N = pkg.permissions.size(); 12222 for (int i = N-1; i >= 0; i--) { 12223 PackageParser.Permission perm = pkg.permissions.get(i); 12224 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12225 if (bp != null) { 12226 // If the defining package is signed with our cert, it's okay. This 12227 // also includes the "updating the same package" case, of course. 12228 // "updating same package" could also involve key-rotation. 12229 final boolean sigsOk; 12230 if (bp.sourcePackage.equals(pkg.packageName) 12231 && (bp.packageSetting instanceof PackageSetting) 12232 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12233 scanFlags))) { 12234 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12235 } else { 12236 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12237 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12238 } 12239 if (!sigsOk) { 12240 // If the owning package is the system itself, we log but allow 12241 // install to proceed; we fail the install on all other permission 12242 // redefinitions. 12243 if (!bp.sourcePackage.equals("android")) { 12244 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12245 + pkg.packageName + " attempting to redeclare permission " 12246 + perm.info.name + " already owned by " + bp.sourcePackage); 12247 res.origPermission = perm.info.name; 12248 res.origPackage = bp.sourcePackage; 12249 return; 12250 } else { 12251 Slog.w(TAG, "Package " + pkg.packageName 12252 + " attempting to redeclare system permission " 12253 + perm.info.name + "; ignoring new declaration"); 12254 pkg.permissions.remove(i); 12255 } 12256 } 12257 } 12258 } 12259 12260 } 12261 12262 if (systemApp && onExternal) { 12263 // Disable updates to system apps on sdcard 12264 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12265 "Cannot install updates to system apps on sdcard"); 12266 return; 12267 } 12268 12269 if (args.move != null) { 12270 // We did an in-place move, so dex is ready to roll 12271 scanFlags |= SCAN_NO_DEX; 12272 scanFlags |= SCAN_MOVE; 12273 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12274 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12275 scanFlags |= SCAN_NO_DEX; 12276 12277 try { 12278 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12279 true /* extract libs */); 12280 } catch (PackageManagerException pme) { 12281 Slog.e(TAG, "Error deriving application ABI", pme); 12282 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12283 return; 12284 } 12285 12286 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12287 int result = mPackageDexOptimizer 12288 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12289 false /* defer */, false /* inclDependencies */); 12290 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12291 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12292 return; 12293 } 12294 } 12295 12296 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12297 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12298 return; 12299 } 12300 12301 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12302 12303 if (replace) { 12304 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12305 installerPackageName, volumeUuid, res); 12306 } else { 12307 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12308 args.user, installerPackageName, volumeUuid, res); 12309 } 12310 synchronized (mPackages) { 12311 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12312 if (ps != null) { 12313 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12314 } 12315 } 12316 } 12317 12318 private void startIntentFilterVerifications(int userId, boolean replacing, 12319 PackageParser.Package pkg) { 12320 if (mIntentFilterVerifierComponent == null) { 12321 Slog.w(TAG, "No IntentFilter verification will not be done as " 12322 + "there is no IntentFilterVerifier available!"); 12323 return; 12324 } 12325 12326 final int verifierUid = getPackageUid( 12327 mIntentFilterVerifierComponent.getPackageName(), 12328 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12329 12330 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12331 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12332 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12333 mHandler.sendMessage(msg); 12334 } 12335 12336 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12337 PackageParser.Package pkg) { 12338 int size = pkg.activities.size(); 12339 if (size == 0) { 12340 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12341 "No activity, so no need to verify any IntentFilter!"); 12342 return; 12343 } 12344 12345 final boolean hasDomainURLs = hasDomainURLs(pkg); 12346 if (!hasDomainURLs) { 12347 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12348 "No domain URLs, so no need to verify any IntentFilter!"); 12349 return; 12350 } 12351 12352 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12353 + " if any IntentFilter from the " + size 12354 + " Activities needs verification ..."); 12355 12356 int count = 0; 12357 final String packageName = pkg.packageName; 12358 12359 synchronized (mPackages) { 12360 // If this is a new install and we see that we've already run verification for this 12361 // package, we have nothing to do: it means the state was restored from backup. 12362 if (!replacing) { 12363 IntentFilterVerificationInfo ivi = 12364 mSettings.getIntentFilterVerificationLPr(packageName); 12365 if (ivi != null) { 12366 if (DEBUG_DOMAIN_VERIFICATION) { 12367 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12368 + ivi.getStatusString()); 12369 } 12370 return; 12371 } 12372 } 12373 12374 // If any filters need to be verified, then all need to be. 12375 boolean needToVerify = false; 12376 for (PackageParser.Activity a : pkg.activities) { 12377 for (ActivityIntentInfo filter : a.intents) { 12378 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12379 if (DEBUG_DOMAIN_VERIFICATION) { 12380 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12381 } 12382 needToVerify = true; 12383 break; 12384 } 12385 } 12386 } 12387 12388 if (needToVerify) { 12389 final int verificationId = mIntentFilterVerificationToken++; 12390 for (PackageParser.Activity a : pkg.activities) { 12391 for (ActivityIntentInfo filter : a.intents) { 12392 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12393 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12394 "Verification needed for IntentFilter:" + filter.toString()); 12395 mIntentFilterVerifier.addOneIntentFilterVerification( 12396 verifierUid, userId, verificationId, filter, packageName); 12397 count++; 12398 } 12399 } 12400 } 12401 } 12402 } 12403 12404 if (count > 0) { 12405 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12406 + " IntentFilter verification" + (count > 1 ? "s" : "") 12407 + " for userId:" + userId); 12408 mIntentFilterVerifier.startVerifications(userId); 12409 } else { 12410 if (DEBUG_DOMAIN_VERIFICATION) { 12411 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12412 } 12413 } 12414 } 12415 12416 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12417 final ComponentName cn = filter.activity.getComponentName(); 12418 final String packageName = cn.getPackageName(); 12419 12420 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12421 packageName); 12422 if (ivi == null) { 12423 return true; 12424 } 12425 int status = ivi.getStatus(); 12426 switch (status) { 12427 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12428 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12429 return true; 12430 12431 default: 12432 // Nothing to do 12433 return false; 12434 } 12435 } 12436 12437 private static boolean isMultiArch(PackageSetting ps) { 12438 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12439 } 12440 12441 private static boolean isMultiArch(ApplicationInfo info) { 12442 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12443 } 12444 12445 private static boolean isExternal(PackageParser.Package pkg) { 12446 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12447 } 12448 12449 private static boolean isExternal(PackageSetting ps) { 12450 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12451 } 12452 12453 private static boolean isExternal(ApplicationInfo info) { 12454 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12455 } 12456 12457 private static boolean isSystemApp(PackageParser.Package pkg) { 12458 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12459 } 12460 12461 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12462 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12463 } 12464 12465 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12466 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12467 } 12468 12469 private static boolean isSystemApp(PackageSetting ps) { 12470 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12471 } 12472 12473 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12474 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12475 } 12476 12477 private int packageFlagsToInstallFlags(PackageSetting ps) { 12478 int installFlags = 0; 12479 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12480 // This existing package was an external ASEC install when we have 12481 // the external flag without a UUID 12482 installFlags |= PackageManager.INSTALL_EXTERNAL; 12483 } 12484 if (ps.isForwardLocked()) { 12485 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12486 } 12487 return installFlags; 12488 } 12489 12490 private void deleteTempPackageFiles() { 12491 final FilenameFilter filter = new FilenameFilter() { 12492 public boolean accept(File dir, String name) { 12493 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12494 } 12495 }; 12496 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12497 file.delete(); 12498 } 12499 } 12500 12501 @Override 12502 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12503 int flags) { 12504 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12505 flags); 12506 } 12507 12508 @Override 12509 public void deletePackage(final String packageName, 12510 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12511 mContext.enforceCallingOrSelfPermission( 12512 android.Manifest.permission.DELETE_PACKAGES, null); 12513 Preconditions.checkNotNull(packageName); 12514 Preconditions.checkNotNull(observer); 12515 final int uid = Binder.getCallingUid(); 12516 if (UserHandle.getUserId(uid) != userId) { 12517 mContext.enforceCallingPermission( 12518 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12519 "deletePackage for user " + userId); 12520 } 12521 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12522 try { 12523 observer.onPackageDeleted(packageName, 12524 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12525 } catch (RemoteException re) { 12526 } 12527 return; 12528 } 12529 12530 boolean uninstallBlocked = false; 12531 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12532 int[] users = sUserManager.getUserIds(); 12533 for (int i = 0; i < users.length; ++i) { 12534 if (getBlockUninstallForUser(packageName, users[i])) { 12535 uninstallBlocked = true; 12536 break; 12537 } 12538 } 12539 } else { 12540 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12541 } 12542 if (uninstallBlocked) { 12543 try { 12544 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12545 null); 12546 } catch (RemoteException re) { 12547 } 12548 return; 12549 } 12550 12551 if (DEBUG_REMOVE) { 12552 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12553 } 12554 // Queue up an async operation since the package deletion may take a little while. 12555 mHandler.post(new Runnable() { 12556 public void run() { 12557 mHandler.removeCallbacks(this); 12558 final int returnCode = deletePackageX(packageName, userId, flags); 12559 if (observer != null) { 12560 try { 12561 observer.onPackageDeleted(packageName, returnCode, null); 12562 } catch (RemoteException e) { 12563 Log.i(TAG, "Observer no longer exists."); 12564 } //end catch 12565 } //end if 12566 } //end run 12567 }); 12568 } 12569 12570 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12571 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12572 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12573 try { 12574 if (dpm != null) { 12575 if (dpm.isDeviceOwner(packageName)) { 12576 return true; 12577 } 12578 int[] users; 12579 if (userId == UserHandle.USER_ALL) { 12580 users = sUserManager.getUserIds(); 12581 } else { 12582 users = new int[]{userId}; 12583 } 12584 for (int i = 0; i < users.length; ++i) { 12585 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12586 return true; 12587 } 12588 } 12589 } 12590 } catch (RemoteException e) { 12591 } 12592 return false; 12593 } 12594 12595 /** 12596 * This method is an internal method that could be get invoked either 12597 * to delete an installed package or to clean up a failed installation. 12598 * After deleting an installed package, a broadcast is sent to notify any 12599 * listeners that the package has been installed. For cleaning up a failed 12600 * installation, the broadcast is not necessary since the package's 12601 * installation wouldn't have sent the initial broadcast either 12602 * The key steps in deleting a package are 12603 * deleting the package information in internal structures like mPackages, 12604 * deleting the packages base directories through installd 12605 * updating mSettings to reflect current status 12606 * persisting settings for later use 12607 * sending a broadcast if necessary 12608 */ 12609 private int deletePackageX(String packageName, int userId, int flags) { 12610 final PackageRemovedInfo info = new PackageRemovedInfo(); 12611 final boolean res; 12612 12613 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12614 ? UserHandle.ALL : new UserHandle(userId); 12615 12616 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12617 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12618 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12619 } 12620 12621 boolean removedForAllUsers = false; 12622 boolean systemUpdate = false; 12623 12624 // for the uninstall-updates case and restricted profiles, remember the per- 12625 // userhandle installed state 12626 int[] allUsers; 12627 boolean[] perUserInstalled; 12628 synchronized (mPackages) { 12629 PackageSetting ps = mSettings.mPackages.get(packageName); 12630 allUsers = sUserManager.getUserIds(); 12631 perUserInstalled = new boolean[allUsers.length]; 12632 for (int i = 0; i < allUsers.length; i++) { 12633 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12634 } 12635 } 12636 12637 synchronized (mInstallLock) { 12638 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12639 res = deletePackageLI(packageName, removeForUser, 12640 true, allUsers, perUserInstalled, 12641 flags | REMOVE_CHATTY, info, true); 12642 systemUpdate = info.isRemovedPackageSystemUpdate; 12643 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12644 removedForAllUsers = true; 12645 } 12646 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12647 + " removedForAllUsers=" + removedForAllUsers); 12648 } 12649 12650 if (res) { 12651 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12652 12653 // If the removed package was a system update, the old system package 12654 // was re-enabled; we need to broadcast this information 12655 if (systemUpdate) { 12656 Bundle extras = new Bundle(1); 12657 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12658 ? info.removedAppId : info.uid); 12659 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12660 12661 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12662 extras, null, null, null); 12663 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12664 extras, null, null, null); 12665 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12666 null, packageName, null, null); 12667 } 12668 } 12669 // Force a gc here. 12670 Runtime.getRuntime().gc(); 12671 // Delete the resources here after sending the broadcast to let 12672 // other processes clean up before deleting resources. 12673 if (info.args != null) { 12674 synchronized (mInstallLock) { 12675 info.args.doPostDeleteLI(true); 12676 } 12677 } 12678 12679 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12680 } 12681 12682 class PackageRemovedInfo { 12683 String removedPackage; 12684 int uid = -1; 12685 int removedAppId = -1; 12686 int[] removedUsers = null; 12687 boolean isRemovedPackageSystemUpdate = false; 12688 // Clean up resources deleted packages. 12689 InstallArgs args = null; 12690 12691 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12692 Bundle extras = new Bundle(1); 12693 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12694 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12695 if (replacing) { 12696 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12697 } 12698 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12699 if (removedPackage != null) { 12700 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12701 extras, null, null, removedUsers); 12702 if (fullRemove && !replacing) { 12703 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12704 extras, null, null, removedUsers); 12705 } 12706 } 12707 if (removedAppId >= 0) { 12708 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12709 removedUsers); 12710 } 12711 } 12712 } 12713 12714 /* 12715 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12716 * flag is not set, the data directory is removed as well. 12717 * make sure this flag is set for partially installed apps. If not its meaningless to 12718 * delete a partially installed application. 12719 */ 12720 private void removePackageDataLI(PackageSetting ps, 12721 int[] allUserHandles, boolean[] perUserInstalled, 12722 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12723 String packageName = ps.name; 12724 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12725 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12726 // Retrieve object to delete permissions for shared user later on 12727 final PackageSetting deletedPs; 12728 // reader 12729 synchronized (mPackages) { 12730 deletedPs = mSettings.mPackages.get(packageName); 12731 if (outInfo != null) { 12732 outInfo.removedPackage = packageName; 12733 outInfo.removedUsers = deletedPs != null 12734 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12735 : null; 12736 } 12737 } 12738 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12739 removeDataDirsLI(ps.volumeUuid, packageName); 12740 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12741 } 12742 // writer 12743 synchronized (mPackages) { 12744 if (deletedPs != null) { 12745 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12746 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12747 clearDefaultBrowserIfNeeded(packageName); 12748 if (outInfo != null) { 12749 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12750 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12751 } 12752 updatePermissionsLPw(deletedPs.name, null, 0); 12753 if (deletedPs.sharedUser != null) { 12754 // Remove permissions associated with package. Since runtime 12755 // permissions are per user we have to kill the removed package 12756 // or packages running under the shared user of the removed 12757 // package if revoking the permissions requested only by the removed 12758 // package is successful and this causes a change in gids. 12759 for (int userId : UserManagerService.getInstance().getUserIds()) { 12760 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12761 userId); 12762 if (userIdToKill == UserHandle.USER_ALL 12763 || userIdToKill >= UserHandle.USER_OWNER) { 12764 // If gids changed for this user, kill all affected packages. 12765 mHandler.post(new Runnable() { 12766 @Override 12767 public void run() { 12768 // This has to happen with no lock held. 12769 killSettingPackagesForUser(deletedPs, userIdToKill, 12770 KILL_APP_REASON_GIDS_CHANGED); 12771 } 12772 }); 12773 break; 12774 } 12775 } 12776 } 12777 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12778 } 12779 // make sure to preserve per-user disabled state if this removal was just 12780 // a downgrade of a system app to the factory package 12781 if (allUserHandles != null && perUserInstalled != null) { 12782 if (DEBUG_REMOVE) { 12783 Slog.d(TAG, "Propagating install state across downgrade"); 12784 } 12785 for (int i = 0; i < allUserHandles.length; i++) { 12786 if (DEBUG_REMOVE) { 12787 Slog.d(TAG, " user " + allUserHandles[i] 12788 + " => " + perUserInstalled[i]); 12789 } 12790 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12791 } 12792 } 12793 } 12794 // can downgrade to reader 12795 if (writeSettings) { 12796 // Save settings now 12797 mSettings.writeLPr(); 12798 } 12799 } 12800 if (outInfo != null) { 12801 // A user ID was deleted here. Go through all users and remove it 12802 // from KeyStore. 12803 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12804 } 12805 } 12806 12807 static boolean locationIsPrivileged(File path) { 12808 try { 12809 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12810 .getCanonicalPath(); 12811 return path.getCanonicalPath().startsWith(privilegedAppDir); 12812 } catch (IOException e) { 12813 Slog.e(TAG, "Unable to access code path " + path); 12814 } 12815 return false; 12816 } 12817 12818 /* 12819 * Tries to delete system package. 12820 */ 12821 private boolean deleteSystemPackageLI(PackageSetting newPs, 12822 int[] allUserHandles, boolean[] perUserInstalled, 12823 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12824 final boolean applyUserRestrictions 12825 = (allUserHandles != null) && (perUserInstalled != null); 12826 PackageSetting disabledPs = null; 12827 // Confirm if the system package has been updated 12828 // An updated system app can be deleted. This will also have to restore 12829 // the system pkg from system partition 12830 // reader 12831 synchronized (mPackages) { 12832 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12833 } 12834 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12835 + " disabledPs=" + disabledPs); 12836 if (disabledPs == null) { 12837 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12838 return false; 12839 } else if (DEBUG_REMOVE) { 12840 Slog.d(TAG, "Deleting system pkg from data partition"); 12841 } 12842 if (DEBUG_REMOVE) { 12843 if (applyUserRestrictions) { 12844 Slog.d(TAG, "Remembering install states:"); 12845 for (int i = 0; i < allUserHandles.length; i++) { 12846 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12847 } 12848 } 12849 } 12850 // Delete the updated package 12851 outInfo.isRemovedPackageSystemUpdate = true; 12852 if (disabledPs.versionCode < newPs.versionCode) { 12853 // Delete data for downgrades 12854 flags &= ~PackageManager.DELETE_KEEP_DATA; 12855 } else { 12856 // Preserve data by setting flag 12857 flags |= PackageManager.DELETE_KEEP_DATA; 12858 } 12859 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12860 allUserHandles, perUserInstalled, outInfo, writeSettings); 12861 if (!ret) { 12862 return false; 12863 } 12864 // writer 12865 synchronized (mPackages) { 12866 // Reinstate the old system package 12867 mSettings.enableSystemPackageLPw(newPs.name); 12868 // Remove any native libraries from the upgraded package. 12869 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12870 } 12871 // Install the system package 12872 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12873 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12874 if (locationIsPrivileged(disabledPs.codePath)) { 12875 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12876 } 12877 12878 final PackageParser.Package newPkg; 12879 try { 12880 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12881 } catch (PackageManagerException e) { 12882 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12883 return false; 12884 } 12885 12886 // writer 12887 synchronized (mPackages) { 12888 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12889 12890 // Propagate the permissions state as we do want to drop on the floor 12891 // runtime permissions. The update permissions method below will take 12892 // care of removing obsolete permissions and grant install permissions. 12893 ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState()); 12894 updatePermissionsLPw(newPkg.packageName, newPkg, 12895 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12896 12897 if (applyUserRestrictions) { 12898 if (DEBUG_REMOVE) { 12899 Slog.d(TAG, "Propagating install state across reinstall"); 12900 } 12901 for (int i = 0; i < allUserHandles.length; i++) { 12902 if (DEBUG_REMOVE) { 12903 Slog.d(TAG, " user " + allUserHandles[i] 12904 + " => " + perUserInstalled[i]); 12905 } 12906 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12907 } 12908 // Regardless of writeSettings we need to ensure that this restriction 12909 // state propagation is persisted 12910 mSettings.writeAllUsersPackageRestrictionsLPr(); 12911 } 12912 // can downgrade to reader here 12913 if (writeSettings) { 12914 mSettings.writeLPr(); 12915 } 12916 } 12917 return true; 12918 } 12919 12920 private boolean deleteInstalledPackageLI(PackageSetting ps, 12921 boolean deleteCodeAndResources, int flags, 12922 int[] allUserHandles, boolean[] perUserInstalled, 12923 PackageRemovedInfo outInfo, boolean writeSettings) { 12924 if (outInfo != null) { 12925 outInfo.uid = ps.appId; 12926 } 12927 12928 // Delete package data from internal structures and also remove data if flag is set 12929 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12930 12931 // Delete application code and resources 12932 if (deleteCodeAndResources && (outInfo != null)) { 12933 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12934 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12935 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12936 } 12937 return true; 12938 } 12939 12940 @Override 12941 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12942 int userId) { 12943 mContext.enforceCallingOrSelfPermission( 12944 android.Manifest.permission.DELETE_PACKAGES, null); 12945 synchronized (mPackages) { 12946 PackageSetting ps = mSettings.mPackages.get(packageName); 12947 if (ps == null) { 12948 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12949 return false; 12950 } 12951 if (!ps.getInstalled(userId)) { 12952 // Can't block uninstall for an app that is not installed or enabled. 12953 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12954 return false; 12955 } 12956 ps.setBlockUninstall(blockUninstall, userId); 12957 mSettings.writePackageRestrictionsLPr(userId); 12958 } 12959 return true; 12960 } 12961 12962 @Override 12963 public boolean getBlockUninstallForUser(String packageName, int userId) { 12964 synchronized (mPackages) { 12965 PackageSetting ps = mSettings.mPackages.get(packageName); 12966 if (ps == null) { 12967 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12968 return false; 12969 } 12970 return ps.getBlockUninstall(userId); 12971 } 12972 } 12973 12974 /* 12975 * This method handles package deletion in general 12976 */ 12977 private boolean deletePackageLI(String packageName, UserHandle user, 12978 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12979 int flags, PackageRemovedInfo outInfo, 12980 boolean writeSettings) { 12981 if (packageName == null) { 12982 Slog.w(TAG, "Attempt to delete null packageName."); 12983 return false; 12984 } 12985 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12986 PackageSetting ps; 12987 boolean dataOnly = false; 12988 int removeUser = -1; 12989 int appId = -1; 12990 synchronized (mPackages) { 12991 ps = mSettings.mPackages.get(packageName); 12992 if (ps == null) { 12993 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12994 return false; 12995 } 12996 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12997 && user.getIdentifier() != UserHandle.USER_ALL) { 12998 // The caller is asking that the package only be deleted for a single 12999 // user. To do this, we just mark its uninstalled state and delete 13000 // its data. If this is a system app, we only allow this to happen if 13001 // they have set the special DELETE_SYSTEM_APP which requests different 13002 // semantics than normal for uninstalling system apps. 13003 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13004 ps.setUserState(user.getIdentifier(), 13005 COMPONENT_ENABLED_STATE_DEFAULT, 13006 false, //installed 13007 true, //stopped 13008 true, //notLaunched 13009 false, //hidden 13010 null, null, null, 13011 false, // blockUninstall 13012 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0); 13013 if (!isSystemApp(ps)) { 13014 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13015 // Other user still have this package installed, so all 13016 // we need to do is clear this user's data and save that 13017 // it is uninstalled. 13018 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13019 removeUser = user.getIdentifier(); 13020 appId = ps.appId; 13021 scheduleWritePackageRestrictionsLocked(removeUser); 13022 } else { 13023 // We need to set it back to 'installed' so the uninstall 13024 // broadcasts will be sent correctly. 13025 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13026 ps.setInstalled(true, user.getIdentifier()); 13027 } 13028 } else { 13029 // This is a system app, so we assume that the 13030 // other users still have this package installed, so all 13031 // we need to do is clear this user's data and save that 13032 // it is uninstalled. 13033 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13034 removeUser = user.getIdentifier(); 13035 appId = ps.appId; 13036 scheduleWritePackageRestrictionsLocked(removeUser); 13037 } 13038 } 13039 } 13040 13041 if (removeUser >= 0) { 13042 // From above, we determined that we are deleting this only 13043 // for a single user. Continue the work here. 13044 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13045 if (outInfo != null) { 13046 outInfo.removedPackage = packageName; 13047 outInfo.removedAppId = appId; 13048 outInfo.removedUsers = new int[] {removeUser}; 13049 } 13050 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13051 removeKeystoreDataIfNeeded(removeUser, appId); 13052 schedulePackageCleaning(packageName, removeUser, false); 13053 synchronized (mPackages) { 13054 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13055 scheduleWritePackageRestrictionsLocked(removeUser); 13056 } 13057 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser); 13058 } 13059 return true; 13060 } 13061 13062 if (dataOnly) { 13063 // Delete application data first 13064 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13065 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13066 return true; 13067 } 13068 13069 boolean ret = false; 13070 if (isSystemApp(ps)) { 13071 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13072 // When an updated system application is deleted we delete the existing resources as well and 13073 // fall back to existing code in system partition 13074 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13075 flags, outInfo, writeSettings); 13076 } else { 13077 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13078 // Kill application pre-emptively especially for apps on sd. 13079 killApplication(packageName, ps.appId, "uninstall pkg"); 13080 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13081 allUserHandles, perUserInstalled, 13082 outInfo, writeSettings); 13083 } 13084 13085 return ret; 13086 } 13087 13088 private final class ClearStorageConnection implements ServiceConnection { 13089 IMediaContainerService mContainerService; 13090 13091 @Override 13092 public void onServiceConnected(ComponentName name, IBinder service) { 13093 synchronized (this) { 13094 mContainerService = IMediaContainerService.Stub.asInterface(service); 13095 notifyAll(); 13096 } 13097 } 13098 13099 @Override 13100 public void onServiceDisconnected(ComponentName name) { 13101 } 13102 } 13103 13104 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13105 final boolean mounted; 13106 if (Environment.isExternalStorageEmulated()) { 13107 mounted = true; 13108 } else { 13109 final String status = Environment.getExternalStorageState(); 13110 13111 mounted = status.equals(Environment.MEDIA_MOUNTED) 13112 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13113 } 13114 13115 if (!mounted) { 13116 return; 13117 } 13118 13119 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13120 int[] users; 13121 if (userId == UserHandle.USER_ALL) { 13122 users = sUserManager.getUserIds(); 13123 } else { 13124 users = new int[] { userId }; 13125 } 13126 final ClearStorageConnection conn = new ClearStorageConnection(); 13127 if (mContext.bindServiceAsUser( 13128 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13129 try { 13130 for (int curUser : users) { 13131 long timeout = SystemClock.uptimeMillis() + 5000; 13132 synchronized (conn) { 13133 long now = SystemClock.uptimeMillis(); 13134 while (conn.mContainerService == null && now < timeout) { 13135 try { 13136 conn.wait(timeout - now); 13137 } catch (InterruptedException e) { 13138 } 13139 } 13140 } 13141 if (conn.mContainerService == null) { 13142 return; 13143 } 13144 13145 final UserEnvironment userEnv = new UserEnvironment(curUser); 13146 clearDirectory(conn.mContainerService, 13147 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13148 if (allData) { 13149 clearDirectory(conn.mContainerService, 13150 userEnv.buildExternalStorageAppDataDirs(packageName)); 13151 clearDirectory(conn.mContainerService, 13152 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13153 } 13154 } 13155 } finally { 13156 mContext.unbindService(conn); 13157 } 13158 } 13159 } 13160 13161 @Override 13162 public void clearApplicationUserData(final String packageName, 13163 final IPackageDataObserver observer, final int userId) { 13164 mContext.enforceCallingOrSelfPermission( 13165 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13166 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13167 // Queue up an async operation since the package deletion may take a little while. 13168 mHandler.post(new Runnable() { 13169 public void run() { 13170 mHandler.removeCallbacks(this); 13171 final boolean succeeded; 13172 synchronized (mInstallLock) { 13173 succeeded = clearApplicationUserDataLI(packageName, userId); 13174 } 13175 clearExternalStorageDataSync(packageName, userId, true); 13176 if (succeeded) { 13177 // invoke DeviceStorageMonitor's update method to clear any notifications 13178 DeviceStorageMonitorInternal 13179 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13180 if (dsm != null) { 13181 dsm.checkMemory(); 13182 } 13183 } 13184 if(observer != null) { 13185 try { 13186 observer.onRemoveCompleted(packageName, succeeded); 13187 } catch (RemoteException e) { 13188 Log.i(TAG, "Observer no longer exists."); 13189 } 13190 } //end if observer 13191 } //end run 13192 }); 13193 } 13194 13195 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13196 if (packageName == null) { 13197 Slog.w(TAG, "Attempt to delete null packageName."); 13198 return false; 13199 } 13200 13201 // Try finding details about the requested package 13202 PackageParser.Package pkg; 13203 synchronized (mPackages) { 13204 pkg = mPackages.get(packageName); 13205 if (pkg == null) { 13206 final PackageSetting ps = mSettings.mPackages.get(packageName); 13207 if (ps != null) { 13208 pkg = ps.pkg; 13209 } 13210 } 13211 13212 if (pkg == null) { 13213 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13214 return false; 13215 } 13216 13217 PackageSetting ps = (PackageSetting) pkg.mExtras; 13218 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 13219 } 13220 13221 // Always delete data directories for package, even if we found no other 13222 // record of app. This helps users recover from UID mismatches without 13223 // resorting to a full data wipe. 13224 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13225 if (retCode < 0) { 13226 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13227 return false; 13228 } 13229 13230 final int appId = pkg.applicationInfo.uid; 13231 removeKeystoreDataIfNeeded(userId, appId); 13232 13233 // Create a native library symlink only if we have native libraries 13234 // and if the native libraries are 32 bit libraries. We do not provide 13235 // this symlink for 64 bit libraries. 13236 if (pkg.applicationInfo.primaryCpuAbi != null && 13237 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13238 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13239 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13240 nativeLibPath, userId) < 0) { 13241 Slog.w(TAG, "Failed linking native library dir"); 13242 return false; 13243 } 13244 } 13245 13246 return true; 13247 } 13248 13249 /** 13250 * Reverts user permission state changes (permissions and flags). 13251 * 13252 * @param ps The package for which to reset. 13253 * @param userId The device user for which to do a reset. 13254 */ 13255 private void resetUserChangesToRuntimePermissionsAndFlagsLocked( 13256 final PackageSetting ps, final int userId) { 13257 if (ps.pkg == null) { 13258 return; 13259 } 13260 13261 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13262 | FLAG_PERMISSION_USER_FIXED 13263 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13264 13265 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13266 | FLAG_PERMISSION_POLICY_FIXED; 13267 13268 boolean writeInstallPermissions = false; 13269 boolean writeRuntimePermissions = false; 13270 13271 final int permissionCount = ps.pkg.requestedPermissions.size(); 13272 for (int i = 0; i < permissionCount; i++) { 13273 String permission = ps.pkg.requestedPermissions.get(i); 13274 13275 BasePermission bp = mSettings.mPermissions.get(permission); 13276 if (bp == null) { 13277 continue; 13278 } 13279 13280 // If shared user we just reset the state to which only this app contributed. 13281 if (ps.sharedUser != null) { 13282 boolean used = false; 13283 final int packageCount = ps.sharedUser.packages.size(); 13284 for (int j = 0; j < packageCount; j++) { 13285 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13286 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13287 && pkg.pkg.requestedPermissions.contains(permission)) { 13288 used = true; 13289 break; 13290 } 13291 } 13292 if (used) { 13293 continue; 13294 } 13295 } 13296 13297 PermissionsState permissionsState = ps.getPermissionsState(); 13298 13299 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13300 13301 // Always clear the user settable flags. 13302 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13303 bp.name) != null; 13304 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13305 if (hasInstallState) { 13306 writeInstallPermissions = true; 13307 } else { 13308 writeRuntimePermissions = true; 13309 } 13310 } 13311 13312 // Below is only runtime permission handling. 13313 if (!bp.isRuntime()) { 13314 continue; 13315 } 13316 13317 // Never clobber system or policy. 13318 if ((oldFlags & policyOrSystemFlags) != 0) { 13319 continue; 13320 } 13321 13322 // If this permission was granted by default, make sure it is. 13323 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13324 if (permissionsState.grantRuntimePermission(bp, userId) 13325 != PERMISSION_OPERATION_FAILURE) { 13326 writeRuntimePermissions = true; 13327 } 13328 } else { 13329 // Otherwise, reset the permission. 13330 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13331 switch (revokeResult) { 13332 case PERMISSION_OPERATION_SUCCESS: { 13333 writeRuntimePermissions = true; 13334 } break; 13335 13336 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13337 writeRuntimePermissions = true; 13338 // If gids changed for this user, kill all affected packages. 13339 mHandler.post(new Runnable() { 13340 @Override 13341 public void run() { 13342 // This has to happen with no lock held. 13343 killSettingPackagesForUser(ps, userId, 13344 KILL_APP_REASON_GIDS_CHANGED); 13345 } 13346 }); 13347 } break; 13348 } 13349 } 13350 } 13351 13352 // Synchronously write as we are taking permissions away. 13353 if (writeRuntimePermissions) { 13354 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13355 } 13356 13357 // Synchronously write as we are taking permissions away. 13358 if (writeInstallPermissions) { 13359 mSettings.writeLPr(); 13360 } 13361 } 13362 13363 /** 13364 * Remove entries from the keystore daemon. Will only remove it if the 13365 * {@code appId} is valid. 13366 */ 13367 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13368 if (appId < 0) { 13369 return; 13370 } 13371 13372 final KeyStore keyStore = KeyStore.getInstance(); 13373 if (keyStore != null) { 13374 if (userId == UserHandle.USER_ALL) { 13375 for (final int individual : sUserManager.getUserIds()) { 13376 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13377 } 13378 } else { 13379 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13380 } 13381 } else { 13382 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13383 } 13384 } 13385 13386 @Override 13387 public void deleteApplicationCacheFiles(final String packageName, 13388 final IPackageDataObserver observer) { 13389 mContext.enforceCallingOrSelfPermission( 13390 android.Manifest.permission.DELETE_CACHE_FILES, null); 13391 // Queue up an async operation since the package deletion may take a little while. 13392 final int userId = UserHandle.getCallingUserId(); 13393 mHandler.post(new Runnable() { 13394 public void run() { 13395 mHandler.removeCallbacks(this); 13396 final boolean succeded; 13397 synchronized (mInstallLock) { 13398 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13399 } 13400 clearExternalStorageDataSync(packageName, userId, false); 13401 if (observer != null) { 13402 try { 13403 observer.onRemoveCompleted(packageName, succeded); 13404 } catch (RemoteException e) { 13405 Log.i(TAG, "Observer no longer exists."); 13406 } 13407 } //end if observer 13408 } //end run 13409 }); 13410 } 13411 13412 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13413 if (packageName == null) { 13414 Slog.w(TAG, "Attempt to delete null packageName."); 13415 return false; 13416 } 13417 PackageParser.Package p; 13418 synchronized (mPackages) { 13419 p = mPackages.get(packageName); 13420 } 13421 if (p == null) { 13422 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13423 return false; 13424 } 13425 final ApplicationInfo applicationInfo = p.applicationInfo; 13426 if (applicationInfo == null) { 13427 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13428 return false; 13429 } 13430 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13431 if (retCode < 0) { 13432 Slog.w(TAG, "Couldn't remove cache files for package: " 13433 + packageName + " u" + userId); 13434 return false; 13435 } 13436 return true; 13437 } 13438 13439 @Override 13440 public void getPackageSizeInfo(final String packageName, int userHandle, 13441 final IPackageStatsObserver observer) { 13442 mContext.enforceCallingOrSelfPermission( 13443 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13444 if (packageName == null) { 13445 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13446 } 13447 13448 PackageStats stats = new PackageStats(packageName, userHandle); 13449 13450 /* 13451 * Queue up an async operation since the package measurement may take a 13452 * little while. 13453 */ 13454 Message msg = mHandler.obtainMessage(INIT_COPY); 13455 msg.obj = new MeasureParams(stats, observer); 13456 mHandler.sendMessage(msg); 13457 } 13458 13459 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13460 PackageStats pStats) { 13461 if (packageName == null) { 13462 Slog.w(TAG, "Attempt to get size of null packageName."); 13463 return false; 13464 } 13465 PackageParser.Package p; 13466 boolean dataOnly = false; 13467 String libDirRoot = null; 13468 String asecPath = null; 13469 PackageSetting ps = null; 13470 synchronized (mPackages) { 13471 p = mPackages.get(packageName); 13472 ps = mSettings.mPackages.get(packageName); 13473 if(p == null) { 13474 dataOnly = true; 13475 if((ps == null) || (ps.pkg == null)) { 13476 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13477 return false; 13478 } 13479 p = ps.pkg; 13480 } 13481 if (ps != null) { 13482 libDirRoot = ps.legacyNativeLibraryPathString; 13483 } 13484 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13485 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13486 if (secureContainerId != null) { 13487 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13488 } 13489 } 13490 } 13491 String publicSrcDir = null; 13492 if(!dataOnly) { 13493 final ApplicationInfo applicationInfo = p.applicationInfo; 13494 if (applicationInfo == null) { 13495 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13496 return false; 13497 } 13498 if (p.isForwardLocked()) { 13499 publicSrcDir = applicationInfo.getBaseResourcePath(); 13500 } 13501 } 13502 // TODO: extend to measure size of split APKs 13503 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13504 // not just the first level. 13505 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13506 // just the primary. 13507 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13508 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13509 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13510 if (res < 0) { 13511 return false; 13512 } 13513 13514 // Fix-up for forward-locked applications in ASEC containers. 13515 if (!isExternal(p)) { 13516 pStats.codeSize += pStats.externalCodeSize; 13517 pStats.externalCodeSize = 0L; 13518 } 13519 13520 return true; 13521 } 13522 13523 13524 @Override 13525 public void addPackageToPreferred(String packageName) { 13526 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13527 } 13528 13529 @Override 13530 public void removePackageFromPreferred(String packageName) { 13531 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13532 } 13533 13534 @Override 13535 public List<PackageInfo> getPreferredPackages(int flags) { 13536 return new ArrayList<PackageInfo>(); 13537 } 13538 13539 private int getUidTargetSdkVersionLockedLPr(int uid) { 13540 Object obj = mSettings.getUserIdLPr(uid); 13541 if (obj instanceof SharedUserSetting) { 13542 final SharedUserSetting sus = (SharedUserSetting) obj; 13543 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13544 final Iterator<PackageSetting> it = sus.packages.iterator(); 13545 while (it.hasNext()) { 13546 final PackageSetting ps = it.next(); 13547 if (ps.pkg != null) { 13548 int v = ps.pkg.applicationInfo.targetSdkVersion; 13549 if (v < vers) vers = v; 13550 } 13551 } 13552 return vers; 13553 } else if (obj instanceof PackageSetting) { 13554 final PackageSetting ps = (PackageSetting) obj; 13555 if (ps.pkg != null) { 13556 return ps.pkg.applicationInfo.targetSdkVersion; 13557 } 13558 } 13559 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13560 } 13561 13562 @Override 13563 public void addPreferredActivity(IntentFilter filter, int match, 13564 ComponentName[] set, ComponentName activity, int userId) { 13565 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13566 "Adding preferred"); 13567 } 13568 13569 private void addPreferredActivityInternal(IntentFilter filter, int match, 13570 ComponentName[] set, ComponentName activity, boolean always, int userId, 13571 String opname) { 13572 // writer 13573 int callingUid = Binder.getCallingUid(); 13574 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13575 if (filter.countActions() == 0) { 13576 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13577 return; 13578 } 13579 synchronized (mPackages) { 13580 if (mContext.checkCallingOrSelfPermission( 13581 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13582 != PackageManager.PERMISSION_GRANTED) { 13583 if (getUidTargetSdkVersionLockedLPr(callingUid) 13584 < Build.VERSION_CODES.FROYO) { 13585 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13586 + callingUid); 13587 return; 13588 } 13589 mContext.enforceCallingOrSelfPermission( 13590 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13591 } 13592 13593 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13594 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13595 + userId + ":"); 13596 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13597 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13598 scheduleWritePackageRestrictionsLocked(userId); 13599 } 13600 } 13601 13602 @Override 13603 public void replacePreferredActivity(IntentFilter filter, int match, 13604 ComponentName[] set, ComponentName activity, int userId) { 13605 if (filter.countActions() != 1) { 13606 throw new IllegalArgumentException( 13607 "replacePreferredActivity expects filter to have only 1 action."); 13608 } 13609 if (filter.countDataAuthorities() != 0 13610 || filter.countDataPaths() != 0 13611 || filter.countDataSchemes() > 1 13612 || filter.countDataTypes() != 0) { 13613 throw new IllegalArgumentException( 13614 "replacePreferredActivity expects filter to have no data authorities, " + 13615 "paths, or types; and at most one scheme."); 13616 } 13617 13618 final int callingUid = Binder.getCallingUid(); 13619 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13620 synchronized (mPackages) { 13621 if (mContext.checkCallingOrSelfPermission( 13622 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13623 != PackageManager.PERMISSION_GRANTED) { 13624 if (getUidTargetSdkVersionLockedLPr(callingUid) 13625 < Build.VERSION_CODES.FROYO) { 13626 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13627 + Binder.getCallingUid()); 13628 return; 13629 } 13630 mContext.enforceCallingOrSelfPermission( 13631 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13632 } 13633 13634 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13635 if (pir != null) { 13636 // Get all of the existing entries that exactly match this filter. 13637 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13638 if (existing != null && existing.size() == 1) { 13639 PreferredActivity cur = existing.get(0); 13640 if (DEBUG_PREFERRED) { 13641 Slog.i(TAG, "Checking replace of preferred:"); 13642 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13643 if (!cur.mPref.mAlways) { 13644 Slog.i(TAG, " -- CUR; not mAlways!"); 13645 } else { 13646 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13647 Slog.i(TAG, " -- CUR: mSet=" 13648 + Arrays.toString(cur.mPref.mSetComponents)); 13649 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13650 Slog.i(TAG, " -- NEW: mMatch=" 13651 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13652 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13653 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13654 } 13655 } 13656 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13657 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13658 && cur.mPref.sameSet(set)) { 13659 // Setting the preferred activity to what it happens to be already 13660 if (DEBUG_PREFERRED) { 13661 Slog.i(TAG, "Replacing with same preferred activity " 13662 + cur.mPref.mShortComponent + " for user " 13663 + userId + ":"); 13664 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13665 } 13666 return; 13667 } 13668 } 13669 13670 if (existing != null) { 13671 if (DEBUG_PREFERRED) { 13672 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13673 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13674 } 13675 for (int i = 0; i < existing.size(); i++) { 13676 PreferredActivity pa = existing.get(i); 13677 if (DEBUG_PREFERRED) { 13678 Slog.i(TAG, "Removing existing preferred activity " 13679 + pa.mPref.mComponent + ":"); 13680 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13681 } 13682 pir.removeFilter(pa); 13683 } 13684 } 13685 } 13686 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13687 "Replacing preferred"); 13688 } 13689 } 13690 13691 @Override 13692 public void clearPackagePreferredActivities(String packageName) { 13693 final int uid = Binder.getCallingUid(); 13694 // writer 13695 synchronized (mPackages) { 13696 PackageParser.Package pkg = mPackages.get(packageName); 13697 if (pkg == null || pkg.applicationInfo.uid != uid) { 13698 if (mContext.checkCallingOrSelfPermission( 13699 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13700 != PackageManager.PERMISSION_GRANTED) { 13701 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13702 < Build.VERSION_CODES.FROYO) { 13703 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13704 + Binder.getCallingUid()); 13705 return; 13706 } 13707 mContext.enforceCallingOrSelfPermission( 13708 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13709 } 13710 } 13711 13712 int user = UserHandle.getCallingUserId(); 13713 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13714 scheduleWritePackageRestrictionsLocked(user); 13715 } 13716 } 13717 } 13718 13719 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13720 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13721 ArrayList<PreferredActivity> removed = null; 13722 boolean changed = false; 13723 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13724 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13725 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13726 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13727 continue; 13728 } 13729 Iterator<PreferredActivity> it = pir.filterIterator(); 13730 while (it.hasNext()) { 13731 PreferredActivity pa = it.next(); 13732 // Mark entry for removal only if it matches the package name 13733 // and the entry is of type "always". 13734 if (packageName == null || 13735 (pa.mPref.mComponent.getPackageName().equals(packageName) 13736 && pa.mPref.mAlways)) { 13737 if (removed == null) { 13738 removed = new ArrayList<PreferredActivity>(); 13739 } 13740 removed.add(pa); 13741 } 13742 } 13743 if (removed != null) { 13744 for (int j=0; j<removed.size(); j++) { 13745 PreferredActivity pa = removed.get(j); 13746 pir.removeFilter(pa); 13747 } 13748 changed = true; 13749 } 13750 } 13751 return changed; 13752 } 13753 13754 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13755 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13756 if (userId == UserHandle.USER_ALL) { 13757 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13758 sUserManager.getUserIds())) { 13759 for (int oneUserId : sUserManager.getUserIds()) { 13760 scheduleWritePackageRestrictionsLocked(oneUserId); 13761 } 13762 } 13763 } else { 13764 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13765 scheduleWritePackageRestrictionsLocked(userId); 13766 } 13767 } 13768 } 13769 13770 13771 void clearDefaultBrowserIfNeeded(String packageName) { 13772 for (int oneUserId : sUserManager.getUserIds()) { 13773 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13774 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13775 if (packageName.equals(defaultBrowserPackageName)) { 13776 setDefaultBrowserPackageName(null, oneUserId); 13777 } 13778 } 13779 } 13780 13781 @Override 13782 public void resetPreferredActivities(int userId) { 13783 mContext.enforceCallingOrSelfPermission( 13784 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13785 // writer 13786 synchronized (mPackages) { 13787 clearPackagePreferredActivitiesLPw(null, userId); 13788 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13789 applyFactoryDefaultBrowserLPw(userId); 13790 primeDomainVerificationsLPw(userId); 13791 13792 scheduleWritePackageRestrictionsLocked(userId); 13793 } 13794 } 13795 13796 @Override 13797 public int getPreferredActivities(List<IntentFilter> outFilters, 13798 List<ComponentName> outActivities, String packageName) { 13799 13800 int num = 0; 13801 final int userId = UserHandle.getCallingUserId(); 13802 // reader 13803 synchronized (mPackages) { 13804 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13805 if (pir != null) { 13806 final Iterator<PreferredActivity> it = pir.filterIterator(); 13807 while (it.hasNext()) { 13808 final PreferredActivity pa = it.next(); 13809 if (packageName == null 13810 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13811 && pa.mPref.mAlways)) { 13812 if (outFilters != null) { 13813 outFilters.add(new IntentFilter(pa)); 13814 } 13815 if (outActivities != null) { 13816 outActivities.add(pa.mPref.mComponent); 13817 } 13818 } 13819 } 13820 } 13821 } 13822 13823 return num; 13824 } 13825 13826 @Override 13827 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13828 int userId) { 13829 int callingUid = Binder.getCallingUid(); 13830 if (callingUid != Process.SYSTEM_UID) { 13831 throw new SecurityException( 13832 "addPersistentPreferredActivity can only be run by the system"); 13833 } 13834 if (filter.countActions() == 0) { 13835 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13836 return; 13837 } 13838 synchronized (mPackages) { 13839 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13840 " :"); 13841 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13842 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13843 new PersistentPreferredActivity(filter, activity)); 13844 scheduleWritePackageRestrictionsLocked(userId); 13845 } 13846 } 13847 13848 @Override 13849 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13850 int callingUid = Binder.getCallingUid(); 13851 if (callingUid != Process.SYSTEM_UID) { 13852 throw new SecurityException( 13853 "clearPackagePersistentPreferredActivities can only be run by the system"); 13854 } 13855 ArrayList<PersistentPreferredActivity> removed = null; 13856 boolean changed = false; 13857 synchronized (mPackages) { 13858 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13859 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13860 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13861 .valueAt(i); 13862 if (userId != thisUserId) { 13863 continue; 13864 } 13865 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13866 while (it.hasNext()) { 13867 PersistentPreferredActivity ppa = it.next(); 13868 // Mark entry for removal only if it matches the package name. 13869 if (ppa.mComponent.getPackageName().equals(packageName)) { 13870 if (removed == null) { 13871 removed = new ArrayList<PersistentPreferredActivity>(); 13872 } 13873 removed.add(ppa); 13874 } 13875 } 13876 if (removed != null) { 13877 for (int j=0; j<removed.size(); j++) { 13878 PersistentPreferredActivity ppa = removed.get(j); 13879 ppir.removeFilter(ppa); 13880 } 13881 changed = true; 13882 } 13883 } 13884 13885 if (changed) { 13886 scheduleWritePackageRestrictionsLocked(userId); 13887 } 13888 } 13889 } 13890 13891 /** 13892 * Common machinery for picking apart a restored XML blob and passing 13893 * it to a caller-supplied functor to be applied to the running system. 13894 */ 13895 private void restoreFromXml(XmlPullParser parser, int userId, 13896 String expectedStartTag, BlobXmlRestorer functor) 13897 throws IOException, XmlPullParserException { 13898 int type; 13899 while ((type = parser.next()) != XmlPullParser.START_TAG 13900 && type != XmlPullParser.END_DOCUMENT) { 13901 } 13902 if (type != XmlPullParser.START_TAG) { 13903 // oops didn't find a start tag?! 13904 if (DEBUG_BACKUP) { 13905 Slog.e(TAG, "Didn't find start tag during restore"); 13906 } 13907 return; 13908 } 13909 13910 // this is supposed to be TAG_PREFERRED_BACKUP 13911 if (!expectedStartTag.equals(parser.getName())) { 13912 if (DEBUG_BACKUP) { 13913 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13914 } 13915 return; 13916 } 13917 13918 // skip interfering stuff, then we're aligned with the backing implementation 13919 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13920 functor.apply(parser, userId); 13921 } 13922 13923 private interface BlobXmlRestorer { 13924 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13925 } 13926 13927 /** 13928 * Non-Binder method, support for the backup/restore mechanism: write the 13929 * full set of preferred activities in its canonical XML format. Returns the 13930 * XML output as a byte array, or null if there is none. 13931 */ 13932 @Override 13933 public byte[] getPreferredActivityBackup(int userId) { 13934 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13935 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13936 } 13937 13938 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13939 try { 13940 final XmlSerializer serializer = new FastXmlSerializer(); 13941 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13942 serializer.startDocument(null, true); 13943 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13944 13945 synchronized (mPackages) { 13946 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13947 } 13948 13949 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13950 serializer.endDocument(); 13951 serializer.flush(); 13952 } catch (Exception e) { 13953 if (DEBUG_BACKUP) { 13954 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13955 } 13956 return null; 13957 } 13958 13959 return dataStream.toByteArray(); 13960 } 13961 13962 @Override 13963 public void restorePreferredActivities(byte[] backup, int userId) { 13964 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13965 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13966 } 13967 13968 try { 13969 final XmlPullParser parser = Xml.newPullParser(); 13970 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13971 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13972 new BlobXmlRestorer() { 13973 @Override 13974 public void apply(XmlPullParser parser, int userId) 13975 throws XmlPullParserException, IOException { 13976 synchronized (mPackages) { 13977 mSettings.readPreferredActivitiesLPw(parser, userId); 13978 } 13979 } 13980 } ); 13981 } catch (Exception e) { 13982 if (DEBUG_BACKUP) { 13983 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13984 } 13985 } 13986 } 13987 13988 /** 13989 * Non-Binder method, support for the backup/restore mechanism: write the 13990 * default browser (etc) settings in its canonical XML format. Returns the default 13991 * browser XML representation as a byte array, or null if there is none. 13992 */ 13993 @Override 13994 public byte[] getDefaultAppsBackup(int userId) { 13995 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13996 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13997 } 13998 13999 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14000 try { 14001 final XmlSerializer serializer = new FastXmlSerializer(); 14002 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14003 serializer.startDocument(null, true); 14004 serializer.startTag(null, TAG_DEFAULT_APPS); 14005 14006 synchronized (mPackages) { 14007 mSettings.writeDefaultAppsLPr(serializer, userId); 14008 } 14009 14010 serializer.endTag(null, TAG_DEFAULT_APPS); 14011 serializer.endDocument(); 14012 serializer.flush(); 14013 } catch (Exception e) { 14014 if (DEBUG_BACKUP) { 14015 Slog.e(TAG, "Unable to write default apps for backup", e); 14016 } 14017 return null; 14018 } 14019 14020 return dataStream.toByteArray(); 14021 } 14022 14023 @Override 14024 public void restoreDefaultApps(byte[] backup, int userId) { 14025 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14026 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14027 } 14028 14029 try { 14030 final XmlPullParser parser = Xml.newPullParser(); 14031 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14032 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14033 new BlobXmlRestorer() { 14034 @Override 14035 public void apply(XmlPullParser parser, int userId) 14036 throws XmlPullParserException, IOException { 14037 synchronized (mPackages) { 14038 mSettings.readDefaultAppsLPw(parser, userId); 14039 } 14040 } 14041 } ); 14042 } catch (Exception e) { 14043 if (DEBUG_BACKUP) { 14044 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14045 } 14046 } 14047 } 14048 14049 @Override 14050 public byte[] getIntentFilterVerificationBackup(int userId) { 14051 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14052 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14053 } 14054 14055 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14056 try { 14057 final XmlSerializer serializer = new FastXmlSerializer(); 14058 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14059 serializer.startDocument(null, true); 14060 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14061 14062 synchronized (mPackages) { 14063 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14064 } 14065 14066 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14067 serializer.endDocument(); 14068 serializer.flush(); 14069 } catch (Exception e) { 14070 if (DEBUG_BACKUP) { 14071 Slog.e(TAG, "Unable to write default apps for backup", e); 14072 } 14073 return null; 14074 } 14075 14076 return dataStream.toByteArray(); 14077 } 14078 14079 @Override 14080 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14081 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14082 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14083 } 14084 14085 try { 14086 final XmlPullParser parser = Xml.newPullParser(); 14087 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14088 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14089 new BlobXmlRestorer() { 14090 @Override 14091 public void apply(XmlPullParser parser, int userId) 14092 throws XmlPullParserException, IOException { 14093 synchronized (mPackages) { 14094 mSettings.readAllDomainVerificationsLPr(parser, userId); 14095 mSettings.writeLPr(); 14096 } 14097 } 14098 } ); 14099 } catch (Exception e) { 14100 if (DEBUG_BACKUP) { 14101 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14102 } 14103 } 14104 } 14105 14106 @Override 14107 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14108 int sourceUserId, int targetUserId, int flags) { 14109 mContext.enforceCallingOrSelfPermission( 14110 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14111 int callingUid = Binder.getCallingUid(); 14112 enforceOwnerRights(ownerPackage, callingUid); 14113 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14114 if (intentFilter.countActions() == 0) { 14115 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14116 return; 14117 } 14118 synchronized (mPackages) { 14119 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14120 ownerPackage, targetUserId, flags); 14121 CrossProfileIntentResolver resolver = 14122 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14123 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14124 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14125 if (existing != null) { 14126 int size = existing.size(); 14127 for (int i = 0; i < size; i++) { 14128 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14129 return; 14130 } 14131 } 14132 } 14133 resolver.addFilter(newFilter); 14134 scheduleWritePackageRestrictionsLocked(sourceUserId); 14135 } 14136 } 14137 14138 @Override 14139 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14140 mContext.enforceCallingOrSelfPermission( 14141 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14142 int callingUid = Binder.getCallingUid(); 14143 enforceOwnerRights(ownerPackage, callingUid); 14144 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14145 synchronized (mPackages) { 14146 CrossProfileIntentResolver resolver = 14147 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14148 ArraySet<CrossProfileIntentFilter> set = 14149 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14150 for (CrossProfileIntentFilter filter : set) { 14151 if (filter.getOwnerPackage().equals(ownerPackage)) { 14152 resolver.removeFilter(filter); 14153 } 14154 } 14155 scheduleWritePackageRestrictionsLocked(sourceUserId); 14156 } 14157 } 14158 14159 // Enforcing that callingUid is owning pkg on userId 14160 private void enforceOwnerRights(String pkg, int callingUid) { 14161 // The system owns everything. 14162 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14163 return; 14164 } 14165 int callingUserId = UserHandle.getUserId(callingUid); 14166 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14167 if (pi == null) { 14168 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14169 + callingUserId); 14170 } 14171 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14172 throw new SecurityException("Calling uid " + callingUid 14173 + " does not own package " + pkg); 14174 } 14175 } 14176 14177 @Override 14178 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14179 Intent intent = new Intent(Intent.ACTION_MAIN); 14180 intent.addCategory(Intent.CATEGORY_HOME); 14181 14182 final int callingUserId = UserHandle.getCallingUserId(); 14183 List<ResolveInfo> list = queryIntentActivities(intent, null, 14184 PackageManager.GET_META_DATA, callingUserId); 14185 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14186 true, false, false, callingUserId); 14187 14188 allHomeCandidates.clear(); 14189 if (list != null) { 14190 for (ResolveInfo ri : list) { 14191 allHomeCandidates.add(ri); 14192 } 14193 } 14194 return (preferred == null || preferred.activityInfo == null) 14195 ? null 14196 : new ComponentName(preferred.activityInfo.packageName, 14197 preferred.activityInfo.name); 14198 } 14199 14200 @Override 14201 public void setApplicationEnabledSetting(String appPackageName, 14202 int newState, int flags, int userId, String callingPackage) { 14203 if (!sUserManager.exists(userId)) return; 14204 if (callingPackage == null) { 14205 callingPackage = Integer.toString(Binder.getCallingUid()); 14206 } 14207 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14208 } 14209 14210 @Override 14211 public void setComponentEnabledSetting(ComponentName componentName, 14212 int newState, int flags, int userId) { 14213 if (!sUserManager.exists(userId)) return; 14214 setEnabledSetting(componentName.getPackageName(), 14215 componentName.getClassName(), newState, flags, userId, null); 14216 } 14217 14218 private void setEnabledSetting(final String packageName, String className, int newState, 14219 final int flags, int userId, String callingPackage) { 14220 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14221 || newState == COMPONENT_ENABLED_STATE_ENABLED 14222 || newState == COMPONENT_ENABLED_STATE_DISABLED 14223 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14224 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14225 throw new IllegalArgumentException("Invalid new component state: " 14226 + newState); 14227 } 14228 PackageSetting pkgSetting; 14229 final int uid = Binder.getCallingUid(); 14230 final int permission = mContext.checkCallingOrSelfPermission( 14231 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14232 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14233 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14234 boolean sendNow = false; 14235 boolean isApp = (className == null); 14236 String componentName = isApp ? packageName : className; 14237 int packageUid = -1; 14238 ArrayList<String> components; 14239 14240 // writer 14241 synchronized (mPackages) { 14242 pkgSetting = mSettings.mPackages.get(packageName); 14243 if (pkgSetting == null) { 14244 if (className == null) { 14245 throw new IllegalArgumentException( 14246 "Unknown package: " + packageName); 14247 } 14248 throw new IllegalArgumentException( 14249 "Unknown component: " + packageName 14250 + "/" + className); 14251 } 14252 // Allow root and verify that userId is not being specified by a different user 14253 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14254 throw new SecurityException( 14255 "Permission Denial: attempt to change component state from pid=" 14256 + Binder.getCallingPid() 14257 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14258 } 14259 if (className == null) { 14260 // We're dealing with an application/package level state change 14261 if (pkgSetting.getEnabled(userId) == newState) { 14262 // Nothing to do 14263 return; 14264 } 14265 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14266 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14267 // Don't care about who enables an app. 14268 callingPackage = null; 14269 } 14270 pkgSetting.setEnabled(newState, userId, callingPackage); 14271 // pkgSetting.pkg.mSetEnabled = newState; 14272 } else { 14273 // We're dealing with a component level state change 14274 // First, verify that this is a valid class name. 14275 PackageParser.Package pkg = pkgSetting.pkg; 14276 if (pkg == null || !pkg.hasComponentClassName(className)) { 14277 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14278 throw new IllegalArgumentException("Component class " + className 14279 + " does not exist in " + packageName); 14280 } else { 14281 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14282 + className + " does not exist in " + packageName); 14283 } 14284 } 14285 switch (newState) { 14286 case COMPONENT_ENABLED_STATE_ENABLED: 14287 if (!pkgSetting.enableComponentLPw(className, userId)) { 14288 return; 14289 } 14290 break; 14291 case COMPONENT_ENABLED_STATE_DISABLED: 14292 if (!pkgSetting.disableComponentLPw(className, userId)) { 14293 return; 14294 } 14295 break; 14296 case COMPONENT_ENABLED_STATE_DEFAULT: 14297 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14298 return; 14299 } 14300 break; 14301 default: 14302 Slog.e(TAG, "Invalid new component state: " + newState); 14303 return; 14304 } 14305 } 14306 scheduleWritePackageRestrictionsLocked(userId); 14307 components = mPendingBroadcasts.get(userId, packageName); 14308 final boolean newPackage = components == null; 14309 if (newPackage) { 14310 components = new ArrayList<String>(); 14311 } 14312 if (!components.contains(componentName)) { 14313 components.add(componentName); 14314 } 14315 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14316 sendNow = true; 14317 // Purge entry from pending broadcast list if another one exists already 14318 // since we are sending one right away. 14319 mPendingBroadcasts.remove(userId, packageName); 14320 } else { 14321 if (newPackage) { 14322 mPendingBroadcasts.put(userId, packageName, components); 14323 } 14324 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14325 // Schedule a message 14326 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14327 } 14328 } 14329 } 14330 14331 long callingId = Binder.clearCallingIdentity(); 14332 try { 14333 if (sendNow) { 14334 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14335 sendPackageChangedBroadcast(packageName, 14336 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14337 } 14338 } finally { 14339 Binder.restoreCallingIdentity(callingId); 14340 } 14341 } 14342 14343 private void sendPackageChangedBroadcast(String packageName, 14344 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14345 if (DEBUG_INSTALL) 14346 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14347 + componentNames); 14348 Bundle extras = new Bundle(4); 14349 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14350 String nameList[] = new String[componentNames.size()]; 14351 componentNames.toArray(nameList); 14352 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14353 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14354 extras.putInt(Intent.EXTRA_UID, packageUid); 14355 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14356 new int[] {UserHandle.getUserId(packageUid)}); 14357 } 14358 14359 @Override 14360 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14361 if (!sUserManager.exists(userId)) return; 14362 final int uid = Binder.getCallingUid(); 14363 final int permission = mContext.checkCallingOrSelfPermission( 14364 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14365 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14366 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14367 // writer 14368 synchronized (mPackages) { 14369 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14370 allowedByPermission, uid, userId)) { 14371 scheduleWritePackageRestrictionsLocked(userId); 14372 } 14373 } 14374 } 14375 14376 @Override 14377 public String getInstallerPackageName(String packageName) { 14378 // reader 14379 synchronized (mPackages) { 14380 return mSettings.getInstallerPackageNameLPr(packageName); 14381 } 14382 } 14383 14384 @Override 14385 public int getApplicationEnabledSetting(String packageName, int userId) { 14386 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14387 int uid = Binder.getCallingUid(); 14388 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14389 // reader 14390 synchronized (mPackages) { 14391 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14392 } 14393 } 14394 14395 @Override 14396 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14397 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14398 int uid = Binder.getCallingUid(); 14399 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14400 // reader 14401 synchronized (mPackages) { 14402 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14403 } 14404 } 14405 14406 @Override 14407 public void enterSafeMode() { 14408 enforceSystemOrRoot("Only the system can request entering safe mode"); 14409 14410 if (!mSystemReady) { 14411 mSafeMode = true; 14412 } 14413 } 14414 14415 @Override 14416 public void systemReady() { 14417 mSystemReady = true; 14418 14419 // Read the compatibilty setting when the system is ready. 14420 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14421 mContext.getContentResolver(), 14422 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14423 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14424 if (DEBUG_SETTINGS) { 14425 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14426 } 14427 14428 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14429 14430 synchronized (mPackages) { 14431 // Verify that all of the preferred activity components actually 14432 // exist. It is possible for applications to be updated and at 14433 // that point remove a previously declared activity component that 14434 // had been set as a preferred activity. We try to clean this up 14435 // the next time we encounter that preferred activity, but it is 14436 // possible for the user flow to never be able to return to that 14437 // situation so here we do a sanity check to make sure we haven't 14438 // left any junk around. 14439 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14440 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14441 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14442 removed.clear(); 14443 for (PreferredActivity pa : pir.filterSet()) { 14444 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14445 removed.add(pa); 14446 } 14447 } 14448 if (removed.size() > 0) { 14449 for (int r=0; r<removed.size(); r++) { 14450 PreferredActivity pa = removed.get(r); 14451 Slog.w(TAG, "Removing dangling preferred activity: " 14452 + pa.mPref.mComponent); 14453 pir.removeFilter(pa); 14454 } 14455 mSettings.writePackageRestrictionsLPr( 14456 mSettings.mPreferredActivities.keyAt(i)); 14457 } 14458 } 14459 14460 for (int userId : UserManagerService.getInstance().getUserIds()) { 14461 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14462 grantPermissionsUserIds = ArrayUtils.appendInt( 14463 grantPermissionsUserIds, userId); 14464 } 14465 } 14466 } 14467 sUserManager.systemReady(); 14468 14469 // If we upgraded grant all default permissions before kicking off. 14470 for (int userId : grantPermissionsUserIds) { 14471 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14472 } 14473 14474 // Kick off any messages waiting for system ready 14475 if (mPostSystemReadyMessages != null) { 14476 for (Message msg : mPostSystemReadyMessages) { 14477 msg.sendToTarget(); 14478 } 14479 mPostSystemReadyMessages = null; 14480 } 14481 14482 // Watch for external volumes that come and go over time 14483 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14484 storage.registerListener(mStorageListener); 14485 14486 mInstallerService.systemReady(); 14487 mPackageDexOptimizer.systemReady(); 14488 14489 MountServiceInternal mountServiceInternal = LocalServices.getService( 14490 MountServiceInternal.class); 14491 mountServiceInternal.addExternalStoragePolicy( 14492 new MountServiceInternal.ExternalStorageMountPolicy() { 14493 @Override 14494 public int getMountMode(int uid, String packageName) { 14495 if (Process.isIsolated(uid)) { 14496 return Zygote.MOUNT_EXTERNAL_NONE; 14497 } 14498 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14499 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14500 } 14501 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14502 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14503 } 14504 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14505 return Zygote.MOUNT_EXTERNAL_READ; 14506 } 14507 return Zygote.MOUNT_EXTERNAL_WRITE; 14508 } 14509 14510 @Override 14511 public boolean hasExternalStorage(int uid, String packageName) { 14512 return true; 14513 } 14514 }); 14515 } 14516 14517 @Override 14518 public boolean isSafeMode() { 14519 return mSafeMode; 14520 } 14521 14522 @Override 14523 public boolean hasSystemUidErrors() { 14524 return mHasSystemUidErrors; 14525 } 14526 14527 static String arrayToString(int[] array) { 14528 StringBuffer buf = new StringBuffer(128); 14529 buf.append('['); 14530 if (array != null) { 14531 for (int i=0; i<array.length; i++) { 14532 if (i > 0) buf.append(", "); 14533 buf.append(array[i]); 14534 } 14535 } 14536 buf.append(']'); 14537 return buf.toString(); 14538 } 14539 14540 static class DumpState { 14541 public static final int DUMP_LIBS = 1 << 0; 14542 public static final int DUMP_FEATURES = 1 << 1; 14543 public static final int DUMP_RESOLVERS = 1 << 2; 14544 public static final int DUMP_PERMISSIONS = 1 << 3; 14545 public static final int DUMP_PACKAGES = 1 << 4; 14546 public static final int DUMP_SHARED_USERS = 1 << 5; 14547 public static final int DUMP_MESSAGES = 1 << 6; 14548 public static final int DUMP_PROVIDERS = 1 << 7; 14549 public static final int DUMP_VERIFIERS = 1 << 8; 14550 public static final int DUMP_PREFERRED = 1 << 9; 14551 public static final int DUMP_PREFERRED_XML = 1 << 10; 14552 public static final int DUMP_KEYSETS = 1 << 11; 14553 public static final int DUMP_VERSION = 1 << 12; 14554 public static final int DUMP_INSTALLS = 1 << 13; 14555 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14556 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14557 14558 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14559 14560 private int mTypes; 14561 14562 private int mOptions; 14563 14564 private boolean mTitlePrinted; 14565 14566 private SharedUserSetting mSharedUser; 14567 14568 public boolean isDumping(int type) { 14569 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14570 return true; 14571 } 14572 14573 return (mTypes & type) != 0; 14574 } 14575 14576 public void setDump(int type) { 14577 mTypes |= type; 14578 } 14579 14580 public boolean isOptionEnabled(int option) { 14581 return (mOptions & option) != 0; 14582 } 14583 14584 public void setOptionEnabled(int option) { 14585 mOptions |= option; 14586 } 14587 14588 public boolean onTitlePrinted() { 14589 final boolean printed = mTitlePrinted; 14590 mTitlePrinted = true; 14591 return printed; 14592 } 14593 14594 public boolean getTitlePrinted() { 14595 return mTitlePrinted; 14596 } 14597 14598 public void setTitlePrinted(boolean enabled) { 14599 mTitlePrinted = enabled; 14600 } 14601 14602 public SharedUserSetting getSharedUser() { 14603 return mSharedUser; 14604 } 14605 14606 public void setSharedUser(SharedUserSetting user) { 14607 mSharedUser = user; 14608 } 14609 } 14610 14611 @Override 14612 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14613 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14614 != PackageManager.PERMISSION_GRANTED) { 14615 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14616 + Binder.getCallingPid() 14617 + ", uid=" + Binder.getCallingUid() 14618 + " without permission " 14619 + android.Manifest.permission.DUMP); 14620 return; 14621 } 14622 14623 DumpState dumpState = new DumpState(); 14624 boolean fullPreferred = false; 14625 boolean checkin = false; 14626 14627 String packageName = null; 14628 ArraySet<String> permissionNames = null; 14629 14630 int opti = 0; 14631 while (opti < args.length) { 14632 String opt = args[opti]; 14633 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14634 break; 14635 } 14636 opti++; 14637 14638 if ("-a".equals(opt)) { 14639 // Right now we only know how to print all. 14640 } else if ("-h".equals(opt)) { 14641 pw.println("Package manager dump options:"); 14642 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14643 pw.println(" --checkin: dump for a checkin"); 14644 pw.println(" -f: print details of intent filters"); 14645 pw.println(" -h: print this help"); 14646 pw.println(" cmd may be one of:"); 14647 pw.println(" l[ibraries]: list known shared libraries"); 14648 pw.println(" f[ibraries]: list device features"); 14649 pw.println(" k[eysets]: print known keysets"); 14650 pw.println(" r[esolvers]: dump intent resolvers"); 14651 pw.println(" perm[issions]: dump permissions"); 14652 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14653 pw.println(" pref[erred]: print preferred package settings"); 14654 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14655 pw.println(" prov[iders]: dump content providers"); 14656 pw.println(" p[ackages]: dump installed packages"); 14657 pw.println(" s[hared-users]: dump shared user IDs"); 14658 pw.println(" m[essages]: print collected runtime messages"); 14659 pw.println(" v[erifiers]: print package verifier info"); 14660 pw.println(" version: print database version info"); 14661 pw.println(" write: write current settings now"); 14662 pw.println(" <package.name>: info about given package"); 14663 pw.println(" installs: details about install sessions"); 14664 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14665 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14666 return; 14667 } else if ("--checkin".equals(opt)) { 14668 checkin = true; 14669 } else if ("-f".equals(opt)) { 14670 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14671 } else { 14672 pw.println("Unknown argument: " + opt + "; use -h for help"); 14673 } 14674 } 14675 14676 // Is the caller requesting to dump a particular piece of data? 14677 if (opti < args.length) { 14678 String cmd = args[opti]; 14679 opti++; 14680 // Is this a package name? 14681 if ("android".equals(cmd) || cmd.contains(".")) { 14682 packageName = cmd; 14683 // When dumping a single package, we always dump all of its 14684 // filter information since the amount of data will be reasonable. 14685 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14686 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14687 dumpState.setDump(DumpState.DUMP_LIBS); 14688 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14689 dumpState.setDump(DumpState.DUMP_FEATURES); 14690 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14691 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14692 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14693 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14694 } else if ("permission".equals(cmd)) { 14695 if (opti >= args.length) { 14696 pw.println("Error: permission requires permission name"); 14697 return; 14698 } 14699 permissionNames = new ArraySet<>(); 14700 while (opti < args.length) { 14701 permissionNames.add(args[opti]); 14702 opti++; 14703 } 14704 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14705 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14706 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14707 dumpState.setDump(DumpState.DUMP_PREFERRED); 14708 } else if ("preferred-xml".equals(cmd)) { 14709 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14710 if (opti < args.length && "--full".equals(args[opti])) { 14711 fullPreferred = true; 14712 opti++; 14713 } 14714 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14715 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14716 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14717 dumpState.setDump(DumpState.DUMP_PACKAGES); 14718 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14719 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14720 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14721 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14722 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14723 dumpState.setDump(DumpState.DUMP_MESSAGES); 14724 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14725 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14726 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14727 || "intent-filter-verifiers".equals(cmd)) { 14728 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14729 } else if ("version".equals(cmd)) { 14730 dumpState.setDump(DumpState.DUMP_VERSION); 14731 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14732 dumpState.setDump(DumpState.DUMP_KEYSETS); 14733 } else if ("installs".equals(cmd)) { 14734 dumpState.setDump(DumpState.DUMP_INSTALLS); 14735 } else if ("write".equals(cmd)) { 14736 synchronized (mPackages) { 14737 mSettings.writeLPr(); 14738 pw.println("Settings written."); 14739 return; 14740 } 14741 } 14742 } 14743 14744 if (checkin) { 14745 pw.println("vers,1"); 14746 } 14747 14748 // reader 14749 synchronized (mPackages) { 14750 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14751 if (!checkin) { 14752 if (dumpState.onTitlePrinted()) 14753 pw.println(); 14754 pw.println("Database versions:"); 14755 pw.print(" SDK Version:"); 14756 pw.print(" internal="); 14757 pw.print(mSettings.mInternalSdkPlatform); 14758 pw.print(" external="); 14759 pw.println(mSettings.mExternalSdkPlatform); 14760 pw.print(" DB Version:"); 14761 pw.print(" internal="); 14762 pw.print(mSettings.mInternalDatabaseVersion); 14763 pw.print(" external="); 14764 pw.println(mSettings.mExternalDatabaseVersion); 14765 } 14766 } 14767 14768 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14769 if (!checkin) { 14770 if (dumpState.onTitlePrinted()) 14771 pw.println(); 14772 pw.println("Verifiers:"); 14773 pw.print(" Required: "); 14774 pw.print(mRequiredVerifierPackage); 14775 pw.print(" (uid="); 14776 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14777 pw.println(")"); 14778 } else if (mRequiredVerifierPackage != null) { 14779 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14780 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14781 } 14782 } 14783 14784 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14785 packageName == null) { 14786 if (mIntentFilterVerifierComponent != null) { 14787 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14788 if (!checkin) { 14789 if (dumpState.onTitlePrinted()) 14790 pw.println(); 14791 pw.println("Intent Filter Verifier:"); 14792 pw.print(" Using: "); 14793 pw.print(verifierPackageName); 14794 pw.print(" (uid="); 14795 pw.print(getPackageUid(verifierPackageName, 0)); 14796 pw.println(")"); 14797 } else if (verifierPackageName != null) { 14798 pw.print("ifv,"); pw.print(verifierPackageName); 14799 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14800 } 14801 } else { 14802 pw.println(); 14803 pw.println("No Intent Filter Verifier available!"); 14804 } 14805 } 14806 14807 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14808 boolean printedHeader = false; 14809 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14810 while (it.hasNext()) { 14811 String name = it.next(); 14812 SharedLibraryEntry ent = mSharedLibraries.get(name); 14813 if (!checkin) { 14814 if (!printedHeader) { 14815 if (dumpState.onTitlePrinted()) 14816 pw.println(); 14817 pw.println("Libraries:"); 14818 printedHeader = true; 14819 } 14820 pw.print(" "); 14821 } else { 14822 pw.print("lib,"); 14823 } 14824 pw.print(name); 14825 if (!checkin) { 14826 pw.print(" -> "); 14827 } 14828 if (ent.path != null) { 14829 if (!checkin) { 14830 pw.print("(jar) "); 14831 pw.print(ent.path); 14832 } else { 14833 pw.print(",jar,"); 14834 pw.print(ent.path); 14835 } 14836 } else { 14837 if (!checkin) { 14838 pw.print("(apk) "); 14839 pw.print(ent.apk); 14840 } else { 14841 pw.print(",apk,"); 14842 pw.print(ent.apk); 14843 } 14844 } 14845 pw.println(); 14846 } 14847 } 14848 14849 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14850 if (dumpState.onTitlePrinted()) 14851 pw.println(); 14852 if (!checkin) { 14853 pw.println("Features:"); 14854 } 14855 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14856 while (it.hasNext()) { 14857 String name = it.next(); 14858 if (!checkin) { 14859 pw.print(" "); 14860 } else { 14861 pw.print("feat,"); 14862 } 14863 pw.println(name); 14864 } 14865 } 14866 14867 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14868 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14869 : "Activity Resolver Table:", " ", packageName, 14870 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14871 dumpState.setTitlePrinted(true); 14872 } 14873 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14874 : "Receiver Resolver Table:", " ", packageName, 14875 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14876 dumpState.setTitlePrinted(true); 14877 } 14878 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14879 : "Service Resolver Table:", " ", packageName, 14880 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14881 dumpState.setTitlePrinted(true); 14882 } 14883 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14884 : "Provider Resolver Table:", " ", packageName, 14885 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14886 dumpState.setTitlePrinted(true); 14887 } 14888 } 14889 14890 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14891 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14892 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14893 int user = mSettings.mPreferredActivities.keyAt(i); 14894 if (pir.dump(pw, 14895 dumpState.getTitlePrinted() 14896 ? "\nPreferred Activities User " + user + ":" 14897 : "Preferred Activities User " + user + ":", " ", 14898 packageName, true, false)) { 14899 dumpState.setTitlePrinted(true); 14900 } 14901 } 14902 } 14903 14904 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14905 pw.flush(); 14906 FileOutputStream fout = new FileOutputStream(fd); 14907 BufferedOutputStream str = new BufferedOutputStream(fout); 14908 XmlSerializer serializer = new FastXmlSerializer(); 14909 try { 14910 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14911 serializer.startDocument(null, true); 14912 serializer.setFeature( 14913 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14914 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14915 serializer.endDocument(); 14916 serializer.flush(); 14917 } catch (IllegalArgumentException e) { 14918 pw.println("Failed writing: " + e); 14919 } catch (IllegalStateException e) { 14920 pw.println("Failed writing: " + e); 14921 } catch (IOException e) { 14922 pw.println("Failed writing: " + e); 14923 } 14924 } 14925 14926 if (!checkin 14927 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14928 && packageName == null) { 14929 pw.println(); 14930 int count = mSettings.mPackages.size(); 14931 if (count == 0) { 14932 pw.println("No applications!"); 14933 pw.println(); 14934 } else { 14935 final String prefix = " "; 14936 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14937 if (allPackageSettings.size() == 0) { 14938 pw.println("No domain preferred apps!"); 14939 pw.println(); 14940 } else { 14941 pw.println("App verification status:"); 14942 pw.println(); 14943 count = 0; 14944 for (PackageSetting ps : allPackageSettings) { 14945 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14946 if (ivi == null || ivi.getPackageName() == null) continue; 14947 pw.println(prefix + "Package: " + ivi.getPackageName()); 14948 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14949 pw.println(prefix + "Status: " + ivi.getStatusString()); 14950 pw.println(); 14951 count++; 14952 } 14953 if (count == 0) { 14954 pw.println(prefix + "No app verification established."); 14955 pw.println(); 14956 } 14957 for (int userId : sUserManager.getUserIds()) { 14958 pw.println("App linkages for user " + userId + ":"); 14959 pw.println(); 14960 count = 0; 14961 for (PackageSetting ps : allPackageSettings) { 14962 final long status = ps.getDomainVerificationStatusForUser(userId); 14963 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14964 continue; 14965 } 14966 pw.println(prefix + "Package: " + ps.name); 14967 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 14968 String statusStr = IntentFilterVerificationInfo. 14969 getStatusStringFromValue(status); 14970 pw.println(prefix + "Status: " + statusStr); 14971 pw.println(); 14972 count++; 14973 } 14974 if (count == 0) { 14975 pw.println(prefix + "No configured app linkages."); 14976 pw.println(); 14977 } 14978 } 14979 } 14980 } 14981 } 14982 14983 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14984 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14985 if (packageName == null && permissionNames == null) { 14986 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14987 if (iperm == 0) { 14988 if (dumpState.onTitlePrinted()) 14989 pw.println(); 14990 pw.println("AppOp Permissions:"); 14991 } 14992 pw.print(" AppOp Permission "); 14993 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14994 pw.println(":"); 14995 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14996 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14997 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14998 } 14999 } 15000 } 15001 } 15002 15003 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15004 boolean printedSomething = false; 15005 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15006 if (packageName != null && !packageName.equals(p.info.packageName)) { 15007 continue; 15008 } 15009 if (!printedSomething) { 15010 if (dumpState.onTitlePrinted()) 15011 pw.println(); 15012 pw.println("Registered ContentProviders:"); 15013 printedSomething = true; 15014 } 15015 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15016 pw.print(" "); pw.println(p.toString()); 15017 } 15018 printedSomething = false; 15019 for (Map.Entry<String, PackageParser.Provider> entry : 15020 mProvidersByAuthority.entrySet()) { 15021 PackageParser.Provider p = entry.getValue(); 15022 if (packageName != null && !packageName.equals(p.info.packageName)) { 15023 continue; 15024 } 15025 if (!printedSomething) { 15026 if (dumpState.onTitlePrinted()) 15027 pw.println(); 15028 pw.println("ContentProvider Authorities:"); 15029 printedSomething = true; 15030 } 15031 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15032 pw.print(" "); pw.println(p.toString()); 15033 if (p.info != null && p.info.applicationInfo != null) { 15034 final String appInfo = p.info.applicationInfo.toString(); 15035 pw.print(" applicationInfo="); pw.println(appInfo); 15036 } 15037 } 15038 } 15039 15040 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15041 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15042 } 15043 15044 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15045 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15046 } 15047 15048 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15049 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15050 } 15051 15052 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15053 // XXX should handle packageName != null by dumping only install data that 15054 // the given package is involved with. 15055 if (dumpState.onTitlePrinted()) pw.println(); 15056 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15057 } 15058 15059 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15060 if (dumpState.onTitlePrinted()) pw.println(); 15061 mSettings.dumpReadMessagesLPr(pw, dumpState); 15062 15063 pw.println(); 15064 pw.println("Package warning messages:"); 15065 BufferedReader in = null; 15066 String line = null; 15067 try { 15068 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15069 while ((line = in.readLine()) != null) { 15070 if (line.contains("ignored: updated version")) continue; 15071 pw.println(line); 15072 } 15073 } catch (IOException ignored) { 15074 } finally { 15075 IoUtils.closeQuietly(in); 15076 } 15077 } 15078 15079 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15080 BufferedReader in = null; 15081 String line = null; 15082 try { 15083 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15084 while ((line = in.readLine()) != null) { 15085 if (line.contains("ignored: updated version")) continue; 15086 pw.print("msg,"); 15087 pw.println(line); 15088 } 15089 } catch (IOException ignored) { 15090 } finally { 15091 IoUtils.closeQuietly(in); 15092 } 15093 } 15094 } 15095 } 15096 15097 private String dumpDomainString(String packageName) { 15098 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15099 List<IntentFilter> filters = getAllIntentFilters(packageName); 15100 15101 ArraySet<String> result = new ArraySet<>(); 15102 if (iviList.size() > 0) { 15103 for (IntentFilterVerificationInfo ivi : iviList) { 15104 for (String host : ivi.getDomains()) { 15105 result.add(host); 15106 } 15107 } 15108 } 15109 if (filters != null && filters.size() > 0) { 15110 for (IntentFilter filter : filters) { 15111 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15112 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15113 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15114 result.addAll(filter.getHostsList()); 15115 } 15116 } 15117 } 15118 15119 StringBuilder sb = new StringBuilder(result.size() * 16); 15120 for (String domain : result) { 15121 if (sb.length() > 0) sb.append(" "); 15122 sb.append(domain); 15123 } 15124 return sb.toString(); 15125 } 15126 15127 // ------- apps on sdcard specific code ------- 15128 static final boolean DEBUG_SD_INSTALL = false; 15129 15130 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15131 15132 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15133 15134 private boolean mMediaMounted = false; 15135 15136 static String getEncryptKey() { 15137 try { 15138 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15139 SD_ENCRYPTION_KEYSTORE_NAME); 15140 if (sdEncKey == null) { 15141 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15142 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15143 if (sdEncKey == null) { 15144 Slog.e(TAG, "Failed to create encryption keys"); 15145 return null; 15146 } 15147 } 15148 return sdEncKey; 15149 } catch (NoSuchAlgorithmException nsae) { 15150 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15151 return null; 15152 } catch (IOException ioe) { 15153 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15154 return null; 15155 } 15156 } 15157 15158 /* 15159 * Update media status on PackageManager. 15160 */ 15161 @Override 15162 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15163 int callingUid = Binder.getCallingUid(); 15164 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15165 throw new SecurityException("Media status can only be updated by the system"); 15166 } 15167 // reader; this apparently protects mMediaMounted, but should probably 15168 // be a different lock in that case. 15169 synchronized (mPackages) { 15170 Log.i(TAG, "Updating external media status from " 15171 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15172 + (mediaStatus ? "mounted" : "unmounted")); 15173 if (DEBUG_SD_INSTALL) 15174 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15175 + ", mMediaMounted=" + mMediaMounted); 15176 if (mediaStatus == mMediaMounted) { 15177 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15178 : 0, -1); 15179 mHandler.sendMessage(msg); 15180 return; 15181 } 15182 mMediaMounted = mediaStatus; 15183 } 15184 // Queue up an async operation since the package installation may take a 15185 // little while. 15186 mHandler.post(new Runnable() { 15187 public void run() { 15188 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15189 } 15190 }); 15191 } 15192 15193 /** 15194 * Called by MountService when the initial ASECs to scan are available. 15195 * Should block until all the ASEC containers are finished being scanned. 15196 */ 15197 public void scanAvailableAsecs() { 15198 updateExternalMediaStatusInner(true, false, false); 15199 if (mShouldRestoreconData) { 15200 SELinuxMMAC.setRestoreconDone(); 15201 mShouldRestoreconData = false; 15202 } 15203 } 15204 15205 /* 15206 * Collect information of applications on external media, map them against 15207 * existing containers and update information based on current mount status. 15208 * Please note that we always have to report status if reportStatus has been 15209 * set to true especially when unloading packages. 15210 */ 15211 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15212 boolean externalStorage) { 15213 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15214 int[] uidArr = EmptyArray.INT; 15215 15216 final String[] list = PackageHelper.getSecureContainerList(); 15217 if (ArrayUtils.isEmpty(list)) { 15218 Log.i(TAG, "No secure containers found"); 15219 } else { 15220 // Process list of secure containers and categorize them 15221 // as active or stale based on their package internal state. 15222 15223 // reader 15224 synchronized (mPackages) { 15225 for (String cid : list) { 15226 // Leave stages untouched for now; installer service owns them 15227 if (PackageInstallerService.isStageName(cid)) continue; 15228 15229 if (DEBUG_SD_INSTALL) 15230 Log.i(TAG, "Processing container " + cid); 15231 String pkgName = getAsecPackageName(cid); 15232 if (pkgName == null) { 15233 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15234 continue; 15235 } 15236 if (DEBUG_SD_INSTALL) 15237 Log.i(TAG, "Looking for pkg : " + pkgName); 15238 15239 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15240 if (ps == null) { 15241 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15242 continue; 15243 } 15244 15245 /* 15246 * Skip packages that are not external if we're unmounting 15247 * external storage. 15248 */ 15249 if (externalStorage && !isMounted && !isExternal(ps)) { 15250 continue; 15251 } 15252 15253 final AsecInstallArgs args = new AsecInstallArgs(cid, 15254 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15255 // The package status is changed only if the code path 15256 // matches between settings and the container id. 15257 if (ps.codePathString != null 15258 && ps.codePathString.startsWith(args.getCodePath())) { 15259 if (DEBUG_SD_INSTALL) { 15260 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15261 + " at code path: " + ps.codePathString); 15262 } 15263 15264 // We do have a valid package installed on sdcard 15265 processCids.put(args, ps.codePathString); 15266 final int uid = ps.appId; 15267 if (uid != -1) { 15268 uidArr = ArrayUtils.appendInt(uidArr, uid); 15269 } 15270 } else { 15271 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15272 + ps.codePathString); 15273 } 15274 } 15275 } 15276 15277 Arrays.sort(uidArr); 15278 } 15279 15280 // Process packages with valid entries. 15281 if (isMounted) { 15282 if (DEBUG_SD_INSTALL) 15283 Log.i(TAG, "Loading packages"); 15284 loadMediaPackages(processCids, uidArr); 15285 startCleaningPackages(); 15286 mInstallerService.onSecureContainersAvailable(); 15287 } else { 15288 if (DEBUG_SD_INSTALL) 15289 Log.i(TAG, "Unloading packages"); 15290 unloadMediaPackages(processCids, uidArr, reportStatus); 15291 } 15292 } 15293 15294 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15295 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15296 final int size = infos.size(); 15297 final String[] packageNames = new String[size]; 15298 final int[] packageUids = new int[size]; 15299 for (int i = 0; i < size; i++) { 15300 final ApplicationInfo info = infos.get(i); 15301 packageNames[i] = info.packageName; 15302 packageUids[i] = info.uid; 15303 } 15304 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15305 finishedReceiver); 15306 } 15307 15308 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15309 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15310 sendResourcesChangedBroadcast(mediaStatus, replacing, 15311 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15312 } 15313 15314 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15315 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15316 int size = pkgList.length; 15317 if (size > 0) { 15318 // Send broadcasts here 15319 Bundle extras = new Bundle(); 15320 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15321 if (uidArr != null) { 15322 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15323 } 15324 if (replacing) { 15325 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15326 } 15327 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15328 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15329 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15330 } 15331 } 15332 15333 /* 15334 * Look at potentially valid container ids from processCids If package 15335 * information doesn't match the one on record or package scanning fails, 15336 * the cid is added to list of removeCids. We currently don't delete stale 15337 * containers. 15338 */ 15339 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15340 ArrayList<String> pkgList = new ArrayList<String>(); 15341 Set<AsecInstallArgs> keys = processCids.keySet(); 15342 15343 for (AsecInstallArgs args : keys) { 15344 String codePath = processCids.get(args); 15345 if (DEBUG_SD_INSTALL) 15346 Log.i(TAG, "Loading container : " + args.cid); 15347 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15348 try { 15349 // Make sure there are no container errors first. 15350 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15351 Slog.e(TAG, "Failed to mount cid : " + args.cid 15352 + " when installing from sdcard"); 15353 continue; 15354 } 15355 // Check code path here. 15356 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15357 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15358 + " does not match one in settings " + codePath); 15359 continue; 15360 } 15361 // Parse package 15362 int parseFlags = mDefParseFlags; 15363 if (args.isExternalAsec()) { 15364 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15365 } 15366 if (args.isFwdLocked()) { 15367 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15368 } 15369 15370 synchronized (mInstallLock) { 15371 PackageParser.Package pkg = null; 15372 try { 15373 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15374 } catch (PackageManagerException e) { 15375 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15376 } 15377 // Scan the package 15378 if (pkg != null) { 15379 /* 15380 * TODO why is the lock being held? doPostInstall is 15381 * called in other places without the lock. This needs 15382 * to be straightened out. 15383 */ 15384 // writer 15385 synchronized (mPackages) { 15386 retCode = PackageManager.INSTALL_SUCCEEDED; 15387 pkgList.add(pkg.packageName); 15388 // Post process args 15389 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15390 pkg.applicationInfo.uid); 15391 } 15392 } else { 15393 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15394 } 15395 } 15396 15397 } finally { 15398 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15399 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15400 } 15401 } 15402 } 15403 // writer 15404 synchronized (mPackages) { 15405 // If the platform SDK has changed since the last time we booted, 15406 // we need to re-grant app permission to catch any new ones that 15407 // appear. This is really a hack, and means that apps can in some 15408 // cases get permissions that the user didn't initially explicitly 15409 // allow... it would be nice to have some better way to handle 15410 // this situation. 15411 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15412 if (regrantPermissions) 15413 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15414 + mSdkVersion + "; regranting permissions for external storage"); 15415 mSettings.mExternalSdkPlatform = mSdkVersion; 15416 15417 // Make sure group IDs have been assigned, and any permission 15418 // changes in other apps are accounted for 15419 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15420 | (regrantPermissions 15421 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15422 : 0)); 15423 15424 mSettings.updateExternalDatabaseVersion(); 15425 15426 // can downgrade to reader 15427 // Persist settings 15428 mSettings.writeLPr(); 15429 } 15430 // Send a broadcast to let everyone know we are done processing 15431 if (pkgList.size() > 0) { 15432 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15433 } 15434 } 15435 15436 /* 15437 * Utility method to unload a list of specified containers 15438 */ 15439 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15440 // Just unmount all valid containers. 15441 for (AsecInstallArgs arg : cidArgs) { 15442 synchronized (mInstallLock) { 15443 arg.doPostDeleteLI(false); 15444 } 15445 } 15446 } 15447 15448 /* 15449 * Unload packages mounted on external media. This involves deleting package 15450 * data from internal structures, sending broadcasts about diabled packages, 15451 * gc'ing to free up references, unmounting all secure containers 15452 * corresponding to packages on external media, and posting a 15453 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15454 * that we always have to post this message if status has been requested no 15455 * matter what. 15456 */ 15457 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15458 final boolean reportStatus) { 15459 if (DEBUG_SD_INSTALL) 15460 Log.i(TAG, "unloading media packages"); 15461 ArrayList<String> pkgList = new ArrayList<String>(); 15462 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15463 final Set<AsecInstallArgs> keys = processCids.keySet(); 15464 for (AsecInstallArgs args : keys) { 15465 String pkgName = args.getPackageName(); 15466 if (DEBUG_SD_INSTALL) 15467 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15468 // Delete package internally 15469 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15470 synchronized (mInstallLock) { 15471 boolean res = deletePackageLI(pkgName, null, false, null, null, 15472 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15473 if (res) { 15474 pkgList.add(pkgName); 15475 } else { 15476 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15477 failedList.add(args); 15478 } 15479 } 15480 } 15481 15482 // reader 15483 synchronized (mPackages) { 15484 // We didn't update the settings after removing each package; 15485 // write them now for all packages. 15486 mSettings.writeLPr(); 15487 } 15488 15489 // We have to absolutely send UPDATED_MEDIA_STATUS only 15490 // after confirming that all the receivers processed the ordered 15491 // broadcast when packages get disabled, force a gc to clean things up. 15492 // and unload all the containers. 15493 if (pkgList.size() > 0) { 15494 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15495 new IIntentReceiver.Stub() { 15496 public void performReceive(Intent intent, int resultCode, String data, 15497 Bundle extras, boolean ordered, boolean sticky, 15498 int sendingUser) throws RemoteException { 15499 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15500 reportStatus ? 1 : 0, 1, keys); 15501 mHandler.sendMessage(msg); 15502 } 15503 }); 15504 } else { 15505 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15506 keys); 15507 mHandler.sendMessage(msg); 15508 } 15509 } 15510 15511 private void loadPrivatePackages(VolumeInfo vol) { 15512 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15513 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15514 synchronized (mInstallLock) { 15515 synchronized (mPackages) { 15516 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15517 for (PackageSetting ps : packages) { 15518 final PackageParser.Package pkg; 15519 try { 15520 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15521 loaded.add(pkg.applicationInfo); 15522 } catch (PackageManagerException e) { 15523 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15524 } 15525 } 15526 15527 // TODO: regrant any permissions that changed based since original install 15528 15529 mSettings.writeLPr(); 15530 } 15531 } 15532 15533 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15534 sendResourcesChangedBroadcast(true, false, loaded, null); 15535 } 15536 15537 private void unloadPrivatePackages(VolumeInfo vol) { 15538 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15539 synchronized (mInstallLock) { 15540 synchronized (mPackages) { 15541 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15542 for (PackageSetting ps : packages) { 15543 if (ps.pkg == null) continue; 15544 15545 final ApplicationInfo info = ps.pkg.applicationInfo; 15546 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15547 if (deletePackageLI(ps.name, null, false, null, null, 15548 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15549 unloaded.add(info); 15550 } else { 15551 Slog.w(TAG, "Failed to unload " + ps.codePath); 15552 } 15553 } 15554 15555 mSettings.writeLPr(); 15556 } 15557 } 15558 15559 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15560 sendResourcesChangedBroadcast(false, false, unloaded, null); 15561 } 15562 15563 /** 15564 * Examine all users present on given mounted volume, and destroy data 15565 * belonging to users that are no longer valid, or whose user ID has been 15566 * recycled. 15567 */ 15568 private void reconcileUsers(String volumeUuid) { 15569 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15570 if (ArrayUtils.isEmpty(files)) { 15571 Slog.d(TAG, "No users found on " + volumeUuid); 15572 return; 15573 } 15574 15575 for (File file : files) { 15576 if (!file.isDirectory()) continue; 15577 15578 final int userId; 15579 final UserInfo info; 15580 try { 15581 userId = Integer.parseInt(file.getName()); 15582 info = sUserManager.getUserInfo(userId); 15583 } catch (NumberFormatException e) { 15584 Slog.w(TAG, "Invalid user directory " + file); 15585 continue; 15586 } 15587 15588 boolean destroyUser = false; 15589 if (info == null) { 15590 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15591 + " because no matching user was found"); 15592 destroyUser = true; 15593 } else { 15594 try { 15595 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15596 } catch (IOException e) { 15597 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15598 + " because we failed to enforce serial number: " + e); 15599 destroyUser = true; 15600 } 15601 } 15602 15603 if (destroyUser) { 15604 synchronized (mInstallLock) { 15605 mInstaller.removeUserDataDirs(volumeUuid, userId); 15606 } 15607 } 15608 } 15609 15610 final UserManager um = mContext.getSystemService(UserManager.class); 15611 for (UserInfo user : um.getUsers()) { 15612 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15613 if (userDir.exists()) continue; 15614 15615 try { 15616 UserManagerService.prepareUserDirectory(userDir); 15617 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15618 } catch (IOException e) { 15619 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15620 } 15621 } 15622 } 15623 15624 /** 15625 * Examine all apps present on given mounted volume, and destroy apps that 15626 * aren't expected, either due to uninstallation or reinstallation on 15627 * another volume. 15628 */ 15629 private void reconcileApps(String volumeUuid) { 15630 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15631 if (ArrayUtils.isEmpty(files)) { 15632 Slog.d(TAG, "No apps found on " + volumeUuid); 15633 return; 15634 } 15635 15636 for (File file : files) { 15637 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15638 && !PackageInstallerService.isStageName(file.getName()); 15639 if (!isPackage) { 15640 // Ignore entries which are not packages 15641 continue; 15642 } 15643 15644 boolean destroyApp = false; 15645 String packageName = null; 15646 try { 15647 final PackageLite pkg = PackageParser.parsePackageLite(file, 15648 PackageParser.PARSE_MUST_BE_APK); 15649 packageName = pkg.packageName; 15650 15651 synchronized (mPackages) { 15652 final PackageSetting ps = mSettings.mPackages.get(packageName); 15653 if (ps == null) { 15654 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15655 + volumeUuid + " because we found no install record"); 15656 destroyApp = true; 15657 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15658 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15659 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15660 destroyApp = true; 15661 } 15662 } 15663 15664 } catch (PackageParserException e) { 15665 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15666 destroyApp = true; 15667 } 15668 15669 if (destroyApp) { 15670 synchronized (mInstallLock) { 15671 if (packageName != null) { 15672 removeDataDirsLI(volumeUuid, packageName); 15673 } 15674 if (file.isDirectory()) { 15675 mInstaller.rmPackageDir(file.getAbsolutePath()); 15676 } else { 15677 file.delete(); 15678 } 15679 } 15680 } 15681 } 15682 } 15683 15684 private void unfreezePackage(String packageName) { 15685 synchronized (mPackages) { 15686 final PackageSetting ps = mSettings.mPackages.get(packageName); 15687 if (ps != null) { 15688 ps.frozen = false; 15689 } 15690 } 15691 } 15692 15693 @Override 15694 public int movePackage(final String packageName, final String volumeUuid) { 15695 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15696 15697 final int moveId = mNextMoveId.getAndIncrement(); 15698 try { 15699 movePackageInternal(packageName, volumeUuid, moveId); 15700 } catch (PackageManagerException e) { 15701 Slog.w(TAG, "Failed to move " + packageName, e); 15702 mMoveCallbacks.notifyStatusChanged(moveId, 15703 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15704 } 15705 return moveId; 15706 } 15707 15708 private void movePackageInternal(final String packageName, final String volumeUuid, 15709 final int moveId) throws PackageManagerException { 15710 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15711 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15712 final PackageManager pm = mContext.getPackageManager(); 15713 15714 final boolean currentAsec; 15715 final String currentVolumeUuid; 15716 final File codeFile; 15717 final String installerPackageName; 15718 final String packageAbiOverride; 15719 final int appId; 15720 final String seinfo; 15721 final String label; 15722 15723 // reader 15724 synchronized (mPackages) { 15725 final PackageParser.Package pkg = mPackages.get(packageName); 15726 final PackageSetting ps = mSettings.mPackages.get(packageName); 15727 if (pkg == null || ps == null) { 15728 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15729 } 15730 15731 if (pkg.applicationInfo.isSystemApp()) { 15732 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15733 "Cannot move system application"); 15734 } 15735 15736 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15737 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15738 "Package already moved to " + volumeUuid); 15739 } 15740 15741 final File probe = new File(pkg.codePath); 15742 final File probeOat = new File(probe, "oat"); 15743 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15744 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15745 "Move only supported for modern cluster style installs"); 15746 } 15747 15748 if (ps.frozen) { 15749 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15750 "Failed to move already frozen package"); 15751 } 15752 ps.frozen = true; 15753 15754 currentAsec = pkg.applicationInfo.isForwardLocked() 15755 || pkg.applicationInfo.isExternalAsec(); 15756 currentVolumeUuid = ps.volumeUuid; 15757 codeFile = new File(pkg.codePath); 15758 installerPackageName = ps.installerPackageName; 15759 packageAbiOverride = ps.cpuAbiOverrideString; 15760 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15761 seinfo = pkg.applicationInfo.seinfo; 15762 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15763 } 15764 15765 // Now that we're guarded by frozen state, kill app during move 15766 killApplication(packageName, appId, "move pkg"); 15767 15768 final Bundle extras = new Bundle(); 15769 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15770 extras.putString(Intent.EXTRA_TITLE, label); 15771 mMoveCallbacks.notifyCreated(moveId, extras); 15772 15773 int installFlags; 15774 final boolean moveCompleteApp; 15775 final File measurePath; 15776 15777 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15778 installFlags = INSTALL_INTERNAL; 15779 moveCompleteApp = !currentAsec; 15780 measurePath = Environment.getDataAppDirectory(volumeUuid); 15781 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15782 installFlags = INSTALL_EXTERNAL; 15783 moveCompleteApp = false; 15784 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15785 } else { 15786 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15787 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15788 || !volume.isMountedWritable()) { 15789 unfreezePackage(packageName); 15790 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15791 "Move location not mounted private volume"); 15792 } 15793 15794 Preconditions.checkState(!currentAsec); 15795 15796 installFlags = INSTALL_INTERNAL; 15797 moveCompleteApp = true; 15798 measurePath = Environment.getDataAppDirectory(volumeUuid); 15799 } 15800 15801 final PackageStats stats = new PackageStats(null, -1); 15802 synchronized (mInstaller) { 15803 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15804 unfreezePackage(packageName); 15805 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15806 "Failed to measure package size"); 15807 } 15808 } 15809 15810 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15811 + stats.dataSize); 15812 15813 final long startFreeBytes = measurePath.getFreeSpace(); 15814 final long sizeBytes; 15815 if (moveCompleteApp) { 15816 sizeBytes = stats.codeSize + stats.dataSize; 15817 } else { 15818 sizeBytes = stats.codeSize; 15819 } 15820 15821 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15822 unfreezePackage(packageName); 15823 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15824 "Not enough free space to move"); 15825 } 15826 15827 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15828 15829 final CountDownLatch installedLatch = new CountDownLatch(1); 15830 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15831 @Override 15832 public void onUserActionRequired(Intent intent) throws RemoteException { 15833 throw new IllegalStateException(); 15834 } 15835 15836 @Override 15837 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15838 Bundle extras) throws RemoteException { 15839 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15840 + PackageManager.installStatusToString(returnCode, msg)); 15841 15842 installedLatch.countDown(); 15843 15844 // Regardless of success or failure of the move operation, 15845 // always unfreeze the package 15846 unfreezePackage(packageName); 15847 15848 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15849 switch (status) { 15850 case PackageInstaller.STATUS_SUCCESS: 15851 mMoveCallbacks.notifyStatusChanged(moveId, 15852 PackageManager.MOVE_SUCCEEDED); 15853 break; 15854 case PackageInstaller.STATUS_FAILURE_STORAGE: 15855 mMoveCallbacks.notifyStatusChanged(moveId, 15856 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15857 break; 15858 default: 15859 mMoveCallbacks.notifyStatusChanged(moveId, 15860 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15861 break; 15862 } 15863 } 15864 }; 15865 15866 final MoveInfo move; 15867 if (moveCompleteApp) { 15868 // Kick off a thread to report progress estimates 15869 new Thread() { 15870 @Override 15871 public void run() { 15872 while (true) { 15873 try { 15874 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15875 break; 15876 } 15877 } catch (InterruptedException ignored) { 15878 } 15879 15880 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15881 final int progress = 10 + (int) MathUtils.constrain( 15882 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15883 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15884 } 15885 } 15886 }.start(); 15887 15888 final String dataAppName = codeFile.getName(); 15889 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15890 dataAppName, appId, seinfo); 15891 } else { 15892 move = null; 15893 } 15894 15895 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15896 15897 final Message msg = mHandler.obtainMessage(INIT_COPY); 15898 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15899 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15900 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 15901 mHandler.sendMessage(msg); 15902 } 15903 15904 @Override 15905 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15906 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15907 15908 final int realMoveId = mNextMoveId.getAndIncrement(); 15909 final Bundle extras = new Bundle(); 15910 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15911 mMoveCallbacks.notifyCreated(realMoveId, extras); 15912 15913 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15914 @Override 15915 public void onCreated(int moveId, Bundle extras) { 15916 // Ignored 15917 } 15918 15919 @Override 15920 public void onStatusChanged(int moveId, int status, long estMillis) { 15921 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15922 } 15923 }; 15924 15925 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15926 storage.setPrimaryStorageUuid(volumeUuid, callback); 15927 return realMoveId; 15928 } 15929 15930 @Override 15931 public int getMoveStatus(int moveId) { 15932 mContext.enforceCallingOrSelfPermission( 15933 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15934 return mMoveCallbacks.mLastStatus.get(moveId); 15935 } 15936 15937 @Override 15938 public void registerMoveCallback(IPackageMoveObserver callback) { 15939 mContext.enforceCallingOrSelfPermission( 15940 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15941 mMoveCallbacks.register(callback); 15942 } 15943 15944 @Override 15945 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15946 mContext.enforceCallingOrSelfPermission( 15947 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15948 mMoveCallbacks.unregister(callback); 15949 } 15950 15951 @Override 15952 public boolean setInstallLocation(int loc) { 15953 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15954 null); 15955 if (getInstallLocation() == loc) { 15956 return true; 15957 } 15958 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15959 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15960 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15961 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15962 return true; 15963 } 15964 return false; 15965 } 15966 15967 @Override 15968 public int getInstallLocation() { 15969 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15970 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15971 PackageHelper.APP_INSTALL_AUTO); 15972 } 15973 15974 /** Called by UserManagerService */ 15975 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15976 mDirtyUsers.remove(userHandle); 15977 mSettings.removeUserLPw(userHandle); 15978 mPendingBroadcasts.remove(userHandle); 15979 if (mInstaller != null) { 15980 // Technically, we shouldn't be doing this with the package lock 15981 // held. However, this is very rare, and there is already so much 15982 // other disk I/O going on, that we'll let it slide for now. 15983 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15984 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15985 final String volumeUuid = vol.getFsUuid(); 15986 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15987 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15988 } 15989 } 15990 mUserNeedsBadging.delete(userHandle); 15991 removeUnusedPackagesLILPw(userManager, userHandle); 15992 } 15993 15994 /** 15995 * We're removing userHandle and would like to remove any downloaded packages 15996 * that are no longer in use by any other user. 15997 * @param userHandle the user being removed 15998 */ 15999 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16000 final boolean DEBUG_CLEAN_APKS = false; 16001 int [] users = userManager.getUserIdsLPr(); 16002 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16003 while (psit.hasNext()) { 16004 PackageSetting ps = psit.next(); 16005 if (ps.pkg == null) { 16006 continue; 16007 } 16008 final String packageName = ps.pkg.packageName; 16009 // Skip over if system app 16010 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16011 continue; 16012 } 16013 if (DEBUG_CLEAN_APKS) { 16014 Slog.i(TAG, "Checking package " + packageName); 16015 } 16016 boolean keep = false; 16017 for (int i = 0; i < users.length; i++) { 16018 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16019 keep = true; 16020 if (DEBUG_CLEAN_APKS) { 16021 Slog.i(TAG, " Keeping package " + packageName + " for user " 16022 + users[i]); 16023 } 16024 break; 16025 } 16026 } 16027 if (!keep) { 16028 if (DEBUG_CLEAN_APKS) { 16029 Slog.i(TAG, " Removing package " + packageName); 16030 } 16031 mHandler.post(new Runnable() { 16032 public void run() { 16033 deletePackageX(packageName, userHandle, 0); 16034 } //end run 16035 }); 16036 } 16037 } 16038 } 16039 16040 /** Called by UserManagerService */ 16041 void createNewUserLILPw(int userHandle) { 16042 if (mInstaller != null) { 16043 mInstaller.createUserConfig(userHandle); 16044 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16045 applyFactoryDefaultBrowserLPw(userHandle); 16046 primeDomainVerificationsLPw(userHandle); 16047 } 16048 } 16049 16050 void newUserCreated(final int userHandle) { 16051 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16052 } 16053 16054 @Override 16055 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16056 mContext.enforceCallingOrSelfPermission( 16057 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16058 "Only package verification agents can read the verifier device identity"); 16059 16060 synchronized (mPackages) { 16061 return mSettings.getVerifierDeviceIdentityLPw(); 16062 } 16063 } 16064 16065 @Override 16066 public void setPermissionEnforced(String permission, boolean enforced) { 16067 // TODO: Now that we no longer change GID for storage, this should to away. 16068 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16069 "setPermissionEnforced"); 16070 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16071 synchronized (mPackages) { 16072 if (mSettings.mReadExternalStorageEnforced == null 16073 || mSettings.mReadExternalStorageEnforced != enforced) { 16074 mSettings.mReadExternalStorageEnforced = enforced; 16075 mSettings.writeLPr(); 16076 } 16077 } 16078 // kill any non-foreground processes so we restart them and 16079 // grant/revoke the GID. 16080 final IActivityManager am = ActivityManagerNative.getDefault(); 16081 if (am != null) { 16082 final long token = Binder.clearCallingIdentity(); 16083 try { 16084 am.killProcessesBelowForeground("setPermissionEnforcement"); 16085 } catch (RemoteException e) { 16086 } finally { 16087 Binder.restoreCallingIdentity(token); 16088 } 16089 } 16090 } else { 16091 throw new IllegalArgumentException("No selective enforcement for " + permission); 16092 } 16093 } 16094 16095 @Override 16096 @Deprecated 16097 public boolean isPermissionEnforced(String permission) { 16098 return true; 16099 } 16100 16101 @Override 16102 public boolean isStorageLow() { 16103 final long token = Binder.clearCallingIdentity(); 16104 try { 16105 final DeviceStorageMonitorInternal 16106 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16107 if (dsm != null) { 16108 return dsm.isMemoryLow(); 16109 } else { 16110 return false; 16111 } 16112 } finally { 16113 Binder.restoreCallingIdentity(token); 16114 } 16115 } 16116 16117 @Override 16118 public IPackageInstaller getPackageInstaller() { 16119 return mInstallerService; 16120 } 16121 16122 private boolean userNeedsBadging(int userId) { 16123 int index = mUserNeedsBadging.indexOfKey(userId); 16124 if (index < 0) { 16125 final UserInfo userInfo; 16126 final long token = Binder.clearCallingIdentity(); 16127 try { 16128 userInfo = sUserManager.getUserInfo(userId); 16129 } finally { 16130 Binder.restoreCallingIdentity(token); 16131 } 16132 final boolean b; 16133 if (userInfo != null && userInfo.isManagedProfile()) { 16134 b = true; 16135 } else { 16136 b = false; 16137 } 16138 mUserNeedsBadging.put(userId, b); 16139 return b; 16140 } 16141 return mUserNeedsBadging.valueAt(index); 16142 } 16143 16144 @Override 16145 public KeySet getKeySetByAlias(String packageName, String alias) { 16146 if (packageName == null || alias == null) { 16147 return null; 16148 } 16149 synchronized(mPackages) { 16150 final PackageParser.Package pkg = mPackages.get(packageName); 16151 if (pkg == null) { 16152 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16153 throw new IllegalArgumentException("Unknown package: " + packageName); 16154 } 16155 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16156 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16157 } 16158 } 16159 16160 @Override 16161 public KeySet getSigningKeySet(String packageName) { 16162 if (packageName == null) { 16163 return null; 16164 } 16165 synchronized(mPackages) { 16166 final PackageParser.Package pkg = mPackages.get(packageName); 16167 if (pkg == null) { 16168 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16169 throw new IllegalArgumentException("Unknown package: " + packageName); 16170 } 16171 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16172 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16173 throw new SecurityException("May not access signing KeySet of other apps."); 16174 } 16175 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16176 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16177 } 16178 } 16179 16180 @Override 16181 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16182 if (packageName == null || ks == null) { 16183 return false; 16184 } 16185 synchronized(mPackages) { 16186 final PackageParser.Package pkg = mPackages.get(packageName); 16187 if (pkg == null) { 16188 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16189 throw new IllegalArgumentException("Unknown package: " + packageName); 16190 } 16191 IBinder ksh = ks.getToken(); 16192 if (ksh instanceof KeySetHandle) { 16193 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16194 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16195 } 16196 return false; 16197 } 16198 } 16199 16200 @Override 16201 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16202 if (packageName == null || ks == null) { 16203 return false; 16204 } 16205 synchronized(mPackages) { 16206 final PackageParser.Package pkg = mPackages.get(packageName); 16207 if (pkg == null) { 16208 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16209 throw new IllegalArgumentException("Unknown package: " + packageName); 16210 } 16211 IBinder ksh = ks.getToken(); 16212 if (ksh instanceof KeySetHandle) { 16213 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16214 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16215 } 16216 return false; 16217 } 16218 } 16219 16220 public void getUsageStatsIfNoPackageUsageInfo() { 16221 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16222 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16223 if (usm == null) { 16224 throw new IllegalStateException("UsageStatsManager must be initialized"); 16225 } 16226 long now = System.currentTimeMillis(); 16227 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16228 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16229 String packageName = entry.getKey(); 16230 PackageParser.Package pkg = mPackages.get(packageName); 16231 if (pkg == null) { 16232 continue; 16233 } 16234 UsageStats usage = entry.getValue(); 16235 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16236 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16237 } 16238 } 16239 } 16240 16241 /** 16242 * Check and throw if the given before/after packages would be considered a 16243 * downgrade. 16244 */ 16245 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16246 throws PackageManagerException { 16247 if (after.versionCode < before.mVersionCode) { 16248 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16249 "Update version code " + after.versionCode + " is older than current " 16250 + before.mVersionCode); 16251 } else if (after.versionCode == before.mVersionCode) { 16252 if (after.baseRevisionCode < before.baseRevisionCode) { 16253 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16254 "Update base revision code " + after.baseRevisionCode 16255 + " is older than current " + before.baseRevisionCode); 16256 } 16257 16258 if (!ArrayUtils.isEmpty(after.splitNames)) { 16259 for (int i = 0; i < after.splitNames.length; i++) { 16260 final String splitName = after.splitNames[i]; 16261 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16262 if (j != -1) { 16263 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16264 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16265 "Update split " + splitName + " revision code " 16266 + after.splitRevisionCodes[i] + " is older than current " 16267 + before.splitRevisionCodes[j]); 16268 } 16269 } 16270 } 16271 } 16272 } 16273 } 16274 16275 private static class MoveCallbacks extends Handler { 16276 private static final int MSG_CREATED = 1; 16277 private static final int MSG_STATUS_CHANGED = 2; 16278 16279 private final RemoteCallbackList<IPackageMoveObserver> 16280 mCallbacks = new RemoteCallbackList<>(); 16281 16282 private final SparseIntArray mLastStatus = new SparseIntArray(); 16283 16284 public MoveCallbacks(Looper looper) { 16285 super(looper); 16286 } 16287 16288 public void register(IPackageMoveObserver callback) { 16289 mCallbacks.register(callback); 16290 } 16291 16292 public void unregister(IPackageMoveObserver callback) { 16293 mCallbacks.unregister(callback); 16294 } 16295 16296 @Override 16297 public void handleMessage(Message msg) { 16298 final SomeArgs args = (SomeArgs) msg.obj; 16299 final int n = mCallbacks.beginBroadcast(); 16300 for (int i = 0; i < n; i++) { 16301 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16302 try { 16303 invokeCallback(callback, msg.what, args); 16304 } catch (RemoteException ignored) { 16305 } 16306 } 16307 mCallbacks.finishBroadcast(); 16308 args.recycle(); 16309 } 16310 16311 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16312 throws RemoteException { 16313 switch (what) { 16314 case MSG_CREATED: { 16315 callback.onCreated(args.argi1, (Bundle) args.arg2); 16316 break; 16317 } 16318 case MSG_STATUS_CHANGED: { 16319 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16320 break; 16321 } 16322 } 16323 } 16324 16325 private void notifyCreated(int moveId, Bundle extras) { 16326 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16327 16328 final SomeArgs args = SomeArgs.obtain(); 16329 args.argi1 = moveId; 16330 args.arg2 = extras; 16331 obtainMessage(MSG_CREATED, args).sendToTarget(); 16332 } 16333 16334 private void notifyStatusChanged(int moveId, int status) { 16335 notifyStatusChanged(moveId, status, -1); 16336 } 16337 16338 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16339 Slog.v(TAG, "Move " + moveId + " status " + status); 16340 16341 final SomeArgs args = SomeArgs.obtain(); 16342 args.argi1 = moveId; 16343 args.argi2 = status; 16344 args.arg3 = estMillis; 16345 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16346 16347 synchronized (mLastStatus) { 16348 mLastStatus.put(moveId, status); 16349 } 16350 } 16351 } 16352 16353 private final class OnPermissionChangeListeners extends Handler { 16354 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16355 16356 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16357 new RemoteCallbackList<>(); 16358 16359 public OnPermissionChangeListeners(Looper looper) { 16360 super(looper); 16361 } 16362 16363 @Override 16364 public void handleMessage(Message msg) { 16365 switch (msg.what) { 16366 case MSG_ON_PERMISSIONS_CHANGED: { 16367 final int uid = msg.arg1; 16368 handleOnPermissionsChanged(uid); 16369 } break; 16370 } 16371 } 16372 16373 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16374 mPermissionListeners.register(listener); 16375 16376 } 16377 16378 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16379 mPermissionListeners.unregister(listener); 16380 } 16381 16382 public void onPermissionsChanged(int uid) { 16383 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16384 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16385 } 16386 } 16387 16388 private void handleOnPermissionsChanged(int uid) { 16389 final int count = mPermissionListeners.beginBroadcast(); 16390 try { 16391 for (int i = 0; i < count; i++) { 16392 IOnPermissionsChangeListener callback = mPermissionListeners 16393 .getBroadcastItem(i); 16394 try { 16395 callback.onPermissionsChanged(uid); 16396 } catch (RemoteException e) { 16397 Log.e(TAG, "Permission listener is dead", e); 16398 } 16399 } 16400 } finally { 16401 mPermissionListeners.finishBroadcast(); 16402 } 16403 } 16404 } 16405 16406 private class PackageManagerInternalImpl extends PackageManagerInternal { 16407 @Override 16408 public void setLocationPackagesProvider(PackagesProvider provider) { 16409 synchronized (mPackages) { 16410 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16411 } 16412 } 16413 16414 @Override 16415 public void setImePackagesProvider(PackagesProvider provider) { 16416 synchronized (mPackages) { 16417 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16418 } 16419 } 16420 16421 @Override 16422 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16423 synchronized (mPackages) { 16424 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16425 } 16426 } 16427 16428 @Override 16429 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16430 synchronized (mPackages) { 16431 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16432 } 16433 } 16434 16435 @Override 16436 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16437 synchronized (mPackages) { 16438 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16439 } 16440 } 16441 16442 @Override 16443 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16444 synchronized (mPackages) { 16445 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16446 } 16447 } 16448 16449 @Override 16450 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16451 synchronized (mPackages) { 16452 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16453 packageName, userId); 16454 } 16455 } 16456 16457 @Override 16458 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16459 synchronized (mPackages) { 16460 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16461 packageName, userId); 16462 } 16463 } 16464 } 16465 16466 @Override 16467 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16468 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16469 synchronized (mPackages) { 16470 final long identity = Binder.clearCallingIdentity(); 16471 try { 16472 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16473 packageNames, userId); 16474 } finally { 16475 Binder.restoreCallingIdentity(identity); 16476 } 16477 } 16478 } 16479 16480 private static void enforceSystemOrPhoneCaller(String tag) { 16481 int callingUid = Binder.getCallingUid(); 16482 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16483 throw new SecurityException( 16484 "Cannot call " + tag + " from UID " + callingUid); 16485 } 16486 } 16487} 16488