PackageManagerService.java revision aa41add33b8d7d318387cc74c34e3d347d245211
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.pm.Settings.VersionInfo; 228import com.android.server.storage.DeviceStorageMonitorInternal; 229 230import org.xmlpull.v1.XmlPullParser; 231import org.xmlpull.v1.XmlPullParserException; 232import org.xmlpull.v1.XmlSerializer; 233 234import java.io.BufferedInputStream; 235import java.io.BufferedOutputStream; 236import java.io.BufferedReader; 237import java.io.ByteArrayInputStream; 238import java.io.ByteArrayOutputStream; 239import java.io.File; 240import java.io.FileDescriptor; 241import java.io.FileNotFoundException; 242import java.io.FileOutputStream; 243import java.io.FileReader; 244import java.io.FilenameFilter; 245import java.io.IOException; 246import java.io.InputStream; 247import java.io.PrintWriter; 248import java.nio.charset.StandardCharsets; 249import java.security.NoSuchAlgorithmException; 250import java.security.PublicKey; 251import java.security.cert.CertificateEncodingException; 252import java.security.cert.CertificateException; 253import java.text.SimpleDateFormat; 254import java.util.ArrayList; 255import java.util.Arrays; 256import java.util.Collection; 257import java.util.Collections; 258import java.util.Comparator; 259import java.util.Date; 260import java.util.Iterator; 261import java.util.List; 262import java.util.Map; 263import java.util.Objects; 264import java.util.Set; 265import java.util.concurrent.CountDownLatch; 266import java.util.concurrent.TimeUnit; 267import java.util.concurrent.atomic.AtomicBoolean; 268import java.util.concurrent.atomic.AtomicInteger; 269import java.util.concurrent.atomic.AtomicLong; 270 271/** 272 * Keep track of all those .apks everywhere. 273 * 274 * This is very central to the platform's security; please run the unit 275 * tests whenever making modifications here: 276 * 277mmm frameworks/base/tests/AndroidTests 278adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 279adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 280 * 281 * {@hide} 282 */ 283public class PackageManagerService extends IPackageManager.Stub { 284 static final String TAG = "PackageManager"; 285 static final boolean DEBUG_SETTINGS = false; 286 static final boolean DEBUG_PREFERRED = false; 287 static final boolean DEBUG_UPGRADE = false; 288 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 289 private static final boolean DEBUG_BACKUP = false; 290 private static final boolean DEBUG_INSTALL = false; 291 private static final boolean DEBUG_REMOVE = false; 292 private static final boolean DEBUG_BROADCASTS = false; 293 private static final boolean DEBUG_SHOW_INFO = false; 294 private static final boolean DEBUG_PACKAGE_INFO = false; 295 private static final boolean DEBUG_INTENT_MATCHING = false; 296 private static final boolean DEBUG_PACKAGE_SCANNING = false; 297 private static final boolean DEBUG_VERIFY = false; 298 private static final boolean DEBUG_DEXOPT = false; 299 private static final boolean DEBUG_ABI_SELECTION = false; 300 301 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 302 303 private static final int RADIO_UID = Process.PHONE_UID; 304 private static final int LOG_UID = Process.LOG_UID; 305 private static final int NFC_UID = Process.NFC_UID; 306 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 307 private static final int SHELL_UID = Process.SHELL_UID; 308 309 // Cap the size of permission trees that 3rd party apps can define 310 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 311 312 // Suffix used during package installation when copying/moving 313 // package apks to install directory. 314 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 315 316 static final int SCAN_NO_DEX = 1<<1; 317 static final int SCAN_FORCE_DEX = 1<<2; 318 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 319 static final int SCAN_NEW_INSTALL = 1<<4; 320 static final int SCAN_NO_PATHS = 1<<5; 321 static final int SCAN_UPDATE_TIME = 1<<6; 322 static final int SCAN_DEFER_DEX = 1<<7; 323 static final int SCAN_BOOTING = 1<<8; 324 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 325 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 326 static final int SCAN_REPLACING = 1<<11; 327 static final int SCAN_REQUIRE_KNOWN = 1<<12; 328 static final int SCAN_MOVE = 1<<13; 329 static final int SCAN_INITIAL = 1<<14; 330 331 static final int REMOVE_CHATTY = 1<<16; 332 333 private static final int[] EMPTY_INT_ARRAY = new int[0]; 334 335 /** 336 * Timeout (in milliseconds) after which the watchdog should declare that 337 * our handler thread is wedged. The usual default for such things is one 338 * minute but we sometimes do very lengthy I/O operations on this thread, 339 * such as installing multi-gigabyte applications, so ours needs to be longer. 340 */ 341 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 342 343 /** 344 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 345 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 346 * settings entry if available, otherwise we use the hardcoded default. If it's been 347 * more than this long since the last fstrim, we force one during the boot sequence. 348 * 349 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 350 * one gets run at the next available charging+idle time. This final mandatory 351 * no-fstrim check kicks in only of the other scheduling criteria is never met. 352 */ 353 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 354 355 /** 356 * Whether verification is enabled by default. 357 */ 358 private static final boolean DEFAULT_VERIFY_ENABLE = true; 359 360 /** 361 * The default maximum time to wait for the verification agent to return in 362 * milliseconds. 363 */ 364 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 365 366 /** 367 * The default response for package verification timeout. 368 * 369 * This can be either PackageManager.VERIFICATION_ALLOW or 370 * PackageManager.VERIFICATION_REJECT. 371 */ 372 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 373 374 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 375 376 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 377 DEFAULT_CONTAINER_PACKAGE, 378 "com.android.defcontainer.DefaultContainerService"); 379 380 private static final String KILL_APP_REASON_GIDS_CHANGED = 381 "permission grant or revoke changed gids"; 382 383 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 384 "permissions revoked"; 385 386 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 387 388 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 389 390 /** Permission grant: not grant the permission. */ 391 private static final int GRANT_DENIED = 1; 392 393 /** Permission grant: grant the permission as an install permission. */ 394 private static final int GRANT_INSTALL = 2; 395 396 /** Permission grant: grant the permission as an install permission for a legacy app. */ 397 private static final int GRANT_INSTALL_LEGACY = 3; 398 399 /** Permission grant: grant the permission as a runtime one. */ 400 private static final int GRANT_RUNTIME = 4; 401 402 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 403 private static final int GRANT_UPGRADE = 5; 404 405 /** Canonical intent used to identify what counts as a "web browser" app */ 406 private static final Intent sBrowserIntent; 407 static { 408 sBrowserIntent = new Intent(); 409 sBrowserIntent.setAction(Intent.ACTION_VIEW); 410 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 411 sBrowserIntent.setData(Uri.parse("http:")); 412 } 413 414 final ServiceThread mHandlerThread; 415 416 final PackageHandler mHandler; 417 418 /** 419 * Messages for {@link #mHandler} that need to wait for system ready before 420 * being dispatched. 421 */ 422 private ArrayList<Message> mPostSystemReadyMessages; 423 424 final int mSdkVersion = Build.VERSION.SDK_INT; 425 426 final Context mContext; 427 final boolean mFactoryTest; 428 final boolean mOnlyCore; 429 final boolean mLazyDexOpt; 430 final long mDexOptLRUThresholdInMills; 431 final DisplayMetrics mMetrics; 432 final int mDefParseFlags; 433 final String[] mSeparateProcesses; 434 final boolean mIsUpgrade; 435 436 // This is where all application persistent data goes. 437 final File mAppDataDir; 438 439 // This is where all application persistent data goes for secondary users. 440 final File mUserAppDataDir; 441 442 /** The location for ASEC container files on internal storage. */ 443 final String mAsecInternalPath; 444 445 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 446 // LOCK HELD. Can be called with mInstallLock held. 447 @GuardedBy("mInstallLock") 448 final Installer mInstaller; 449 450 /** Directory where installed third-party apps stored */ 451 final File mAppInstallDir; 452 453 /** 454 * Directory to which applications installed internally have their 455 * 32 bit native libraries copied. 456 */ 457 private File mAppLib32InstallDir; 458 459 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 460 // apps. 461 final File mDrmAppPrivateInstallDir; 462 463 // ---------------------------------------------------------------- 464 465 // Lock for state used when installing and doing other long running 466 // operations. Methods that must be called with this lock held have 467 // the suffix "LI". 468 final Object mInstallLock = new Object(); 469 470 // ---------------------------------------------------------------- 471 472 // Keys are String (package name), values are Package. This also serves 473 // as the lock for the global state. Methods that must be called with 474 // this lock held have the prefix "LP". 475 @GuardedBy("mPackages") 476 final ArrayMap<String, PackageParser.Package> mPackages = 477 new ArrayMap<String, PackageParser.Package>(); 478 479 // Tracks available target package names -> overlay package paths. 480 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 481 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 482 483 /** 484 * Tracks new system packages [receiving in an OTA] that we expect to 485 * find updated user-installed versions. Keys are package name, values 486 * are package location. 487 */ 488 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 489 490 final Settings mSettings; 491 boolean mRestoredSettings; 492 493 // System configuration read by SystemConfig. 494 final int[] mGlobalGids; 495 final SparseArray<ArraySet<String>> mSystemPermissions; 496 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 497 498 // If mac_permissions.xml was found for seinfo labeling. 499 boolean mFoundPolicyFile; 500 501 // If a recursive restorecon of /data/data/<pkg> is needed. 502 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 503 504 public static final class SharedLibraryEntry { 505 public final String path; 506 public final String apk; 507 508 SharedLibraryEntry(String _path, String _apk) { 509 path = _path; 510 apk = _apk; 511 } 512 } 513 514 // Currently known shared libraries. 515 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 516 new ArrayMap<String, SharedLibraryEntry>(); 517 518 // All available activities, for your resolving pleasure. 519 final ActivityIntentResolver mActivities = 520 new ActivityIntentResolver(); 521 522 // All available receivers, for your resolving pleasure. 523 final ActivityIntentResolver mReceivers = 524 new ActivityIntentResolver(); 525 526 // All available services, for your resolving pleasure. 527 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 528 529 // All available providers, for your resolving pleasure. 530 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 531 532 // Mapping from provider base names (first directory in content URI codePath) 533 // to the provider information. 534 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 535 new ArrayMap<String, PackageParser.Provider>(); 536 537 // Mapping from instrumentation class names to info about them. 538 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 539 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 540 541 // Mapping from permission names to info about them. 542 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 543 new ArrayMap<String, PackageParser.PermissionGroup>(); 544 545 // Packages whose data we have transfered into another package, thus 546 // should no longer exist. 547 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 548 549 // Broadcast actions that are only available to the system. 550 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 551 552 /** List of packages waiting for verification. */ 553 final SparseArray<PackageVerificationState> mPendingVerification 554 = new SparseArray<PackageVerificationState>(); 555 556 /** Set of packages associated with each app op permission. */ 557 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 558 559 final PackageInstallerService mInstallerService; 560 561 private final PackageDexOptimizer mPackageDexOptimizer; 562 563 private AtomicInteger mNextMoveId = new AtomicInteger(); 564 private final MoveCallbacks mMoveCallbacks; 565 566 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 567 568 // Cache of users who need badging. 569 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 570 571 /** Token for keys in mPendingVerification. */ 572 private int mPendingVerificationToken = 0; 573 574 volatile boolean mSystemReady; 575 volatile boolean mSafeMode; 576 volatile boolean mHasSystemUidErrors; 577 578 ApplicationInfo mAndroidApplication; 579 final ActivityInfo mResolveActivity = new ActivityInfo(); 580 final ResolveInfo mResolveInfo = new ResolveInfo(); 581 ComponentName mResolveComponentName; 582 PackageParser.Package mPlatformPackage; 583 ComponentName mCustomResolverComponentName; 584 585 boolean mResolverReplaced = false; 586 587 private final ComponentName mIntentFilterVerifierComponent; 588 private int mIntentFilterVerificationToken = 0; 589 590 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 591 = new SparseArray<IntentFilterVerificationState>(); 592 593 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 594 new DefaultPermissionGrantPolicy(this); 595 596 private static class IFVerificationParams { 597 PackageParser.Package pkg; 598 boolean replacing; 599 int userId; 600 int verifierUid; 601 602 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 603 int _userId, int _verifierUid) { 604 pkg = _pkg; 605 replacing = _replacing; 606 userId = _userId; 607 replacing = _replacing; 608 verifierUid = _verifierUid; 609 } 610 } 611 612 private interface IntentFilterVerifier<T extends IntentFilter> { 613 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 614 T filter, String packageName); 615 void startVerifications(int userId); 616 void receiveVerificationResponse(int verificationId); 617 } 618 619 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 620 private Context mContext; 621 private ComponentName mIntentFilterVerifierComponent; 622 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 623 624 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 625 mContext = context; 626 mIntentFilterVerifierComponent = verifierComponent; 627 } 628 629 private String getDefaultScheme() { 630 return IntentFilter.SCHEME_HTTPS; 631 } 632 633 @Override 634 public void startVerifications(int userId) { 635 // Launch verifications requests 636 int count = mCurrentIntentFilterVerifications.size(); 637 for (int n=0; n<count; n++) { 638 int verificationId = mCurrentIntentFilterVerifications.get(n); 639 final IntentFilterVerificationState ivs = 640 mIntentFilterVerificationStates.get(verificationId); 641 642 String packageName = ivs.getPackageName(); 643 644 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 645 final int filterCount = filters.size(); 646 ArraySet<String> domainsSet = new ArraySet<>(); 647 for (int m=0; m<filterCount; m++) { 648 PackageParser.ActivityIntentInfo filter = filters.get(m); 649 domainsSet.addAll(filter.getHostsList()); 650 } 651 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 652 synchronized (mPackages) { 653 if (mSettings.createIntentFilterVerificationIfNeededLPw( 654 packageName, domainsList) != null) { 655 scheduleWriteSettingsLocked(); 656 } 657 } 658 sendVerificationRequest(userId, verificationId, ivs); 659 } 660 mCurrentIntentFilterVerifications.clear(); 661 } 662 663 private void sendVerificationRequest(int userId, int verificationId, 664 IntentFilterVerificationState ivs) { 665 666 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 667 verificationIntent.putExtra( 668 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 669 verificationId); 670 verificationIntent.putExtra( 671 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 672 getDefaultScheme()); 673 verificationIntent.putExtra( 674 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 675 ivs.getHostsString()); 676 verificationIntent.putExtra( 677 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 678 ivs.getPackageName()); 679 verificationIntent.setComponent(mIntentFilterVerifierComponent); 680 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 681 682 UserHandle user = new UserHandle(userId); 683 mContext.sendBroadcastAsUser(verificationIntent, user); 684 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 685 "Sending IntentFilter verification broadcast"); 686 } 687 688 public void receiveVerificationResponse(int verificationId) { 689 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 690 691 final boolean verified = ivs.isVerified(); 692 693 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 694 final int count = filters.size(); 695 if (DEBUG_DOMAIN_VERIFICATION) { 696 Slog.i(TAG, "Received verification response " + verificationId 697 + " for " + count + " filters, verified=" + verified); 698 } 699 for (int n=0; n<count; n++) { 700 PackageParser.ActivityIntentInfo filter = filters.get(n); 701 filter.setVerified(verified); 702 703 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 704 + " verified with result:" + verified + " and hosts:" 705 + ivs.getHostsString()); 706 } 707 708 mIntentFilterVerificationStates.remove(verificationId); 709 710 final String packageName = ivs.getPackageName(); 711 IntentFilterVerificationInfo ivi = null; 712 713 synchronized (mPackages) { 714 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 715 } 716 if (ivi == null) { 717 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 718 + verificationId + " packageName:" + packageName); 719 return; 720 } 721 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 722 "Updating IntentFilterVerificationInfo for package " + packageName 723 +" verificationId:" + verificationId); 724 725 synchronized (mPackages) { 726 if (verified) { 727 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 728 } else { 729 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 730 } 731 scheduleWriteSettingsLocked(); 732 733 final int userId = ivs.getUserId(); 734 if (userId != UserHandle.USER_ALL) { 735 final int userStatus = 736 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 737 738 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 739 boolean needUpdate = false; 740 741 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 742 // already been set by the User thru the Disambiguation dialog 743 switch (userStatus) { 744 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 745 if (verified) { 746 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 747 } else { 748 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 749 } 750 needUpdate = true; 751 break; 752 753 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 754 if (verified) { 755 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 756 needUpdate = true; 757 } 758 break; 759 760 default: 761 // Nothing to do 762 } 763 764 if (needUpdate) { 765 mSettings.updateIntentFilterVerificationStatusLPw( 766 packageName, updatedStatus, userId); 767 scheduleWritePackageRestrictionsLocked(userId); 768 } 769 } 770 } 771 } 772 773 @Override 774 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 775 ActivityIntentInfo filter, String packageName) { 776 if (!hasValidDomains(filter)) { 777 return false; 778 } 779 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 780 if (ivs == null) { 781 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 782 packageName); 783 } 784 if (DEBUG_DOMAIN_VERIFICATION) { 785 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 786 } 787 ivs.addFilter(filter); 788 return true; 789 } 790 791 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 792 int userId, int verificationId, String packageName) { 793 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 794 verifierUid, userId, packageName); 795 ivs.setPendingState(); 796 synchronized (mPackages) { 797 mIntentFilterVerificationStates.append(verificationId, ivs); 798 mCurrentIntentFilterVerifications.add(verificationId); 799 } 800 return ivs; 801 } 802 } 803 804 private static boolean hasValidDomains(ActivityIntentInfo filter) { 805 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 806 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 807 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 808 } 809 810 private IntentFilterVerifier mIntentFilterVerifier; 811 812 // Set of pending broadcasts for aggregating enable/disable of components. 813 static class PendingPackageBroadcasts { 814 // for each user id, a map of <package name -> components within that package> 815 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 816 817 public PendingPackageBroadcasts() { 818 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 819 } 820 821 public ArrayList<String> get(int userId, String packageName) { 822 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 823 return packages.get(packageName); 824 } 825 826 public void put(int userId, String packageName, ArrayList<String> components) { 827 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 828 packages.put(packageName, components); 829 } 830 831 public void remove(int userId, String packageName) { 832 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 833 if (packages != null) { 834 packages.remove(packageName); 835 } 836 } 837 838 public void remove(int userId) { 839 mUidMap.remove(userId); 840 } 841 842 public int userIdCount() { 843 return mUidMap.size(); 844 } 845 846 public int userIdAt(int n) { 847 return mUidMap.keyAt(n); 848 } 849 850 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 851 return mUidMap.get(userId); 852 } 853 854 public int size() { 855 // total number of pending broadcast entries across all userIds 856 int num = 0; 857 for (int i = 0; i< mUidMap.size(); i++) { 858 num += mUidMap.valueAt(i).size(); 859 } 860 return num; 861 } 862 863 public void clear() { 864 mUidMap.clear(); 865 } 866 867 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 868 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 869 if (map == null) { 870 map = new ArrayMap<String, ArrayList<String>>(); 871 mUidMap.put(userId, map); 872 } 873 return map; 874 } 875 } 876 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 877 878 // Service Connection to remote media container service to copy 879 // package uri's from external media onto secure containers 880 // or internal storage. 881 private IMediaContainerService mContainerService = null; 882 883 static final int SEND_PENDING_BROADCAST = 1; 884 static final int MCS_BOUND = 3; 885 static final int END_COPY = 4; 886 static final int INIT_COPY = 5; 887 static final int MCS_UNBIND = 6; 888 static final int START_CLEANING_PACKAGE = 7; 889 static final int FIND_INSTALL_LOC = 8; 890 static final int POST_INSTALL = 9; 891 static final int MCS_RECONNECT = 10; 892 static final int MCS_GIVE_UP = 11; 893 static final int UPDATED_MEDIA_STATUS = 12; 894 static final int WRITE_SETTINGS = 13; 895 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 896 static final int PACKAGE_VERIFIED = 15; 897 static final int CHECK_PENDING_VERIFICATION = 16; 898 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 899 static final int INTENT_FILTER_VERIFIED = 18; 900 901 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 902 903 // Delay time in millisecs 904 static final int BROADCAST_DELAY = 10 * 1000; 905 906 static UserManagerService sUserManager; 907 908 // Stores a list of users whose package restrictions file needs to be updated 909 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 910 911 final private DefaultContainerConnection mDefContainerConn = 912 new DefaultContainerConnection(); 913 class DefaultContainerConnection implements ServiceConnection { 914 public void onServiceConnected(ComponentName name, IBinder service) { 915 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 916 IMediaContainerService imcs = 917 IMediaContainerService.Stub.asInterface(service); 918 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 919 } 920 921 public void onServiceDisconnected(ComponentName name) { 922 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 923 } 924 } 925 926 // Recordkeeping of restore-after-install operations that are currently in flight 927 // between the Package Manager and the Backup Manager 928 class PostInstallData { 929 public InstallArgs args; 930 public PackageInstalledInfo res; 931 932 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 933 args = _a; 934 res = _r; 935 } 936 } 937 938 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 939 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 940 941 // XML tags for backup/restore of various bits of state 942 private static final String TAG_PREFERRED_BACKUP = "pa"; 943 private static final String TAG_DEFAULT_APPS = "da"; 944 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 945 946 final String mRequiredVerifierPackage; 947 final String mRequiredInstallerPackage; 948 949 private final PackageUsage mPackageUsage = new PackageUsage(); 950 951 private class PackageUsage { 952 private static final int WRITE_INTERVAL 953 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 954 955 private final Object mFileLock = new Object(); 956 private final AtomicLong mLastWritten = new AtomicLong(0); 957 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 958 959 private boolean mIsHistoricalPackageUsageAvailable = true; 960 961 boolean isHistoricalPackageUsageAvailable() { 962 return mIsHistoricalPackageUsageAvailable; 963 } 964 965 void write(boolean force) { 966 if (force) { 967 writeInternal(); 968 return; 969 } 970 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 971 && !DEBUG_DEXOPT) { 972 return; 973 } 974 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 975 new Thread("PackageUsage_DiskWriter") { 976 @Override 977 public void run() { 978 try { 979 writeInternal(); 980 } finally { 981 mBackgroundWriteRunning.set(false); 982 } 983 } 984 }.start(); 985 } 986 } 987 988 private void writeInternal() { 989 synchronized (mPackages) { 990 synchronized (mFileLock) { 991 AtomicFile file = getFile(); 992 FileOutputStream f = null; 993 try { 994 f = file.startWrite(); 995 BufferedOutputStream out = new BufferedOutputStream(f); 996 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 997 StringBuilder sb = new StringBuilder(); 998 for (PackageParser.Package pkg : mPackages.values()) { 999 if (pkg.mLastPackageUsageTimeInMills == 0) { 1000 continue; 1001 } 1002 sb.setLength(0); 1003 sb.append(pkg.packageName); 1004 sb.append(' '); 1005 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1006 sb.append('\n'); 1007 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1008 } 1009 out.flush(); 1010 file.finishWrite(f); 1011 } catch (IOException e) { 1012 if (f != null) { 1013 file.failWrite(f); 1014 } 1015 Log.e(TAG, "Failed to write package usage times", e); 1016 } 1017 } 1018 } 1019 mLastWritten.set(SystemClock.elapsedRealtime()); 1020 } 1021 1022 void readLP() { 1023 synchronized (mFileLock) { 1024 AtomicFile file = getFile(); 1025 BufferedInputStream in = null; 1026 try { 1027 in = new BufferedInputStream(file.openRead()); 1028 StringBuffer sb = new StringBuffer(); 1029 while (true) { 1030 String packageName = readToken(in, sb, ' '); 1031 if (packageName == null) { 1032 break; 1033 } 1034 String timeInMillisString = readToken(in, sb, '\n'); 1035 if (timeInMillisString == null) { 1036 throw new IOException("Failed to find last usage time for package " 1037 + packageName); 1038 } 1039 PackageParser.Package pkg = mPackages.get(packageName); 1040 if (pkg == null) { 1041 continue; 1042 } 1043 long timeInMillis; 1044 try { 1045 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1046 } catch (NumberFormatException e) { 1047 throw new IOException("Failed to parse " + timeInMillisString 1048 + " as a long.", e); 1049 } 1050 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1051 } 1052 } catch (FileNotFoundException expected) { 1053 mIsHistoricalPackageUsageAvailable = false; 1054 } catch (IOException e) { 1055 Log.w(TAG, "Failed to read package usage times", e); 1056 } finally { 1057 IoUtils.closeQuietly(in); 1058 } 1059 } 1060 mLastWritten.set(SystemClock.elapsedRealtime()); 1061 } 1062 1063 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1064 throws IOException { 1065 sb.setLength(0); 1066 while (true) { 1067 int ch = in.read(); 1068 if (ch == -1) { 1069 if (sb.length() == 0) { 1070 return null; 1071 } 1072 throw new IOException("Unexpected EOF"); 1073 } 1074 if (ch == endOfToken) { 1075 return sb.toString(); 1076 } 1077 sb.append((char)ch); 1078 } 1079 } 1080 1081 private AtomicFile getFile() { 1082 File dataDir = Environment.getDataDirectory(); 1083 File systemDir = new File(dataDir, "system"); 1084 File fname = new File(systemDir, "package-usage.list"); 1085 return new AtomicFile(fname); 1086 } 1087 } 1088 1089 class PackageHandler extends Handler { 1090 private boolean mBound = false; 1091 final ArrayList<HandlerParams> mPendingInstalls = 1092 new ArrayList<HandlerParams>(); 1093 1094 private boolean connectToService() { 1095 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1096 " DefaultContainerService"); 1097 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1098 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1099 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1100 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1101 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1102 mBound = true; 1103 return true; 1104 } 1105 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1106 return false; 1107 } 1108 1109 private void disconnectService() { 1110 mContainerService = null; 1111 mBound = false; 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1113 mContext.unbindService(mDefContainerConn); 1114 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1115 } 1116 1117 PackageHandler(Looper looper) { 1118 super(looper); 1119 } 1120 1121 public void handleMessage(Message msg) { 1122 try { 1123 doHandleMessage(msg); 1124 } finally { 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } 1127 } 1128 1129 void doHandleMessage(Message msg) { 1130 switch (msg.what) { 1131 case INIT_COPY: { 1132 HandlerParams params = (HandlerParams) msg.obj; 1133 int idx = mPendingInstalls.size(); 1134 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1135 // If a bind was already initiated we dont really 1136 // need to do anything. The pending install 1137 // will be processed later on. 1138 if (!mBound) { 1139 // If this is the only one pending we might 1140 // have to bind to the service again. 1141 if (!connectToService()) { 1142 Slog.e(TAG, "Failed to bind to media container service"); 1143 params.serviceError(); 1144 return; 1145 } else { 1146 // Once we bind to the service, the first 1147 // pending request will be processed. 1148 mPendingInstalls.add(idx, params); 1149 } 1150 } else { 1151 mPendingInstalls.add(idx, params); 1152 // Already bound to the service. Just make 1153 // sure we trigger off processing the first request. 1154 if (idx == 0) { 1155 mHandler.sendEmptyMessage(MCS_BOUND); 1156 } 1157 } 1158 break; 1159 } 1160 case MCS_BOUND: { 1161 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1162 if (msg.obj != null) { 1163 mContainerService = (IMediaContainerService) msg.obj; 1164 } 1165 if (mContainerService == null) { 1166 if (!mBound) { 1167 // Something seriously wrong since we are not bound and we are not 1168 // waiting for connection. Bail out. 1169 Slog.e(TAG, "Cannot bind to media container service"); 1170 for (HandlerParams params : mPendingInstalls) { 1171 // Indicate service bind error 1172 params.serviceError(); 1173 } 1174 mPendingInstalls.clear(); 1175 } else { 1176 Slog.w(TAG, "Waiting to connect to media container service"); 1177 } 1178 } else if (mPendingInstalls.size() > 0) { 1179 HandlerParams params = mPendingInstalls.get(0); 1180 if (params != null) { 1181 if (params.startCopy()) { 1182 // We are done... look for more work or to 1183 // go idle. 1184 if (DEBUG_SD_INSTALL) Log.i(TAG, 1185 "Checking for more work or unbind..."); 1186 // Delete pending install 1187 if (mPendingInstalls.size() > 0) { 1188 mPendingInstalls.remove(0); 1189 } 1190 if (mPendingInstalls.size() == 0) { 1191 if (mBound) { 1192 if (DEBUG_SD_INSTALL) Log.i(TAG, 1193 "Posting delayed MCS_UNBIND"); 1194 removeMessages(MCS_UNBIND); 1195 Message ubmsg = obtainMessage(MCS_UNBIND); 1196 // Unbind after a little delay, to avoid 1197 // continual thrashing. 1198 sendMessageDelayed(ubmsg, 10000); 1199 } 1200 } else { 1201 // There are more pending requests in queue. 1202 // Just post MCS_BOUND message to trigger processing 1203 // of next pending install. 1204 if (DEBUG_SD_INSTALL) Log.i(TAG, 1205 "Posting MCS_BOUND for next work"); 1206 mHandler.sendEmptyMessage(MCS_BOUND); 1207 } 1208 } 1209 } 1210 } else { 1211 // Should never happen ideally. 1212 Slog.w(TAG, "Empty queue"); 1213 } 1214 break; 1215 } 1216 case MCS_RECONNECT: { 1217 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1218 if (mPendingInstalls.size() > 0) { 1219 if (mBound) { 1220 disconnectService(); 1221 } 1222 if (!connectToService()) { 1223 Slog.e(TAG, "Failed to bind to media container service"); 1224 for (HandlerParams params : mPendingInstalls) { 1225 // Indicate service bind error 1226 params.serviceError(); 1227 } 1228 mPendingInstalls.clear(); 1229 } 1230 } 1231 break; 1232 } 1233 case MCS_UNBIND: { 1234 // If there is no actual work left, then time to unbind. 1235 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1236 1237 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1238 if (mBound) { 1239 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1240 1241 disconnectService(); 1242 } 1243 } else if (mPendingInstalls.size() > 0) { 1244 // There are more pending requests in queue. 1245 // Just post MCS_BOUND message to trigger processing 1246 // of next pending install. 1247 mHandler.sendEmptyMessage(MCS_BOUND); 1248 } 1249 1250 break; 1251 } 1252 case MCS_GIVE_UP: { 1253 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1254 mPendingInstalls.remove(0); 1255 break; 1256 } 1257 case SEND_PENDING_BROADCAST: { 1258 String packages[]; 1259 ArrayList<String> components[]; 1260 int size = 0; 1261 int uids[]; 1262 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1263 synchronized (mPackages) { 1264 if (mPendingBroadcasts == null) { 1265 return; 1266 } 1267 size = mPendingBroadcasts.size(); 1268 if (size <= 0) { 1269 // Nothing to be done. Just return 1270 return; 1271 } 1272 packages = new String[size]; 1273 components = new ArrayList[size]; 1274 uids = new int[size]; 1275 int i = 0; // filling out the above arrays 1276 1277 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1278 int packageUserId = mPendingBroadcasts.userIdAt(n); 1279 Iterator<Map.Entry<String, ArrayList<String>>> it 1280 = mPendingBroadcasts.packagesForUserId(packageUserId) 1281 .entrySet().iterator(); 1282 while (it.hasNext() && i < size) { 1283 Map.Entry<String, ArrayList<String>> ent = it.next(); 1284 packages[i] = ent.getKey(); 1285 components[i] = ent.getValue(); 1286 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1287 uids[i] = (ps != null) 1288 ? UserHandle.getUid(packageUserId, ps.appId) 1289 : -1; 1290 i++; 1291 } 1292 } 1293 size = i; 1294 mPendingBroadcasts.clear(); 1295 } 1296 // Send broadcasts 1297 for (int i = 0; i < size; i++) { 1298 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1299 } 1300 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1301 break; 1302 } 1303 case START_CLEANING_PACKAGE: { 1304 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1305 final String packageName = (String)msg.obj; 1306 final int userId = msg.arg1; 1307 final boolean andCode = msg.arg2 != 0; 1308 synchronized (mPackages) { 1309 if (userId == UserHandle.USER_ALL) { 1310 int[] users = sUserManager.getUserIds(); 1311 for (int user : users) { 1312 mSettings.addPackageToCleanLPw( 1313 new PackageCleanItem(user, packageName, andCode)); 1314 } 1315 } else { 1316 mSettings.addPackageToCleanLPw( 1317 new PackageCleanItem(userId, packageName, andCode)); 1318 } 1319 } 1320 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1321 startCleaningPackages(); 1322 } break; 1323 case POST_INSTALL: { 1324 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1325 PostInstallData data = mRunningInstalls.get(msg.arg1); 1326 mRunningInstalls.delete(msg.arg1); 1327 boolean deleteOld = false; 1328 1329 if (data != null) { 1330 InstallArgs args = data.args; 1331 PackageInstalledInfo res = data.res; 1332 1333 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1334 final String packageName = res.pkg.applicationInfo.packageName; 1335 res.removedInfo.sendBroadcast(false, true, false); 1336 Bundle extras = new Bundle(1); 1337 extras.putInt(Intent.EXTRA_UID, res.uid); 1338 1339 // Now that we successfully installed the package, grant runtime 1340 // permissions if requested before broadcasting the install. 1341 if ((args.installFlags 1342 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1343 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1344 args.installGrantPermissions); 1345 } 1346 1347 // Determine the set of users who are adding this 1348 // package for the first time vs. those who are seeing 1349 // an update. 1350 int[] firstUsers; 1351 int[] updateUsers = new int[0]; 1352 if (res.origUsers == null || res.origUsers.length == 0) { 1353 firstUsers = res.newUsers; 1354 } else { 1355 firstUsers = new int[0]; 1356 for (int i=0; i<res.newUsers.length; i++) { 1357 int user = res.newUsers[i]; 1358 boolean isNew = true; 1359 for (int j=0; j<res.origUsers.length; j++) { 1360 if (res.origUsers[j] == user) { 1361 isNew = false; 1362 break; 1363 } 1364 } 1365 if (isNew) { 1366 int[] newFirst = new int[firstUsers.length+1]; 1367 System.arraycopy(firstUsers, 0, newFirst, 0, 1368 firstUsers.length); 1369 newFirst[firstUsers.length] = user; 1370 firstUsers = newFirst; 1371 } else { 1372 int[] newUpdate = new int[updateUsers.length+1]; 1373 System.arraycopy(updateUsers, 0, newUpdate, 0, 1374 updateUsers.length); 1375 newUpdate[updateUsers.length] = user; 1376 updateUsers = newUpdate; 1377 } 1378 } 1379 } 1380 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1381 packageName, extras, null, null, firstUsers); 1382 final boolean update = res.removedInfo.removedPackage != null; 1383 if (update) { 1384 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1385 } 1386 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1387 packageName, extras, null, null, updateUsers); 1388 if (update) { 1389 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1390 packageName, extras, null, null, updateUsers); 1391 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1392 null, null, packageName, null, updateUsers); 1393 1394 // treat asec-hosted packages like removable media on upgrade 1395 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1396 if (DEBUG_INSTALL) { 1397 Slog.i(TAG, "upgrading pkg " + res.pkg 1398 + " is ASEC-hosted -> AVAILABLE"); 1399 } 1400 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1401 ArrayList<String> pkgList = new ArrayList<String>(1); 1402 pkgList.add(packageName); 1403 sendResourcesChangedBroadcast(true, true, 1404 pkgList,uidArray, null); 1405 } 1406 } 1407 if (res.removedInfo.args != null) { 1408 // Remove the replaced package's older resources safely now 1409 deleteOld = true; 1410 } 1411 1412 // If this app is a browser and it's newly-installed for some 1413 // users, clear any default-browser state in those users 1414 if (firstUsers.length > 0) { 1415 // the app's nature doesn't depend on the user, so we can just 1416 // check its browser nature in any user and generalize. 1417 if (packageIsBrowser(packageName, firstUsers[0])) { 1418 synchronized (mPackages) { 1419 for (int userId : firstUsers) { 1420 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1421 } 1422 } 1423 } 1424 } 1425 // Log current value of "unknown sources" setting 1426 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1427 getUnknownSourcesSettings()); 1428 } 1429 // Force a gc to clear up things 1430 Runtime.getRuntime().gc(); 1431 // We delete after a gc for applications on sdcard. 1432 if (deleteOld) { 1433 synchronized (mInstallLock) { 1434 res.removedInfo.args.doPostDeleteLI(true); 1435 } 1436 } 1437 if (args.observer != null) { 1438 try { 1439 Bundle extras = extrasForInstallResult(res); 1440 args.observer.onPackageInstalled(res.name, res.returnCode, 1441 res.returnMsg, extras); 1442 } catch (RemoteException e) { 1443 Slog.i(TAG, "Observer no longer exists."); 1444 } 1445 } 1446 } else { 1447 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1448 } 1449 } break; 1450 case UPDATED_MEDIA_STATUS: { 1451 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1452 boolean reportStatus = msg.arg1 == 1; 1453 boolean doGc = msg.arg2 == 1; 1454 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1455 if (doGc) { 1456 // Force a gc to clear up stale containers. 1457 Runtime.getRuntime().gc(); 1458 } 1459 if (msg.obj != null) { 1460 @SuppressWarnings("unchecked") 1461 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1462 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1463 // Unload containers 1464 unloadAllContainers(args); 1465 } 1466 if (reportStatus) { 1467 try { 1468 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1469 PackageHelper.getMountService().finishMediaUpdate(); 1470 } catch (RemoteException e) { 1471 Log.e(TAG, "MountService not running?"); 1472 } 1473 } 1474 } break; 1475 case WRITE_SETTINGS: { 1476 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1477 synchronized (mPackages) { 1478 removeMessages(WRITE_SETTINGS); 1479 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1480 mSettings.writeLPr(); 1481 mDirtyUsers.clear(); 1482 } 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1484 } break; 1485 case WRITE_PACKAGE_RESTRICTIONS: { 1486 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1487 synchronized (mPackages) { 1488 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1489 for (int userId : mDirtyUsers) { 1490 mSettings.writePackageRestrictionsLPr(userId); 1491 } 1492 mDirtyUsers.clear(); 1493 } 1494 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1495 } break; 1496 case CHECK_PENDING_VERIFICATION: { 1497 final int verificationId = msg.arg1; 1498 final PackageVerificationState state = mPendingVerification.get(verificationId); 1499 1500 if ((state != null) && !state.timeoutExtended()) { 1501 final InstallArgs args = state.getInstallArgs(); 1502 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1503 1504 Slog.i(TAG, "Verification timed out for " + originUri); 1505 mPendingVerification.remove(verificationId); 1506 1507 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1508 1509 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1510 Slog.i(TAG, "Continuing with installation of " + originUri); 1511 state.setVerifierResponse(Binder.getCallingUid(), 1512 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1513 broadcastPackageVerified(verificationId, originUri, 1514 PackageManager.VERIFICATION_ALLOW, 1515 state.getInstallArgs().getUser()); 1516 try { 1517 ret = args.copyApk(mContainerService, true); 1518 } catch (RemoteException e) { 1519 Slog.e(TAG, "Could not contact the ContainerService"); 1520 } 1521 } else { 1522 broadcastPackageVerified(verificationId, originUri, 1523 PackageManager.VERIFICATION_REJECT, 1524 state.getInstallArgs().getUser()); 1525 } 1526 1527 processPendingInstall(args, ret); 1528 mHandler.sendEmptyMessage(MCS_UNBIND); 1529 } 1530 break; 1531 } 1532 case PACKAGE_VERIFIED: { 1533 final int verificationId = msg.arg1; 1534 1535 final PackageVerificationState state = mPendingVerification.get(verificationId); 1536 if (state == null) { 1537 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1538 break; 1539 } 1540 1541 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1542 1543 state.setVerifierResponse(response.callerUid, response.code); 1544 1545 if (state.isVerificationComplete()) { 1546 mPendingVerification.remove(verificationId); 1547 1548 final InstallArgs args = state.getInstallArgs(); 1549 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1550 1551 int ret; 1552 if (state.isInstallAllowed()) { 1553 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1554 broadcastPackageVerified(verificationId, originUri, 1555 response.code, state.getInstallArgs().getUser()); 1556 try { 1557 ret = args.copyApk(mContainerService, true); 1558 } catch (RemoteException e) { 1559 Slog.e(TAG, "Could not contact the ContainerService"); 1560 } 1561 } else { 1562 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1563 } 1564 1565 processPendingInstall(args, ret); 1566 1567 mHandler.sendEmptyMessage(MCS_UNBIND); 1568 } 1569 1570 break; 1571 } 1572 case START_INTENT_FILTER_VERIFICATIONS: { 1573 IFVerificationParams params = (IFVerificationParams) msg.obj; 1574 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1575 params.replacing, params.pkg); 1576 break; 1577 } 1578 case INTENT_FILTER_VERIFIED: { 1579 final int verificationId = msg.arg1; 1580 1581 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1582 verificationId); 1583 if (state == null) { 1584 Slog.w(TAG, "Invalid IntentFilter verification token " 1585 + verificationId + " received"); 1586 break; 1587 } 1588 1589 final int userId = state.getUserId(); 1590 1591 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1592 "Processing IntentFilter verification with token:" 1593 + verificationId + " and userId:" + userId); 1594 1595 final IntentFilterVerificationResponse response = 1596 (IntentFilterVerificationResponse) msg.obj; 1597 1598 state.setVerifierResponse(response.callerUid, response.code); 1599 1600 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1601 "IntentFilter verification with token:" + verificationId 1602 + " and userId:" + userId 1603 + " is settings verifier response with response code:" 1604 + response.code); 1605 1606 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1607 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1608 + response.getFailedDomainsString()); 1609 } 1610 1611 if (state.isVerificationComplete()) { 1612 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1613 } else { 1614 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1615 "IntentFilter verification with token:" + verificationId 1616 + " was not said to be complete"); 1617 } 1618 1619 break; 1620 } 1621 } 1622 } 1623 } 1624 1625 private StorageEventListener mStorageListener = new StorageEventListener() { 1626 @Override 1627 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1628 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1629 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1630 final String volumeUuid = vol.getFsUuid(); 1631 1632 // Clean up any users or apps that were removed or recreated 1633 // while this volume was missing 1634 reconcileUsers(volumeUuid); 1635 reconcileApps(volumeUuid); 1636 1637 // Clean up any install sessions that expired or were 1638 // cancelled while this volume was missing 1639 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1640 1641 loadPrivatePackages(vol); 1642 1643 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1644 unloadPrivatePackages(vol); 1645 } 1646 } 1647 1648 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1649 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1650 updateExternalMediaStatus(true, false); 1651 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1652 updateExternalMediaStatus(false, false); 1653 } 1654 } 1655 } 1656 1657 @Override 1658 public void onVolumeForgotten(String fsUuid) { 1659 if (TextUtils.isEmpty(fsUuid)) { 1660 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1661 return; 1662 } 1663 1664 // Remove any apps installed on the forgotten volume 1665 synchronized (mPackages) { 1666 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1667 for (PackageSetting ps : packages) { 1668 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1669 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1670 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1671 } 1672 1673 mSettings.onVolumeForgotten(fsUuid); 1674 mSettings.writeLPr(); 1675 } 1676 } 1677 }; 1678 1679 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1680 String[] grantedPermissions) { 1681 if (userId >= UserHandle.USER_OWNER) { 1682 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1683 } else if (userId == UserHandle.USER_ALL) { 1684 final int[] userIds; 1685 synchronized (mPackages) { 1686 userIds = UserManagerService.getInstance().getUserIds(); 1687 } 1688 for (int someUserId : userIds) { 1689 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1690 } 1691 } 1692 1693 // We could have touched GID membership, so flush out packages.list 1694 synchronized (mPackages) { 1695 mSettings.writePackageListLPr(); 1696 } 1697 } 1698 1699 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1700 String[] grantedPermissions) { 1701 SettingBase sb = (SettingBase) pkg.mExtras; 1702 if (sb == null) { 1703 return; 1704 } 1705 1706 PermissionsState permissionsState = sb.getPermissionsState(); 1707 1708 for (String permission : pkg.requestedPermissions) { 1709 BasePermission bp = mSettings.mPermissions.get(permission); 1710 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1711 || ArrayUtils.contains(grantedPermissions, permission))) { 1712 permissionsState.grantRuntimePermission(bp, userId); 1713 } 1714 } 1715 } 1716 1717 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1718 Bundle extras = null; 1719 switch (res.returnCode) { 1720 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1721 extras = new Bundle(); 1722 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1723 res.origPermission); 1724 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1725 res.origPackage); 1726 break; 1727 } 1728 case PackageManager.INSTALL_SUCCEEDED: { 1729 extras = new Bundle(); 1730 extras.putBoolean(Intent.EXTRA_REPLACING, 1731 res.removedInfo != null && res.removedInfo.removedPackage != null); 1732 break; 1733 } 1734 } 1735 return extras; 1736 } 1737 1738 void scheduleWriteSettingsLocked() { 1739 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1740 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1741 } 1742 } 1743 1744 void scheduleWritePackageRestrictionsLocked(int userId) { 1745 if (!sUserManager.exists(userId)) return; 1746 mDirtyUsers.add(userId); 1747 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1748 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1749 } 1750 } 1751 1752 public static PackageManagerService main(Context context, Installer installer, 1753 boolean factoryTest, boolean onlyCore) { 1754 PackageManagerService m = new PackageManagerService(context, installer, 1755 factoryTest, onlyCore); 1756 ServiceManager.addService("package", m); 1757 return m; 1758 } 1759 1760 static String[] splitString(String str, char sep) { 1761 int count = 1; 1762 int i = 0; 1763 while ((i=str.indexOf(sep, i)) >= 0) { 1764 count++; 1765 i++; 1766 } 1767 1768 String[] res = new String[count]; 1769 i=0; 1770 count = 0; 1771 int lastI=0; 1772 while ((i=str.indexOf(sep, i)) >= 0) { 1773 res[count] = str.substring(lastI, i); 1774 count++; 1775 i++; 1776 lastI = i; 1777 } 1778 res[count] = str.substring(lastI, str.length()); 1779 return res; 1780 } 1781 1782 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1783 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1784 Context.DISPLAY_SERVICE); 1785 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1786 } 1787 1788 public PackageManagerService(Context context, Installer installer, 1789 boolean factoryTest, boolean onlyCore) { 1790 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1791 SystemClock.uptimeMillis()); 1792 1793 if (mSdkVersion <= 0) { 1794 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1795 } 1796 1797 mContext = context; 1798 mFactoryTest = factoryTest; 1799 mOnlyCore = onlyCore; 1800 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1801 mMetrics = new DisplayMetrics(); 1802 mSettings = new Settings(mPackages); 1803 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1804 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1805 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1806 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1807 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1808 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1809 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1810 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1811 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1812 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1813 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1814 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1815 1816 // TODO: add a property to control this? 1817 long dexOptLRUThresholdInMinutes; 1818 if (mLazyDexOpt) { 1819 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1820 } else { 1821 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1822 } 1823 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1824 1825 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1826 if (separateProcesses != null && separateProcesses.length() > 0) { 1827 if ("*".equals(separateProcesses)) { 1828 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1829 mSeparateProcesses = null; 1830 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1831 } else { 1832 mDefParseFlags = 0; 1833 mSeparateProcesses = separateProcesses.split(","); 1834 Slog.w(TAG, "Running with debug.separate_processes: " 1835 + separateProcesses); 1836 } 1837 } else { 1838 mDefParseFlags = 0; 1839 mSeparateProcesses = null; 1840 } 1841 1842 mInstaller = installer; 1843 mPackageDexOptimizer = new PackageDexOptimizer(this); 1844 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1845 1846 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1847 FgThread.get().getLooper()); 1848 1849 getDefaultDisplayMetrics(context, mMetrics); 1850 1851 SystemConfig systemConfig = SystemConfig.getInstance(); 1852 mGlobalGids = systemConfig.getGlobalGids(); 1853 mSystemPermissions = systemConfig.getSystemPermissions(); 1854 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1855 1856 synchronized (mInstallLock) { 1857 // writer 1858 synchronized (mPackages) { 1859 mHandlerThread = new ServiceThread(TAG, 1860 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1861 mHandlerThread.start(); 1862 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1863 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1864 1865 File dataDir = Environment.getDataDirectory(); 1866 mAppDataDir = new File(dataDir, "data"); 1867 mAppInstallDir = new File(dataDir, "app"); 1868 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1869 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1870 mUserAppDataDir = new File(dataDir, "user"); 1871 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1872 1873 sUserManager = new UserManagerService(context, this, 1874 mInstallLock, mPackages); 1875 1876 // Propagate permission configuration in to package manager. 1877 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1878 = systemConfig.getPermissions(); 1879 for (int i=0; i<permConfig.size(); i++) { 1880 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1881 BasePermission bp = mSettings.mPermissions.get(perm.name); 1882 if (bp == null) { 1883 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1884 mSettings.mPermissions.put(perm.name, bp); 1885 } 1886 if (perm.gids != null) { 1887 bp.setGids(perm.gids, perm.perUser); 1888 } 1889 } 1890 1891 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1892 for (int i=0; i<libConfig.size(); i++) { 1893 mSharedLibraries.put(libConfig.keyAt(i), 1894 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1895 } 1896 1897 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1898 1899 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1900 mSdkVersion, mOnlyCore); 1901 1902 String customResolverActivity = Resources.getSystem().getString( 1903 R.string.config_customResolverActivity); 1904 if (TextUtils.isEmpty(customResolverActivity)) { 1905 customResolverActivity = null; 1906 } else { 1907 mCustomResolverComponentName = ComponentName.unflattenFromString( 1908 customResolverActivity); 1909 } 1910 1911 long startTime = SystemClock.uptimeMillis(); 1912 1913 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1914 startTime); 1915 1916 // Set flag to monitor and not change apk file paths when 1917 // scanning install directories. 1918 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1919 1920 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1921 1922 /** 1923 * Add everything in the in the boot class path to the 1924 * list of process files because dexopt will have been run 1925 * if necessary during zygote startup. 1926 */ 1927 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1928 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1929 1930 if (bootClassPath != null) { 1931 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1932 for (String element : bootClassPathElements) { 1933 alreadyDexOpted.add(element); 1934 } 1935 } else { 1936 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1937 } 1938 1939 if (systemServerClassPath != null) { 1940 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1941 for (String element : systemServerClassPathElements) { 1942 alreadyDexOpted.add(element); 1943 } 1944 } else { 1945 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1946 } 1947 1948 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1949 final String[] dexCodeInstructionSets = 1950 getDexCodeInstructionSets( 1951 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1952 1953 /** 1954 * Ensure all external libraries have had dexopt run on them. 1955 */ 1956 if (mSharedLibraries.size() > 0) { 1957 // NOTE: For now, we're compiling these system "shared libraries" 1958 // (and framework jars) into all available architectures. It's possible 1959 // to compile them only when we come across an app that uses them (there's 1960 // already logic for that in scanPackageLI) but that adds some complexity. 1961 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1962 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1963 final String lib = libEntry.path; 1964 if (lib == null) { 1965 continue; 1966 } 1967 1968 try { 1969 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1970 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1971 alreadyDexOpted.add(lib); 1972 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1973 } 1974 } catch (FileNotFoundException e) { 1975 Slog.w(TAG, "Library not found: " + lib); 1976 } catch (IOException e) { 1977 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1978 + e.getMessage()); 1979 } 1980 } 1981 } 1982 } 1983 1984 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1985 1986 // Gross hack for now: we know this file doesn't contain any 1987 // code, so don't dexopt it to avoid the resulting log spew. 1988 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1989 1990 // Gross hack for now: we know this file is only part of 1991 // the boot class path for art, so don't dexopt it to 1992 // avoid the resulting log spew. 1993 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1994 1995 /** 1996 * There are a number of commands implemented in Java, which 1997 * we currently need to do the dexopt on so that they can be 1998 * run from a non-root shell. 1999 */ 2000 String[] frameworkFiles = frameworkDir.list(); 2001 if (frameworkFiles != null) { 2002 // TODO: We could compile these only for the most preferred ABI. We should 2003 // first double check that the dex files for these commands are not referenced 2004 // by other system apps. 2005 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2006 for (int i=0; i<frameworkFiles.length; i++) { 2007 File libPath = new File(frameworkDir, frameworkFiles[i]); 2008 String path = libPath.getPath(); 2009 // Skip the file if we already did it. 2010 if (alreadyDexOpted.contains(path)) { 2011 continue; 2012 } 2013 // Skip the file if it is not a type we want to dexopt. 2014 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2015 continue; 2016 } 2017 try { 2018 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2019 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2020 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2021 } 2022 } catch (FileNotFoundException e) { 2023 Slog.w(TAG, "Jar not found: " + path); 2024 } catch (IOException e) { 2025 Slog.w(TAG, "Exception reading jar: " + path, e); 2026 } 2027 } 2028 } 2029 } 2030 2031 // Collect vendor overlay packages. 2032 // (Do this before scanning any apps.) 2033 // For security and version matching reason, only consider 2034 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2035 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2036 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2037 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2038 2039 // Find base frameworks (resource packages without code). 2040 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2041 | PackageParser.PARSE_IS_SYSTEM_DIR 2042 | PackageParser.PARSE_IS_PRIVILEGED, 2043 scanFlags | SCAN_NO_DEX, 0); 2044 2045 // Collected privileged system packages. 2046 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2047 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2048 | PackageParser.PARSE_IS_SYSTEM_DIR 2049 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2050 2051 // Collect ordinary system packages. 2052 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2053 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2054 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2055 2056 // Collect all vendor packages. 2057 File vendorAppDir = new File("/vendor/app"); 2058 try { 2059 vendorAppDir = vendorAppDir.getCanonicalFile(); 2060 } catch (IOException e) { 2061 // failed to look up canonical path, continue with original one 2062 } 2063 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2064 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2065 2066 // Collect all OEM packages. 2067 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2068 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2069 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2070 2071 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2072 mInstaller.moveFiles(); 2073 2074 // Prune any system packages that no longer exist. 2075 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2076 if (!mOnlyCore) { 2077 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2078 while (psit.hasNext()) { 2079 PackageSetting ps = psit.next(); 2080 2081 /* 2082 * If this is not a system app, it can't be a 2083 * disable system app. 2084 */ 2085 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2086 continue; 2087 } 2088 2089 /* 2090 * If the package is scanned, it's not erased. 2091 */ 2092 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2093 if (scannedPkg != null) { 2094 /* 2095 * If the system app is both scanned and in the 2096 * disabled packages list, then it must have been 2097 * added via OTA. Remove it from the currently 2098 * scanned package so the previously user-installed 2099 * application can be scanned. 2100 */ 2101 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2102 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2103 + ps.name + "; removing system app. Last known codePath=" 2104 + ps.codePathString + ", installStatus=" + ps.installStatus 2105 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2106 + scannedPkg.mVersionCode); 2107 removePackageLI(ps, true); 2108 mExpectingBetter.put(ps.name, ps.codePath); 2109 } 2110 2111 continue; 2112 } 2113 2114 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2115 psit.remove(); 2116 logCriticalInfo(Log.WARN, "System package " + ps.name 2117 + " no longer exists; wiping its data"); 2118 removeDataDirsLI(null, ps.name); 2119 } else { 2120 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2121 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2122 possiblyDeletedUpdatedSystemApps.add(ps.name); 2123 } 2124 } 2125 } 2126 } 2127 2128 //look for any incomplete package installations 2129 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2130 //clean up list 2131 for(int i = 0; i < deletePkgsList.size(); i++) { 2132 //clean up here 2133 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2134 } 2135 //delete tmp files 2136 deleteTempPackageFiles(); 2137 2138 // Remove any shared userIDs that have no associated packages 2139 mSettings.pruneSharedUsersLPw(); 2140 2141 if (!mOnlyCore) { 2142 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2143 SystemClock.uptimeMillis()); 2144 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2145 2146 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2147 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2148 2149 /** 2150 * Remove disable package settings for any updated system 2151 * apps that were removed via an OTA. If they're not a 2152 * previously-updated app, remove them completely. 2153 * Otherwise, just revoke their system-level permissions. 2154 */ 2155 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2156 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2157 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2158 2159 String msg; 2160 if (deletedPkg == null) { 2161 msg = "Updated system package " + deletedAppName 2162 + " no longer exists; wiping its data"; 2163 removeDataDirsLI(null, deletedAppName); 2164 } else { 2165 msg = "Updated system app + " + deletedAppName 2166 + " no longer present; removing system privileges for " 2167 + deletedAppName; 2168 2169 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2170 2171 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2172 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2173 } 2174 logCriticalInfo(Log.WARN, msg); 2175 } 2176 2177 /** 2178 * Make sure all system apps that we expected to appear on 2179 * the userdata partition actually showed up. If they never 2180 * appeared, crawl back and revive the system version. 2181 */ 2182 for (int i = 0; i < mExpectingBetter.size(); i++) { 2183 final String packageName = mExpectingBetter.keyAt(i); 2184 if (!mPackages.containsKey(packageName)) { 2185 final File scanFile = mExpectingBetter.valueAt(i); 2186 2187 logCriticalInfo(Log.WARN, "Expected better " + packageName 2188 + " but never showed up; reverting to system"); 2189 2190 final int reparseFlags; 2191 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2192 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2193 | PackageParser.PARSE_IS_SYSTEM_DIR 2194 | PackageParser.PARSE_IS_PRIVILEGED; 2195 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2196 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2197 | PackageParser.PARSE_IS_SYSTEM_DIR; 2198 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2199 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2200 | PackageParser.PARSE_IS_SYSTEM_DIR; 2201 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2202 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2203 | PackageParser.PARSE_IS_SYSTEM_DIR; 2204 } else { 2205 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2206 continue; 2207 } 2208 2209 mSettings.enableSystemPackageLPw(packageName); 2210 2211 try { 2212 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2213 } catch (PackageManagerException e) { 2214 Slog.e(TAG, "Failed to parse original system package: " 2215 + e.getMessage()); 2216 } 2217 } 2218 } 2219 } 2220 mExpectingBetter.clear(); 2221 2222 // Now that we know all of the shared libraries, update all clients to have 2223 // the correct library paths. 2224 updateAllSharedLibrariesLPw(); 2225 2226 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2227 // NOTE: We ignore potential failures here during a system scan (like 2228 // the rest of the commands above) because there's precious little we 2229 // can do about it. A settings error is reported, though. 2230 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2231 false /* force dexopt */, false /* defer dexopt */); 2232 } 2233 2234 // Now that we know all the packages we are keeping, 2235 // read and update their last usage times. 2236 mPackageUsage.readLP(); 2237 2238 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2239 SystemClock.uptimeMillis()); 2240 Slog.i(TAG, "Time to scan packages: " 2241 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2242 + " seconds"); 2243 2244 // If the platform SDK has changed since the last time we booted, 2245 // we need to re-grant app permission to catch any new ones that 2246 // appear. This is really a hack, and means that apps can in some 2247 // cases get permissions that the user didn't initially explicitly 2248 // allow... it would be nice to have some better way to handle 2249 // this situation. 2250 final VersionInfo ver = mSettings.getInternalVersion(); 2251 2252 int updateFlags = UPDATE_PERMISSIONS_ALL; 2253 if (ver.sdkVersion != mSdkVersion) { 2254 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2255 + mSdkVersion + "; regranting permissions for internal storage"); 2256 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2257 } 2258 updatePermissionsLPw(null, null, updateFlags); 2259 ver.sdkVersion = mSdkVersion; 2260 2261 // If this is the first boot, and it is a normal boot, then 2262 // we need to initialize the default preferred apps. 2263 if (!mRestoredSettings && !onlyCore) { 2264 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2265 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2266 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2267 } 2268 2269 // If this is first boot after an OTA, and a normal boot, then 2270 // we need to clear code cache directories. 2271 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2272 if (mIsUpgrade && !onlyCore) { 2273 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2274 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2275 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2276 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2277 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2278 } 2279 } 2280 ver.fingerprint = Build.FINGERPRINT; 2281 } 2282 2283 checkDefaultBrowser(); 2284 2285 // All the changes are done during package scanning. 2286 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2287 2288 // can downgrade to reader 2289 mSettings.writeLPr(); 2290 2291 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2292 SystemClock.uptimeMillis()); 2293 2294 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2295 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2296 2297 mInstallerService = new PackageInstallerService(context, this); 2298 2299 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2300 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2301 mIntentFilterVerifierComponent); 2302 2303 } // synchronized (mPackages) 2304 } // synchronized (mInstallLock) 2305 2306 // Now after opening every single application zip, make sure they 2307 // are all flushed. Not really needed, but keeps things nice and 2308 // tidy. 2309 Runtime.getRuntime().gc(); 2310 2311 // Expose private service for system components to use. 2312 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2313 } 2314 2315 @Override 2316 public boolean isFirstBoot() { 2317 return !mRestoredSettings; 2318 } 2319 2320 @Override 2321 public boolean isOnlyCoreApps() { 2322 return mOnlyCore; 2323 } 2324 2325 @Override 2326 public boolean isUpgrade() { 2327 return mIsUpgrade; 2328 } 2329 2330 private String getRequiredVerifierLPr() { 2331 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2332 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2333 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2334 2335 String requiredVerifier = null; 2336 2337 final int N = receivers.size(); 2338 for (int i = 0; i < N; i++) { 2339 final ResolveInfo info = receivers.get(i); 2340 2341 if (info.activityInfo == null) { 2342 continue; 2343 } 2344 2345 final String packageName = info.activityInfo.packageName; 2346 2347 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2348 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2349 continue; 2350 } 2351 2352 if (requiredVerifier != null) { 2353 throw new RuntimeException("There can be only one required verifier"); 2354 } 2355 2356 requiredVerifier = packageName; 2357 } 2358 2359 return requiredVerifier; 2360 } 2361 2362 private String getRequiredInstallerLPr() { 2363 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2364 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2365 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2366 2367 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2368 PACKAGE_MIME_TYPE, 0, 0); 2369 2370 String requiredInstaller = null; 2371 2372 final int N = installers.size(); 2373 for (int i = 0; i < N; i++) { 2374 final ResolveInfo info = installers.get(i); 2375 final String packageName = info.activityInfo.packageName; 2376 2377 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2378 continue; 2379 } 2380 2381 if (requiredInstaller != null) { 2382 throw new RuntimeException("There must be one required installer"); 2383 } 2384 2385 requiredInstaller = packageName; 2386 } 2387 2388 if (requiredInstaller == null) { 2389 throw new RuntimeException("There must be one required installer"); 2390 } 2391 2392 return requiredInstaller; 2393 } 2394 2395 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2396 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2397 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2398 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2399 2400 ComponentName verifierComponentName = null; 2401 2402 int priority = -1000; 2403 final int N = receivers.size(); 2404 for (int i = 0; i < N; i++) { 2405 final ResolveInfo info = receivers.get(i); 2406 2407 if (info.activityInfo == null) { 2408 continue; 2409 } 2410 2411 final String packageName = info.activityInfo.packageName; 2412 2413 final PackageSetting ps = mSettings.mPackages.get(packageName); 2414 if (ps == null) { 2415 continue; 2416 } 2417 2418 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2419 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2420 continue; 2421 } 2422 2423 // Select the IntentFilterVerifier with the highest priority 2424 if (priority < info.priority) { 2425 priority = info.priority; 2426 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2427 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2428 + verifierComponentName + " with priority: " + info.priority); 2429 } 2430 } 2431 2432 return verifierComponentName; 2433 } 2434 2435 private void primeDomainVerificationsLPw(int userId) { 2436 if (DEBUG_DOMAIN_VERIFICATION) { 2437 Slog.d(TAG, "Priming domain verifications in user " + userId); 2438 } 2439 2440 SystemConfig systemConfig = SystemConfig.getInstance(); 2441 ArraySet<String> packages = systemConfig.getLinkedApps(); 2442 ArraySet<String> domains = new ArraySet<String>(); 2443 2444 for (String packageName : packages) { 2445 PackageParser.Package pkg = mPackages.get(packageName); 2446 if (pkg != null) { 2447 if (!pkg.isSystemApp()) { 2448 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2449 continue; 2450 } 2451 2452 domains.clear(); 2453 for (PackageParser.Activity a : pkg.activities) { 2454 for (ActivityIntentInfo filter : a.intents) { 2455 if (hasValidDomains(filter)) { 2456 domains.addAll(filter.getHostsList()); 2457 } 2458 } 2459 } 2460 2461 if (domains.size() > 0) { 2462 if (DEBUG_DOMAIN_VERIFICATION) { 2463 Slog.v(TAG, " + " + packageName); 2464 } 2465 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2466 // state w.r.t. the formal app-linkage "no verification attempted" state; 2467 // and then 'always' in the per-user state actually used for intent resolution. 2468 final IntentFilterVerificationInfo ivi; 2469 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2470 new ArrayList<String>(domains)); 2471 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2472 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2473 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2474 } else { 2475 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2476 + "' does not handle web links"); 2477 } 2478 } else { 2479 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2480 } 2481 } 2482 2483 scheduleWritePackageRestrictionsLocked(userId); 2484 scheduleWriteSettingsLocked(); 2485 } 2486 2487 private void applyFactoryDefaultBrowserLPw(int userId) { 2488 // The default browser app's package name is stored in a string resource, 2489 // with a product-specific overlay used for vendor customization. 2490 String browserPkg = mContext.getResources().getString( 2491 com.android.internal.R.string.default_browser); 2492 if (!TextUtils.isEmpty(browserPkg)) { 2493 // non-empty string => required to be a known package 2494 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2495 if (ps == null) { 2496 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2497 browserPkg = null; 2498 } else { 2499 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2500 } 2501 } 2502 2503 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2504 // default. If there's more than one, just leave everything alone. 2505 if (browserPkg == null) { 2506 calculateDefaultBrowserLPw(userId); 2507 } 2508 } 2509 2510 private void calculateDefaultBrowserLPw(int userId) { 2511 List<String> allBrowsers = resolveAllBrowserApps(userId); 2512 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2513 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2514 } 2515 2516 private List<String> resolveAllBrowserApps(int userId) { 2517 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2518 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2519 PackageManager.MATCH_ALL, userId); 2520 2521 final int count = list.size(); 2522 List<String> result = new ArrayList<String>(count); 2523 for (int i=0; i<count; i++) { 2524 ResolveInfo info = list.get(i); 2525 if (info.activityInfo == null 2526 || !info.handleAllWebDataURI 2527 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2528 || result.contains(info.activityInfo.packageName)) { 2529 continue; 2530 } 2531 result.add(info.activityInfo.packageName); 2532 } 2533 2534 return result; 2535 } 2536 2537 private boolean packageIsBrowser(String packageName, int userId) { 2538 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2539 PackageManager.MATCH_ALL, userId); 2540 final int N = list.size(); 2541 for (int i = 0; i < N; i++) { 2542 ResolveInfo info = list.get(i); 2543 if (packageName.equals(info.activityInfo.packageName)) { 2544 return true; 2545 } 2546 } 2547 return false; 2548 } 2549 2550 private void checkDefaultBrowser() { 2551 final int myUserId = UserHandle.myUserId(); 2552 final String packageName = getDefaultBrowserPackageName(myUserId); 2553 if (packageName != null) { 2554 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2555 if (info == null) { 2556 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2557 synchronized (mPackages) { 2558 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2559 } 2560 } 2561 } 2562 } 2563 2564 @Override 2565 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2566 throws RemoteException { 2567 try { 2568 return super.onTransact(code, data, reply, flags); 2569 } catch (RuntimeException e) { 2570 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2571 Slog.wtf(TAG, "Package Manager Crash", e); 2572 } 2573 throw e; 2574 } 2575 } 2576 2577 void cleanupInstallFailedPackage(PackageSetting ps) { 2578 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2579 2580 removeDataDirsLI(ps.volumeUuid, ps.name); 2581 if (ps.codePath != null) { 2582 if (ps.codePath.isDirectory()) { 2583 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2584 } else { 2585 ps.codePath.delete(); 2586 } 2587 } 2588 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2589 if (ps.resourcePath.isDirectory()) { 2590 FileUtils.deleteContents(ps.resourcePath); 2591 } 2592 ps.resourcePath.delete(); 2593 } 2594 mSettings.removePackageLPw(ps.name); 2595 } 2596 2597 static int[] appendInts(int[] cur, int[] add) { 2598 if (add == null) return cur; 2599 if (cur == null) return add; 2600 final int N = add.length; 2601 for (int i=0; i<N; i++) { 2602 cur = appendInt(cur, add[i]); 2603 } 2604 return cur; 2605 } 2606 2607 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2608 if (!sUserManager.exists(userId)) return null; 2609 final PackageSetting ps = (PackageSetting) p.mExtras; 2610 if (ps == null) { 2611 return null; 2612 } 2613 2614 final PermissionsState permissionsState = ps.getPermissionsState(); 2615 2616 final int[] gids = permissionsState.computeGids(userId); 2617 final Set<String> permissions = permissionsState.getPermissions(userId); 2618 final PackageUserState state = ps.readUserState(userId); 2619 2620 return PackageParser.generatePackageInfo(p, gids, flags, 2621 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2622 } 2623 2624 @Override 2625 public boolean isPackageFrozen(String packageName) { 2626 synchronized (mPackages) { 2627 final PackageSetting ps = mSettings.mPackages.get(packageName); 2628 if (ps != null) { 2629 return ps.frozen; 2630 } 2631 } 2632 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2633 return true; 2634 } 2635 2636 @Override 2637 public boolean isPackageAvailable(String packageName, int userId) { 2638 if (!sUserManager.exists(userId)) return false; 2639 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2640 synchronized (mPackages) { 2641 PackageParser.Package p = mPackages.get(packageName); 2642 if (p != null) { 2643 final PackageSetting ps = (PackageSetting) p.mExtras; 2644 if (ps != null) { 2645 final PackageUserState state = ps.readUserState(userId); 2646 if (state != null) { 2647 return PackageParser.isAvailable(state); 2648 } 2649 } 2650 } 2651 } 2652 return false; 2653 } 2654 2655 @Override 2656 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2657 if (!sUserManager.exists(userId)) return null; 2658 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2659 // reader 2660 synchronized (mPackages) { 2661 PackageParser.Package p = mPackages.get(packageName); 2662 if (DEBUG_PACKAGE_INFO) 2663 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2664 if (p != null) { 2665 return generatePackageInfo(p, flags, userId); 2666 } 2667 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2668 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2669 } 2670 } 2671 return null; 2672 } 2673 2674 @Override 2675 public String[] currentToCanonicalPackageNames(String[] names) { 2676 String[] out = new String[names.length]; 2677 // reader 2678 synchronized (mPackages) { 2679 for (int i=names.length-1; i>=0; i--) { 2680 PackageSetting ps = mSettings.mPackages.get(names[i]); 2681 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2682 } 2683 } 2684 return out; 2685 } 2686 2687 @Override 2688 public String[] canonicalToCurrentPackageNames(String[] names) { 2689 String[] out = new String[names.length]; 2690 // reader 2691 synchronized (mPackages) { 2692 for (int i=names.length-1; i>=0; i--) { 2693 String cur = mSettings.mRenamedPackages.get(names[i]); 2694 out[i] = cur != null ? cur : names[i]; 2695 } 2696 } 2697 return out; 2698 } 2699 2700 @Override 2701 public int getPackageUid(String packageName, int userId) { 2702 if (!sUserManager.exists(userId)) return -1; 2703 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2704 2705 // reader 2706 synchronized (mPackages) { 2707 PackageParser.Package p = mPackages.get(packageName); 2708 if(p != null) { 2709 return UserHandle.getUid(userId, p.applicationInfo.uid); 2710 } 2711 PackageSetting ps = mSettings.mPackages.get(packageName); 2712 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2713 return -1; 2714 } 2715 p = ps.pkg; 2716 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2717 } 2718 } 2719 2720 @Override 2721 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2722 if (!sUserManager.exists(userId)) { 2723 return null; 2724 } 2725 2726 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2727 "getPackageGids"); 2728 2729 // reader 2730 synchronized (mPackages) { 2731 PackageParser.Package p = mPackages.get(packageName); 2732 if (DEBUG_PACKAGE_INFO) { 2733 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2734 } 2735 if (p != null) { 2736 PackageSetting ps = (PackageSetting) p.mExtras; 2737 return ps.getPermissionsState().computeGids(userId); 2738 } 2739 } 2740 2741 return null; 2742 } 2743 2744 static PermissionInfo generatePermissionInfo( 2745 BasePermission bp, int flags) { 2746 if (bp.perm != null) { 2747 return PackageParser.generatePermissionInfo(bp.perm, flags); 2748 } 2749 PermissionInfo pi = new PermissionInfo(); 2750 pi.name = bp.name; 2751 pi.packageName = bp.sourcePackage; 2752 pi.nonLocalizedLabel = bp.name; 2753 pi.protectionLevel = bp.protectionLevel; 2754 return pi; 2755 } 2756 2757 @Override 2758 public PermissionInfo getPermissionInfo(String name, int flags) { 2759 // reader 2760 synchronized (mPackages) { 2761 final BasePermission p = mSettings.mPermissions.get(name); 2762 if (p != null) { 2763 return generatePermissionInfo(p, flags); 2764 } 2765 return null; 2766 } 2767 } 2768 2769 @Override 2770 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2771 // reader 2772 synchronized (mPackages) { 2773 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2774 for (BasePermission p : mSettings.mPermissions.values()) { 2775 if (group == null) { 2776 if (p.perm == null || p.perm.info.group == null) { 2777 out.add(generatePermissionInfo(p, flags)); 2778 } 2779 } else { 2780 if (p.perm != null && group.equals(p.perm.info.group)) { 2781 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2782 } 2783 } 2784 } 2785 2786 if (out.size() > 0) { 2787 return out; 2788 } 2789 return mPermissionGroups.containsKey(group) ? out : null; 2790 } 2791 } 2792 2793 @Override 2794 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2795 // reader 2796 synchronized (mPackages) { 2797 return PackageParser.generatePermissionGroupInfo( 2798 mPermissionGroups.get(name), flags); 2799 } 2800 } 2801 2802 @Override 2803 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2804 // reader 2805 synchronized (mPackages) { 2806 final int N = mPermissionGroups.size(); 2807 ArrayList<PermissionGroupInfo> out 2808 = new ArrayList<PermissionGroupInfo>(N); 2809 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2810 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2811 } 2812 return out; 2813 } 2814 } 2815 2816 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2817 int userId) { 2818 if (!sUserManager.exists(userId)) return null; 2819 PackageSetting ps = mSettings.mPackages.get(packageName); 2820 if (ps != null) { 2821 if (ps.pkg == null) { 2822 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2823 flags, userId); 2824 if (pInfo != null) { 2825 return pInfo.applicationInfo; 2826 } 2827 return null; 2828 } 2829 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2830 ps.readUserState(userId), userId); 2831 } 2832 return null; 2833 } 2834 2835 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2836 int userId) { 2837 if (!sUserManager.exists(userId)) return null; 2838 PackageSetting ps = mSettings.mPackages.get(packageName); 2839 if (ps != null) { 2840 PackageParser.Package pkg = ps.pkg; 2841 if (pkg == null) { 2842 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2843 return null; 2844 } 2845 // Only data remains, so we aren't worried about code paths 2846 pkg = new PackageParser.Package(packageName); 2847 pkg.applicationInfo.packageName = packageName; 2848 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2849 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2850 pkg.applicationInfo.dataDir = Environment 2851 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2852 .getAbsolutePath(); 2853 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2854 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2855 } 2856 return generatePackageInfo(pkg, flags, userId); 2857 } 2858 return null; 2859 } 2860 2861 @Override 2862 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2863 if (!sUserManager.exists(userId)) return null; 2864 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2865 // writer 2866 synchronized (mPackages) { 2867 PackageParser.Package p = mPackages.get(packageName); 2868 if (DEBUG_PACKAGE_INFO) Log.v( 2869 TAG, "getApplicationInfo " + packageName 2870 + ": " + p); 2871 if (p != null) { 2872 PackageSetting ps = mSettings.mPackages.get(packageName); 2873 if (ps == null) return null; 2874 // Note: isEnabledLP() does not apply here - always return info 2875 return PackageParser.generateApplicationInfo( 2876 p, flags, ps.readUserState(userId), userId); 2877 } 2878 if ("android".equals(packageName)||"system".equals(packageName)) { 2879 return mAndroidApplication; 2880 } 2881 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2882 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2883 } 2884 } 2885 return null; 2886 } 2887 2888 @Override 2889 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2890 final IPackageDataObserver observer) { 2891 mContext.enforceCallingOrSelfPermission( 2892 android.Manifest.permission.CLEAR_APP_CACHE, null); 2893 // Queue up an async operation since clearing cache may take a little while. 2894 mHandler.post(new Runnable() { 2895 public void run() { 2896 mHandler.removeCallbacks(this); 2897 int retCode = -1; 2898 synchronized (mInstallLock) { 2899 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2900 if (retCode < 0) { 2901 Slog.w(TAG, "Couldn't clear application caches"); 2902 } 2903 } 2904 if (observer != null) { 2905 try { 2906 observer.onRemoveCompleted(null, (retCode >= 0)); 2907 } catch (RemoteException e) { 2908 Slog.w(TAG, "RemoveException when invoking call back"); 2909 } 2910 } 2911 } 2912 }); 2913 } 2914 2915 @Override 2916 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2917 final IntentSender pi) { 2918 mContext.enforceCallingOrSelfPermission( 2919 android.Manifest.permission.CLEAR_APP_CACHE, null); 2920 // Queue up an async operation since clearing cache may take a little while. 2921 mHandler.post(new Runnable() { 2922 public void run() { 2923 mHandler.removeCallbacks(this); 2924 int retCode = -1; 2925 synchronized (mInstallLock) { 2926 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2927 if (retCode < 0) { 2928 Slog.w(TAG, "Couldn't clear application caches"); 2929 } 2930 } 2931 if(pi != null) { 2932 try { 2933 // Callback via pending intent 2934 int code = (retCode >= 0) ? 1 : 0; 2935 pi.sendIntent(null, code, null, 2936 null, null); 2937 } catch (SendIntentException e1) { 2938 Slog.i(TAG, "Failed to send pending intent"); 2939 } 2940 } 2941 } 2942 }); 2943 } 2944 2945 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2946 synchronized (mInstallLock) { 2947 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2948 throw new IOException("Failed to free enough space"); 2949 } 2950 } 2951 } 2952 2953 @Override 2954 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2955 if (!sUserManager.exists(userId)) return null; 2956 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2957 synchronized (mPackages) { 2958 PackageParser.Activity a = mActivities.mActivities.get(component); 2959 2960 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2961 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2962 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2963 if (ps == null) return null; 2964 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2965 userId); 2966 } 2967 if (mResolveComponentName.equals(component)) { 2968 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2969 new PackageUserState(), userId); 2970 } 2971 } 2972 return null; 2973 } 2974 2975 @Override 2976 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2977 String resolvedType) { 2978 synchronized (mPackages) { 2979 if (component.equals(mResolveComponentName)) { 2980 // The resolver supports EVERYTHING! 2981 return true; 2982 } 2983 PackageParser.Activity a = mActivities.mActivities.get(component); 2984 if (a == null) { 2985 return false; 2986 } 2987 for (int i=0; i<a.intents.size(); i++) { 2988 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2989 intent.getData(), intent.getCategories(), TAG) >= 0) { 2990 return true; 2991 } 2992 } 2993 return false; 2994 } 2995 } 2996 2997 @Override 2998 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2999 if (!sUserManager.exists(userId)) return null; 3000 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3001 synchronized (mPackages) { 3002 PackageParser.Activity a = mReceivers.mActivities.get(component); 3003 if (DEBUG_PACKAGE_INFO) Log.v( 3004 TAG, "getReceiverInfo " + component + ": " + a); 3005 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3006 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3007 if (ps == null) return null; 3008 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3009 userId); 3010 } 3011 } 3012 return null; 3013 } 3014 3015 @Override 3016 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3017 if (!sUserManager.exists(userId)) return null; 3018 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3019 synchronized (mPackages) { 3020 PackageParser.Service s = mServices.mServices.get(component); 3021 if (DEBUG_PACKAGE_INFO) Log.v( 3022 TAG, "getServiceInfo " + component + ": " + s); 3023 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3024 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3025 if (ps == null) return null; 3026 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3027 userId); 3028 } 3029 } 3030 return null; 3031 } 3032 3033 @Override 3034 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3035 if (!sUserManager.exists(userId)) return null; 3036 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3037 synchronized (mPackages) { 3038 PackageParser.Provider p = mProviders.mProviders.get(component); 3039 if (DEBUG_PACKAGE_INFO) Log.v( 3040 TAG, "getProviderInfo " + component + ": " + p); 3041 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3042 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3043 if (ps == null) return null; 3044 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3045 userId); 3046 } 3047 } 3048 return null; 3049 } 3050 3051 @Override 3052 public String[] getSystemSharedLibraryNames() { 3053 Set<String> libSet; 3054 synchronized (mPackages) { 3055 libSet = mSharedLibraries.keySet(); 3056 int size = libSet.size(); 3057 if (size > 0) { 3058 String[] libs = new String[size]; 3059 libSet.toArray(libs); 3060 return libs; 3061 } 3062 } 3063 return null; 3064 } 3065 3066 /** 3067 * @hide 3068 */ 3069 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3070 synchronized (mPackages) { 3071 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3072 if (lib != null && lib.apk != null) { 3073 return mPackages.get(lib.apk); 3074 } 3075 } 3076 return null; 3077 } 3078 3079 @Override 3080 public FeatureInfo[] getSystemAvailableFeatures() { 3081 Collection<FeatureInfo> featSet; 3082 synchronized (mPackages) { 3083 featSet = mAvailableFeatures.values(); 3084 int size = featSet.size(); 3085 if (size > 0) { 3086 FeatureInfo[] features = new FeatureInfo[size+1]; 3087 featSet.toArray(features); 3088 FeatureInfo fi = new FeatureInfo(); 3089 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3090 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3091 features[size] = fi; 3092 return features; 3093 } 3094 } 3095 return null; 3096 } 3097 3098 @Override 3099 public boolean hasSystemFeature(String name) { 3100 synchronized (mPackages) { 3101 return mAvailableFeatures.containsKey(name); 3102 } 3103 } 3104 3105 private void checkValidCaller(int uid, int userId) { 3106 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3107 return; 3108 3109 throw new SecurityException("Caller uid=" + uid 3110 + " is not privileged to communicate with user=" + userId); 3111 } 3112 3113 @Override 3114 public int checkPermission(String permName, String pkgName, int userId) { 3115 if (!sUserManager.exists(userId)) { 3116 return PackageManager.PERMISSION_DENIED; 3117 } 3118 3119 synchronized (mPackages) { 3120 final PackageParser.Package p = mPackages.get(pkgName); 3121 if (p != null && p.mExtras != null) { 3122 final PackageSetting ps = (PackageSetting) p.mExtras; 3123 final PermissionsState permissionsState = ps.getPermissionsState(); 3124 if (permissionsState.hasPermission(permName, userId)) { 3125 return PackageManager.PERMISSION_GRANTED; 3126 } 3127 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3128 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3129 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3130 return PackageManager.PERMISSION_GRANTED; 3131 } 3132 } 3133 } 3134 3135 return PackageManager.PERMISSION_DENIED; 3136 } 3137 3138 @Override 3139 public int checkUidPermission(String permName, int uid) { 3140 final int userId = UserHandle.getUserId(uid); 3141 3142 if (!sUserManager.exists(userId)) { 3143 return PackageManager.PERMISSION_DENIED; 3144 } 3145 3146 synchronized (mPackages) { 3147 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3148 if (obj != null) { 3149 final SettingBase ps = (SettingBase) obj; 3150 final PermissionsState permissionsState = ps.getPermissionsState(); 3151 if (permissionsState.hasPermission(permName, userId)) { 3152 return PackageManager.PERMISSION_GRANTED; 3153 } 3154 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3155 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3156 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3157 return PackageManager.PERMISSION_GRANTED; 3158 } 3159 } else { 3160 ArraySet<String> perms = mSystemPermissions.get(uid); 3161 if (perms != null) { 3162 if (perms.contains(permName)) { 3163 return PackageManager.PERMISSION_GRANTED; 3164 } 3165 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3166 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3167 return PackageManager.PERMISSION_GRANTED; 3168 } 3169 } 3170 } 3171 } 3172 3173 return PackageManager.PERMISSION_DENIED; 3174 } 3175 3176 @Override 3177 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3178 if (UserHandle.getCallingUserId() != userId) { 3179 mContext.enforceCallingPermission( 3180 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3181 "isPermissionRevokedByPolicy for user " + userId); 3182 } 3183 3184 if (checkPermission(permission, packageName, userId) 3185 == PackageManager.PERMISSION_GRANTED) { 3186 return false; 3187 } 3188 3189 final long identity = Binder.clearCallingIdentity(); 3190 try { 3191 final int flags = getPermissionFlags(permission, packageName, userId); 3192 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3193 } finally { 3194 Binder.restoreCallingIdentity(identity); 3195 } 3196 } 3197 3198 @Override 3199 public String getPermissionControllerPackageName() { 3200 synchronized (mPackages) { 3201 return mRequiredInstallerPackage; 3202 } 3203 } 3204 3205 /** 3206 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3207 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3208 * @param checkShell TODO(yamasani): 3209 * @param message the message to log on security exception 3210 */ 3211 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3212 boolean checkShell, String message) { 3213 if (userId < 0) { 3214 throw new IllegalArgumentException("Invalid userId " + userId); 3215 } 3216 if (checkShell) { 3217 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3218 } 3219 if (userId == UserHandle.getUserId(callingUid)) return; 3220 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3221 if (requireFullPermission) { 3222 mContext.enforceCallingOrSelfPermission( 3223 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3224 } else { 3225 try { 3226 mContext.enforceCallingOrSelfPermission( 3227 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3228 } catch (SecurityException se) { 3229 mContext.enforceCallingOrSelfPermission( 3230 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3231 } 3232 } 3233 } 3234 } 3235 3236 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3237 if (callingUid == Process.SHELL_UID) { 3238 if (userHandle >= 0 3239 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3240 throw new SecurityException("Shell does not have permission to access user " 3241 + userHandle); 3242 } else if (userHandle < 0) { 3243 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3244 + Debug.getCallers(3)); 3245 } 3246 } 3247 } 3248 3249 private BasePermission findPermissionTreeLP(String permName) { 3250 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3251 if (permName.startsWith(bp.name) && 3252 permName.length() > bp.name.length() && 3253 permName.charAt(bp.name.length()) == '.') { 3254 return bp; 3255 } 3256 } 3257 return null; 3258 } 3259 3260 private BasePermission checkPermissionTreeLP(String permName) { 3261 if (permName != null) { 3262 BasePermission bp = findPermissionTreeLP(permName); 3263 if (bp != null) { 3264 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3265 return bp; 3266 } 3267 throw new SecurityException("Calling uid " 3268 + Binder.getCallingUid() 3269 + " is not allowed to add to permission tree " 3270 + bp.name + " owned by uid " + bp.uid); 3271 } 3272 } 3273 throw new SecurityException("No permission tree found for " + permName); 3274 } 3275 3276 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3277 if (s1 == null) { 3278 return s2 == null; 3279 } 3280 if (s2 == null) { 3281 return false; 3282 } 3283 if (s1.getClass() != s2.getClass()) { 3284 return false; 3285 } 3286 return s1.equals(s2); 3287 } 3288 3289 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3290 if (pi1.icon != pi2.icon) return false; 3291 if (pi1.logo != pi2.logo) return false; 3292 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3293 if (!compareStrings(pi1.name, pi2.name)) return false; 3294 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3295 // We'll take care of setting this one. 3296 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3297 // These are not currently stored in settings. 3298 //if (!compareStrings(pi1.group, pi2.group)) return false; 3299 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3300 //if (pi1.labelRes != pi2.labelRes) return false; 3301 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3302 return true; 3303 } 3304 3305 int permissionInfoFootprint(PermissionInfo info) { 3306 int size = info.name.length(); 3307 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3308 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3309 return size; 3310 } 3311 3312 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3313 int size = 0; 3314 for (BasePermission perm : mSettings.mPermissions.values()) { 3315 if (perm.uid == tree.uid) { 3316 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3317 } 3318 } 3319 return size; 3320 } 3321 3322 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3323 // We calculate the max size of permissions defined by this uid and throw 3324 // if that plus the size of 'info' would exceed our stated maximum. 3325 if (tree.uid != Process.SYSTEM_UID) { 3326 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3327 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3328 throw new SecurityException("Permission tree size cap exceeded"); 3329 } 3330 } 3331 } 3332 3333 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3334 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3335 throw new SecurityException("Label must be specified in permission"); 3336 } 3337 BasePermission tree = checkPermissionTreeLP(info.name); 3338 BasePermission bp = mSettings.mPermissions.get(info.name); 3339 boolean added = bp == null; 3340 boolean changed = true; 3341 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3342 if (added) { 3343 enforcePermissionCapLocked(info, tree); 3344 bp = new BasePermission(info.name, tree.sourcePackage, 3345 BasePermission.TYPE_DYNAMIC); 3346 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3347 throw new SecurityException( 3348 "Not allowed to modify non-dynamic permission " 3349 + info.name); 3350 } else { 3351 if (bp.protectionLevel == fixedLevel 3352 && bp.perm.owner.equals(tree.perm.owner) 3353 && bp.uid == tree.uid 3354 && comparePermissionInfos(bp.perm.info, info)) { 3355 changed = false; 3356 } 3357 } 3358 bp.protectionLevel = fixedLevel; 3359 info = new PermissionInfo(info); 3360 info.protectionLevel = fixedLevel; 3361 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3362 bp.perm.info.packageName = tree.perm.info.packageName; 3363 bp.uid = tree.uid; 3364 if (added) { 3365 mSettings.mPermissions.put(info.name, bp); 3366 } 3367 if (changed) { 3368 if (!async) { 3369 mSettings.writeLPr(); 3370 } else { 3371 scheduleWriteSettingsLocked(); 3372 } 3373 } 3374 return added; 3375 } 3376 3377 @Override 3378 public boolean addPermission(PermissionInfo info) { 3379 synchronized (mPackages) { 3380 return addPermissionLocked(info, false); 3381 } 3382 } 3383 3384 @Override 3385 public boolean addPermissionAsync(PermissionInfo info) { 3386 synchronized (mPackages) { 3387 return addPermissionLocked(info, true); 3388 } 3389 } 3390 3391 @Override 3392 public void removePermission(String name) { 3393 synchronized (mPackages) { 3394 checkPermissionTreeLP(name); 3395 BasePermission bp = mSettings.mPermissions.get(name); 3396 if (bp != null) { 3397 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3398 throw new SecurityException( 3399 "Not allowed to modify non-dynamic permission " 3400 + name); 3401 } 3402 mSettings.mPermissions.remove(name); 3403 mSettings.writeLPr(); 3404 } 3405 } 3406 } 3407 3408 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3409 BasePermission bp) { 3410 int index = pkg.requestedPermissions.indexOf(bp.name); 3411 if (index == -1) { 3412 throw new SecurityException("Package " + pkg.packageName 3413 + " has not requested permission " + bp.name); 3414 } 3415 if (!bp.isRuntime()) { 3416 throw new SecurityException("Permission " + bp.name 3417 + " is not a changeable permission type"); 3418 } 3419 } 3420 3421 @Override 3422 public void grantRuntimePermission(String packageName, String name, final int userId) { 3423 if (!sUserManager.exists(userId)) { 3424 Log.e(TAG, "No such user:" + userId); 3425 return; 3426 } 3427 3428 mContext.enforceCallingOrSelfPermission( 3429 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3430 "grantRuntimePermission"); 3431 3432 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3433 "grantRuntimePermission"); 3434 3435 final int uid; 3436 final SettingBase sb; 3437 3438 synchronized (mPackages) { 3439 final PackageParser.Package pkg = mPackages.get(packageName); 3440 if (pkg == null) { 3441 throw new IllegalArgumentException("Unknown package: " + packageName); 3442 } 3443 3444 final BasePermission bp = mSettings.mPermissions.get(name); 3445 if (bp == null) { 3446 throw new IllegalArgumentException("Unknown permission: " + name); 3447 } 3448 3449 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3450 3451 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3452 sb = (SettingBase) pkg.mExtras; 3453 if (sb == null) { 3454 throw new IllegalArgumentException("Unknown package: " + packageName); 3455 } 3456 3457 final PermissionsState permissionsState = sb.getPermissionsState(); 3458 3459 final int flags = permissionsState.getPermissionFlags(name, userId); 3460 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3461 throw new SecurityException("Cannot grant system fixed permission: " 3462 + name + " for package: " + packageName); 3463 } 3464 3465 final int result = permissionsState.grantRuntimePermission(bp, userId); 3466 switch (result) { 3467 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3468 return; 3469 } 3470 3471 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3472 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3473 mHandler.post(new Runnable() { 3474 @Override 3475 public void run() { 3476 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3477 } 3478 }); 3479 } break; 3480 } 3481 3482 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3483 3484 // Not critical if that is lost - app has to request again. 3485 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3486 } 3487 3488 // Only need to do this if user is initialized. Otherwise it's a new user 3489 // and there are no processes running as the user yet and there's no need 3490 // to make an expensive call to remount processes for the changed permissions. 3491 if (READ_EXTERNAL_STORAGE.equals(name) 3492 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3493 final long token = Binder.clearCallingIdentity(); 3494 try { 3495 if (sUserManager.isInitialized(userId)) { 3496 MountServiceInternal mountServiceInternal = LocalServices.getService( 3497 MountServiceInternal.class); 3498 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3499 } 3500 } finally { 3501 Binder.restoreCallingIdentity(token); 3502 } 3503 } 3504 } 3505 3506 @Override 3507 public void revokeRuntimePermission(String packageName, String name, int userId) { 3508 if (!sUserManager.exists(userId)) { 3509 Log.e(TAG, "No such user:" + userId); 3510 return; 3511 } 3512 3513 mContext.enforceCallingOrSelfPermission( 3514 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3515 "revokeRuntimePermission"); 3516 3517 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3518 "revokeRuntimePermission"); 3519 3520 final int appId; 3521 3522 synchronized (mPackages) { 3523 final PackageParser.Package pkg = mPackages.get(packageName); 3524 if (pkg == null) { 3525 throw new IllegalArgumentException("Unknown package: " + packageName); 3526 } 3527 3528 final BasePermission bp = mSettings.mPermissions.get(name); 3529 if (bp == null) { 3530 throw new IllegalArgumentException("Unknown permission: " + name); 3531 } 3532 3533 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3534 3535 SettingBase sb = (SettingBase) pkg.mExtras; 3536 if (sb == null) { 3537 throw new IllegalArgumentException("Unknown package: " + packageName); 3538 } 3539 3540 final PermissionsState permissionsState = sb.getPermissionsState(); 3541 3542 final int flags = permissionsState.getPermissionFlags(name, userId); 3543 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3544 throw new SecurityException("Cannot revoke system fixed permission: " 3545 + name + " for package: " + packageName); 3546 } 3547 3548 if (permissionsState.revokeRuntimePermission(bp, userId) == 3549 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3550 return; 3551 } 3552 3553 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3554 3555 // Critical, after this call app should never have the permission. 3556 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3557 3558 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3559 } 3560 3561 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3562 } 3563 3564 @Override 3565 public void resetRuntimePermissions() { 3566 mContext.enforceCallingOrSelfPermission( 3567 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3568 "revokeRuntimePermission"); 3569 3570 int callingUid = Binder.getCallingUid(); 3571 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3572 mContext.enforceCallingOrSelfPermission( 3573 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3574 "resetRuntimePermissions"); 3575 } 3576 3577 synchronized (mPackages) { 3578 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3579 for (int userId : UserManagerService.getInstance().getUserIds()) { 3580 final int packageCount = mPackages.size(); 3581 for (int i = 0; i < packageCount; i++) { 3582 PackageParser.Package pkg = mPackages.valueAt(i); 3583 if (!(pkg.mExtras instanceof PackageSetting)) { 3584 continue; 3585 } 3586 PackageSetting ps = (PackageSetting) pkg.mExtras; 3587 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3588 } 3589 } 3590 } 3591 } 3592 3593 @Override 3594 public int getPermissionFlags(String name, String packageName, int userId) { 3595 if (!sUserManager.exists(userId)) { 3596 return 0; 3597 } 3598 3599 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3600 3601 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3602 "getPermissionFlags"); 3603 3604 synchronized (mPackages) { 3605 final PackageParser.Package pkg = mPackages.get(packageName); 3606 if (pkg == null) { 3607 throw new IllegalArgumentException("Unknown package: " + packageName); 3608 } 3609 3610 final BasePermission bp = mSettings.mPermissions.get(name); 3611 if (bp == null) { 3612 throw new IllegalArgumentException("Unknown permission: " + name); 3613 } 3614 3615 SettingBase sb = (SettingBase) pkg.mExtras; 3616 if (sb == null) { 3617 throw new IllegalArgumentException("Unknown package: " + packageName); 3618 } 3619 3620 PermissionsState permissionsState = sb.getPermissionsState(); 3621 return permissionsState.getPermissionFlags(name, userId); 3622 } 3623 } 3624 3625 @Override 3626 public void updatePermissionFlags(String name, String packageName, int flagMask, 3627 int flagValues, int userId) { 3628 if (!sUserManager.exists(userId)) { 3629 return; 3630 } 3631 3632 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3633 3634 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3635 "updatePermissionFlags"); 3636 3637 // Only the system can change these flags and nothing else. 3638 if (getCallingUid() != Process.SYSTEM_UID) { 3639 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3640 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3641 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3642 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3643 } 3644 3645 synchronized (mPackages) { 3646 final PackageParser.Package pkg = mPackages.get(packageName); 3647 if (pkg == null) { 3648 throw new IllegalArgumentException("Unknown package: " + packageName); 3649 } 3650 3651 final BasePermission bp = mSettings.mPermissions.get(name); 3652 if (bp == null) { 3653 throw new IllegalArgumentException("Unknown permission: " + name); 3654 } 3655 3656 SettingBase sb = (SettingBase) pkg.mExtras; 3657 if (sb == null) { 3658 throw new IllegalArgumentException("Unknown package: " + packageName); 3659 } 3660 3661 PermissionsState permissionsState = sb.getPermissionsState(); 3662 3663 // Only the package manager can change flags for system component permissions. 3664 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3665 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3666 return; 3667 } 3668 3669 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3670 3671 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3672 // Install and runtime permissions are stored in different places, 3673 // so figure out what permission changed and persist the change. 3674 if (permissionsState.getInstallPermissionState(name) != null) { 3675 scheduleWriteSettingsLocked(); 3676 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3677 || hadState) { 3678 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3679 } 3680 } 3681 } 3682 } 3683 3684 /** 3685 * Update the permission flags for all packages and runtime permissions of a user in order 3686 * to allow device or profile owner to remove POLICY_FIXED. 3687 */ 3688 @Override 3689 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3690 if (!sUserManager.exists(userId)) { 3691 return; 3692 } 3693 3694 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3695 3696 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3697 "updatePermissionFlagsForAllApps"); 3698 3699 // Only the system can change system fixed flags. 3700 if (getCallingUid() != Process.SYSTEM_UID) { 3701 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3702 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3703 } 3704 3705 synchronized (mPackages) { 3706 boolean changed = false; 3707 final int packageCount = mPackages.size(); 3708 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3709 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3710 SettingBase sb = (SettingBase) pkg.mExtras; 3711 if (sb == null) { 3712 continue; 3713 } 3714 PermissionsState permissionsState = sb.getPermissionsState(); 3715 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3716 userId, flagMask, flagValues); 3717 } 3718 if (changed) { 3719 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3720 } 3721 } 3722 } 3723 3724 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3725 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3726 != PackageManager.PERMISSION_GRANTED 3727 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3728 != PackageManager.PERMISSION_GRANTED) { 3729 throw new SecurityException(message + " requires " 3730 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3731 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3732 } 3733 } 3734 3735 @Override 3736 public boolean shouldShowRequestPermissionRationale(String permissionName, 3737 String packageName, int userId) { 3738 if (UserHandle.getCallingUserId() != userId) { 3739 mContext.enforceCallingPermission( 3740 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3741 "canShowRequestPermissionRationale for user " + userId); 3742 } 3743 3744 final int uid = getPackageUid(packageName, userId); 3745 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3746 return false; 3747 } 3748 3749 if (checkPermission(permissionName, packageName, userId) 3750 == PackageManager.PERMISSION_GRANTED) { 3751 return false; 3752 } 3753 3754 final int flags; 3755 3756 final long identity = Binder.clearCallingIdentity(); 3757 try { 3758 flags = getPermissionFlags(permissionName, 3759 packageName, userId); 3760 } finally { 3761 Binder.restoreCallingIdentity(identity); 3762 } 3763 3764 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3765 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3766 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3767 3768 if ((flags & fixedFlags) != 0) { 3769 return false; 3770 } 3771 3772 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3773 } 3774 3775 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3776 BasePermission bp = mSettings.mPermissions.get(permission); 3777 if (bp == null) { 3778 throw new SecurityException("Missing " + permission + " permission"); 3779 } 3780 3781 SettingBase sb = (SettingBase) pkg.mExtras; 3782 PermissionsState permissionsState = sb.getPermissionsState(); 3783 3784 if (permissionsState.grantInstallPermission(bp) != 3785 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3786 scheduleWriteSettingsLocked(); 3787 } 3788 } 3789 3790 @Override 3791 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3792 mContext.enforceCallingOrSelfPermission( 3793 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3794 "addOnPermissionsChangeListener"); 3795 3796 synchronized (mPackages) { 3797 mOnPermissionChangeListeners.addListenerLocked(listener); 3798 } 3799 } 3800 3801 @Override 3802 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3803 synchronized (mPackages) { 3804 mOnPermissionChangeListeners.removeListenerLocked(listener); 3805 } 3806 } 3807 3808 @Override 3809 public boolean isProtectedBroadcast(String actionName) { 3810 synchronized (mPackages) { 3811 return mProtectedBroadcasts.contains(actionName); 3812 } 3813 } 3814 3815 @Override 3816 public int checkSignatures(String pkg1, String pkg2) { 3817 synchronized (mPackages) { 3818 final PackageParser.Package p1 = mPackages.get(pkg1); 3819 final PackageParser.Package p2 = mPackages.get(pkg2); 3820 if (p1 == null || p1.mExtras == null 3821 || p2 == null || p2.mExtras == null) { 3822 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3823 } 3824 return compareSignatures(p1.mSignatures, p2.mSignatures); 3825 } 3826 } 3827 3828 @Override 3829 public int checkUidSignatures(int uid1, int uid2) { 3830 // Map to base uids. 3831 uid1 = UserHandle.getAppId(uid1); 3832 uid2 = UserHandle.getAppId(uid2); 3833 // reader 3834 synchronized (mPackages) { 3835 Signature[] s1; 3836 Signature[] s2; 3837 Object obj = mSettings.getUserIdLPr(uid1); 3838 if (obj != null) { 3839 if (obj instanceof SharedUserSetting) { 3840 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3841 } else if (obj instanceof PackageSetting) { 3842 s1 = ((PackageSetting)obj).signatures.mSignatures; 3843 } else { 3844 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3845 } 3846 } else { 3847 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3848 } 3849 obj = mSettings.getUserIdLPr(uid2); 3850 if (obj != null) { 3851 if (obj instanceof SharedUserSetting) { 3852 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3853 } else if (obj instanceof PackageSetting) { 3854 s2 = ((PackageSetting)obj).signatures.mSignatures; 3855 } else { 3856 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3857 } 3858 } else { 3859 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3860 } 3861 return compareSignatures(s1, s2); 3862 } 3863 } 3864 3865 private void killUid(int appId, int userId, String reason) { 3866 final long identity = Binder.clearCallingIdentity(); 3867 try { 3868 IActivityManager am = ActivityManagerNative.getDefault(); 3869 if (am != null) { 3870 try { 3871 am.killUid(appId, userId, reason); 3872 } catch (RemoteException e) { 3873 /* ignore - same process */ 3874 } 3875 } 3876 } finally { 3877 Binder.restoreCallingIdentity(identity); 3878 } 3879 } 3880 3881 /** 3882 * Compares two sets of signatures. Returns: 3883 * <br /> 3884 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3885 * <br /> 3886 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3887 * <br /> 3888 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3889 * <br /> 3890 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3891 * <br /> 3892 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3893 */ 3894 static int compareSignatures(Signature[] s1, Signature[] s2) { 3895 if (s1 == null) { 3896 return s2 == null 3897 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3898 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3899 } 3900 3901 if (s2 == null) { 3902 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3903 } 3904 3905 if (s1.length != s2.length) { 3906 return PackageManager.SIGNATURE_NO_MATCH; 3907 } 3908 3909 // Since both signature sets are of size 1, we can compare without HashSets. 3910 if (s1.length == 1) { 3911 return s1[0].equals(s2[0]) ? 3912 PackageManager.SIGNATURE_MATCH : 3913 PackageManager.SIGNATURE_NO_MATCH; 3914 } 3915 3916 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3917 for (Signature sig : s1) { 3918 set1.add(sig); 3919 } 3920 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3921 for (Signature sig : s2) { 3922 set2.add(sig); 3923 } 3924 // Make sure s2 contains all signatures in s1. 3925 if (set1.equals(set2)) { 3926 return PackageManager.SIGNATURE_MATCH; 3927 } 3928 return PackageManager.SIGNATURE_NO_MATCH; 3929 } 3930 3931 /** 3932 * If the database version for this type of package (internal storage or 3933 * external storage) is less than the version where package signatures 3934 * were updated, return true. 3935 */ 3936 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3937 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3938 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3939 } 3940 3941 /** 3942 * Used for backward compatibility to make sure any packages with 3943 * certificate chains get upgraded to the new style. {@code existingSigs} 3944 * will be in the old format (since they were stored on disk from before the 3945 * system upgrade) and {@code scannedSigs} will be in the newer format. 3946 */ 3947 private int compareSignaturesCompat(PackageSignatures existingSigs, 3948 PackageParser.Package scannedPkg) { 3949 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3950 return PackageManager.SIGNATURE_NO_MATCH; 3951 } 3952 3953 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3954 for (Signature sig : existingSigs.mSignatures) { 3955 existingSet.add(sig); 3956 } 3957 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3958 for (Signature sig : scannedPkg.mSignatures) { 3959 try { 3960 Signature[] chainSignatures = sig.getChainSignatures(); 3961 for (Signature chainSig : chainSignatures) { 3962 scannedCompatSet.add(chainSig); 3963 } 3964 } catch (CertificateEncodingException e) { 3965 scannedCompatSet.add(sig); 3966 } 3967 } 3968 /* 3969 * Make sure the expanded scanned set contains all signatures in the 3970 * existing one. 3971 */ 3972 if (scannedCompatSet.equals(existingSet)) { 3973 // Migrate the old signatures to the new scheme. 3974 existingSigs.assignSignatures(scannedPkg.mSignatures); 3975 // The new KeySets will be re-added later in the scanning process. 3976 synchronized (mPackages) { 3977 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3978 } 3979 return PackageManager.SIGNATURE_MATCH; 3980 } 3981 return PackageManager.SIGNATURE_NO_MATCH; 3982 } 3983 3984 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3985 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3986 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 3987 } 3988 3989 private int compareSignaturesRecover(PackageSignatures existingSigs, 3990 PackageParser.Package scannedPkg) { 3991 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3992 return PackageManager.SIGNATURE_NO_MATCH; 3993 } 3994 3995 String msg = null; 3996 try { 3997 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3998 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3999 + scannedPkg.packageName); 4000 return PackageManager.SIGNATURE_MATCH; 4001 } 4002 } catch (CertificateException e) { 4003 msg = e.getMessage(); 4004 } 4005 4006 logCriticalInfo(Log.INFO, 4007 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4008 return PackageManager.SIGNATURE_NO_MATCH; 4009 } 4010 4011 @Override 4012 public String[] getPackagesForUid(int uid) { 4013 uid = UserHandle.getAppId(uid); 4014 // reader 4015 synchronized (mPackages) { 4016 Object obj = mSettings.getUserIdLPr(uid); 4017 if (obj instanceof SharedUserSetting) { 4018 final SharedUserSetting sus = (SharedUserSetting) obj; 4019 final int N = sus.packages.size(); 4020 final String[] res = new String[N]; 4021 final Iterator<PackageSetting> it = sus.packages.iterator(); 4022 int i = 0; 4023 while (it.hasNext()) { 4024 res[i++] = it.next().name; 4025 } 4026 return res; 4027 } else if (obj instanceof PackageSetting) { 4028 final PackageSetting ps = (PackageSetting) obj; 4029 return new String[] { ps.name }; 4030 } 4031 } 4032 return null; 4033 } 4034 4035 @Override 4036 public String getNameForUid(int uid) { 4037 // reader 4038 synchronized (mPackages) { 4039 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4040 if (obj instanceof SharedUserSetting) { 4041 final SharedUserSetting sus = (SharedUserSetting) obj; 4042 return sus.name + ":" + sus.userId; 4043 } else if (obj instanceof PackageSetting) { 4044 final PackageSetting ps = (PackageSetting) obj; 4045 return ps.name; 4046 } 4047 } 4048 return null; 4049 } 4050 4051 @Override 4052 public int getUidForSharedUser(String sharedUserName) { 4053 if(sharedUserName == null) { 4054 return -1; 4055 } 4056 // reader 4057 synchronized (mPackages) { 4058 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4059 if (suid == null) { 4060 return -1; 4061 } 4062 return suid.userId; 4063 } 4064 } 4065 4066 @Override 4067 public int getFlagsForUid(int uid) { 4068 synchronized (mPackages) { 4069 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4070 if (obj instanceof SharedUserSetting) { 4071 final SharedUserSetting sus = (SharedUserSetting) obj; 4072 return sus.pkgFlags; 4073 } else if (obj instanceof PackageSetting) { 4074 final PackageSetting ps = (PackageSetting) obj; 4075 return ps.pkgFlags; 4076 } 4077 } 4078 return 0; 4079 } 4080 4081 @Override 4082 public int getPrivateFlagsForUid(int uid) { 4083 synchronized (mPackages) { 4084 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4085 if (obj instanceof SharedUserSetting) { 4086 final SharedUserSetting sus = (SharedUserSetting) obj; 4087 return sus.pkgPrivateFlags; 4088 } else if (obj instanceof PackageSetting) { 4089 final PackageSetting ps = (PackageSetting) obj; 4090 return ps.pkgPrivateFlags; 4091 } 4092 } 4093 return 0; 4094 } 4095 4096 @Override 4097 public boolean isUidPrivileged(int uid) { 4098 uid = UserHandle.getAppId(uid); 4099 // reader 4100 synchronized (mPackages) { 4101 Object obj = mSettings.getUserIdLPr(uid); 4102 if (obj instanceof SharedUserSetting) { 4103 final SharedUserSetting sus = (SharedUserSetting) obj; 4104 final Iterator<PackageSetting> it = sus.packages.iterator(); 4105 while (it.hasNext()) { 4106 if (it.next().isPrivileged()) { 4107 return true; 4108 } 4109 } 4110 } else if (obj instanceof PackageSetting) { 4111 final PackageSetting ps = (PackageSetting) obj; 4112 return ps.isPrivileged(); 4113 } 4114 } 4115 return false; 4116 } 4117 4118 @Override 4119 public String[] getAppOpPermissionPackages(String permissionName) { 4120 synchronized (mPackages) { 4121 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4122 if (pkgs == null) { 4123 return null; 4124 } 4125 return pkgs.toArray(new String[pkgs.size()]); 4126 } 4127 } 4128 4129 @Override 4130 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4131 int flags, int userId) { 4132 if (!sUserManager.exists(userId)) return null; 4133 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4134 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4135 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4136 } 4137 4138 @Override 4139 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4140 IntentFilter filter, int match, ComponentName activity) { 4141 final int userId = UserHandle.getCallingUserId(); 4142 if (DEBUG_PREFERRED) { 4143 Log.v(TAG, "setLastChosenActivity intent=" + intent 4144 + " resolvedType=" + resolvedType 4145 + " flags=" + flags 4146 + " filter=" + filter 4147 + " match=" + match 4148 + " activity=" + activity); 4149 filter.dump(new PrintStreamPrinter(System.out), " "); 4150 } 4151 intent.setComponent(null); 4152 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4153 // Find any earlier preferred or last chosen entries and nuke them 4154 findPreferredActivity(intent, resolvedType, 4155 flags, query, 0, false, true, false, userId); 4156 // Add the new activity as the last chosen for this filter 4157 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4158 "Setting last chosen"); 4159 } 4160 4161 @Override 4162 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4163 final int userId = UserHandle.getCallingUserId(); 4164 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4165 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4166 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4167 false, false, false, userId); 4168 } 4169 4170 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4171 int flags, List<ResolveInfo> query, int userId) { 4172 if (query != null) { 4173 final int N = query.size(); 4174 if (N == 1) { 4175 return query.get(0); 4176 } else if (N > 1) { 4177 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4178 // If there is more than one activity with the same priority, 4179 // then let the user decide between them. 4180 ResolveInfo r0 = query.get(0); 4181 ResolveInfo r1 = query.get(1); 4182 if (DEBUG_INTENT_MATCHING || debug) { 4183 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4184 + r1.activityInfo.name + "=" + r1.priority); 4185 } 4186 // If the first activity has a higher priority, or a different 4187 // default, then it is always desireable to pick it. 4188 if (r0.priority != r1.priority 4189 || r0.preferredOrder != r1.preferredOrder 4190 || r0.isDefault != r1.isDefault) { 4191 return query.get(0); 4192 } 4193 // If we have saved a preference for a preferred activity for 4194 // this Intent, use that. 4195 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4196 flags, query, r0.priority, true, false, debug, userId); 4197 if (ri != null) { 4198 return ri; 4199 } 4200 if (userId != 0) { 4201 ri = new ResolveInfo(mResolveInfo); 4202 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4203 ri.activityInfo.applicationInfo = new ApplicationInfo( 4204 ri.activityInfo.applicationInfo); 4205 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4206 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4207 return ri; 4208 } 4209 return mResolveInfo; 4210 } 4211 } 4212 return null; 4213 } 4214 4215 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4216 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4217 final int N = query.size(); 4218 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4219 .get(userId); 4220 // Get the list of persistent preferred activities that handle the intent 4221 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4222 List<PersistentPreferredActivity> pprefs = ppir != null 4223 ? ppir.queryIntent(intent, resolvedType, 4224 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4225 : null; 4226 if (pprefs != null && pprefs.size() > 0) { 4227 final int M = pprefs.size(); 4228 for (int i=0; i<M; i++) { 4229 final PersistentPreferredActivity ppa = pprefs.get(i); 4230 if (DEBUG_PREFERRED || debug) { 4231 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4232 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4233 + "\n component=" + ppa.mComponent); 4234 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4235 } 4236 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4237 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4238 if (DEBUG_PREFERRED || debug) { 4239 Slog.v(TAG, "Found persistent preferred activity:"); 4240 if (ai != null) { 4241 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4242 } else { 4243 Slog.v(TAG, " null"); 4244 } 4245 } 4246 if (ai == null) { 4247 // This previously registered persistent preferred activity 4248 // component is no longer known. Ignore it and do NOT remove it. 4249 continue; 4250 } 4251 for (int j=0; j<N; j++) { 4252 final ResolveInfo ri = query.get(j); 4253 if (!ri.activityInfo.applicationInfo.packageName 4254 .equals(ai.applicationInfo.packageName)) { 4255 continue; 4256 } 4257 if (!ri.activityInfo.name.equals(ai.name)) { 4258 continue; 4259 } 4260 // Found a persistent preference that can handle the intent. 4261 if (DEBUG_PREFERRED || debug) { 4262 Slog.v(TAG, "Returning persistent preferred activity: " + 4263 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4264 } 4265 return ri; 4266 } 4267 } 4268 } 4269 return null; 4270 } 4271 4272 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4273 List<ResolveInfo> query, int priority, boolean always, 4274 boolean removeMatches, boolean debug, int userId) { 4275 if (!sUserManager.exists(userId)) return null; 4276 // writer 4277 synchronized (mPackages) { 4278 if (intent.getSelector() != null) { 4279 intent = intent.getSelector(); 4280 } 4281 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4282 4283 // Try to find a matching persistent preferred activity. 4284 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4285 debug, userId); 4286 4287 // If a persistent preferred activity matched, use it. 4288 if (pri != null) { 4289 return pri; 4290 } 4291 4292 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4293 // Get the list of preferred activities that handle the intent 4294 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4295 List<PreferredActivity> prefs = pir != null 4296 ? pir.queryIntent(intent, resolvedType, 4297 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4298 : null; 4299 if (prefs != null && prefs.size() > 0) { 4300 boolean changed = false; 4301 try { 4302 // First figure out how good the original match set is. 4303 // We will only allow preferred activities that came 4304 // from the same match quality. 4305 int match = 0; 4306 4307 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4308 4309 final int N = query.size(); 4310 for (int j=0; j<N; j++) { 4311 final ResolveInfo ri = query.get(j); 4312 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4313 + ": 0x" + Integer.toHexString(match)); 4314 if (ri.match > match) { 4315 match = ri.match; 4316 } 4317 } 4318 4319 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4320 + Integer.toHexString(match)); 4321 4322 match &= IntentFilter.MATCH_CATEGORY_MASK; 4323 final int M = prefs.size(); 4324 for (int i=0; i<M; i++) { 4325 final PreferredActivity pa = prefs.get(i); 4326 if (DEBUG_PREFERRED || debug) { 4327 Slog.v(TAG, "Checking PreferredActivity ds=" 4328 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4329 + "\n component=" + pa.mPref.mComponent); 4330 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4331 } 4332 if (pa.mPref.mMatch != match) { 4333 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4334 + Integer.toHexString(pa.mPref.mMatch)); 4335 continue; 4336 } 4337 // If it's not an "always" type preferred activity and that's what we're 4338 // looking for, skip it. 4339 if (always && !pa.mPref.mAlways) { 4340 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4341 continue; 4342 } 4343 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4344 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4345 if (DEBUG_PREFERRED || debug) { 4346 Slog.v(TAG, "Found preferred activity:"); 4347 if (ai != null) { 4348 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4349 } else { 4350 Slog.v(TAG, " null"); 4351 } 4352 } 4353 if (ai == null) { 4354 // This previously registered preferred activity 4355 // component is no longer known. Most likely an update 4356 // to the app was installed and in the new version this 4357 // component no longer exists. Clean it up by removing 4358 // it from the preferred activities list, and skip it. 4359 Slog.w(TAG, "Removing dangling preferred activity: " 4360 + pa.mPref.mComponent); 4361 pir.removeFilter(pa); 4362 changed = true; 4363 continue; 4364 } 4365 for (int j=0; j<N; j++) { 4366 final ResolveInfo ri = query.get(j); 4367 if (!ri.activityInfo.applicationInfo.packageName 4368 .equals(ai.applicationInfo.packageName)) { 4369 continue; 4370 } 4371 if (!ri.activityInfo.name.equals(ai.name)) { 4372 continue; 4373 } 4374 4375 if (removeMatches) { 4376 pir.removeFilter(pa); 4377 changed = true; 4378 if (DEBUG_PREFERRED) { 4379 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4380 } 4381 break; 4382 } 4383 4384 // Okay we found a previously set preferred or last chosen app. 4385 // If the result set is different from when this 4386 // was created, we need to clear it and re-ask the 4387 // user their preference, if we're looking for an "always" type entry. 4388 if (always && !pa.mPref.sameSet(query)) { 4389 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4390 + intent + " type " + resolvedType); 4391 if (DEBUG_PREFERRED) { 4392 Slog.v(TAG, "Removing preferred activity since set changed " 4393 + pa.mPref.mComponent); 4394 } 4395 pir.removeFilter(pa); 4396 // Re-add the filter as a "last chosen" entry (!always) 4397 PreferredActivity lastChosen = new PreferredActivity( 4398 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4399 pir.addFilter(lastChosen); 4400 changed = true; 4401 return null; 4402 } 4403 4404 // Yay! Either the set matched or we're looking for the last chosen 4405 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4406 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4407 return ri; 4408 } 4409 } 4410 } finally { 4411 if (changed) { 4412 if (DEBUG_PREFERRED) { 4413 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4414 } 4415 scheduleWritePackageRestrictionsLocked(userId); 4416 } 4417 } 4418 } 4419 } 4420 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4421 return null; 4422 } 4423 4424 /* 4425 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4426 */ 4427 @Override 4428 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4429 int targetUserId) { 4430 mContext.enforceCallingOrSelfPermission( 4431 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4432 List<CrossProfileIntentFilter> matches = 4433 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4434 if (matches != null) { 4435 int size = matches.size(); 4436 for (int i = 0; i < size; i++) { 4437 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4438 } 4439 } 4440 if (hasWebURI(intent)) { 4441 // cross-profile app linking works only towards the parent. 4442 final UserInfo parent = getProfileParent(sourceUserId); 4443 synchronized(mPackages) { 4444 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4445 intent, resolvedType, 0, sourceUserId, parent.id); 4446 return xpDomainInfo != null; 4447 } 4448 } 4449 return false; 4450 } 4451 4452 private UserInfo getProfileParent(int userId) { 4453 final long identity = Binder.clearCallingIdentity(); 4454 try { 4455 return sUserManager.getProfileParent(userId); 4456 } finally { 4457 Binder.restoreCallingIdentity(identity); 4458 } 4459 } 4460 4461 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4462 String resolvedType, int userId) { 4463 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4464 if (resolver != null) { 4465 return resolver.queryIntent(intent, resolvedType, false, userId); 4466 } 4467 return null; 4468 } 4469 4470 @Override 4471 public List<ResolveInfo> queryIntentActivities(Intent intent, 4472 String resolvedType, int flags, int userId) { 4473 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4474 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4475 ComponentName comp = intent.getComponent(); 4476 if (comp == null) { 4477 if (intent.getSelector() != null) { 4478 intent = intent.getSelector(); 4479 comp = intent.getComponent(); 4480 } 4481 } 4482 4483 if (comp != null) { 4484 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4485 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4486 if (ai != null) { 4487 final ResolveInfo ri = new ResolveInfo(); 4488 ri.activityInfo = ai; 4489 list.add(ri); 4490 } 4491 return list; 4492 } 4493 4494 // reader 4495 synchronized (mPackages) { 4496 final String pkgName = intent.getPackage(); 4497 if (pkgName == null) { 4498 List<CrossProfileIntentFilter> matchingFilters = 4499 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4500 // Check for results that need to skip the current profile. 4501 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4502 resolvedType, flags, userId); 4503 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4504 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4505 result.add(xpResolveInfo); 4506 return filterIfNotPrimaryUser(result, userId); 4507 } 4508 4509 // Check for results in the current profile. 4510 List<ResolveInfo> result = mActivities.queryIntent( 4511 intent, resolvedType, flags, userId); 4512 4513 // Check for cross profile results. 4514 xpResolveInfo = queryCrossProfileIntents( 4515 matchingFilters, intent, resolvedType, flags, userId); 4516 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4517 result.add(xpResolveInfo); 4518 Collections.sort(result, mResolvePrioritySorter); 4519 } 4520 result = filterIfNotPrimaryUser(result, userId); 4521 if (hasWebURI(intent)) { 4522 CrossProfileDomainInfo xpDomainInfo = null; 4523 final UserInfo parent = getProfileParent(userId); 4524 if (parent != null) { 4525 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4526 flags, userId, parent.id); 4527 } 4528 if (xpDomainInfo != null) { 4529 if (xpResolveInfo != null) { 4530 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4531 // in the result. 4532 result.remove(xpResolveInfo); 4533 } 4534 if (result.size() == 0) { 4535 result.add(xpDomainInfo.resolveInfo); 4536 return result; 4537 } 4538 } else if (result.size() <= 1) { 4539 return result; 4540 } 4541 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4542 xpDomainInfo, userId); 4543 Collections.sort(result, mResolvePrioritySorter); 4544 } 4545 return result; 4546 } 4547 final PackageParser.Package pkg = mPackages.get(pkgName); 4548 if (pkg != null) { 4549 return filterIfNotPrimaryUser( 4550 mActivities.queryIntentForPackage( 4551 intent, resolvedType, flags, pkg.activities, userId), 4552 userId); 4553 } 4554 return new ArrayList<ResolveInfo>(); 4555 } 4556 } 4557 4558 private static class CrossProfileDomainInfo { 4559 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4560 ResolveInfo resolveInfo; 4561 /* Best domain verification status of the activities found in the other profile */ 4562 int bestDomainVerificationStatus; 4563 } 4564 4565 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4566 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4567 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4568 sourceUserId)) { 4569 return null; 4570 } 4571 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4572 resolvedType, flags, parentUserId); 4573 4574 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4575 return null; 4576 } 4577 CrossProfileDomainInfo result = null; 4578 int size = resultTargetUser.size(); 4579 for (int i = 0; i < size; i++) { 4580 ResolveInfo riTargetUser = resultTargetUser.get(i); 4581 // Intent filter verification is only for filters that specify a host. So don't return 4582 // those that handle all web uris. 4583 if (riTargetUser.handleAllWebDataURI) { 4584 continue; 4585 } 4586 String packageName = riTargetUser.activityInfo.packageName; 4587 PackageSetting ps = mSettings.mPackages.get(packageName); 4588 if (ps == null) { 4589 continue; 4590 } 4591 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4592 int status = (int)(verificationState >> 32); 4593 if (result == null) { 4594 result = new CrossProfileDomainInfo(); 4595 result.resolveInfo = 4596 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4597 result.bestDomainVerificationStatus = status; 4598 } else { 4599 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4600 result.bestDomainVerificationStatus); 4601 } 4602 } 4603 // Don't consider matches with status NEVER across profiles. 4604 if (result != null && result.bestDomainVerificationStatus 4605 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4606 return null; 4607 } 4608 return result; 4609 } 4610 4611 /** 4612 * Verification statuses are ordered from the worse to the best, except for 4613 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4614 */ 4615 private int bestDomainVerificationStatus(int status1, int status2) { 4616 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4617 return status2; 4618 } 4619 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4620 return status1; 4621 } 4622 return (int) MathUtils.max(status1, status2); 4623 } 4624 4625 private boolean isUserEnabled(int userId) { 4626 long callingId = Binder.clearCallingIdentity(); 4627 try { 4628 UserInfo userInfo = sUserManager.getUserInfo(userId); 4629 return userInfo != null && userInfo.isEnabled(); 4630 } finally { 4631 Binder.restoreCallingIdentity(callingId); 4632 } 4633 } 4634 4635 /** 4636 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4637 * 4638 * @return filtered list 4639 */ 4640 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4641 if (userId == UserHandle.USER_OWNER) { 4642 return resolveInfos; 4643 } 4644 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4645 ResolveInfo info = resolveInfos.get(i); 4646 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4647 resolveInfos.remove(i); 4648 } 4649 } 4650 return resolveInfos; 4651 } 4652 4653 private static boolean hasWebURI(Intent intent) { 4654 if (intent.getData() == null) { 4655 return false; 4656 } 4657 final String scheme = intent.getScheme(); 4658 if (TextUtils.isEmpty(scheme)) { 4659 return false; 4660 } 4661 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4662 } 4663 4664 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4665 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4666 int userId) { 4667 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4668 4669 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4670 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4671 candidates.size()); 4672 } 4673 4674 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4675 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4676 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4677 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4678 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4679 4680 synchronized (mPackages) { 4681 final int count = candidates.size(); 4682 // First, try to use linked apps. Partition the candidates into four lists: 4683 // one for the final results, one for the "do not use ever", one for "undefined status" 4684 // and finally one for "browser app type". 4685 for (int n=0; n<count; n++) { 4686 ResolveInfo info = candidates.get(n); 4687 String packageName = info.activityInfo.packageName; 4688 PackageSetting ps = mSettings.mPackages.get(packageName); 4689 if (ps != null) { 4690 // Add to the special match all list (Browser use case) 4691 if (info.handleAllWebDataURI) { 4692 matchAllList.add(info); 4693 continue; 4694 } 4695 // Try to get the status from User settings first 4696 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4697 int status = (int)(packedStatus >> 32); 4698 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4699 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4700 if (DEBUG_DOMAIN_VERIFICATION) { 4701 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4702 + " : linkgen=" + linkGeneration); 4703 } 4704 // Use link-enabled generation as preferredOrder, i.e. 4705 // prefer newly-enabled over earlier-enabled. 4706 info.preferredOrder = linkGeneration; 4707 alwaysList.add(info); 4708 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4709 if (DEBUG_DOMAIN_VERIFICATION) { 4710 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4711 } 4712 neverList.add(info); 4713 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4714 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4715 if (DEBUG_DOMAIN_VERIFICATION) { 4716 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4717 } 4718 undefinedList.add(info); 4719 } 4720 } 4721 } 4722 // First try to add the "always" resolution(s) for the current user, if any 4723 if (alwaysList.size() > 0) { 4724 result.addAll(alwaysList); 4725 // if there is an "always" for the parent user, add it. 4726 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4727 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4728 result.add(xpDomainInfo.resolveInfo); 4729 } else { 4730 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4731 result.addAll(undefinedList); 4732 if (xpDomainInfo != null && ( 4733 xpDomainInfo.bestDomainVerificationStatus 4734 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4735 || xpDomainInfo.bestDomainVerificationStatus 4736 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4737 result.add(xpDomainInfo.resolveInfo); 4738 } 4739 // Also add Browsers (all of them or only the default one) 4740 if ((matchFlags & MATCH_ALL) != 0) { 4741 result.addAll(matchAllList); 4742 } else { 4743 // Browser/generic handling case. If there's a default browser, go straight 4744 // to that (but only if there is no other higher-priority match). 4745 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4746 int maxMatchPrio = 0; 4747 ResolveInfo defaultBrowserMatch = null; 4748 final int numCandidates = matchAllList.size(); 4749 for (int n = 0; n < numCandidates; n++) { 4750 ResolveInfo info = matchAllList.get(n); 4751 // track the highest overall match priority... 4752 if (info.priority > maxMatchPrio) { 4753 maxMatchPrio = info.priority; 4754 } 4755 // ...and the highest-priority default browser match 4756 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4757 if (defaultBrowserMatch == null 4758 || (defaultBrowserMatch.priority < info.priority)) { 4759 if (debug) { 4760 Slog.v(TAG, "Considering default browser match " + info); 4761 } 4762 defaultBrowserMatch = info; 4763 } 4764 } 4765 } 4766 if (defaultBrowserMatch != null 4767 && defaultBrowserMatch.priority >= maxMatchPrio 4768 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4769 { 4770 if (debug) { 4771 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4772 } 4773 result.add(defaultBrowserMatch); 4774 } else { 4775 result.addAll(matchAllList); 4776 } 4777 } 4778 4779 // If there is nothing selected, add all candidates and remove the ones that the user 4780 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4781 if (result.size() == 0) { 4782 result.addAll(candidates); 4783 result.removeAll(neverList); 4784 } 4785 } 4786 } 4787 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4788 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4789 result.size()); 4790 for (ResolveInfo info : result) { 4791 Slog.v(TAG, " + " + info.activityInfo); 4792 } 4793 } 4794 return result; 4795 } 4796 4797 // Returns a packed value as a long: 4798 // 4799 // high 'int'-sized word: link status: undefined/ask/never/always. 4800 // low 'int'-sized word: relative priority among 'always' results. 4801 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4802 long result = ps.getDomainVerificationStatusForUser(userId); 4803 // if none available, get the master status 4804 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4805 if (ps.getIntentFilterVerificationInfo() != null) { 4806 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4807 } 4808 } 4809 return result; 4810 } 4811 4812 private ResolveInfo querySkipCurrentProfileIntents( 4813 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4814 int flags, int sourceUserId) { 4815 if (matchingFilters != null) { 4816 int size = matchingFilters.size(); 4817 for (int i = 0; i < size; i ++) { 4818 CrossProfileIntentFilter filter = matchingFilters.get(i); 4819 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4820 // Checking if there are activities in the target user that can handle the 4821 // intent. 4822 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4823 flags, sourceUserId); 4824 if (resolveInfo != null) { 4825 return resolveInfo; 4826 } 4827 } 4828 } 4829 } 4830 return null; 4831 } 4832 4833 // Return matching ResolveInfo if any for skip current profile intent filters. 4834 private ResolveInfo queryCrossProfileIntents( 4835 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4836 int flags, int sourceUserId) { 4837 if (matchingFilters != null) { 4838 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4839 // match the same intent. For performance reasons, it is better not to 4840 // run queryIntent twice for the same userId 4841 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4842 int size = matchingFilters.size(); 4843 for (int i = 0; i < size; i++) { 4844 CrossProfileIntentFilter filter = matchingFilters.get(i); 4845 int targetUserId = filter.getTargetUserId(); 4846 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4847 && !alreadyTriedUserIds.get(targetUserId)) { 4848 // Checking if there are activities in the target user that can handle the 4849 // intent. 4850 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4851 flags, sourceUserId); 4852 if (resolveInfo != null) return resolveInfo; 4853 alreadyTriedUserIds.put(targetUserId, true); 4854 } 4855 } 4856 } 4857 return null; 4858 } 4859 4860 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4861 String resolvedType, int flags, int sourceUserId) { 4862 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4863 resolvedType, flags, filter.getTargetUserId()); 4864 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4865 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4866 } 4867 return null; 4868 } 4869 4870 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4871 int sourceUserId, int targetUserId) { 4872 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4873 String className; 4874 if (targetUserId == UserHandle.USER_OWNER) { 4875 className = FORWARD_INTENT_TO_USER_OWNER; 4876 } else { 4877 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4878 } 4879 ComponentName forwardingActivityComponentName = new ComponentName( 4880 mAndroidApplication.packageName, className); 4881 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4882 sourceUserId); 4883 if (targetUserId == UserHandle.USER_OWNER) { 4884 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4885 forwardingResolveInfo.noResourceId = true; 4886 } 4887 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4888 forwardingResolveInfo.priority = 0; 4889 forwardingResolveInfo.preferredOrder = 0; 4890 forwardingResolveInfo.match = 0; 4891 forwardingResolveInfo.isDefault = true; 4892 forwardingResolveInfo.filter = filter; 4893 forwardingResolveInfo.targetUserId = targetUserId; 4894 return forwardingResolveInfo; 4895 } 4896 4897 @Override 4898 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4899 Intent[] specifics, String[] specificTypes, Intent intent, 4900 String resolvedType, int flags, int userId) { 4901 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4902 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4903 false, "query intent activity options"); 4904 final String resultsAction = intent.getAction(); 4905 4906 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4907 | PackageManager.GET_RESOLVED_FILTER, userId); 4908 4909 if (DEBUG_INTENT_MATCHING) { 4910 Log.v(TAG, "Query " + intent + ": " + results); 4911 } 4912 4913 int specificsPos = 0; 4914 int N; 4915 4916 // todo: note that the algorithm used here is O(N^2). This 4917 // isn't a problem in our current environment, but if we start running 4918 // into situations where we have more than 5 or 10 matches then this 4919 // should probably be changed to something smarter... 4920 4921 // First we go through and resolve each of the specific items 4922 // that were supplied, taking care of removing any corresponding 4923 // duplicate items in the generic resolve list. 4924 if (specifics != null) { 4925 for (int i=0; i<specifics.length; i++) { 4926 final Intent sintent = specifics[i]; 4927 if (sintent == null) { 4928 continue; 4929 } 4930 4931 if (DEBUG_INTENT_MATCHING) { 4932 Log.v(TAG, "Specific #" + i + ": " + sintent); 4933 } 4934 4935 String action = sintent.getAction(); 4936 if (resultsAction != null && resultsAction.equals(action)) { 4937 // If this action was explicitly requested, then don't 4938 // remove things that have it. 4939 action = null; 4940 } 4941 4942 ResolveInfo ri = null; 4943 ActivityInfo ai = null; 4944 4945 ComponentName comp = sintent.getComponent(); 4946 if (comp == null) { 4947 ri = resolveIntent( 4948 sintent, 4949 specificTypes != null ? specificTypes[i] : null, 4950 flags, userId); 4951 if (ri == null) { 4952 continue; 4953 } 4954 if (ri == mResolveInfo) { 4955 // ACK! Must do something better with this. 4956 } 4957 ai = ri.activityInfo; 4958 comp = new ComponentName(ai.applicationInfo.packageName, 4959 ai.name); 4960 } else { 4961 ai = getActivityInfo(comp, flags, userId); 4962 if (ai == null) { 4963 continue; 4964 } 4965 } 4966 4967 // Look for any generic query activities that are duplicates 4968 // of this specific one, and remove them from the results. 4969 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4970 N = results.size(); 4971 int j; 4972 for (j=specificsPos; j<N; j++) { 4973 ResolveInfo sri = results.get(j); 4974 if ((sri.activityInfo.name.equals(comp.getClassName()) 4975 && sri.activityInfo.applicationInfo.packageName.equals( 4976 comp.getPackageName())) 4977 || (action != null && sri.filter.matchAction(action))) { 4978 results.remove(j); 4979 if (DEBUG_INTENT_MATCHING) Log.v( 4980 TAG, "Removing duplicate item from " + j 4981 + " due to specific " + specificsPos); 4982 if (ri == null) { 4983 ri = sri; 4984 } 4985 j--; 4986 N--; 4987 } 4988 } 4989 4990 // Add this specific item to its proper place. 4991 if (ri == null) { 4992 ri = new ResolveInfo(); 4993 ri.activityInfo = ai; 4994 } 4995 results.add(specificsPos, ri); 4996 ri.specificIndex = i; 4997 specificsPos++; 4998 } 4999 } 5000 5001 // Now we go through the remaining generic results and remove any 5002 // duplicate actions that are found here. 5003 N = results.size(); 5004 for (int i=specificsPos; i<N-1; i++) { 5005 final ResolveInfo rii = results.get(i); 5006 if (rii.filter == null) { 5007 continue; 5008 } 5009 5010 // Iterate over all of the actions of this result's intent 5011 // filter... typically this should be just one. 5012 final Iterator<String> it = rii.filter.actionsIterator(); 5013 if (it == null) { 5014 continue; 5015 } 5016 while (it.hasNext()) { 5017 final String action = it.next(); 5018 if (resultsAction != null && resultsAction.equals(action)) { 5019 // If this action was explicitly requested, then don't 5020 // remove things that have it. 5021 continue; 5022 } 5023 for (int j=i+1; j<N; j++) { 5024 final ResolveInfo rij = results.get(j); 5025 if (rij.filter != null && rij.filter.hasAction(action)) { 5026 results.remove(j); 5027 if (DEBUG_INTENT_MATCHING) Log.v( 5028 TAG, "Removing duplicate item from " + j 5029 + " due to action " + action + " at " + i); 5030 j--; 5031 N--; 5032 } 5033 } 5034 } 5035 5036 // If the caller didn't request filter information, drop it now 5037 // so we don't have to marshall/unmarshall it. 5038 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5039 rii.filter = null; 5040 } 5041 } 5042 5043 // Filter out the caller activity if so requested. 5044 if (caller != null) { 5045 N = results.size(); 5046 for (int i=0; i<N; i++) { 5047 ActivityInfo ainfo = results.get(i).activityInfo; 5048 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5049 && caller.getClassName().equals(ainfo.name)) { 5050 results.remove(i); 5051 break; 5052 } 5053 } 5054 } 5055 5056 // If the caller didn't request filter information, 5057 // drop them now so we don't have to 5058 // marshall/unmarshall it. 5059 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5060 N = results.size(); 5061 for (int i=0; i<N; i++) { 5062 results.get(i).filter = null; 5063 } 5064 } 5065 5066 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5067 return results; 5068 } 5069 5070 @Override 5071 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5072 int userId) { 5073 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5074 ComponentName comp = intent.getComponent(); 5075 if (comp == null) { 5076 if (intent.getSelector() != null) { 5077 intent = intent.getSelector(); 5078 comp = intent.getComponent(); 5079 } 5080 } 5081 if (comp != null) { 5082 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5083 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5084 if (ai != null) { 5085 ResolveInfo ri = new ResolveInfo(); 5086 ri.activityInfo = ai; 5087 list.add(ri); 5088 } 5089 return list; 5090 } 5091 5092 // reader 5093 synchronized (mPackages) { 5094 String pkgName = intent.getPackage(); 5095 if (pkgName == null) { 5096 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5097 } 5098 final PackageParser.Package pkg = mPackages.get(pkgName); 5099 if (pkg != null) { 5100 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5101 userId); 5102 } 5103 return null; 5104 } 5105 } 5106 5107 @Override 5108 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5109 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5110 if (!sUserManager.exists(userId)) return null; 5111 if (query != null) { 5112 if (query.size() >= 1) { 5113 // If there is more than one service with the same priority, 5114 // just arbitrarily pick the first one. 5115 return query.get(0); 5116 } 5117 } 5118 return null; 5119 } 5120 5121 @Override 5122 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5123 int userId) { 5124 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5125 ComponentName comp = intent.getComponent(); 5126 if (comp == null) { 5127 if (intent.getSelector() != null) { 5128 intent = intent.getSelector(); 5129 comp = intent.getComponent(); 5130 } 5131 } 5132 if (comp != null) { 5133 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5134 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5135 if (si != null) { 5136 final ResolveInfo ri = new ResolveInfo(); 5137 ri.serviceInfo = si; 5138 list.add(ri); 5139 } 5140 return list; 5141 } 5142 5143 // reader 5144 synchronized (mPackages) { 5145 String pkgName = intent.getPackage(); 5146 if (pkgName == null) { 5147 return mServices.queryIntent(intent, resolvedType, flags, userId); 5148 } 5149 final PackageParser.Package pkg = mPackages.get(pkgName); 5150 if (pkg != null) { 5151 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5152 userId); 5153 } 5154 return null; 5155 } 5156 } 5157 5158 @Override 5159 public List<ResolveInfo> queryIntentContentProviders( 5160 Intent intent, String resolvedType, int flags, int userId) { 5161 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5162 ComponentName comp = intent.getComponent(); 5163 if (comp == null) { 5164 if (intent.getSelector() != null) { 5165 intent = intent.getSelector(); 5166 comp = intent.getComponent(); 5167 } 5168 } 5169 if (comp != null) { 5170 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5171 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5172 if (pi != null) { 5173 final ResolveInfo ri = new ResolveInfo(); 5174 ri.providerInfo = pi; 5175 list.add(ri); 5176 } 5177 return list; 5178 } 5179 5180 // reader 5181 synchronized (mPackages) { 5182 String pkgName = intent.getPackage(); 5183 if (pkgName == null) { 5184 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5185 } 5186 final PackageParser.Package pkg = mPackages.get(pkgName); 5187 if (pkg != null) { 5188 return mProviders.queryIntentForPackage( 5189 intent, resolvedType, flags, pkg.providers, userId); 5190 } 5191 return null; 5192 } 5193 } 5194 5195 @Override 5196 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5197 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5198 5199 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5200 5201 // writer 5202 synchronized (mPackages) { 5203 ArrayList<PackageInfo> list; 5204 if (listUninstalled) { 5205 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5206 for (PackageSetting ps : mSettings.mPackages.values()) { 5207 PackageInfo pi; 5208 if (ps.pkg != null) { 5209 pi = generatePackageInfo(ps.pkg, flags, userId); 5210 } else { 5211 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5212 } 5213 if (pi != null) { 5214 list.add(pi); 5215 } 5216 } 5217 } else { 5218 list = new ArrayList<PackageInfo>(mPackages.size()); 5219 for (PackageParser.Package p : mPackages.values()) { 5220 PackageInfo pi = generatePackageInfo(p, flags, userId); 5221 if (pi != null) { 5222 list.add(pi); 5223 } 5224 } 5225 } 5226 5227 return new ParceledListSlice<PackageInfo>(list); 5228 } 5229 } 5230 5231 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5232 String[] permissions, boolean[] tmp, int flags, int userId) { 5233 int numMatch = 0; 5234 final PermissionsState permissionsState = ps.getPermissionsState(); 5235 for (int i=0; i<permissions.length; i++) { 5236 final String permission = permissions[i]; 5237 if (permissionsState.hasPermission(permission, userId)) { 5238 tmp[i] = true; 5239 numMatch++; 5240 } else { 5241 tmp[i] = false; 5242 } 5243 } 5244 if (numMatch == 0) { 5245 return; 5246 } 5247 PackageInfo pi; 5248 if (ps.pkg != null) { 5249 pi = generatePackageInfo(ps.pkg, flags, userId); 5250 } else { 5251 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5252 } 5253 // The above might return null in cases of uninstalled apps or install-state 5254 // skew across users/profiles. 5255 if (pi != null) { 5256 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5257 if (numMatch == permissions.length) { 5258 pi.requestedPermissions = permissions; 5259 } else { 5260 pi.requestedPermissions = new String[numMatch]; 5261 numMatch = 0; 5262 for (int i=0; i<permissions.length; i++) { 5263 if (tmp[i]) { 5264 pi.requestedPermissions[numMatch] = permissions[i]; 5265 numMatch++; 5266 } 5267 } 5268 } 5269 } 5270 list.add(pi); 5271 } 5272 } 5273 5274 @Override 5275 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5276 String[] permissions, int flags, int userId) { 5277 if (!sUserManager.exists(userId)) return null; 5278 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5279 5280 // writer 5281 synchronized (mPackages) { 5282 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5283 boolean[] tmpBools = new boolean[permissions.length]; 5284 if (listUninstalled) { 5285 for (PackageSetting ps : mSettings.mPackages.values()) { 5286 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5287 } 5288 } else { 5289 for (PackageParser.Package pkg : mPackages.values()) { 5290 PackageSetting ps = (PackageSetting)pkg.mExtras; 5291 if (ps != null) { 5292 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5293 userId); 5294 } 5295 } 5296 } 5297 5298 return new ParceledListSlice<PackageInfo>(list); 5299 } 5300 } 5301 5302 @Override 5303 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5304 if (!sUserManager.exists(userId)) return null; 5305 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5306 5307 // writer 5308 synchronized (mPackages) { 5309 ArrayList<ApplicationInfo> list; 5310 if (listUninstalled) { 5311 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5312 for (PackageSetting ps : mSettings.mPackages.values()) { 5313 ApplicationInfo ai; 5314 if (ps.pkg != null) { 5315 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5316 ps.readUserState(userId), userId); 5317 } else { 5318 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5319 } 5320 if (ai != null) { 5321 list.add(ai); 5322 } 5323 } 5324 } else { 5325 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5326 for (PackageParser.Package p : mPackages.values()) { 5327 if (p.mExtras != null) { 5328 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5329 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5330 if (ai != null) { 5331 list.add(ai); 5332 } 5333 } 5334 } 5335 } 5336 5337 return new ParceledListSlice<ApplicationInfo>(list); 5338 } 5339 } 5340 5341 public List<ApplicationInfo> getPersistentApplications(int flags) { 5342 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5343 5344 // reader 5345 synchronized (mPackages) { 5346 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5347 final int userId = UserHandle.getCallingUserId(); 5348 while (i.hasNext()) { 5349 final PackageParser.Package p = i.next(); 5350 if (p.applicationInfo != null 5351 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5352 && (!mSafeMode || isSystemApp(p))) { 5353 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5354 if (ps != null) { 5355 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5356 ps.readUserState(userId), userId); 5357 if (ai != null) { 5358 finalList.add(ai); 5359 } 5360 } 5361 } 5362 } 5363 } 5364 5365 return finalList; 5366 } 5367 5368 @Override 5369 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5370 if (!sUserManager.exists(userId)) return null; 5371 // reader 5372 synchronized (mPackages) { 5373 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5374 PackageSetting ps = provider != null 5375 ? mSettings.mPackages.get(provider.owner.packageName) 5376 : null; 5377 return ps != null 5378 && mSettings.isEnabledLPr(provider.info, flags, userId) 5379 && (!mSafeMode || (provider.info.applicationInfo.flags 5380 &ApplicationInfo.FLAG_SYSTEM) != 0) 5381 ? PackageParser.generateProviderInfo(provider, flags, 5382 ps.readUserState(userId), userId) 5383 : null; 5384 } 5385 } 5386 5387 /** 5388 * @deprecated 5389 */ 5390 @Deprecated 5391 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5392 // reader 5393 synchronized (mPackages) { 5394 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5395 .entrySet().iterator(); 5396 final int userId = UserHandle.getCallingUserId(); 5397 while (i.hasNext()) { 5398 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5399 PackageParser.Provider p = entry.getValue(); 5400 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5401 5402 if (ps != null && p.syncable 5403 && (!mSafeMode || (p.info.applicationInfo.flags 5404 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5405 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5406 ps.readUserState(userId), userId); 5407 if (info != null) { 5408 outNames.add(entry.getKey()); 5409 outInfo.add(info); 5410 } 5411 } 5412 } 5413 } 5414 } 5415 5416 @Override 5417 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5418 int uid, int flags) { 5419 ArrayList<ProviderInfo> finalList = null; 5420 // reader 5421 synchronized (mPackages) { 5422 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5423 final int userId = processName != null ? 5424 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5425 while (i.hasNext()) { 5426 final PackageParser.Provider p = i.next(); 5427 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5428 if (ps != null && p.info.authority != null 5429 && (processName == null 5430 || (p.info.processName.equals(processName) 5431 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5432 && mSettings.isEnabledLPr(p.info, flags, userId) 5433 && (!mSafeMode 5434 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5435 if (finalList == null) { 5436 finalList = new ArrayList<ProviderInfo>(3); 5437 } 5438 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5439 ps.readUserState(userId), userId); 5440 if (info != null) { 5441 finalList.add(info); 5442 } 5443 } 5444 } 5445 } 5446 5447 if (finalList != null) { 5448 Collections.sort(finalList, mProviderInitOrderSorter); 5449 return new ParceledListSlice<ProviderInfo>(finalList); 5450 } 5451 5452 return null; 5453 } 5454 5455 @Override 5456 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5457 int flags) { 5458 // reader 5459 synchronized (mPackages) { 5460 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5461 return PackageParser.generateInstrumentationInfo(i, flags); 5462 } 5463 } 5464 5465 @Override 5466 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5467 int flags) { 5468 ArrayList<InstrumentationInfo> finalList = 5469 new ArrayList<InstrumentationInfo>(); 5470 5471 // reader 5472 synchronized (mPackages) { 5473 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5474 while (i.hasNext()) { 5475 final PackageParser.Instrumentation p = i.next(); 5476 if (targetPackage == null 5477 || targetPackage.equals(p.info.targetPackage)) { 5478 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5479 flags); 5480 if (ii != null) { 5481 finalList.add(ii); 5482 } 5483 } 5484 } 5485 } 5486 5487 return finalList; 5488 } 5489 5490 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5491 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5492 if (overlays == null) { 5493 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5494 return; 5495 } 5496 for (PackageParser.Package opkg : overlays.values()) { 5497 // Not much to do if idmap fails: we already logged the error 5498 // and we certainly don't want to abort installation of pkg simply 5499 // because an overlay didn't fit properly. For these reasons, 5500 // ignore the return value of createIdmapForPackagePairLI. 5501 createIdmapForPackagePairLI(pkg, opkg); 5502 } 5503 } 5504 5505 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5506 PackageParser.Package opkg) { 5507 if (!opkg.mTrustedOverlay) { 5508 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5509 opkg.baseCodePath + ": overlay not trusted"); 5510 return false; 5511 } 5512 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5513 if (overlaySet == null) { 5514 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5515 opkg.baseCodePath + " but target package has no known overlays"); 5516 return false; 5517 } 5518 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5519 // TODO: generate idmap for split APKs 5520 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5521 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5522 + opkg.baseCodePath); 5523 return false; 5524 } 5525 PackageParser.Package[] overlayArray = 5526 overlaySet.values().toArray(new PackageParser.Package[0]); 5527 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5528 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5529 return p1.mOverlayPriority - p2.mOverlayPriority; 5530 } 5531 }; 5532 Arrays.sort(overlayArray, cmp); 5533 5534 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5535 int i = 0; 5536 for (PackageParser.Package p : overlayArray) { 5537 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5538 } 5539 return true; 5540 } 5541 5542 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5543 final File[] files = dir.listFiles(); 5544 if (ArrayUtils.isEmpty(files)) { 5545 Log.d(TAG, "No files in app dir " + dir); 5546 return; 5547 } 5548 5549 if (DEBUG_PACKAGE_SCANNING) { 5550 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5551 + " flags=0x" + Integer.toHexString(parseFlags)); 5552 } 5553 5554 for (File file : files) { 5555 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5556 && !PackageInstallerService.isStageName(file.getName()); 5557 if (!isPackage) { 5558 // Ignore entries which are not packages 5559 continue; 5560 } 5561 try { 5562 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5563 scanFlags, currentTime, null); 5564 } catch (PackageManagerException e) { 5565 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5566 5567 // Delete invalid userdata apps 5568 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5569 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5570 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5571 if (file.isDirectory()) { 5572 mInstaller.rmPackageDir(file.getAbsolutePath()); 5573 } else { 5574 file.delete(); 5575 } 5576 } 5577 } 5578 } 5579 } 5580 5581 private static File getSettingsProblemFile() { 5582 File dataDir = Environment.getDataDirectory(); 5583 File systemDir = new File(dataDir, "system"); 5584 File fname = new File(systemDir, "uiderrors.txt"); 5585 return fname; 5586 } 5587 5588 static void reportSettingsProblem(int priority, String msg) { 5589 logCriticalInfo(priority, msg); 5590 } 5591 5592 static void logCriticalInfo(int priority, String msg) { 5593 Slog.println(priority, TAG, msg); 5594 EventLogTags.writePmCriticalInfo(msg); 5595 try { 5596 File fname = getSettingsProblemFile(); 5597 FileOutputStream out = new FileOutputStream(fname, true); 5598 PrintWriter pw = new FastPrintWriter(out); 5599 SimpleDateFormat formatter = new SimpleDateFormat(); 5600 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5601 pw.println(dateString + ": " + msg); 5602 pw.close(); 5603 FileUtils.setPermissions( 5604 fname.toString(), 5605 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5606 -1, -1); 5607 } catch (java.io.IOException e) { 5608 } 5609 } 5610 5611 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5612 PackageParser.Package pkg, File srcFile, int parseFlags) 5613 throws PackageManagerException { 5614 if (ps != null 5615 && ps.codePath.equals(srcFile) 5616 && ps.timeStamp == srcFile.lastModified() 5617 && !isCompatSignatureUpdateNeeded(pkg) 5618 && !isRecoverSignatureUpdateNeeded(pkg)) { 5619 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5620 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5621 ArraySet<PublicKey> signingKs; 5622 synchronized (mPackages) { 5623 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5624 } 5625 if (ps.signatures.mSignatures != null 5626 && ps.signatures.mSignatures.length != 0 5627 && signingKs != null) { 5628 // Optimization: reuse the existing cached certificates 5629 // if the package appears to be unchanged. 5630 pkg.mSignatures = ps.signatures.mSignatures; 5631 pkg.mSigningKeys = signingKs; 5632 return; 5633 } 5634 5635 Slog.w(TAG, "PackageSetting for " + ps.name 5636 + " is missing signatures. Collecting certs again to recover them."); 5637 } else { 5638 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5639 } 5640 5641 try { 5642 pp.collectCertificates(pkg, parseFlags); 5643 pp.collectManifestDigest(pkg); 5644 } catch (PackageParserException e) { 5645 throw PackageManagerException.from(e); 5646 } 5647 } 5648 5649 /* 5650 * Scan a package and return the newly parsed package. 5651 * Returns null in case of errors and the error code is stored in mLastScanError 5652 */ 5653 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5654 long currentTime, UserHandle user) throws PackageManagerException { 5655 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5656 parseFlags |= mDefParseFlags; 5657 PackageParser pp = new PackageParser(); 5658 pp.setSeparateProcesses(mSeparateProcesses); 5659 pp.setOnlyCoreApps(mOnlyCore); 5660 pp.setDisplayMetrics(mMetrics); 5661 5662 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5663 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5664 } 5665 5666 final PackageParser.Package pkg; 5667 try { 5668 pkg = pp.parsePackage(scanFile, parseFlags); 5669 } catch (PackageParserException e) { 5670 throw PackageManagerException.from(e); 5671 } 5672 5673 PackageSetting ps = null; 5674 PackageSetting updatedPkg; 5675 // reader 5676 synchronized (mPackages) { 5677 // Look to see if we already know about this package. 5678 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5679 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5680 // This package has been renamed to its original name. Let's 5681 // use that. 5682 ps = mSettings.peekPackageLPr(oldName); 5683 } 5684 // If there was no original package, see one for the real package name. 5685 if (ps == null) { 5686 ps = mSettings.peekPackageLPr(pkg.packageName); 5687 } 5688 // Check to see if this package could be hiding/updating a system 5689 // package. Must look for it either under the original or real 5690 // package name depending on our state. 5691 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5692 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5693 } 5694 boolean updatedPkgBetter = false; 5695 // First check if this is a system package that may involve an update 5696 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5697 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5698 // it needs to drop FLAG_PRIVILEGED. 5699 if (locationIsPrivileged(scanFile)) { 5700 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5701 } else { 5702 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5703 } 5704 5705 if (ps != null && !ps.codePath.equals(scanFile)) { 5706 // The path has changed from what was last scanned... check the 5707 // version of the new path against what we have stored to determine 5708 // what to do. 5709 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5710 if (pkg.mVersionCode <= ps.versionCode) { 5711 // The system package has been updated and the code path does not match 5712 // Ignore entry. Skip it. 5713 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5714 + " ignored: updated version " + ps.versionCode 5715 + " better than this " + pkg.mVersionCode); 5716 if (!updatedPkg.codePath.equals(scanFile)) { 5717 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5718 + ps.name + " changing from " + updatedPkg.codePathString 5719 + " to " + scanFile); 5720 updatedPkg.codePath = scanFile; 5721 updatedPkg.codePathString = scanFile.toString(); 5722 updatedPkg.resourcePath = scanFile; 5723 updatedPkg.resourcePathString = scanFile.toString(); 5724 } 5725 updatedPkg.pkg = pkg; 5726 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5727 "Package " + ps.name + " at " + scanFile 5728 + " ignored: updated version " + ps.versionCode 5729 + " better than this " + pkg.mVersionCode); 5730 } else { 5731 // The current app on the system partition is better than 5732 // what we have updated to on the data partition; switch 5733 // back to the system partition version. 5734 // At this point, its safely assumed that package installation for 5735 // apps in system partition will go through. If not there won't be a working 5736 // version of the app 5737 // writer 5738 synchronized (mPackages) { 5739 // Just remove the loaded entries from package lists. 5740 mPackages.remove(ps.name); 5741 } 5742 5743 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5744 + " reverting from " + ps.codePathString 5745 + ": new version " + pkg.mVersionCode 5746 + " better than installed " + ps.versionCode); 5747 5748 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5749 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5750 synchronized (mInstallLock) { 5751 args.cleanUpResourcesLI(); 5752 } 5753 synchronized (mPackages) { 5754 mSettings.enableSystemPackageLPw(ps.name); 5755 } 5756 updatedPkgBetter = true; 5757 } 5758 } 5759 } 5760 5761 if (updatedPkg != null) { 5762 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5763 // initially 5764 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5765 5766 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5767 // flag set initially 5768 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5769 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5770 } 5771 } 5772 5773 // Verify certificates against what was last scanned 5774 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5775 5776 /* 5777 * A new system app appeared, but we already had a non-system one of the 5778 * same name installed earlier. 5779 */ 5780 boolean shouldHideSystemApp = false; 5781 if (updatedPkg == null && ps != null 5782 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5783 /* 5784 * Check to make sure the signatures match first. If they don't, 5785 * wipe the installed application and its data. 5786 */ 5787 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5788 != PackageManager.SIGNATURE_MATCH) { 5789 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5790 + " signatures don't match existing userdata copy; removing"); 5791 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5792 ps = null; 5793 } else { 5794 /* 5795 * If the newly-added system app is an older version than the 5796 * already installed version, hide it. It will be scanned later 5797 * and re-added like an update. 5798 */ 5799 if (pkg.mVersionCode <= ps.versionCode) { 5800 shouldHideSystemApp = true; 5801 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5802 + " but new version " + pkg.mVersionCode + " better than installed " 5803 + ps.versionCode + "; hiding system"); 5804 } else { 5805 /* 5806 * The newly found system app is a newer version that the 5807 * one previously installed. Simply remove the 5808 * already-installed application and replace it with our own 5809 * while keeping the application data. 5810 */ 5811 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5812 + " reverting from " + ps.codePathString + ": new version " 5813 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5814 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5815 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5816 synchronized (mInstallLock) { 5817 args.cleanUpResourcesLI(); 5818 } 5819 } 5820 } 5821 } 5822 5823 // The apk is forward locked (not public) if its code and resources 5824 // are kept in different files. (except for app in either system or 5825 // vendor path). 5826 // TODO grab this value from PackageSettings 5827 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5828 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5829 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5830 } 5831 } 5832 5833 // TODO: extend to support forward-locked splits 5834 String resourcePath = null; 5835 String baseResourcePath = null; 5836 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5837 if (ps != null && ps.resourcePathString != null) { 5838 resourcePath = ps.resourcePathString; 5839 baseResourcePath = ps.resourcePathString; 5840 } else { 5841 // Should not happen at all. Just log an error. 5842 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5843 } 5844 } else { 5845 resourcePath = pkg.codePath; 5846 baseResourcePath = pkg.baseCodePath; 5847 } 5848 5849 // Set application objects path explicitly. 5850 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5851 pkg.applicationInfo.setCodePath(pkg.codePath); 5852 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5853 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5854 pkg.applicationInfo.setResourcePath(resourcePath); 5855 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5856 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5857 5858 // Note that we invoke the following method only if we are about to unpack an application 5859 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5860 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5861 5862 /* 5863 * If the system app should be overridden by a previously installed 5864 * data, hide the system app now and let the /data/app scan pick it up 5865 * again. 5866 */ 5867 if (shouldHideSystemApp) { 5868 synchronized (mPackages) { 5869 /* 5870 * We have to grant systems permissions before we hide, because 5871 * grantPermissions will assume the package update is trying to 5872 * expand its permissions. 5873 */ 5874 grantPermissionsLPw(pkg, true, pkg.packageName); 5875 mSettings.disableSystemPackageLPw(pkg.packageName); 5876 } 5877 } 5878 5879 return scannedPkg; 5880 } 5881 5882 private static String fixProcessName(String defProcessName, 5883 String processName, int uid) { 5884 if (processName == null) { 5885 return defProcessName; 5886 } 5887 return processName; 5888 } 5889 5890 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5891 throws PackageManagerException { 5892 if (pkgSetting.signatures.mSignatures != null) { 5893 // Already existing package. Make sure signatures match 5894 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5895 == PackageManager.SIGNATURE_MATCH; 5896 if (!match) { 5897 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5898 == PackageManager.SIGNATURE_MATCH; 5899 } 5900 if (!match) { 5901 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5902 == PackageManager.SIGNATURE_MATCH; 5903 } 5904 if (!match) { 5905 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5906 + pkg.packageName + " signatures do not match the " 5907 + "previously installed version; ignoring!"); 5908 } 5909 } 5910 5911 // Check for shared user signatures 5912 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5913 // Already existing package. Make sure signatures match 5914 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5915 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5916 if (!match) { 5917 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5918 == PackageManager.SIGNATURE_MATCH; 5919 } 5920 if (!match) { 5921 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5922 == PackageManager.SIGNATURE_MATCH; 5923 } 5924 if (!match) { 5925 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5926 "Package " + pkg.packageName 5927 + " has no signatures that match those in shared user " 5928 + pkgSetting.sharedUser.name + "; ignoring!"); 5929 } 5930 } 5931 } 5932 5933 /** 5934 * Enforces that only the system UID or root's UID can call a method exposed 5935 * via Binder. 5936 * 5937 * @param message used as message if SecurityException is thrown 5938 * @throws SecurityException if the caller is not system or root 5939 */ 5940 private static final void enforceSystemOrRoot(String message) { 5941 final int uid = Binder.getCallingUid(); 5942 if (uid != Process.SYSTEM_UID && uid != 0) { 5943 throw new SecurityException(message); 5944 } 5945 } 5946 5947 @Override 5948 public void performBootDexOpt() { 5949 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5950 5951 // Before everything else, see whether we need to fstrim. 5952 try { 5953 IMountService ms = PackageHelper.getMountService(); 5954 if (ms != null) { 5955 final boolean isUpgrade = isUpgrade(); 5956 boolean doTrim = isUpgrade; 5957 if (doTrim) { 5958 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5959 } else { 5960 final long interval = android.provider.Settings.Global.getLong( 5961 mContext.getContentResolver(), 5962 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5963 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5964 if (interval > 0) { 5965 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5966 if (timeSinceLast > interval) { 5967 doTrim = true; 5968 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5969 + "; running immediately"); 5970 } 5971 } 5972 } 5973 if (doTrim) { 5974 if (!isFirstBoot()) { 5975 try { 5976 ActivityManagerNative.getDefault().showBootMessage( 5977 mContext.getResources().getString( 5978 R.string.android_upgrading_fstrim), true); 5979 } catch (RemoteException e) { 5980 } 5981 } 5982 ms.runMaintenance(); 5983 } 5984 } else { 5985 Slog.e(TAG, "Mount service unavailable!"); 5986 } 5987 } catch (RemoteException e) { 5988 // Can't happen; MountService is local 5989 } 5990 5991 final ArraySet<PackageParser.Package> pkgs; 5992 synchronized (mPackages) { 5993 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5994 } 5995 5996 if (pkgs != null) { 5997 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5998 // in case the device runs out of space. 5999 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6000 // Give priority to core apps. 6001 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6002 PackageParser.Package pkg = it.next(); 6003 if (pkg.coreApp) { 6004 if (DEBUG_DEXOPT) { 6005 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6006 } 6007 sortedPkgs.add(pkg); 6008 it.remove(); 6009 } 6010 } 6011 // Give priority to system apps that listen for pre boot complete. 6012 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6013 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6014 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6015 PackageParser.Package pkg = it.next(); 6016 if (pkgNames.contains(pkg.packageName)) { 6017 if (DEBUG_DEXOPT) { 6018 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6019 } 6020 sortedPkgs.add(pkg); 6021 it.remove(); 6022 } 6023 } 6024 // Give priority to system apps. 6025 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6026 PackageParser.Package pkg = it.next(); 6027 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6028 if (DEBUG_DEXOPT) { 6029 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6030 } 6031 sortedPkgs.add(pkg); 6032 it.remove(); 6033 } 6034 } 6035 // Give priority to updated system apps. 6036 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6037 PackageParser.Package pkg = it.next(); 6038 if (pkg.isUpdatedSystemApp()) { 6039 if (DEBUG_DEXOPT) { 6040 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6041 } 6042 sortedPkgs.add(pkg); 6043 it.remove(); 6044 } 6045 } 6046 // Give priority to apps that listen for boot complete. 6047 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6048 pkgNames = getPackageNamesForIntent(intent); 6049 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6050 PackageParser.Package pkg = it.next(); 6051 if (pkgNames.contains(pkg.packageName)) { 6052 if (DEBUG_DEXOPT) { 6053 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6054 } 6055 sortedPkgs.add(pkg); 6056 it.remove(); 6057 } 6058 } 6059 // Filter out packages that aren't recently used. 6060 filterRecentlyUsedApps(pkgs); 6061 // Add all remaining apps. 6062 for (PackageParser.Package pkg : pkgs) { 6063 if (DEBUG_DEXOPT) { 6064 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6065 } 6066 sortedPkgs.add(pkg); 6067 } 6068 6069 // If we want to be lazy, filter everything that wasn't recently used. 6070 if (mLazyDexOpt) { 6071 filterRecentlyUsedApps(sortedPkgs); 6072 } 6073 6074 int i = 0; 6075 int total = sortedPkgs.size(); 6076 File dataDir = Environment.getDataDirectory(); 6077 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6078 if (lowThreshold == 0) { 6079 throw new IllegalStateException("Invalid low memory threshold"); 6080 } 6081 for (PackageParser.Package pkg : sortedPkgs) { 6082 long usableSpace = dataDir.getUsableSpace(); 6083 if (usableSpace < lowThreshold) { 6084 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6085 break; 6086 } 6087 performBootDexOpt(pkg, ++i, total); 6088 } 6089 } 6090 } 6091 6092 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6093 // Filter out packages that aren't recently used. 6094 // 6095 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6096 // should do a full dexopt. 6097 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6098 int total = pkgs.size(); 6099 int skipped = 0; 6100 long now = System.currentTimeMillis(); 6101 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6102 PackageParser.Package pkg = i.next(); 6103 long then = pkg.mLastPackageUsageTimeInMills; 6104 if (then + mDexOptLRUThresholdInMills < now) { 6105 if (DEBUG_DEXOPT) { 6106 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6107 ((then == 0) ? "never" : new Date(then))); 6108 } 6109 i.remove(); 6110 skipped++; 6111 } 6112 } 6113 if (DEBUG_DEXOPT) { 6114 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6115 } 6116 } 6117 } 6118 6119 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6120 List<ResolveInfo> ris = null; 6121 try { 6122 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6123 intent, null, 0, UserHandle.USER_OWNER); 6124 } catch (RemoteException e) { 6125 } 6126 ArraySet<String> pkgNames = new ArraySet<String>(); 6127 if (ris != null) { 6128 for (ResolveInfo ri : ris) { 6129 pkgNames.add(ri.activityInfo.packageName); 6130 } 6131 } 6132 return pkgNames; 6133 } 6134 6135 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6136 if (DEBUG_DEXOPT) { 6137 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6138 } 6139 if (!isFirstBoot()) { 6140 try { 6141 ActivityManagerNative.getDefault().showBootMessage( 6142 mContext.getResources().getString(R.string.android_upgrading_apk, 6143 curr, total), true); 6144 } catch (RemoteException e) { 6145 } 6146 } 6147 PackageParser.Package p = pkg; 6148 synchronized (mInstallLock) { 6149 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6150 false /* force dex */, false /* defer */, true /* include dependencies */); 6151 } 6152 } 6153 6154 @Override 6155 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6156 return performDexOpt(packageName, instructionSet, false); 6157 } 6158 6159 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6160 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6161 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6162 if (!dexopt && !updateUsage) { 6163 // We aren't going to dexopt or update usage, so bail early. 6164 return false; 6165 } 6166 PackageParser.Package p; 6167 final String targetInstructionSet; 6168 synchronized (mPackages) { 6169 p = mPackages.get(packageName); 6170 if (p == null) { 6171 return false; 6172 } 6173 if (updateUsage) { 6174 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6175 } 6176 mPackageUsage.write(false); 6177 if (!dexopt) { 6178 // We aren't going to dexopt, so bail early. 6179 return false; 6180 } 6181 6182 targetInstructionSet = instructionSet != null ? instructionSet : 6183 getPrimaryInstructionSet(p.applicationInfo); 6184 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6185 return false; 6186 } 6187 } 6188 long callingId = Binder.clearCallingIdentity(); 6189 try { 6190 synchronized (mInstallLock) { 6191 final String[] instructionSets = new String[] { targetInstructionSet }; 6192 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6193 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6194 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6195 } 6196 } finally { 6197 Binder.restoreCallingIdentity(callingId); 6198 } 6199 } 6200 6201 public ArraySet<String> getPackagesThatNeedDexOpt() { 6202 ArraySet<String> pkgs = null; 6203 synchronized (mPackages) { 6204 for (PackageParser.Package p : mPackages.values()) { 6205 if (DEBUG_DEXOPT) { 6206 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6207 } 6208 if (!p.mDexOptPerformed.isEmpty()) { 6209 continue; 6210 } 6211 if (pkgs == null) { 6212 pkgs = new ArraySet<String>(); 6213 } 6214 pkgs.add(p.packageName); 6215 } 6216 } 6217 return pkgs; 6218 } 6219 6220 public void shutdown() { 6221 mPackageUsage.write(true); 6222 } 6223 6224 @Override 6225 public void forceDexOpt(String packageName) { 6226 enforceSystemOrRoot("forceDexOpt"); 6227 6228 PackageParser.Package pkg; 6229 synchronized (mPackages) { 6230 pkg = mPackages.get(packageName); 6231 if (pkg == null) { 6232 throw new IllegalArgumentException("Missing package: " + packageName); 6233 } 6234 } 6235 6236 synchronized (mInstallLock) { 6237 final String[] instructionSets = new String[] { 6238 getPrimaryInstructionSet(pkg.applicationInfo) }; 6239 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6240 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6241 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6242 throw new IllegalStateException("Failed to dexopt: " + res); 6243 } 6244 } 6245 } 6246 6247 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6248 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6249 Slog.w(TAG, "Unable to update from " + oldPkg.name 6250 + " to " + newPkg.packageName 6251 + ": old package not in system partition"); 6252 return false; 6253 } else if (mPackages.get(oldPkg.name) != null) { 6254 Slog.w(TAG, "Unable to update from " + oldPkg.name 6255 + " to " + newPkg.packageName 6256 + ": old package still exists"); 6257 return false; 6258 } 6259 return true; 6260 } 6261 6262 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6263 int[] users = sUserManager.getUserIds(); 6264 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6265 if (res < 0) { 6266 return res; 6267 } 6268 for (int user : users) { 6269 if (user != 0) { 6270 res = mInstaller.createUserData(volumeUuid, packageName, 6271 UserHandle.getUid(user, uid), user, seinfo); 6272 if (res < 0) { 6273 return res; 6274 } 6275 } 6276 } 6277 return res; 6278 } 6279 6280 private int removeDataDirsLI(String volumeUuid, String packageName) { 6281 int[] users = sUserManager.getUserIds(); 6282 int res = 0; 6283 for (int user : users) { 6284 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6285 if (resInner < 0) { 6286 res = resInner; 6287 } 6288 } 6289 6290 return res; 6291 } 6292 6293 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6294 int[] users = sUserManager.getUserIds(); 6295 int res = 0; 6296 for (int user : users) { 6297 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6298 if (resInner < 0) { 6299 res = resInner; 6300 } 6301 } 6302 return res; 6303 } 6304 6305 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6306 PackageParser.Package changingLib) { 6307 if (file.path != null) { 6308 usesLibraryFiles.add(file.path); 6309 return; 6310 } 6311 PackageParser.Package p = mPackages.get(file.apk); 6312 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6313 // If we are doing this while in the middle of updating a library apk, 6314 // then we need to make sure to use that new apk for determining the 6315 // dependencies here. (We haven't yet finished committing the new apk 6316 // to the package manager state.) 6317 if (p == null || p.packageName.equals(changingLib.packageName)) { 6318 p = changingLib; 6319 } 6320 } 6321 if (p != null) { 6322 usesLibraryFiles.addAll(p.getAllCodePaths()); 6323 } 6324 } 6325 6326 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6327 PackageParser.Package changingLib) throws PackageManagerException { 6328 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6329 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6330 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6331 for (int i=0; i<N; i++) { 6332 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6333 if (file == null) { 6334 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6335 "Package " + pkg.packageName + " requires unavailable shared library " 6336 + pkg.usesLibraries.get(i) + "; failing!"); 6337 } 6338 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6339 } 6340 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6341 for (int i=0; i<N; i++) { 6342 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6343 if (file == null) { 6344 Slog.w(TAG, "Package " + pkg.packageName 6345 + " desires unavailable shared library " 6346 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6347 } else { 6348 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6349 } 6350 } 6351 N = usesLibraryFiles.size(); 6352 if (N > 0) { 6353 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6354 } else { 6355 pkg.usesLibraryFiles = null; 6356 } 6357 } 6358 } 6359 6360 private static boolean hasString(List<String> list, List<String> which) { 6361 if (list == null) { 6362 return false; 6363 } 6364 for (int i=list.size()-1; i>=0; i--) { 6365 for (int j=which.size()-1; j>=0; j--) { 6366 if (which.get(j).equals(list.get(i))) { 6367 return true; 6368 } 6369 } 6370 } 6371 return false; 6372 } 6373 6374 private void updateAllSharedLibrariesLPw() { 6375 for (PackageParser.Package pkg : mPackages.values()) { 6376 try { 6377 updateSharedLibrariesLPw(pkg, null); 6378 } catch (PackageManagerException e) { 6379 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6380 } 6381 } 6382 } 6383 6384 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6385 PackageParser.Package changingPkg) { 6386 ArrayList<PackageParser.Package> res = null; 6387 for (PackageParser.Package pkg : mPackages.values()) { 6388 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6389 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6390 if (res == null) { 6391 res = new ArrayList<PackageParser.Package>(); 6392 } 6393 res.add(pkg); 6394 try { 6395 updateSharedLibrariesLPw(pkg, changingPkg); 6396 } catch (PackageManagerException e) { 6397 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6398 } 6399 } 6400 } 6401 return res; 6402 } 6403 6404 /** 6405 * Derive the value of the {@code cpuAbiOverride} based on the provided 6406 * value and an optional stored value from the package settings. 6407 */ 6408 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6409 String cpuAbiOverride = null; 6410 6411 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6412 cpuAbiOverride = null; 6413 } else if (abiOverride != null) { 6414 cpuAbiOverride = abiOverride; 6415 } else if (settings != null) { 6416 cpuAbiOverride = settings.cpuAbiOverrideString; 6417 } 6418 6419 return cpuAbiOverride; 6420 } 6421 6422 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6423 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6424 boolean success = false; 6425 try { 6426 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6427 currentTime, user); 6428 success = true; 6429 return res; 6430 } finally { 6431 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6432 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6433 } 6434 } 6435 } 6436 6437 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6438 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6439 final File scanFile = new File(pkg.codePath); 6440 if (pkg.applicationInfo.getCodePath() == null || 6441 pkg.applicationInfo.getResourcePath() == null) { 6442 // Bail out. The resource and code paths haven't been set. 6443 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6444 "Code and resource paths haven't been set correctly"); 6445 } 6446 6447 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6448 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6449 } else { 6450 // Only allow system apps to be flagged as core apps. 6451 pkg.coreApp = false; 6452 } 6453 6454 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6455 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6456 } 6457 6458 if (mCustomResolverComponentName != null && 6459 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6460 setUpCustomResolverActivity(pkg); 6461 } 6462 6463 if (pkg.packageName.equals("android")) { 6464 synchronized (mPackages) { 6465 if (mAndroidApplication != null) { 6466 Slog.w(TAG, "*************************************************"); 6467 Slog.w(TAG, "Core android package being redefined. Skipping."); 6468 Slog.w(TAG, " file=" + scanFile); 6469 Slog.w(TAG, "*************************************************"); 6470 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6471 "Core android package being redefined. Skipping."); 6472 } 6473 6474 // Set up information for our fall-back user intent resolution activity. 6475 mPlatformPackage = pkg; 6476 pkg.mVersionCode = mSdkVersion; 6477 mAndroidApplication = pkg.applicationInfo; 6478 6479 if (!mResolverReplaced) { 6480 mResolveActivity.applicationInfo = mAndroidApplication; 6481 mResolveActivity.name = ResolverActivity.class.getName(); 6482 mResolveActivity.packageName = mAndroidApplication.packageName; 6483 mResolveActivity.processName = "system:ui"; 6484 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6485 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6486 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6487 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6488 mResolveActivity.exported = true; 6489 mResolveActivity.enabled = true; 6490 mResolveInfo.activityInfo = mResolveActivity; 6491 mResolveInfo.priority = 0; 6492 mResolveInfo.preferredOrder = 0; 6493 mResolveInfo.match = 0; 6494 mResolveComponentName = new ComponentName( 6495 mAndroidApplication.packageName, mResolveActivity.name); 6496 } 6497 } 6498 } 6499 6500 if (DEBUG_PACKAGE_SCANNING) { 6501 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6502 Log.d(TAG, "Scanning package " + pkg.packageName); 6503 } 6504 6505 if (mPackages.containsKey(pkg.packageName) 6506 || mSharedLibraries.containsKey(pkg.packageName)) { 6507 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6508 "Application package " + pkg.packageName 6509 + " already installed. Skipping duplicate."); 6510 } 6511 6512 // If we're only installing presumed-existing packages, require that the 6513 // scanned APK is both already known and at the path previously established 6514 // for it. Previously unknown packages we pick up normally, but if we have an 6515 // a priori expectation about this package's install presence, enforce it. 6516 // With a singular exception for new system packages. When an OTA contains 6517 // a new system package, we allow the codepath to change from a system location 6518 // to the user-installed location. If we don't allow this change, any newer, 6519 // user-installed version of the application will be ignored. 6520 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6521 if (mExpectingBetter.containsKey(pkg.packageName)) { 6522 logCriticalInfo(Log.WARN, 6523 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6524 } else { 6525 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6526 if (known != null) { 6527 if (DEBUG_PACKAGE_SCANNING) { 6528 Log.d(TAG, "Examining " + pkg.codePath 6529 + " and requiring known paths " + known.codePathString 6530 + " & " + known.resourcePathString); 6531 } 6532 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6533 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6534 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6535 "Application package " + pkg.packageName 6536 + " found at " + pkg.applicationInfo.getCodePath() 6537 + " but expected at " + known.codePathString + "; ignoring."); 6538 } 6539 } 6540 } 6541 } 6542 6543 // Initialize package source and resource directories 6544 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6545 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6546 6547 SharedUserSetting suid = null; 6548 PackageSetting pkgSetting = null; 6549 6550 if (!isSystemApp(pkg)) { 6551 // Only system apps can use these features. 6552 pkg.mOriginalPackages = null; 6553 pkg.mRealPackage = null; 6554 pkg.mAdoptPermissions = null; 6555 } 6556 6557 // writer 6558 synchronized (mPackages) { 6559 if (pkg.mSharedUserId != null) { 6560 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6561 if (suid == null) { 6562 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6563 "Creating application package " + pkg.packageName 6564 + " for shared user failed"); 6565 } 6566 if (DEBUG_PACKAGE_SCANNING) { 6567 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6568 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6569 + "): packages=" + suid.packages); 6570 } 6571 } 6572 6573 // Check if we are renaming from an original package name. 6574 PackageSetting origPackage = null; 6575 String realName = null; 6576 if (pkg.mOriginalPackages != null) { 6577 // This package may need to be renamed to a previously 6578 // installed name. Let's check on that... 6579 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6580 if (pkg.mOriginalPackages.contains(renamed)) { 6581 // This package had originally been installed as the 6582 // original name, and we have already taken care of 6583 // transitioning to the new one. Just update the new 6584 // one to continue using the old name. 6585 realName = pkg.mRealPackage; 6586 if (!pkg.packageName.equals(renamed)) { 6587 // Callers into this function may have already taken 6588 // care of renaming the package; only do it here if 6589 // it is not already done. 6590 pkg.setPackageName(renamed); 6591 } 6592 6593 } else { 6594 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6595 if ((origPackage = mSettings.peekPackageLPr( 6596 pkg.mOriginalPackages.get(i))) != null) { 6597 // We do have the package already installed under its 6598 // original name... should we use it? 6599 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6600 // New package is not compatible with original. 6601 origPackage = null; 6602 continue; 6603 } else if (origPackage.sharedUser != null) { 6604 // Make sure uid is compatible between packages. 6605 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6606 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6607 + " to " + pkg.packageName + ": old uid " 6608 + origPackage.sharedUser.name 6609 + " differs from " + pkg.mSharedUserId); 6610 origPackage = null; 6611 continue; 6612 } 6613 } else { 6614 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6615 + pkg.packageName + " to old name " + origPackage.name); 6616 } 6617 break; 6618 } 6619 } 6620 } 6621 } 6622 6623 if (mTransferedPackages.contains(pkg.packageName)) { 6624 Slog.w(TAG, "Package " + pkg.packageName 6625 + " was transferred to another, but its .apk remains"); 6626 } 6627 6628 // Just create the setting, don't add it yet. For already existing packages 6629 // the PkgSetting exists already and doesn't have to be created. 6630 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6631 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6632 pkg.applicationInfo.primaryCpuAbi, 6633 pkg.applicationInfo.secondaryCpuAbi, 6634 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6635 user, false); 6636 if (pkgSetting == null) { 6637 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6638 "Creating application package " + pkg.packageName + " failed"); 6639 } 6640 6641 if (pkgSetting.origPackage != null) { 6642 // If we are first transitioning from an original package, 6643 // fix up the new package's name now. We need to do this after 6644 // looking up the package under its new name, so getPackageLP 6645 // can take care of fiddling things correctly. 6646 pkg.setPackageName(origPackage.name); 6647 6648 // File a report about this. 6649 String msg = "New package " + pkgSetting.realName 6650 + " renamed to replace old package " + pkgSetting.name; 6651 reportSettingsProblem(Log.WARN, msg); 6652 6653 // Make a note of it. 6654 mTransferedPackages.add(origPackage.name); 6655 6656 // No longer need to retain this. 6657 pkgSetting.origPackage = null; 6658 } 6659 6660 if (realName != null) { 6661 // Make a note of it. 6662 mTransferedPackages.add(pkg.packageName); 6663 } 6664 6665 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6666 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6667 } 6668 6669 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6670 // Check all shared libraries and map to their actual file path. 6671 // We only do this here for apps not on a system dir, because those 6672 // are the only ones that can fail an install due to this. We 6673 // will take care of the system apps by updating all of their 6674 // library paths after the scan is done. 6675 updateSharedLibrariesLPw(pkg, null); 6676 } 6677 6678 if (mFoundPolicyFile) { 6679 SELinuxMMAC.assignSeinfoValue(pkg); 6680 } 6681 6682 pkg.applicationInfo.uid = pkgSetting.appId; 6683 pkg.mExtras = pkgSetting; 6684 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6685 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6686 // We just determined the app is signed correctly, so bring 6687 // over the latest parsed certs. 6688 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6689 } else { 6690 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6691 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6692 "Package " + pkg.packageName + " upgrade keys do not match the " 6693 + "previously installed version"); 6694 } else { 6695 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6696 String msg = "System package " + pkg.packageName 6697 + " signature changed; retaining data."; 6698 reportSettingsProblem(Log.WARN, msg); 6699 } 6700 } 6701 } else { 6702 try { 6703 verifySignaturesLP(pkgSetting, pkg); 6704 // We just determined the app is signed correctly, so bring 6705 // over the latest parsed certs. 6706 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6707 } catch (PackageManagerException e) { 6708 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6709 throw e; 6710 } 6711 // The signature has changed, but this package is in the system 6712 // image... let's recover! 6713 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6714 // However... if this package is part of a shared user, but it 6715 // doesn't match the signature of the shared user, let's fail. 6716 // What this means is that you can't change the signatures 6717 // associated with an overall shared user, which doesn't seem all 6718 // that unreasonable. 6719 if (pkgSetting.sharedUser != null) { 6720 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6721 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6722 throw new PackageManagerException( 6723 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6724 "Signature mismatch for shared user : " 6725 + pkgSetting.sharedUser); 6726 } 6727 } 6728 // File a report about this. 6729 String msg = "System package " + pkg.packageName 6730 + " signature changed; retaining data."; 6731 reportSettingsProblem(Log.WARN, msg); 6732 } 6733 } 6734 // Verify that this new package doesn't have any content providers 6735 // that conflict with existing packages. Only do this if the 6736 // package isn't already installed, since we don't want to break 6737 // things that are installed. 6738 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6739 final int N = pkg.providers.size(); 6740 int i; 6741 for (i=0; i<N; i++) { 6742 PackageParser.Provider p = pkg.providers.get(i); 6743 if (p.info.authority != null) { 6744 String names[] = p.info.authority.split(";"); 6745 for (int j = 0; j < names.length; j++) { 6746 if (mProvidersByAuthority.containsKey(names[j])) { 6747 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6748 final String otherPackageName = 6749 ((other != null && other.getComponentName() != null) ? 6750 other.getComponentName().getPackageName() : "?"); 6751 throw new PackageManagerException( 6752 INSTALL_FAILED_CONFLICTING_PROVIDER, 6753 "Can't install because provider name " + names[j] 6754 + " (in package " + pkg.applicationInfo.packageName 6755 + ") is already used by " + otherPackageName); 6756 } 6757 } 6758 } 6759 } 6760 } 6761 6762 if (pkg.mAdoptPermissions != null) { 6763 // This package wants to adopt ownership of permissions from 6764 // another package. 6765 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6766 final String origName = pkg.mAdoptPermissions.get(i); 6767 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6768 if (orig != null) { 6769 if (verifyPackageUpdateLPr(orig, pkg)) { 6770 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6771 + pkg.packageName); 6772 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6773 } 6774 } 6775 } 6776 } 6777 } 6778 6779 final String pkgName = pkg.packageName; 6780 6781 final long scanFileTime = scanFile.lastModified(); 6782 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6783 pkg.applicationInfo.processName = fixProcessName( 6784 pkg.applicationInfo.packageName, 6785 pkg.applicationInfo.processName, 6786 pkg.applicationInfo.uid); 6787 6788 File dataPath; 6789 if (mPlatformPackage == pkg) { 6790 // The system package is special. 6791 dataPath = new File(Environment.getDataDirectory(), "system"); 6792 6793 pkg.applicationInfo.dataDir = dataPath.getPath(); 6794 6795 } else { 6796 // This is a normal package, need to make its data directory. 6797 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6798 UserHandle.USER_OWNER, pkg.packageName); 6799 6800 boolean uidError = false; 6801 if (dataPath.exists()) { 6802 int currentUid = 0; 6803 try { 6804 StructStat stat = Os.stat(dataPath.getPath()); 6805 currentUid = stat.st_uid; 6806 } catch (ErrnoException e) { 6807 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6808 } 6809 6810 // If we have mismatched owners for the data path, we have a problem. 6811 if (currentUid != pkg.applicationInfo.uid) { 6812 boolean recovered = false; 6813 if (currentUid == 0) { 6814 // The directory somehow became owned by root. Wow. 6815 // This is probably because the system was stopped while 6816 // installd was in the middle of messing with its libs 6817 // directory. Ask installd to fix that. 6818 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6819 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6820 if (ret >= 0) { 6821 recovered = true; 6822 String msg = "Package " + pkg.packageName 6823 + " unexpectedly changed to uid 0; recovered to " + 6824 + pkg.applicationInfo.uid; 6825 reportSettingsProblem(Log.WARN, msg); 6826 } 6827 } 6828 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6829 || (scanFlags&SCAN_BOOTING) != 0)) { 6830 // If this is a system app, we can at least delete its 6831 // current data so the application will still work. 6832 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6833 if (ret >= 0) { 6834 // TODO: Kill the processes first 6835 // Old data gone! 6836 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6837 ? "System package " : "Third party package "; 6838 String msg = prefix + pkg.packageName 6839 + " has changed from uid: " 6840 + currentUid + " to " 6841 + pkg.applicationInfo.uid + "; old data erased"; 6842 reportSettingsProblem(Log.WARN, msg); 6843 recovered = true; 6844 6845 // And now re-install the app. 6846 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6847 pkg.applicationInfo.seinfo); 6848 if (ret == -1) { 6849 // Ack should not happen! 6850 msg = prefix + pkg.packageName 6851 + " could not have data directory re-created after delete."; 6852 reportSettingsProblem(Log.WARN, msg); 6853 throw new PackageManagerException( 6854 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6855 } 6856 } 6857 if (!recovered) { 6858 mHasSystemUidErrors = true; 6859 } 6860 } else if (!recovered) { 6861 // If we allow this install to proceed, we will be broken. 6862 // Abort, abort! 6863 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6864 "scanPackageLI"); 6865 } 6866 if (!recovered) { 6867 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6868 + pkg.applicationInfo.uid + "/fs_" 6869 + currentUid; 6870 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6871 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6872 String msg = "Package " + pkg.packageName 6873 + " has mismatched uid: " 6874 + currentUid + " on disk, " 6875 + pkg.applicationInfo.uid + " in settings"; 6876 // writer 6877 synchronized (mPackages) { 6878 mSettings.mReadMessages.append(msg); 6879 mSettings.mReadMessages.append('\n'); 6880 uidError = true; 6881 if (!pkgSetting.uidError) { 6882 reportSettingsProblem(Log.ERROR, msg); 6883 } 6884 } 6885 } 6886 } 6887 pkg.applicationInfo.dataDir = dataPath.getPath(); 6888 if (mShouldRestoreconData) { 6889 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6890 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6891 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6892 } 6893 } else { 6894 if (DEBUG_PACKAGE_SCANNING) { 6895 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6896 Log.v(TAG, "Want this data dir: " + dataPath); 6897 } 6898 //invoke installer to do the actual installation 6899 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6900 pkg.applicationInfo.seinfo); 6901 if (ret < 0) { 6902 // Error from installer 6903 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6904 "Unable to create data dirs [errorCode=" + ret + "]"); 6905 } 6906 6907 if (dataPath.exists()) { 6908 pkg.applicationInfo.dataDir = dataPath.getPath(); 6909 } else { 6910 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6911 pkg.applicationInfo.dataDir = null; 6912 } 6913 } 6914 6915 pkgSetting.uidError = uidError; 6916 } 6917 6918 final String path = scanFile.getPath(); 6919 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6920 6921 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6922 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6923 6924 // Some system apps still use directory structure for native libraries 6925 // in which case we might end up not detecting abi solely based on apk 6926 // structure. Try to detect abi based on directory structure. 6927 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6928 pkg.applicationInfo.primaryCpuAbi == null) { 6929 setBundledAppAbisAndRoots(pkg, pkgSetting); 6930 setNativeLibraryPaths(pkg); 6931 } 6932 6933 } else { 6934 if ((scanFlags & SCAN_MOVE) != 0) { 6935 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6936 // but we already have this packages package info in the PackageSetting. We just 6937 // use that and derive the native library path based on the new codepath. 6938 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6939 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6940 } 6941 6942 // Set native library paths again. For moves, the path will be updated based on the 6943 // ABIs we've determined above. For non-moves, the path will be updated based on the 6944 // ABIs we determined during compilation, but the path will depend on the final 6945 // package path (after the rename away from the stage path). 6946 setNativeLibraryPaths(pkg); 6947 } 6948 6949 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6950 final int[] userIds = sUserManager.getUserIds(); 6951 synchronized (mInstallLock) { 6952 // Make sure all user data directories are ready to roll; we're okay 6953 // if they already exist 6954 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6955 for (int userId : userIds) { 6956 if (userId != 0) { 6957 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6958 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6959 pkg.applicationInfo.seinfo); 6960 } 6961 } 6962 } 6963 6964 // Create a native library symlink only if we have native libraries 6965 // and if the native libraries are 32 bit libraries. We do not provide 6966 // this symlink for 64 bit libraries. 6967 if (pkg.applicationInfo.primaryCpuAbi != null && 6968 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6969 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6970 for (int userId : userIds) { 6971 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6972 nativeLibPath, userId) < 0) { 6973 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6974 "Failed linking native library dir (user=" + userId + ")"); 6975 } 6976 } 6977 } 6978 } 6979 6980 // This is a special case for the "system" package, where the ABI is 6981 // dictated by the zygote configuration (and init.rc). We should keep track 6982 // of this ABI so that we can deal with "normal" applications that run under 6983 // the same UID correctly. 6984 if (mPlatformPackage == pkg) { 6985 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6986 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6987 } 6988 6989 // If there's a mismatch between the abi-override in the package setting 6990 // and the abiOverride specified for the install. Warn about this because we 6991 // would've already compiled the app without taking the package setting into 6992 // account. 6993 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6994 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6995 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6996 " for package: " + pkg.packageName); 6997 } 6998 } 6999 7000 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7001 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7002 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7003 7004 // Copy the derived override back to the parsed package, so that we can 7005 // update the package settings accordingly. 7006 pkg.cpuAbiOverride = cpuAbiOverride; 7007 7008 if (DEBUG_ABI_SELECTION) { 7009 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7010 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7011 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7012 } 7013 7014 // Push the derived path down into PackageSettings so we know what to 7015 // clean up at uninstall time. 7016 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7017 7018 if (DEBUG_ABI_SELECTION) { 7019 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7020 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7021 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7022 } 7023 7024 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7025 // We don't do this here during boot because we can do it all 7026 // at once after scanning all existing packages. 7027 // 7028 // We also do this *before* we perform dexopt on this package, so that 7029 // we can avoid redundant dexopts, and also to make sure we've got the 7030 // code and package path correct. 7031 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7032 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7033 } 7034 7035 if ((scanFlags & SCAN_NO_DEX) == 0) { 7036 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7037 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7038 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7039 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7040 } 7041 } 7042 if (mFactoryTest && pkg.requestedPermissions.contains( 7043 android.Manifest.permission.FACTORY_TEST)) { 7044 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7045 } 7046 7047 ArrayList<PackageParser.Package> clientLibPkgs = null; 7048 7049 // writer 7050 synchronized (mPackages) { 7051 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7052 // Only system apps can add new shared libraries. 7053 if (pkg.libraryNames != null) { 7054 for (int i=0; i<pkg.libraryNames.size(); i++) { 7055 String name = pkg.libraryNames.get(i); 7056 boolean allowed = false; 7057 if (pkg.isUpdatedSystemApp()) { 7058 // New library entries can only be added through the 7059 // system image. This is important to get rid of a lot 7060 // of nasty edge cases: for example if we allowed a non- 7061 // system update of the app to add a library, then uninstalling 7062 // the update would make the library go away, and assumptions 7063 // we made such as through app install filtering would now 7064 // have allowed apps on the device which aren't compatible 7065 // with it. Better to just have the restriction here, be 7066 // conservative, and create many fewer cases that can negatively 7067 // impact the user experience. 7068 final PackageSetting sysPs = mSettings 7069 .getDisabledSystemPkgLPr(pkg.packageName); 7070 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7071 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7072 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7073 allowed = true; 7074 allowed = true; 7075 break; 7076 } 7077 } 7078 } 7079 } else { 7080 allowed = true; 7081 } 7082 if (allowed) { 7083 if (!mSharedLibraries.containsKey(name)) { 7084 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7085 } else if (!name.equals(pkg.packageName)) { 7086 Slog.w(TAG, "Package " + pkg.packageName + " library " 7087 + name + " already exists; skipping"); 7088 } 7089 } else { 7090 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7091 + name + " that is not declared on system image; skipping"); 7092 } 7093 } 7094 if ((scanFlags&SCAN_BOOTING) == 0) { 7095 // If we are not booting, we need to update any applications 7096 // that are clients of our shared library. If we are booting, 7097 // this will all be done once the scan is complete. 7098 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7099 } 7100 } 7101 } 7102 } 7103 7104 // We also need to dexopt any apps that are dependent on this library. Note that 7105 // if these fail, we should abort the install since installing the library will 7106 // result in some apps being broken. 7107 if (clientLibPkgs != null) { 7108 if ((scanFlags & SCAN_NO_DEX) == 0) { 7109 for (int i = 0; i < clientLibPkgs.size(); i++) { 7110 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7111 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7112 null /* instruction sets */, forceDex, 7113 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7114 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7115 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7116 "scanPackageLI failed to dexopt clientLibPkgs"); 7117 } 7118 } 7119 } 7120 } 7121 7122 // Request the ActivityManager to kill the process(only for existing packages) 7123 // so that we do not end up in a confused state while the user is still using the older 7124 // version of the application while the new one gets installed. 7125 if ((scanFlags & SCAN_REPLACING) != 0) { 7126 killApplication(pkg.applicationInfo.packageName, 7127 pkg.applicationInfo.uid, "replace pkg"); 7128 } 7129 7130 // Also need to kill any apps that are dependent on the library. 7131 if (clientLibPkgs != null) { 7132 for (int i=0; i<clientLibPkgs.size(); i++) { 7133 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7134 killApplication(clientPkg.applicationInfo.packageName, 7135 clientPkg.applicationInfo.uid, "update lib"); 7136 } 7137 } 7138 7139 // Make sure we're not adding any bogus keyset info 7140 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7141 ksms.assertScannedPackageValid(pkg); 7142 7143 // writer 7144 synchronized (mPackages) { 7145 // We don't expect installation to fail beyond this point 7146 7147 // Add the new setting to mSettings 7148 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7149 // Add the new setting to mPackages 7150 mPackages.put(pkg.applicationInfo.packageName, pkg); 7151 // Make sure we don't accidentally delete its data. 7152 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7153 while (iter.hasNext()) { 7154 PackageCleanItem item = iter.next(); 7155 if (pkgName.equals(item.packageName)) { 7156 iter.remove(); 7157 } 7158 } 7159 7160 // Take care of first install / last update times. 7161 if (currentTime != 0) { 7162 if (pkgSetting.firstInstallTime == 0) { 7163 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7164 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7165 pkgSetting.lastUpdateTime = currentTime; 7166 } 7167 } else if (pkgSetting.firstInstallTime == 0) { 7168 // We need *something*. Take time time stamp of the file. 7169 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7170 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7171 if (scanFileTime != pkgSetting.timeStamp) { 7172 // A package on the system image has changed; consider this 7173 // to be an update. 7174 pkgSetting.lastUpdateTime = scanFileTime; 7175 } 7176 } 7177 7178 // Add the package's KeySets to the global KeySetManagerService 7179 ksms.addScannedPackageLPw(pkg); 7180 7181 int N = pkg.providers.size(); 7182 StringBuilder r = null; 7183 int i; 7184 for (i=0; i<N; i++) { 7185 PackageParser.Provider p = pkg.providers.get(i); 7186 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7187 p.info.processName, pkg.applicationInfo.uid); 7188 mProviders.addProvider(p); 7189 p.syncable = p.info.isSyncable; 7190 if (p.info.authority != null) { 7191 String names[] = p.info.authority.split(";"); 7192 p.info.authority = null; 7193 for (int j = 0; j < names.length; j++) { 7194 if (j == 1 && p.syncable) { 7195 // We only want the first authority for a provider to possibly be 7196 // syncable, so if we already added this provider using a different 7197 // authority clear the syncable flag. We copy the provider before 7198 // changing it because the mProviders object contains a reference 7199 // to a provider that we don't want to change. 7200 // Only do this for the second authority since the resulting provider 7201 // object can be the same for all future authorities for this provider. 7202 p = new PackageParser.Provider(p); 7203 p.syncable = false; 7204 } 7205 if (!mProvidersByAuthority.containsKey(names[j])) { 7206 mProvidersByAuthority.put(names[j], p); 7207 if (p.info.authority == null) { 7208 p.info.authority = names[j]; 7209 } else { 7210 p.info.authority = p.info.authority + ";" + names[j]; 7211 } 7212 if (DEBUG_PACKAGE_SCANNING) { 7213 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7214 Log.d(TAG, "Registered content provider: " + names[j] 7215 + ", className = " + p.info.name + ", isSyncable = " 7216 + p.info.isSyncable); 7217 } 7218 } else { 7219 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7220 Slog.w(TAG, "Skipping provider name " + names[j] + 7221 " (in package " + pkg.applicationInfo.packageName + 7222 "): name already used by " 7223 + ((other != null && other.getComponentName() != null) 7224 ? other.getComponentName().getPackageName() : "?")); 7225 } 7226 } 7227 } 7228 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7229 if (r == null) { 7230 r = new StringBuilder(256); 7231 } else { 7232 r.append(' '); 7233 } 7234 r.append(p.info.name); 7235 } 7236 } 7237 if (r != null) { 7238 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7239 } 7240 7241 N = pkg.services.size(); 7242 r = null; 7243 for (i=0; i<N; i++) { 7244 PackageParser.Service s = pkg.services.get(i); 7245 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7246 s.info.processName, pkg.applicationInfo.uid); 7247 mServices.addService(s); 7248 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7249 if (r == null) { 7250 r = new StringBuilder(256); 7251 } else { 7252 r.append(' '); 7253 } 7254 r.append(s.info.name); 7255 } 7256 } 7257 if (r != null) { 7258 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7259 } 7260 7261 N = pkg.receivers.size(); 7262 r = null; 7263 for (i=0; i<N; i++) { 7264 PackageParser.Activity a = pkg.receivers.get(i); 7265 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7266 a.info.processName, pkg.applicationInfo.uid); 7267 mReceivers.addActivity(a, "receiver"); 7268 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7269 if (r == null) { 7270 r = new StringBuilder(256); 7271 } else { 7272 r.append(' '); 7273 } 7274 r.append(a.info.name); 7275 } 7276 } 7277 if (r != null) { 7278 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7279 } 7280 7281 N = pkg.activities.size(); 7282 r = null; 7283 for (i=0; i<N; i++) { 7284 PackageParser.Activity a = pkg.activities.get(i); 7285 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7286 a.info.processName, pkg.applicationInfo.uid); 7287 mActivities.addActivity(a, "activity"); 7288 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7289 if (r == null) { 7290 r = new StringBuilder(256); 7291 } else { 7292 r.append(' '); 7293 } 7294 r.append(a.info.name); 7295 } 7296 } 7297 if (r != null) { 7298 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7299 } 7300 7301 N = pkg.permissionGroups.size(); 7302 r = null; 7303 for (i=0; i<N; i++) { 7304 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7305 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7306 if (cur == null) { 7307 mPermissionGroups.put(pg.info.name, pg); 7308 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7309 if (r == null) { 7310 r = new StringBuilder(256); 7311 } else { 7312 r.append(' '); 7313 } 7314 r.append(pg.info.name); 7315 } 7316 } else { 7317 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7318 + pg.info.packageName + " ignored: original from " 7319 + cur.info.packageName); 7320 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7321 if (r == null) { 7322 r = new StringBuilder(256); 7323 } else { 7324 r.append(' '); 7325 } 7326 r.append("DUP:"); 7327 r.append(pg.info.name); 7328 } 7329 } 7330 } 7331 if (r != null) { 7332 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7333 } 7334 7335 N = pkg.permissions.size(); 7336 r = null; 7337 for (i=0; i<N; i++) { 7338 PackageParser.Permission p = pkg.permissions.get(i); 7339 7340 // Assume by default that we did not install this permission into the system. 7341 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7342 7343 // Now that permission groups have a special meaning, we ignore permission 7344 // groups for legacy apps to prevent unexpected behavior. In particular, 7345 // permissions for one app being granted to someone just becuase they happen 7346 // to be in a group defined by another app (before this had no implications). 7347 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7348 p.group = mPermissionGroups.get(p.info.group); 7349 // Warn for a permission in an unknown group. 7350 if (p.info.group != null && p.group == null) { 7351 Slog.w(TAG, "Permission " + p.info.name + " from package " 7352 + p.info.packageName + " in an unknown group " + p.info.group); 7353 } 7354 } 7355 7356 ArrayMap<String, BasePermission> permissionMap = 7357 p.tree ? mSettings.mPermissionTrees 7358 : mSettings.mPermissions; 7359 BasePermission bp = permissionMap.get(p.info.name); 7360 7361 // Allow system apps to redefine non-system permissions 7362 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7363 final boolean currentOwnerIsSystem = (bp.perm != null 7364 && isSystemApp(bp.perm.owner)); 7365 if (isSystemApp(p.owner)) { 7366 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7367 // It's a built-in permission and no owner, take ownership now 7368 bp.packageSetting = pkgSetting; 7369 bp.perm = p; 7370 bp.uid = pkg.applicationInfo.uid; 7371 bp.sourcePackage = p.info.packageName; 7372 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7373 } else if (!currentOwnerIsSystem) { 7374 String msg = "New decl " + p.owner + " of permission " 7375 + p.info.name + " is system; overriding " + bp.sourcePackage; 7376 reportSettingsProblem(Log.WARN, msg); 7377 bp = null; 7378 } 7379 } 7380 } 7381 7382 if (bp == null) { 7383 bp = new BasePermission(p.info.name, p.info.packageName, 7384 BasePermission.TYPE_NORMAL); 7385 permissionMap.put(p.info.name, bp); 7386 } 7387 7388 if (bp.perm == null) { 7389 if (bp.sourcePackage == null 7390 || bp.sourcePackage.equals(p.info.packageName)) { 7391 BasePermission tree = findPermissionTreeLP(p.info.name); 7392 if (tree == null 7393 || tree.sourcePackage.equals(p.info.packageName)) { 7394 bp.packageSetting = pkgSetting; 7395 bp.perm = p; 7396 bp.uid = pkg.applicationInfo.uid; 7397 bp.sourcePackage = p.info.packageName; 7398 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7399 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7400 if (r == null) { 7401 r = new StringBuilder(256); 7402 } else { 7403 r.append(' '); 7404 } 7405 r.append(p.info.name); 7406 } 7407 } else { 7408 Slog.w(TAG, "Permission " + p.info.name + " from package " 7409 + p.info.packageName + " ignored: base tree " 7410 + tree.name + " is from package " 7411 + tree.sourcePackage); 7412 } 7413 } else { 7414 Slog.w(TAG, "Permission " + p.info.name + " from package " 7415 + p.info.packageName + " ignored: original from " 7416 + bp.sourcePackage); 7417 } 7418 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7419 if (r == null) { 7420 r = new StringBuilder(256); 7421 } else { 7422 r.append(' '); 7423 } 7424 r.append("DUP:"); 7425 r.append(p.info.name); 7426 } 7427 if (bp.perm == p) { 7428 bp.protectionLevel = p.info.protectionLevel; 7429 } 7430 } 7431 7432 if (r != null) { 7433 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7434 } 7435 7436 N = pkg.instrumentation.size(); 7437 r = null; 7438 for (i=0; i<N; i++) { 7439 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7440 a.info.packageName = pkg.applicationInfo.packageName; 7441 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7442 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7443 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7444 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7445 a.info.dataDir = pkg.applicationInfo.dataDir; 7446 7447 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7448 // need other information about the application, like the ABI and what not ? 7449 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7450 mInstrumentation.put(a.getComponentName(), a); 7451 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7452 if (r == null) { 7453 r = new StringBuilder(256); 7454 } else { 7455 r.append(' '); 7456 } 7457 r.append(a.info.name); 7458 } 7459 } 7460 if (r != null) { 7461 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7462 } 7463 7464 if (pkg.protectedBroadcasts != null) { 7465 N = pkg.protectedBroadcasts.size(); 7466 for (i=0; i<N; i++) { 7467 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7468 } 7469 } 7470 7471 pkgSetting.setTimeStamp(scanFileTime); 7472 7473 // Create idmap files for pairs of (packages, overlay packages). 7474 // Note: "android", ie framework-res.apk, is handled by native layers. 7475 if (pkg.mOverlayTarget != null) { 7476 // This is an overlay package. 7477 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7478 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7479 mOverlays.put(pkg.mOverlayTarget, 7480 new ArrayMap<String, PackageParser.Package>()); 7481 } 7482 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7483 map.put(pkg.packageName, pkg); 7484 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7485 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7486 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7487 "scanPackageLI failed to createIdmap"); 7488 } 7489 } 7490 } else if (mOverlays.containsKey(pkg.packageName) && 7491 !pkg.packageName.equals("android")) { 7492 // This is a regular package, with one or more known overlay packages. 7493 createIdmapsForPackageLI(pkg); 7494 } 7495 } 7496 7497 return pkg; 7498 } 7499 7500 /** 7501 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7502 * is derived purely on the basis of the contents of {@code scanFile} and 7503 * {@code cpuAbiOverride}. 7504 * 7505 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7506 */ 7507 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7508 String cpuAbiOverride, boolean extractLibs) 7509 throws PackageManagerException { 7510 // TODO: We can probably be smarter about this stuff. For installed apps, 7511 // we can calculate this information at install time once and for all. For 7512 // system apps, we can probably assume that this information doesn't change 7513 // after the first boot scan. As things stand, we do lots of unnecessary work. 7514 7515 // Give ourselves some initial paths; we'll come back for another 7516 // pass once we've determined ABI below. 7517 setNativeLibraryPaths(pkg); 7518 7519 // We would never need to extract libs for forward-locked and external packages, 7520 // since the container service will do it for us. We shouldn't attempt to 7521 // extract libs from system app when it was not updated. 7522 if (pkg.isForwardLocked() || isExternal(pkg) || 7523 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7524 extractLibs = false; 7525 } 7526 7527 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7528 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7529 7530 NativeLibraryHelper.Handle handle = null; 7531 try { 7532 handle = NativeLibraryHelper.Handle.create(scanFile); 7533 // TODO(multiArch): This can be null for apps that didn't go through the 7534 // usual installation process. We can calculate it again, like we 7535 // do during install time. 7536 // 7537 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7538 // unnecessary. 7539 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7540 7541 // Null out the abis so that they can be recalculated. 7542 pkg.applicationInfo.primaryCpuAbi = null; 7543 pkg.applicationInfo.secondaryCpuAbi = null; 7544 if (isMultiArch(pkg.applicationInfo)) { 7545 // Warn if we've set an abiOverride for multi-lib packages.. 7546 // By definition, we need to copy both 32 and 64 bit libraries for 7547 // such packages. 7548 if (pkg.cpuAbiOverride != null 7549 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7550 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7551 } 7552 7553 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7554 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7555 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7556 if (extractLibs) { 7557 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7558 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7559 useIsaSpecificSubdirs); 7560 } else { 7561 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7562 } 7563 } 7564 7565 maybeThrowExceptionForMultiArchCopy( 7566 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7567 7568 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7569 if (extractLibs) { 7570 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7571 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7572 useIsaSpecificSubdirs); 7573 } else { 7574 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7575 } 7576 } 7577 7578 maybeThrowExceptionForMultiArchCopy( 7579 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7580 7581 if (abi64 >= 0) { 7582 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7583 } 7584 7585 if (abi32 >= 0) { 7586 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7587 if (abi64 >= 0) { 7588 pkg.applicationInfo.secondaryCpuAbi = abi; 7589 } else { 7590 pkg.applicationInfo.primaryCpuAbi = abi; 7591 } 7592 } 7593 } else { 7594 String[] abiList = (cpuAbiOverride != null) ? 7595 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7596 7597 // Enable gross and lame hacks for apps that are built with old 7598 // SDK tools. We must scan their APKs for renderscript bitcode and 7599 // not launch them if it's present. Don't bother checking on devices 7600 // that don't have 64 bit support. 7601 boolean needsRenderScriptOverride = false; 7602 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7603 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7604 abiList = Build.SUPPORTED_32_BIT_ABIS; 7605 needsRenderScriptOverride = true; 7606 } 7607 7608 final int copyRet; 7609 if (extractLibs) { 7610 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7611 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7612 } else { 7613 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7614 } 7615 7616 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7617 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7618 "Error unpackaging native libs for app, errorCode=" + copyRet); 7619 } 7620 7621 if (copyRet >= 0) { 7622 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7623 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7624 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7625 } else if (needsRenderScriptOverride) { 7626 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7627 } 7628 } 7629 } catch (IOException ioe) { 7630 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7631 } finally { 7632 IoUtils.closeQuietly(handle); 7633 } 7634 7635 // Now that we've calculated the ABIs and determined if it's an internal app, 7636 // we will go ahead and populate the nativeLibraryPath. 7637 setNativeLibraryPaths(pkg); 7638 } 7639 7640 /** 7641 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7642 * i.e, so that all packages can be run inside a single process if required. 7643 * 7644 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7645 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7646 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7647 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7648 * updating a package that belongs to a shared user. 7649 * 7650 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7651 * adds unnecessary complexity. 7652 */ 7653 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7654 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7655 String requiredInstructionSet = null; 7656 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7657 requiredInstructionSet = VMRuntime.getInstructionSet( 7658 scannedPackage.applicationInfo.primaryCpuAbi); 7659 } 7660 7661 PackageSetting requirer = null; 7662 for (PackageSetting ps : packagesForUser) { 7663 // If packagesForUser contains scannedPackage, we skip it. This will happen 7664 // when scannedPackage is an update of an existing package. Without this check, 7665 // we will never be able to change the ABI of any package belonging to a shared 7666 // user, even if it's compatible with other packages. 7667 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7668 if (ps.primaryCpuAbiString == null) { 7669 continue; 7670 } 7671 7672 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7673 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7674 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7675 // this but there's not much we can do. 7676 String errorMessage = "Instruction set mismatch, " 7677 + ((requirer == null) ? "[caller]" : requirer) 7678 + " requires " + requiredInstructionSet + " whereas " + ps 7679 + " requires " + instructionSet; 7680 Slog.w(TAG, errorMessage); 7681 } 7682 7683 if (requiredInstructionSet == null) { 7684 requiredInstructionSet = instructionSet; 7685 requirer = ps; 7686 } 7687 } 7688 } 7689 7690 if (requiredInstructionSet != null) { 7691 String adjustedAbi; 7692 if (requirer != null) { 7693 // requirer != null implies that either scannedPackage was null or that scannedPackage 7694 // did not require an ABI, in which case we have to adjust scannedPackage to match 7695 // the ABI of the set (which is the same as requirer's ABI) 7696 adjustedAbi = requirer.primaryCpuAbiString; 7697 if (scannedPackage != null) { 7698 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7699 } 7700 } else { 7701 // requirer == null implies that we're updating all ABIs in the set to 7702 // match scannedPackage. 7703 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7704 } 7705 7706 for (PackageSetting ps : packagesForUser) { 7707 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7708 if (ps.primaryCpuAbiString != null) { 7709 continue; 7710 } 7711 7712 ps.primaryCpuAbiString = adjustedAbi; 7713 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7714 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7715 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7716 7717 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7718 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7719 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7720 ps.primaryCpuAbiString = null; 7721 ps.pkg.applicationInfo.primaryCpuAbi = null; 7722 return; 7723 } else { 7724 mInstaller.rmdex(ps.codePathString, 7725 getDexCodeInstructionSet(getPreferredInstructionSet())); 7726 } 7727 } 7728 } 7729 } 7730 } 7731 } 7732 7733 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7734 synchronized (mPackages) { 7735 mResolverReplaced = true; 7736 // Set up information for custom user intent resolution activity. 7737 mResolveActivity.applicationInfo = pkg.applicationInfo; 7738 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7739 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7740 mResolveActivity.processName = pkg.applicationInfo.packageName; 7741 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7742 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7743 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7744 mResolveActivity.theme = 0; 7745 mResolveActivity.exported = true; 7746 mResolveActivity.enabled = true; 7747 mResolveInfo.activityInfo = mResolveActivity; 7748 mResolveInfo.priority = 0; 7749 mResolveInfo.preferredOrder = 0; 7750 mResolveInfo.match = 0; 7751 mResolveComponentName = mCustomResolverComponentName; 7752 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7753 mResolveComponentName); 7754 } 7755 } 7756 7757 private static String calculateBundledApkRoot(final String codePathString) { 7758 final File codePath = new File(codePathString); 7759 final File codeRoot; 7760 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7761 codeRoot = Environment.getRootDirectory(); 7762 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7763 codeRoot = Environment.getOemDirectory(); 7764 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7765 codeRoot = Environment.getVendorDirectory(); 7766 } else { 7767 // Unrecognized code path; take its top real segment as the apk root: 7768 // e.g. /something/app/blah.apk => /something 7769 try { 7770 File f = codePath.getCanonicalFile(); 7771 File parent = f.getParentFile(); // non-null because codePath is a file 7772 File tmp; 7773 while ((tmp = parent.getParentFile()) != null) { 7774 f = parent; 7775 parent = tmp; 7776 } 7777 codeRoot = f; 7778 Slog.w(TAG, "Unrecognized code path " 7779 + codePath + " - using " + codeRoot); 7780 } catch (IOException e) { 7781 // Can't canonicalize the code path -- shenanigans? 7782 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7783 return Environment.getRootDirectory().getPath(); 7784 } 7785 } 7786 return codeRoot.getPath(); 7787 } 7788 7789 /** 7790 * Derive and set the location of native libraries for the given package, 7791 * which varies depending on where and how the package was installed. 7792 */ 7793 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7794 final ApplicationInfo info = pkg.applicationInfo; 7795 final String codePath = pkg.codePath; 7796 final File codeFile = new File(codePath); 7797 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7798 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7799 7800 info.nativeLibraryRootDir = null; 7801 info.nativeLibraryRootRequiresIsa = false; 7802 info.nativeLibraryDir = null; 7803 info.secondaryNativeLibraryDir = null; 7804 7805 if (isApkFile(codeFile)) { 7806 // Monolithic install 7807 if (bundledApp) { 7808 // If "/system/lib64/apkname" exists, assume that is the per-package 7809 // native library directory to use; otherwise use "/system/lib/apkname". 7810 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7811 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7812 getPrimaryInstructionSet(info)); 7813 7814 // This is a bundled system app so choose the path based on the ABI. 7815 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7816 // is just the default path. 7817 final String apkName = deriveCodePathName(codePath); 7818 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7819 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7820 apkName).getAbsolutePath(); 7821 7822 if (info.secondaryCpuAbi != null) { 7823 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7824 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7825 secondaryLibDir, apkName).getAbsolutePath(); 7826 } 7827 } else if (asecApp) { 7828 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7829 .getAbsolutePath(); 7830 } else { 7831 final String apkName = deriveCodePathName(codePath); 7832 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7833 .getAbsolutePath(); 7834 } 7835 7836 info.nativeLibraryRootRequiresIsa = false; 7837 info.nativeLibraryDir = info.nativeLibraryRootDir; 7838 } else { 7839 // Cluster install 7840 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7841 info.nativeLibraryRootRequiresIsa = true; 7842 7843 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7844 getPrimaryInstructionSet(info)).getAbsolutePath(); 7845 7846 if (info.secondaryCpuAbi != null) { 7847 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7848 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7849 } 7850 } 7851 } 7852 7853 /** 7854 * Calculate the abis and roots for a bundled app. These can uniquely 7855 * be determined from the contents of the system partition, i.e whether 7856 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7857 * of this information, and instead assume that the system was built 7858 * sensibly. 7859 */ 7860 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7861 PackageSetting pkgSetting) { 7862 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7863 7864 // If "/system/lib64/apkname" exists, assume that is the per-package 7865 // native library directory to use; otherwise use "/system/lib/apkname". 7866 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7867 setBundledAppAbi(pkg, apkRoot, apkName); 7868 // pkgSetting might be null during rescan following uninstall of updates 7869 // to a bundled app, so accommodate that possibility. The settings in 7870 // that case will be established later from the parsed package. 7871 // 7872 // If the settings aren't null, sync them up with what we've just derived. 7873 // note that apkRoot isn't stored in the package settings. 7874 if (pkgSetting != null) { 7875 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7876 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7877 } 7878 } 7879 7880 /** 7881 * Deduces the ABI of a bundled app and sets the relevant fields on the 7882 * parsed pkg object. 7883 * 7884 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7885 * under which system libraries are installed. 7886 * @param apkName the name of the installed package. 7887 */ 7888 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7889 final File codeFile = new File(pkg.codePath); 7890 7891 final boolean has64BitLibs; 7892 final boolean has32BitLibs; 7893 if (isApkFile(codeFile)) { 7894 // Monolithic install 7895 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7896 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7897 } else { 7898 // Cluster install 7899 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7900 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7901 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7902 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7903 has64BitLibs = (new File(rootDir, isa)).exists(); 7904 } else { 7905 has64BitLibs = false; 7906 } 7907 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7908 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7909 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7910 has32BitLibs = (new File(rootDir, isa)).exists(); 7911 } else { 7912 has32BitLibs = false; 7913 } 7914 } 7915 7916 if (has64BitLibs && !has32BitLibs) { 7917 // The package has 64 bit libs, but not 32 bit libs. Its primary 7918 // ABI should be 64 bit. We can safely assume here that the bundled 7919 // native libraries correspond to the most preferred ABI in the list. 7920 7921 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7922 pkg.applicationInfo.secondaryCpuAbi = null; 7923 } else if (has32BitLibs && !has64BitLibs) { 7924 // The package has 32 bit libs but not 64 bit libs. Its primary 7925 // ABI should be 32 bit. 7926 7927 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7928 pkg.applicationInfo.secondaryCpuAbi = null; 7929 } else if (has32BitLibs && has64BitLibs) { 7930 // The application has both 64 and 32 bit bundled libraries. We check 7931 // here that the app declares multiArch support, and warn if it doesn't. 7932 // 7933 // We will be lenient here and record both ABIs. The primary will be the 7934 // ABI that's higher on the list, i.e, a device that's configured to prefer 7935 // 64 bit apps will see a 64 bit primary ABI, 7936 7937 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7938 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7939 } 7940 7941 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7942 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7943 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7944 } else { 7945 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7946 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7947 } 7948 } else { 7949 pkg.applicationInfo.primaryCpuAbi = null; 7950 pkg.applicationInfo.secondaryCpuAbi = null; 7951 } 7952 } 7953 7954 private void killApplication(String pkgName, int appId, String reason) { 7955 // Request the ActivityManager to kill the process(only for existing packages) 7956 // so that we do not end up in a confused state while the user is still using the older 7957 // version of the application while the new one gets installed. 7958 IActivityManager am = ActivityManagerNative.getDefault(); 7959 if (am != null) { 7960 try { 7961 am.killApplicationWithAppId(pkgName, appId, reason); 7962 } catch (RemoteException e) { 7963 } 7964 } 7965 } 7966 7967 void removePackageLI(PackageSetting ps, boolean chatty) { 7968 if (DEBUG_INSTALL) { 7969 if (chatty) 7970 Log.d(TAG, "Removing package " + ps.name); 7971 } 7972 7973 // writer 7974 synchronized (mPackages) { 7975 mPackages.remove(ps.name); 7976 final PackageParser.Package pkg = ps.pkg; 7977 if (pkg != null) { 7978 cleanPackageDataStructuresLILPw(pkg, chatty); 7979 } 7980 } 7981 } 7982 7983 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7984 if (DEBUG_INSTALL) { 7985 if (chatty) 7986 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7987 } 7988 7989 // writer 7990 synchronized (mPackages) { 7991 mPackages.remove(pkg.applicationInfo.packageName); 7992 cleanPackageDataStructuresLILPw(pkg, chatty); 7993 } 7994 } 7995 7996 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7997 int N = pkg.providers.size(); 7998 StringBuilder r = null; 7999 int i; 8000 for (i=0; i<N; i++) { 8001 PackageParser.Provider p = pkg.providers.get(i); 8002 mProviders.removeProvider(p); 8003 if (p.info.authority == null) { 8004 8005 /* There was another ContentProvider with this authority when 8006 * this app was installed so this authority is null, 8007 * Ignore it as we don't have to unregister the provider. 8008 */ 8009 continue; 8010 } 8011 String names[] = p.info.authority.split(";"); 8012 for (int j = 0; j < names.length; j++) { 8013 if (mProvidersByAuthority.get(names[j]) == p) { 8014 mProvidersByAuthority.remove(names[j]); 8015 if (DEBUG_REMOVE) { 8016 if (chatty) 8017 Log.d(TAG, "Unregistered content provider: " + names[j] 8018 + ", className = " + p.info.name + ", isSyncable = " 8019 + p.info.isSyncable); 8020 } 8021 } 8022 } 8023 if (DEBUG_REMOVE && chatty) { 8024 if (r == null) { 8025 r = new StringBuilder(256); 8026 } else { 8027 r.append(' '); 8028 } 8029 r.append(p.info.name); 8030 } 8031 } 8032 if (r != null) { 8033 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8034 } 8035 8036 N = pkg.services.size(); 8037 r = null; 8038 for (i=0; i<N; i++) { 8039 PackageParser.Service s = pkg.services.get(i); 8040 mServices.removeService(s); 8041 if (chatty) { 8042 if (r == null) { 8043 r = new StringBuilder(256); 8044 } else { 8045 r.append(' '); 8046 } 8047 r.append(s.info.name); 8048 } 8049 } 8050 if (r != null) { 8051 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8052 } 8053 8054 N = pkg.receivers.size(); 8055 r = null; 8056 for (i=0; i<N; i++) { 8057 PackageParser.Activity a = pkg.receivers.get(i); 8058 mReceivers.removeActivity(a, "receiver"); 8059 if (DEBUG_REMOVE && chatty) { 8060 if (r == null) { 8061 r = new StringBuilder(256); 8062 } else { 8063 r.append(' '); 8064 } 8065 r.append(a.info.name); 8066 } 8067 } 8068 if (r != null) { 8069 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8070 } 8071 8072 N = pkg.activities.size(); 8073 r = null; 8074 for (i=0; i<N; i++) { 8075 PackageParser.Activity a = pkg.activities.get(i); 8076 mActivities.removeActivity(a, "activity"); 8077 if (DEBUG_REMOVE && chatty) { 8078 if (r == null) { 8079 r = new StringBuilder(256); 8080 } else { 8081 r.append(' '); 8082 } 8083 r.append(a.info.name); 8084 } 8085 } 8086 if (r != null) { 8087 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8088 } 8089 8090 N = pkg.permissions.size(); 8091 r = null; 8092 for (i=0; i<N; i++) { 8093 PackageParser.Permission p = pkg.permissions.get(i); 8094 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8095 if (bp == null) { 8096 bp = mSettings.mPermissionTrees.get(p.info.name); 8097 } 8098 if (bp != null && bp.perm == p) { 8099 bp.perm = null; 8100 if (DEBUG_REMOVE && chatty) { 8101 if (r == null) { 8102 r = new StringBuilder(256); 8103 } else { 8104 r.append(' '); 8105 } 8106 r.append(p.info.name); 8107 } 8108 } 8109 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8110 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8111 if (appOpPerms != null) { 8112 appOpPerms.remove(pkg.packageName); 8113 } 8114 } 8115 } 8116 if (r != null) { 8117 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8118 } 8119 8120 N = pkg.requestedPermissions.size(); 8121 r = null; 8122 for (i=0; i<N; i++) { 8123 String perm = pkg.requestedPermissions.get(i); 8124 BasePermission bp = mSettings.mPermissions.get(perm); 8125 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8126 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8127 if (appOpPerms != null) { 8128 appOpPerms.remove(pkg.packageName); 8129 if (appOpPerms.isEmpty()) { 8130 mAppOpPermissionPackages.remove(perm); 8131 } 8132 } 8133 } 8134 } 8135 if (r != null) { 8136 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8137 } 8138 8139 N = pkg.instrumentation.size(); 8140 r = null; 8141 for (i=0; i<N; i++) { 8142 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8143 mInstrumentation.remove(a.getComponentName()); 8144 if (DEBUG_REMOVE && chatty) { 8145 if (r == null) { 8146 r = new StringBuilder(256); 8147 } else { 8148 r.append(' '); 8149 } 8150 r.append(a.info.name); 8151 } 8152 } 8153 if (r != null) { 8154 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8155 } 8156 8157 r = null; 8158 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8159 // Only system apps can hold shared libraries. 8160 if (pkg.libraryNames != null) { 8161 for (i=0; i<pkg.libraryNames.size(); i++) { 8162 String name = pkg.libraryNames.get(i); 8163 SharedLibraryEntry cur = mSharedLibraries.get(name); 8164 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8165 mSharedLibraries.remove(name); 8166 if (DEBUG_REMOVE && chatty) { 8167 if (r == null) { 8168 r = new StringBuilder(256); 8169 } else { 8170 r.append(' '); 8171 } 8172 r.append(name); 8173 } 8174 } 8175 } 8176 } 8177 } 8178 if (r != null) { 8179 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8180 } 8181 } 8182 8183 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8184 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8185 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8186 return true; 8187 } 8188 } 8189 return false; 8190 } 8191 8192 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8193 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8194 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8195 8196 private void updatePermissionsLPw(String changingPkg, 8197 PackageParser.Package pkgInfo, int flags) { 8198 // Make sure there are no dangling permission trees. 8199 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8200 while (it.hasNext()) { 8201 final BasePermission bp = it.next(); 8202 if (bp.packageSetting == null) { 8203 // We may not yet have parsed the package, so just see if 8204 // we still know about its settings. 8205 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8206 } 8207 if (bp.packageSetting == null) { 8208 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8209 + " from package " + bp.sourcePackage); 8210 it.remove(); 8211 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8212 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8213 Slog.i(TAG, "Removing old permission tree: " + bp.name 8214 + " from package " + bp.sourcePackage); 8215 flags |= UPDATE_PERMISSIONS_ALL; 8216 it.remove(); 8217 } 8218 } 8219 } 8220 8221 // Make sure all dynamic permissions have been assigned to a package, 8222 // and make sure there are no dangling permissions. 8223 it = mSettings.mPermissions.values().iterator(); 8224 while (it.hasNext()) { 8225 final BasePermission bp = it.next(); 8226 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8227 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8228 + bp.name + " pkg=" + bp.sourcePackage 8229 + " info=" + bp.pendingInfo); 8230 if (bp.packageSetting == null && bp.pendingInfo != null) { 8231 final BasePermission tree = findPermissionTreeLP(bp.name); 8232 if (tree != null && tree.perm != null) { 8233 bp.packageSetting = tree.packageSetting; 8234 bp.perm = new PackageParser.Permission(tree.perm.owner, 8235 new PermissionInfo(bp.pendingInfo)); 8236 bp.perm.info.packageName = tree.perm.info.packageName; 8237 bp.perm.info.name = bp.name; 8238 bp.uid = tree.uid; 8239 } 8240 } 8241 } 8242 if (bp.packageSetting == null) { 8243 // We may not yet have parsed the package, so just see if 8244 // we still know about its settings. 8245 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8246 } 8247 if (bp.packageSetting == null) { 8248 Slog.w(TAG, "Removing dangling permission: " + bp.name 8249 + " from package " + bp.sourcePackage); 8250 it.remove(); 8251 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8252 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8253 Slog.i(TAG, "Removing old permission: " + bp.name 8254 + " from package " + bp.sourcePackage); 8255 flags |= UPDATE_PERMISSIONS_ALL; 8256 it.remove(); 8257 } 8258 } 8259 } 8260 8261 // Now update the permissions for all packages, in particular 8262 // replace the granted permissions of the system packages. 8263 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8264 for (PackageParser.Package pkg : mPackages.values()) { 8265 if (pkg != pkgInfo) { 8266 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8267 changingPkg); 8268 } 8269 } 8270 } 8271 8272 if (pkgInfo != null) { 8273 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8274 } 8275 } 8276 8277 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8278 String packageOfInterest) { 8279 // IMPORTANT: There are two types of permissions: install and runtime. 8280 // Install time permissions are granted when the app is installed to 8281 // all device users and users added in the future. Runtime permissions 8282 // are granted at runtime explicitly to specific users. Normal and signature 8283 // protected permissions are install time permissions. Dangerous permissions 8284 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8285 // otherwise they are runtime permissions. This function does not manage 8286 // runtime permissions except for the case an app targeting Lollipop MR1 8287 // being upgraded to target a newer SDK, in which case dangerous permissions 8288 // are transformed from install time to runtime ones. 8289 8290 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8291 if (ps == null) { 8292 return; 8293 } 8294 8295 PermissionsState permissionsState = ps.getPermissionsState(); 8296 PermissionsState origPermissions = permissionsState; 8297 8298 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8299 8300 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8301 8302 boolean changedInstallPermission = false; 8303 8304 if (replace) { 8305 ps.installPermissionsFixed = false; 8306 if (!ps.isSharedUser()) { 8307 origPermissions = new PermissionsState(permissionsState); 8308 permissionsState.reset(); 8309 } 8310 } 8311 8312 permissionsState.setGlobalGids(mGlobalGids); 8313 8314 final int N = pkg.requestedPermissions.size(); 8315 for (int i=0; i<N; i++) { 8316 final String name = pkg.requestedPermissions.get(i); 8317 final BasePermission bp = mSettings.mPermissions.get(name); 8318 8319 if (DEBUG_INSTALL) { 8320 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8321 } 8322 8323 if (bp == null || bp.packageSetting == null) { 8324 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8325 Slog.w(TAG, "Unknown permission " + name 8326 + " in package " + pkg.packageName); 8327 } 8328 continue; 8329 } 8330 8331 final String perm = bp.name; 8332 boolean allowedSig = false; 8333 int grant = GRANT_DENIED; 8334 8335 // Keep track of app op permissions. 8336 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8337 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8338 if (pkgs == null) { 8339 pkgs = new ArraySet<>(); 8340 mAppOpPermissionPackages.put(bp.name, pkgs); 8341 } 8342 pkgs.add(pkg.packageName); 8343 } 8344 8345 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8346 switch (level) { 8347 case PermissionInfo.PROTECTION_NORMAL: { 8348 // For all apps normal permissions are install time ones. 8349 grant = GRANT_INSTALL; 8350 } break; 8351 8352 case PermissionInfo.PROTECTION_DANGEROUS: { 8353 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8354 // For legacy apps dangerous permissions are install time ones. 8355 grant = GRANT_INSTALL_LEGACY; 8356 } else if (origPermissions.hasInstallPermission(bp.name)) { 8357 // For legacy apps that became modern, install becomes runtime. 8358 grant = GRANT_UPGRADE; 8359 } else { 8360 // For modern apps keep runtime permissions unchanged. 8361 grant = GRANT_RUNTIME; 8362 } 8363 } break; 8364 8365 case PermissionInfo.PROTECTION_SIGNATURE: { 8366 // For all apps signature permissions are install time ones. 8367 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8368 if (allowedSig) { 8369 grant = GRANT_INSTALL; 8370 } 8371 } break; 8372 } 8373 8374 if (DEBUG_INSTALL) { 8375 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8376 } 8377 8378 if (grant != GRANT_DENIED) { 8379 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8380 // If this is an existing, non-system package, then 8381 // we can't add any new permissions to it. 8382 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8383 // Except... if this is a permission that was added 8384 // to the platform (note: need to only do this when 8385 // updating the platform). 8386 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8387 grant = GRANT_DENIED; 8388 } 8389 } 8390 } 8391 8392 switch (grant) { 8393 case GRANT_INSTALL: { 8394 // Revoke this as runtime permission to handle the case of 8395 // a runtime permission being downgraded to an install one. 8396 for (int userId : UserManagerService.getInstance().getUserIds()) { 8397 if (origPermissions.getRuntimePermissionState( 8398 bp.name, userId) != null) { 8399 // Revoke the runtime permission and clear the flags. 8400 origPermissions.revokeRuntimePermission(bp, userId); 8401 origPermissions.updatePermissionFlags(bp, userId, 8402 PackageManager.MASK_PERMISSION_FLAGS, 0); 8403 // If we revoked a permission permission, we have to write. 8404 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8405 changedRuntimePermissionUserIds, userId); 8406 } 8407 } 8408 // Grant an install permission. 8409 if (permissionsState.grantInstallPermission(bp) != 8410 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8411 changedInstallPermission = true; 8412 } 8413 } break; 8414 8415 case GRANT_INSTALL_LEGACY: { 8416 // Grant an install permission. 8417 if (permissionsState.grantInstallPermission(bp) != 8418 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8419 changedInstallPermission = true; 8420 } 8421 } break; 8422 8423 case GRANT_RUNTIME: { 8424 // Grant previously granted runtime permissions. 8425 for (int userId : UserManagerService.getInstance().getUserIds()) { 8426 PermissionState permissionState = origPermissions 8427 .getRuntimePermissionState(bp.name, userId); 8428 final int flags = permissionState != null 8429 ? permissionState.getFlags() : 0; 8430 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8431 if (permissionsState.grantRuntimePermission(bp, userId) == 8432 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8433 // If we cannot put the permission as it was, we have to write. 8434 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8435 changedRuntimePermissionUserIds, userId); 8436 } 8437 } 8438 // Propagate the permission flags. 8439 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8440 } 8441 } break; 8442 8443 case GRANT_UPGRADE: { 8444 // Grant runtime permissions for a previously held install permission. 8445 PermissionState permissionState = origPermissions 8446 .getInstallPermissionState(bp.name); 8447 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8448 8449 if (origPermissions.revokeInstallPermission(bp) 8450 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8451 // We will be transferring the permission flags, so clear them. 8452 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8453 PackageManager.MASK_PERMISSION_FLAGS, 0); 8454 changedInstallPermission = true; 8455 } 8456 8457 // If the permission is not to be promoted to runtime we ignore it and 8458 // also its other flags as they are not applicable to install permissions. 8459 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8460 for (int userId : currentUserIds) { 8461 if (permissionsState.grantRuntimePermission(bp, userId) != 8462 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8463 // Transfer the permission flags. 8464 permissionsState.updatePermissionFlags(bp, userId, 8465 flags, flags); 8466 // If we granted the permission, we have to write. 8467 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8468 changedRuntimePermissionUserIds, userId); 8469 } 8470 } 8471 } 8472 } break; 8473 8474 default: { 8475 if (packageOfInterest == null 8476 || packageOfInterest.equals(pkg.packageName)) { 8477 Slog.w(TAG, "Not granting permission " + perm 8478 + " to package " + pkg.packageName 8479 + " because it was previously installed without"); 8480 } 8481 } break; 8482 } 8483 } else { 8484 if (permissionsState.revokeInstallPermission(bp) != 8485 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8486 // Also drop the permission flags. 8487 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8488 PackageManager.MASK_PERMISSION_FLAGS, 0); 8489 changedInstallPermission = true; 8490 Slog.i(TAG, "Un-granting permission " + perm 8491 + " from package " + pkg.packageName 8492 + " (protectionLevel=" + bp.protectionLevel 8493 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8494 + ")"); 8495 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8496 // Don't print warning for app op permissions, since it is fine for them 8497 // not to be granted, there is a UI for the user to decide. 8498 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8499 Slog.w(TAG, "Not granting permission " + perm 8500 + " to package " + pkg.packageName 8501 + " (protectionLevel=" + bp.protectionLevel 8502 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8503 + ")"); 8504 } 8505 } 8506 } 8507 } 8508 8509 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8510 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8511 // This is the first that we have heard about this package, so the 8512 // permissions we have now selected are fixed until explicitly 8513 // changed. 8514 ps.installPermissionsFixed = true; 8515 } 8516 8517 // Persist the runtime permissions state for users with changes. 8518 for (int userId : changedRuntimePermissionUserIds) { 8519 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8520 } 8521 } 8522 8523 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8524 boolean allowed = false; 8525 final int NP = PackageParser.NEW_PERMISSIONS.length; 8526 for (int ip=0; ip<NP; ip++) { 8527 final PackageParser.NewPermissionInfo npi 8528 = PackageParser.NEW_PERMISSIONS[ip]; 8529 if (npi.name.equals(perm) 8530 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8531 allowed = true; 8532 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8533 + pkg.packageName); 8534 break; 8535 } 8536 } 8537 return allowed; 8538 } 8539 8540 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8541 BasePermission bp, PermissionsState origPermissions) { 8542 boolean allowed; 8543 allowed = (compareSignatures( 8544 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8545 == PackageManager.SIGNATURE_MATCH) 8546 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8547 == PackageManager.SIGNATURE_MATCH); 8548 if (!allowed && (bp.protectionLevel 8549 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8550 if (isSystemApp(pkg)) { 8551 // For updated system applications, a system permission 8552 // is granted only if it had been defined by the original application. 8553 if (pkg.isUpdatedSystemApp()) { 8554 final PackageSetting sysPs = mSettings 8555 .getDisabledSystemPkgLPr(pkg.packageName); 8556 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8557 // If the original was granted this permission, we take 8558 // that grant decision as read and propagate it to the 8559 // update. 8560 if (sysPs.isPrivileged()) { 8561 allowed = true; 8562 } 8563 } else { 8564 // The system apk may have been updated with an older 8565 // version of the one on the data partition, but which 8566 // granted a new system permission that it didn't have 8567 // before. In this case we do want to allow the app to 8568 // now get the new permission if the ancestral apk is 8569 // privileged to get it. 8570 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8571 for (int j=0; 8572 j<sysPs.pkg.requestedPermissions.size(); j++) { 8573 if (perm.equals( 8574 sysPs.pkg.requestedPermissions.get(j))) { 8575 allowed = true; 8576 break; 8577 } 8578 } 8579 } 8580 } 8581 } else { 8582 allowed = isPrivilegedApp(pkg); 8583 } 8584 } 8585 } 8586 if (!allowed) { 8587 if (!allowed && (bp.protectionLevel 8588 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8589 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8590 // If this was a previously normal/dangerous permission that got moved 8591 // to a system permission as part of the runtime permission redesign, then 8592 // we still want to blindly grant it to old apps. 8593 allowed = true; 8594 } 8595 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8596 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8597 // If this permission is to be granted to the system installer and 8598 // this app is an installer, then it gets the permission. 8599 allowed = true; 8600 } 8601 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8602 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8603 // If this permission is to be granted to the system verifier and 8604 // this app is a verifier, then it gets the permission. 8605 allowed = true; 8606 } 8607 if (!allowed && (bp.protectionLevel 8608 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8609 && isSystemApp(pkg)) { 8610 // Any pre-installed system app is allowed to get this permission. 8611 allowed = true; 8612 } 8613 if (!allowed && (bp.protectionLevel 8614 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8615 // For development permissions, a development permission 8616 // is granted only if it was already granted. 8617 allowed = origPermissions.hasInstallPermission(perm); 8618 } 8619 } 8620 return allowed; 8621 } 8622 8623 final class ActivityIntentResolver 8624 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8625 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8626 boolean defaultOnly, int userId) { 8627 if (!sUserManager.exists(userId)) return null; 8628 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8629 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8630 } 8631 8632 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8633 int userId) { 8634 if (!sUserManager.exists(userId)) return null; 8635 mFlags = flags; 8636 return super.queryIntent(intent, resolvedType, 8637 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8638 } 8639 8640 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8641 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8642 if (!sUserManager.exists(userId)) return null; 8643 if (packageActivities == null) { 8644 return null; 8645 } 8646 mFlags = flags; 8647 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8648 final int N = packageActivities.size(); 8649 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8650 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8651 8652 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8653 for (int i = 0; i < N; ++i) { 8654 intentFilters = packageActivities.get(i).intents; 8655 if (intentFilters != null && intentFilters.size() > 0) { 8656 PackageParser.ActivityIntentInfo[] array = 8657 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8658 intentFilters.toArray(array); 8659 listCut.add(array); 8660 } 8661 } 8662 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8663 } 8664 8665 public final void addActivity(PackageParser.Activity a, String type) { 8666 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8667 mActivities.put(a.getComponentName(), a); 8668 if (DEBUG_SHOW_INFO) 8669 Log.v( 8670 TAG, " " + type + " " + 8671 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8672 if (DEBUG_SHOW_INFO) 8673 Log.v(TAG, " Class=" + a.info.name); 8674 final int NI = a.intents.size(); 8675 for (int j=0; j<NI; j++) { 8676 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8677 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8678 intent.setPriority(0); 8679 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8680 + a.className + " with priority > 0, forcing to 0"); 8681 } 8682 if (DEBUG_SHOW_INFO) { 8683 Log.v(TAG, " IntentFilter:"); 8684 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8685 } 8686 if (!intent.debugCheck()) { 8687 Log.w(TAG, "==> For Activity " + a.info.name); 8688 } 8689 addFilter(intent); 8690 } 8691 } 8692 8693 public final void removeActivity(PackageParser.Activity a, String type) { 8694 mActivities.remove(a.getComponentName()); 8695 if (DEBUG_SHOW_INFO) { 8696 Log.v(TAG, " " + type + " " 8697 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8698 : a.info.name) + ":"); 8699 Log.v(TAG, " Class=" + a.info.name); 8700 } 8701 final int NI = a.intents.size(); 8702 for (int j=0; j<NI; j++) { 8703 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8704 if (DEBUG_SHOW_INFO) { 8705 Log.v(TAG, " IntentFilter:"); 8706 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8707 } 8708 removeFilter(intent); 8709 } 8710 } 8711 8712 @Override 8713 protected boolean allowFilterResult( 8714 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8715 ActivityInfo filterAi = filter.activity.info; 8716 for (int i=dest.size()-1; i>=0; i--) { 8717 ActivityInfo destAi = dest.get(i).activityInfo; 8718 if (destAi.name == filterAi.name 8719 && destAi.packageName == filterAi.packageName) { 8720 return false; 8721 } 8722 } 8723 return true; 8724 } 8725 8726 @Override 8727 protected ActivityIntentInfo[] newArray(int size) { 8728 return new ActivityIntentInfo[size]; 8729 } 8730 8731 @Override 8732 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8733 if (!sUserManager.exists(userId)) return true; 8734 PackageParser.Package p = filter.activity.owner; 8735 if (p != null) { 8736 PackageSetting ps = (PackageSetting)p.mExtras; 8737 if (ps != null) { 8738 // System apps are never considered stopped for purposes of 8739 // filtering, because there may be no way for the user to 8740 // actually re-launch them. 8741 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8742 && ps.getStopped(userId); 8743 } 8744 } 8745 return false; 8746 } 8747 8748 @Override 8749 protected boolean isPackageForFilter(String packageName, 8750 PackageParser.ActivityIntentInfo info) { 8751 return packageName.equals(info.activity.owner.packageName); 8752 } 8753 8754 @Override 8755 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8756 int match, int userId) { 8757 if (!sUserManager.exists(userId)) return null; 8758 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8759 return null; 8760 } 8761 final PackageParser.Activity activity = info.activity; 8762 if (mSafeMode && (activity.info.applicationInfo.flags 8763 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8764 return null; 8765 } 8766 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8767 if (ps == null) { 8768 return null; 8769 } 8770 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8771 ps.readUserState(userId), userId); 8772 if (ai == null) { 8773 return null; 8774 } 8775 final ResolveInfo res = new ResolveInfo(); 8776 res.activityInfo = ai; 8777 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8778 res.filter = info; 8779 } 8780 if (info != null) { 8781 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8782 } 8783 res.priority = info.getPriority(); 8784 res.preferredOrder = activity.owner.mPreferredOrder; 8785 //System.out.println("Result: " + res.activityInfo.className + 8786 // " = " + res.priority); 8787 res.match = match; 8788 res.isDefault = info.hasDefault; 8789 res.labelRes = info.labelRes; 8790 res.nonLocalizedLabel = info.nonLocalizedLabel; 8791 if (userNeedsBadging(userId)) { 8792 res.noResourceId = true; 8793 } else { 8794 res.icon = info.icon; 8795 } 8796 res.iconResourceId = info.icon; 8797 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8798 return res; 8799 } 8800 8801 @Override 8802 protected void sortResults(List<ResolveInfo> results) { 8803 Collections.sort(results, mResolvePrioritySorter); 8804 } 8805 8806 @Override 8807 protected void dumpFilter(PrintWriter out, String prefix, 8808 PackageParser.ActivityIntentInfo filter) { 8809 out.print(prefix); out.print( 8810 Integer.toHexString(System.identityHashCode(filter.activity))); 8811 out.print(' '); 8812 filter.activity.printComponentShortName(out); 8813 out.print(" filter "); 8814 out.println(Integer.toHexString(System.identityHashCode(filter))); 8815 } 8816 8817 @Override 8818 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8819 return filter.activity; 8820 } 8821 8822 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8823 PackageParser.Activity activity = (PackageParser.Activity)label; 8824 out.print(prefix); out.print( 8825 Integer.toHexString(System.identityHashCode(activity))); 8826 out.print(' '); 8827 activity.printComponentShortName(out); 8828 if (count > 1) { 8829 out.print(" ("); out.print(count); out.print(" filters)"); 8830 } 8831 out.println(); 8832 } 8833 8834// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8835// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8836// final List<ResolveInfo> retList = Lists.newArrayList(); 8837// while (i.hasNext()) { 8838// final ResolveInfo resolveInfo = i.next(); 8839// if (isEnabledLP(resolveInfo.activityInfo)) { 8840// retList.add(resolveInfo); 8841// } 8842// } 8843// return retList; 8844// } 8845 8846 // Keys are String (activity class name), values are Activity. 8847 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8848 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8849 private int mFlags; 8850 } 8851 8852 private final class ServiceIntentResolver 8853 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8854 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8855 boolean defaultOnly, int userId) { 8856 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8857 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8858 } 8859 8860 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8861 int userId) { 8862 if (!sUserManager.exists(userId)) return null; 8863 mFlags = flags; 8864 return super.queryIntent(intent, resolvedType, 8865 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8866 } 8867 8868 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8869 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8870 if (!sUserManager.exists(userId)) return null; 8871 if (packageServices == null) { 8872 return null; 8873 } 8874 mFlags = flags; 8875 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8876 final int N = packageServices.size(); 8877 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8878 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8879 8880 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8881 for (int i = 0; i < N; ++i) { 8882 intentFilters = packageServices.get(i).intents; 8883 if (intentFilters != null && intentFilters.size() > 0) { 8884 PackageParser.ServiceIntentInfo[] array = 8885 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8886 intentFilters.toArray(array); 8887 listCut.add(array); 8888 } 8889 } 8890 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8891 } 8892 8893 public final void addService(PackageParser.Service s) { 8894 mServices.put(s.getComponentName(), s); 8895 if (DEBUG_SHOW_INFO) { 8896 Log.v(TAG, " " 8897 + (s.info.nonLocalizedLabel != null 8898 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8899 Log.v(TAG, " Class=" + s.info.name); 8900 } 8901 final int NI = s.intents.size(); 8902 int j; 8903 for (j=0; j<NI; j++) { 8904 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8905 if (DEBUG_SHOW_INFO) { 8906 Log.v(TAG, " IntentFilter:"); 8907 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8908 } 8909 if (!intent.debugCheck()) { 8910 Log.w(TAG, "==> For Service " + s.info.name); 8911 } 8912 addFilter(intent); 8913 } 8914 } 8915 8916 public final void removeService(PackageParser.Service s) { 8917 mServices.remove(s.getComponentName()); 8918 if (DEBUG_SHOW_INFO) { 8919 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8920 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8921 Log.v(TAG, " Class=" + s.info.name); 8922 } 8923 final int NI = s.intents.size(); 8924 int j; 8925 for (j=0; j<NI; j++) { 8926 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8927 if (DEBUG_SHOW_INFO) { 8928 Log.v(TAG, " IntentFilter:"); 8929 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8930 } 8931 removeFilter(intent); 8932 } 8933 } 8934 8935 @Override 8936 protected boolean allowFilterResult( 8937 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8938 ServiceInfo filterSi = filter.service.info; 8939 for (int i=dest.size()-1; i>=0; i--) { 8940 ServiceInfo destAi = dest.get(i).serviceInfo; 8941 if (destAi.name == filterSi.name 8942 && destAi.packageName == filterSi.packageName) { 8943 return false; 8944 } 8945 } 8946 return true; 8947 } 8948 8949 @Override 8950 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8951 return new PackageParser.ServiceIntentInfo[size]; 8952 } 8953 8954 @Override 8955 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8956 if (!sUserManager.exists(userId)) return true; 8957 PackageParser.Package p = filter.service.owner; 8958 if (p != null) { 8959 PackageSetting ps = (PackageSetting)p.mExtras; 8960 if (ps != null) { 8961 // System apps are never considered stopped for purposes of 8962 // filtering, because there may be no way for the user to 8963 // actually re-launch them. 8964 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8965 && ps.getStopped(userId); 8966 } 8967 } 8968 return false; 8969 } 8970 8971 @Override 8972 protected boolean isPackageForFilter(String packageName, 8973 PackageParser.ServiceIntentInfo info) { 8974 return packageName.equals(info.service.owner.packageName); 8975 } 8976 8977 @Override 8978 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8979 int match, int userId) { 8980 if (!sUserManager.exists(userId)) return null; 8981 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8982 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8983 return null; 8984 } 8985 final PackageParser.Service service = info.service; 8986 if (mSafeMode && (service.info.applicationInfo.flags 8987 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8988 return null; 8989 } 8990 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8991 if (ps == null) { 8992 return null; 8993 } 8994 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8995 ps.readUserState(userId), userId); 8996 if (si == null) { 8997 return null; 8998 } 8999 final ResolveInfo res = new ResolveInfo(); 9000 res.serviceInfo = si; 9001 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9002 res.filter = filter; 9003 } 9004 res.priority = info.getPriority(); 9005 res.preferredOrder = service.owner.mPreferredOrder; 9006 res.match = match; 9007 res.isDefault = info.hasDefault; 9008 res.labelRes = info.labelRes; 9009 res.nonLocalizedLabel = info.nonLocalizedLabel; 9010 res.icon = info.icon; 9011 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9012 return res; 9013 } 9014 9015 @Override 9016 protected void sortResults(List<ResolveInfo> results) { 9017 Collections.sort(results, mResolvePrioritySorter); 9018 } 9019 9020 @Override 9021 protected void dumpFilter(PrintWriter out, String prefix, 9022 PackageParser.ServiceIntentInfo filter) { 9023 out.print(prefix); out.print( 9024 Integer.toHexString(System.identityHashCode(filter.service))); 9025 out.print(' '); 9026 filter.service.printComponentShortName(out); 9027 out.print(" filter "); 9028 out.println(Integer.toHexString(System.identityHashCode(filter))); 9029 } 9030 9031 @Override 9032 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9033 return filter.service; 9034 } 9035 9036 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9037 PackageParser.Service service = (PackageParser.Service)label; 9038 out.print(prefix); out.print( 9039 Integer.toHexString(System.identityHashCode(service))); 9040 out.print(' '); 9041 service.printComponentShortName(out); 9042 if (count > 1) { 9043 out.print(" ("); out.print(count); out.print(" filters)"); 9044 } 9045 out.println(); 9046 } 9047 9048// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9049// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9050// final List<ResolveInfo> retList = Lists.newArrayList(); 9051// while (i.hasNext()) { 9052// final ResolveInfo resolveInfo = (ResolveInfo) i; 9053// if (isEnabledLP(resolveInfo.serviceInfo)) { 9054// retList.add(resolveInfo); 9055// } 9056// } 9057// return retList; 9058// } 9059 9060 // Keys are String (activity class name), values are Activity. 9061 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9062 = new ArrayMap<ComponentName, PackageParser.Service>(); 9063 private int mFlags; 9064 }; 9065 9066 private final class ProviderIntentResolver 9067 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9068 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9069 boolean defaultOnly, int userId) { 9070 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9071 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9072 } 9073 9074 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9075 int userId) { 9076 if (!sUserManager.exists(userId)) 9077 return null; 9078 mFlags = flags; 9079 return super.queryIntent(intent, resolvedType, 9080 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9081 } 9082 9083 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9084 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9085 if (!sUserManager.exists(userId)) 9086 return null; 9087 if (packageProviders == null) { 9088 return null; 9089 } 9090 mFlags = flags; 9091 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9092 final int N = packageProviders.size(); 9093 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9094 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9095 9096 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9097 for (int i = 0; i < N; ++i) { 9098 intentFilters = packageProviders.get(i).intents; 9099 if (intentFilters != null && intentFilters.size() > 0) { 9100 PackageParser.ProviderIntentInfo[] array = 9101 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9102 intentFilters.toArray(array); 9103 listCut.add(array); 9104 } 9105 } 9106 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9107 } 9108 9109 public final void addProvider(PackageParser.Provider p) { 9110 if (mProviders.containsKey(p.getComponentName())) { 9111 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9112 return; 9113 } 9114 9115 mProviders.put(p.getComponentName(), p); 9116 if (DEBUG_SHOW_INFO) { 9117 Log.v(TAG, " " 9118 + (p.info.nonLocalizedLabel != null 9119 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9120 Log.v(TAG, " Class=" + p.info.name); 9121 } 9122 final int NI = p.intents.size(); 9123 int j; 9124 for (j = 0; j < NI; j++) { 9125 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9126 if (DEBUG_SHOW_INFO) { 9127 Log.v(TAG, " IntentFilter:"); 9128 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9129 } 9130 if (!intent.debugCheck()) { 9131 Log.w(TAG, "==> For Provider " + p.info.name); 9132 } 9133 addFilter(intent); 9134 } 9135 } 9136 9137 public final void removeProvider(PackageParser.Provider p) { 9138 mProviders.remove(p.getComponentName()); 9139 if (DEBUG_SHOW_INFO) { 9140 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9141 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9142 Log.v(TAG, " Class=" + p.info.name); 9143 } 9144 final int NI = p.intents.size(); 9145 int j; 9146 for (j = 0; j < NI; j++) { 9147 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9148 if (DEBUG_SHOW_INFO) { 9149 Log.v(TAG, " IntentFilter:"); 9150 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9151 } 9152 removeFilter(intent); 9153 } 9154 } 9155 9156 @Override 9157 protected boolean allowFilterResult( 9158 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9159 ProviderInfo filterPi = filter.provider.info; 9160 for (int i = dest.size() - 1; i >= 0; i--) { 9161 ProviderInfo destPi = dest.get(i).providerInfo; 9162 if (destPi.name == filterPi.name 9163 && destPi.packageName == filterPi.packageName) { 9164 return false; 9165 } 9166 } 9167 return true; 9168 } 9169 9170 @Override 9171 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9172 return new PackageParser.ProviderIntentInfo[size]; 9173 } 9174 9175 @Override 9176 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9177 if (!sUserManager.exists(userId)) 9178 return true; 9179 PackageParser.Package p = filter.provider.owner; 9180 if (p != null) { 9181 PackageSetting ps = (PackageSetting) p.mExtras; 9182 if (ps != null) { 9183 // System apps are never considered stopped for purposes of 9184 // filtering, because there may be no way for the user to 9185 // actually re-launch them. 9186 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9187 && ps.getStopped(userId); 9188 } 9189 } 9190 return false; 9191 } 9192 9193 @Override 9194 protected boolean isPackageForFilter(String packageName, 9195 PackageParser.ProviderIntentInfo info) { 9196 return packageName.equals(info.provider.owner.packageName); 9197 } 9198 9199 @Override 9200 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9201 int match, int userId) { 9202 if (!sUserManager.exists(userId)) 9203 return null; 9204 final PackageParser.ProviderIntentInfo info = filter; 9205 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9206 return null; 9207 } 9208 final PackageParser.Provider provider = info.provider; 9209 if (mSafeMode && (provider.info.applicationInfo.flags 9210 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9211 return null; 9212 } 9213 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9214 if (ps == null) { 9215 return null; 9216 } 9217 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9218 ps.readUserState(userId), userId); 9219 if (pi == null) { 9220 return null; 9221 } 9222 final ResolveInfo res = new ResolveInfo(); 9223 res.providerInfo = pi; 9224 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9225 res.filter = filter; 9226 } 9227 res.priority = info.getPriority(); 9228 res.preferredOrder = provider.owner.mPreferredOrder; 9229 res.match = match; 9230 res.isDefault = info.hasDefault; 9231 res.labelRes = info.labelRes; 9232 res.nonLocalizedLabel = info.nonLocalizedLabel; 9233 res.icon = info.icon; 9234 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9235 return res; 9236 } 9237 9238 @Override 9239 protected void sortResults(List<ResolveInfo> results) { 9240 Collections.sort(results, mResolvePrioritySorter); 9241 } 9242 9243 @Override 9244 protected void dumpFilter(PrintWriter out, String prefix, 9245 PackageParser.ProviderIntentInfo filter) { 9246 out.print(prefix); 9247 out.print( 9248 Integer.toHexString(System.identityHashCode(filter.provider))); 9249 out.print(' '); 9250 filter.provider.printComponentShortName(out); 9251 out.print(" filter "); 9252 out.println(Integer.toHexString(System.identityHashCode(filter))); 9253 } 9254 9255 @Override 9256 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9257 return filter.provider; 9258 } 9259 9260 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9261 PackageParser.Provider provider = (PackageParser.Provider)label; 9262 out.print(prefix); out.print( 9263 Integer.toHexString(System.identityHashCode(provider))); 9264 out.print(' '); 9265 provider.printComponentShortName(out); 9266 if (count > 1) { 9267 out.print(" ("); out.print(count); out.print(" filters)"); 9268 } 9269 out.println(); 9270 } 9271 9272 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9273 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9274 private int mFlags; 9275 }; 9276 9277 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9278 new Comparator<ResolveInfo>() { 9279 public int compare(ResolveInfo r1, ResolveInfo r2) { 9280 int v1 = r1.priority; 9281 int v2 = r2.priority; 9282 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9283 if (v1 != v2) { 9284 return (v1 > v2) ? -1 : 1; 9285 } 9286 v1 = r1.preferredOrder; 9287 v2 = r2.preferredOrder; 9288 if (v1 != v2) { 9289 return (v1 > v2) ? -1 : 1; 9290 } 9291 if (r1.isDefault != r2.isDefault) { 9292 return r1.isDefault ? -1 : 1; 9293 } 9294 v1 = r1.match; 9295 v2 = r2.match; 9296 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9297 if (v1 != v2) { 9298 return (v1 > v2) ? -1 : 1; 9299 } 9300 if (r1.system != r2.system) { 9301 return r1.system ? -1 : 1; 9302 } 9303 return 0; 9304 } 9305 }; 9306 9307 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9308 new Comparator<ProviderInfo>() { 9309 public int compare(ProviderInfo p1, ProviderInfo p2) { 9310 final int v1 = p1.initOrder; 9311 final int v2 = p2.initOrder; 9312 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9313 } 9314 }; 9315 9316 final void sendPackageBroadcast(final String action, final String pkg, 9317 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9318 final int[] userIds) { 9319 mHandler.post(new Runnable() { 9320 @Override 9321 public void run() { 9322 try { 9323 final IActivityManager am = ActivityManagerNative.getDefault(); 9324 if (am == null) return; 9325 final int[] resolvedUserIds; 9326 if (userIds == null) { 9327 resolvedUserIds = am.getRunningUserIds(); 9328 } else { 9329 resolvedUserIds = userIds; 9330 } 9331 for (int id : resolvedUserIds) { 9332 final Intent intent = new Intent(action, 9333 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9334 if (extras != null) { 9335 intent.putExtras(extras); 9336 } 9337 if (targetPkg != null) { 9338 intent.setPackage(targetPkg); 9339 } 9340 // Modify the UID when posting to other users 9341 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9342 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9343 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9344 intent.putExtra(Intent.EXTRA_UID, uid); 9345 } 9346 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9347 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9348 if (DEBUG_BROADCASTS) { 9349 RuntimeException here = new RuntimeException("here"); 9350 here.fillInStackTrace(); 9351 Slog.d(TAG, "Sending to user " + id + ": " 9352 + intent.toShortString(false, true, false, false) 9353 + " " + intent.getExtras(), here); 9354 } 9355 am.broadcastIntent(null, intent, null, finishedReceiver, 9356 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9357 null, finishedReceiver != null, false, id); 9358 } 9359 } catch (RemoteException ex) { 9360 } 9361 } 9362 }); 9363 } 9364 9365 /** 9366 * Check if the external storage media is available. This is true if there 9367 * is a mounted external storage medium or if the external storage is 9368 * emulated. 9369 */ 9370 private boolean isExternalMediaAvailable() { 9371 return mMediaMounted || Environment.isExternalStorageEmulated(); 9372 } 9373 9374 @Override 9375 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9376 // writer 9377 synchronized (mPackages) { 9378 if (!isExternalMediaAvailable()) { 9379 // If the external storage is no longer mounted at this point, 9380 // the caller may not have been able to delete all of this 9381 // packages files and can not delete any more. Bail. 9382 return null; 9383 } 9384 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9385 if (lastPackage != null) { 9386 pkgs.remove(lastPackage); 9387 } 9388 if (pkgs.size() > 0) { 9389 return pkgs.get(0); 9390 } 9391 } 9392 return null; 9393 } 9394 9395 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9396 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9397 userId, andCode ? 1 : 0, packageName); 9398 if (mSystemReady) { 9399 msg.sendToTarget(); 9400 } else { 9401 if (mPostSystemReadyMessages == null) { 9402 mPostSystemReadyMessages = new ArrayList<>(); 9403 } 9404 mPostSystemReadyMessages.add(msg); 9405 } 9406 } 9407 9408 void startCleaningPackages() { 9409 // reader 9410 synchronized (mPackages) { 9411 if (!isExternalMediaAvailable()) { 9412 return; 9413 } 9414 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9415 return; 9416 } 9417 } 9418 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9419 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9420 IActivityManager am = ActivityManagerNative.getDefault(); 9421 if (am != null) { 9422 try { 9423 am.startService(null, intent, null, mContext.getOpPackageName(), 9424 UserHandle.USER_OWNER); 9425 } catch (RemoteException e) { 9426 } 9427 } 9428 } 9429 9430 @Override 9431 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9432 int installFlags, String installerPackageName, VerificationParams verificationParams, 9433 String packageAbiOverride) { 9434 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9435 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9436 } 9437 9438 @Override 9439 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9440 int installFlags, String installerPackageName, VerificationParams verificationParams, 9441 String packageAbiOverride, int userId) { 9442 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9443 9444 final int callingUid = Binder.getCallingUid(); 9445 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9446 9447 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9448 try { 9449 if (observer != null) { 9450 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9451 } 9452 } catch (RemoteException re) { 9453 } 9454 return; 9455 } 9456 9457 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9458 installFlags |= PackageManager.INSTALL_FROM_ADB; 9459 9460 } else { 9461 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9462 // about installerPackageName. 9463 9464 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9465 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9466 } 9467 9468 UserHandle user; 9469 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9470 user = UserHandle.ALL; 9471 } else { 9472 user = new UserHandle(userId); 9473 } 9474 9475 // Only system components can circumvent runtime permissions when installing. 9476 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9477 && mContext.checkCallingOrSelfPermission(Manifest.permission 9478 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9479 throw new SecurityException("You need the " 9480 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9481 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9482 } 9483 9484 verificationParams.setInstallerUid(callingUid); 9485 9486 final File originFile = new File(originPath); 9487 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9488 9489 final Message msg = mHandler.obtainMessage(INIT_COPY); 9490 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9491 null, verificationParams, user, packageAbiOverride, null); 9492 mHandler.sendMessage(msg); 9493 } 9494 9495 void installStage(String packageName, File stagedDir, String stagedCid, 9496 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9497 String installerPackageName, int installerUid, UserHandle user) { 9498 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9499 params.referrerUri, installerUid, null); 9500 verifParams.setInstallerUid(installerUid); 9501 9502 final OriginInfo origin; 9503 if (stagedDir != null) { 9504 origin = OriginInfo.fromStagedFile(stagedDir); 9505 } else { 9506 origin = OriginInfo.fromStagedContainer(stagedCid); 9507 } 9508 9509 final Message msg = mHandler.obtainMessage(INIT_COPY); 9510 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9511 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9512 params.grantedRuntimePermissions); 9513 mHandler.sendMessage(msg); 9514 } 9515 9516 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9517 Bundle extras = new Bundle(1); 9518 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9519 9520 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9521 packageName, extras, null, null, new int[] {userId}); 9522 try { 9523 IActivityManager am = ActivityManagerNative.getDefault(); 9524 final boolean isSystem = 9525 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9526 if (isSystem && am.isUserRunning(userId, false)) { 9527 // The just-installed/enabled app is bundled on the system, so presumed 9528 // to be able to run automatically without needing an explicit launch. 9529 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9530 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9531 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9532 .setPackage(packageName); 9533 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9534 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9535 } 9536 } catch (RemoteException e) { 9537 // shouldn't happen 9538 Slog.w(TAG, "Unable to bootstrap installed package", e); 9539 } 9540 } 9541 9542 @Override 9543 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9544 int userId) { 9545 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9546 PackageSetting pkgSetting; 9547 final int uid = Binder.getCallingUid(); 9548 enforceCrossUserPermission(uid, userId, true, true, 9549 "setApplicationHiddenSetting for user " + userId); 9550 9551 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9552 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9553 return false; 9554 } 9555 9556 long callingId = Binder.clearCallingIdentity(); 9557 try { 9558 boolean sendAdded = false; 9559 boolean sendRemoved = false; 9560 // writer 9561 synchronized (mPackages) { 9562 pkgSetting = mSettings.mPackages.get(packageName); 9563 if (pkgSetting == null) { 9564 return false; 9565 } 9566 if (pkgSetting.getHidden(userId) != hidden) { 9567 pkgSetting.setHidden(hidden, userId); 9568 mSettings.writePackageRestrictionsLPr(userId); 9569 if (hidden) { 9570 sendRemoved = true; 9571 } else { 9572 sendAdded = true; 9573 } 9574 } 9575 } 9576 if (sendAdded) { 9577 sendPackageAddedForUser(packageName, pkgSetting, userId); 9578 return true; 9579 } 9580 if (sendRemoved) { 9581 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9582 "hiding pkg"); 9583 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9584 return true; 9585 } 9586 } finally { 9587 Binder.restoreCallingIdentity(callingId); 9588 } 9589 return false; 9590 } 9591 9592 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9593 int userId) { 9594 final PackageRemovedInfo info = new PackageRemovedInfo(); 9595 info.removedPackage = packageName; 9596 info.removedUsers = new int[] {userId}; 9597 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9598 info.sendBroadcast(false, false, false); 9599 } 9600 9601 /** 9602 * Returns true if application is not found or there was an error. Otherwise it returns 9603 * the hidden state of the package for the given user. 9604 */ 9605 @Override 9606 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9607 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9608 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9609 false, "getApplicationHidden for user " + userId); 9610 PackageSetting pkgSetting; 9611 long callingId = Binder.clearCallingIdentity(); 9612 try { 9613 // writer 9614 synchronized (mPackages) { 9615 pkgSetting = mSettings.mPackages.get(packageName); 9616 if (pkgSetting == null) { 9617 return true; 9618 } 9619 return pkgSetting.getHidden(userId); 9620 } 9621 } finally { 9622 Binder.restoreCallingIdentity(callingId); 9623 } 9624 } 9625 9626 /** 9627 * @hide 9628 */ 9629 @Override 9630 public int installExistingPackageAsUser(String packageName, int userId) { 9631 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9632 null); 9633 PackageSetting pkgSetting; 9634 final int uid = Binder.getCallingUid(); 9635 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9636 + userId); 9637 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9638 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9639 } 9640 9641 long callingId = Binder.clearCallingIdentity(); 9642 try { 9643 boolean sendAdded = false; 9644 9645 // writer 9646 synchronized (mPackages) { 9647 pkgSetting = mSettings.mPackages.get(packageName); 9648 if (pkgSetting == null) { 9649 return PackageManager.INSTALL_FAILED_INVALID_URI; 9650 } 9651 if (!pkgSetting.getInstalled(userId)) { 9652 pkgSetting.setInstalled(true, userId); 9653 pkgSetting.setHidden(false, userId); 9654 mSettings.writePackageRestrictionsLPr(userId); 9655 sendAdded = true; 9656 } 9657 } 9658 9659 if (sendAdded) { 9660 sendPackageAddedForUser(packageName, pkgSetting, userId); 9661 } 9662 } finally { 9663 Binder.restoreCallingIdentity(callingId); 9664 } 9665 9666 return PackageManager.INSTALL_SUCCEEDED; 9667 } 9668 9669 boolean isUserRestricted(int userId, String restrictionKey) { 9670 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9671 if (restrictions.getBoolean(restrictionKey, false)) { 9672 Log.w(TAG, "User is restricted: " + restrictionKey); 9673 return true; 9674 } 9675 return false; 9676 } 9677 9678 @Override 9679 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9680 mContext.enforceCallingOrSelfPermission( 9681 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9682 "Only package verification agents can verify applications"); 9683 9684 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9685 final PackageVerificationResponse response = new PackageVerificationResponse( 9686 verificationCode, Binder.getCallingUid()); 9687 msg.arg1 = id; 9688 msg.obj = response; 9689 mHandler.sendMessage(msg); 9690 } 9691 9692 @Override 9693 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9694 long millisecondsToDelay) { 9695 mContext.enforceCallingOrSelfPermission( 9696 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9697 "Only package verification agents can extend verification timeouts"); 9698 9699 final PackageVerificationState state = mPendingVerification.get(id); 9700 final PackageVerificationResponse response = new PackageVerificationResponse( 9701 verificationCodeAtTimeout, Binder.getCallingUid()); 9702 9703 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9704 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9705 } 9706 if (millisecondsToDelay < 0) { 9707 millisecondsToDelay = 0; 9708 } 9709 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9710 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9711 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9712 } 9713 9714 if ((state != null) && !state.timeoutExtended()) { 9715 state.extendTimeout(); 9716 9717 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9718 msg.arg1 = id; 9719 msg.obj = response; 9720 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9721 } 9722 } 9723 9724 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9725 int verificationCode, UserHandle user) { 9726 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9727 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9728 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9729 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9730 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9731 9732 mContext.sendBroadcastAsUser(intent, user, 9733 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9734 } 9735 9736 private ComponentName matchComponentForVerifier(String packageName, 9737 List<ResolveInfo> receivers) { 9738 ActivityInfo targetReceiver = null; 9739 9740 final int NR = receivers.size(); 9741 for (int i = 0; i < NR; i++) { 9742 final ResolveInfo info = receivers.get(i); 9743 if (info.activityInfo == null) { 9744 continue; 9745 } 9746 9747 if (packageName.equals(info.activityInfo.packageName)) { 9748 targetReceiver = info.activityInfo; 9749 break; 9750 } 9751 } 9752 9753 if (targetReceiver == null) { 9754 return null; 9755 } 9756 9757 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9758 } 9759 9760 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9761 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9762 if (pkgInfo.verifiers.length == 0) { 9763 return null; 9764 } 9765 9766 final int N = pkgInfo.verifiers.length; 9767 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9768 for (int i = 0; i < N; i++) { 9769 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9770 9771 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9772 receivers); 9773 if (comp == null) { 9774 continue; 9775 } 9776 9777 final int verifierUid = getUidForVerifier(verifierInfo); 9778 if (verifierUid == -1) { 9779 continue; 9780 } 9781 9782 if (DEBUG_VERIFY) { 9783 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9784 + " with the correct signature"); 9785 } 9786 sufficientVerifiers.add(comp); 9787 verificationState.addSufficientVerifier(verifierUid); 9788 } 9789 9790 return sufficientVerifiers; 9791 } 9792 9793 private int getUidForVerifier(VerifierInfo verifierInfo) { 9794 synchronized (mPackages) { 9795 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9796 if (pkg == null) { 9797 return -1; 9798 } else if (pkg.mSignatures.length != 1) { 9799 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9800 + " has more than one signature; ignoring"); 9801 return -1; 9802 } 9803 9804 /* 9805 * If the public key of the package's signature does not match 9806 * our expected public key, then this is a different package and 9807 * we should skip. 9808 */ 9809 9810 final byte[] expectedPublicKey; 9811 try { 9812 final Signature verifierSig = pkg.mSignatures[0]; 9813 final PublicKey publicKey = verifierSig.getPublicKey(); 9814 expectedPublicKey = publicKey.getEncoded(); 9815 } catch (CertificateException e) { 9816 return -1; 9817 } 9818 9819 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9820 9821 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9822 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9823 + " does not have the expected public key; ignoring"); 9824 return -1; 9825 } 9826 9827 return pkg.applicationInfo.uid; 9828 } 9829 } 9830 9831 @Override 9832 public void finishPackageInstall(int token) { 9833 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9834 9835 if (DEBUG_INSTALL) { 9836 Slog.v(TAG, "BM finishing package install for " + token); 9837 } 9838 9839 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9840 mHandler.sendMessage(msg); 9841 } 9842 9843 /** 9844 * Get the verification agent timeout. 9845 * 9846 * @return verification timeout in milliseconds 9847 */ 9848 private long getVerificationTimeout() { 9849 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9850 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9851 DEFAULT_VERIFICATION_TIMEOUT); 9852 } 9853 9854 /** 9855 * Get the default verification agent response code. 9856 * 9857 * @return default verification response code 9858 */ 9859 private int getDefaultVerificationResponse() { 9860 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9861 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9862 DEFAULT_VERIFICATION_RESPONSE); 9863 } 9864 9865 /** 9866 * Check whether or not package verification has been enabled. 9867 * 9868 * @return true if verification should be performed 9869 */ 9870 private boolean isVerificationEnabled(int userId, int installFlags) { 9871 if (!DEFAULT_VERIFY_ENABLE) { 9872 return false; 9873 } 9874 9875 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9876 9877 // Check if installing from ADB 9878 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9879 // Do not run verification in a test harness environment 9880 if (ActivityManager.isRunningInTestHarness()) { 9881 return false; 9882 } 9883 if (ensureVerifyAppsEnabled) { 9884 return true; 9885 } 9886 // Check if the developer does not want package verification for ADB installs 9887 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9888 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9889 return false; 9890 } 9891 } 9892 9893 if (ensureVerifyAppsEnabled) { 9894 return true; 9895 } 9896 9897 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9898 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9899 } 9900 9901 @Override 9902 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9903 throws RemoteException { 9904 mContext.enforceCallingOrSelfPermission( 9905 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9906 "Only intentfilter verification agents can verify applications"); 9907 9908 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9909 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9910 Binder.getCallingUid(), verificationCode, failedDomains); 9911 msg.arg1 = id; 9912 msg.obj = response; 9913 mHandler.sendMessage(msg); 9914 } 9915 9916 @Override 9917 public int getIntentVerificationStatus(String packageName, int userId) { 9918 synchronized (mPackages) { 9919 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9920 } 9921 } 9922 9923 @Override 9924 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9925 mContext.enforceCallingOrSelfPermission( 9926 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9927 9928 boolean result = false; 9929 synchronized (mPackages) { 9930 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9931 } 9932 if (result) { 9933 scheduleWritePackageRestrictionsLocked(userId); 9934 } 9935 return result; 9936 } 9937 9938 @Override 9939 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9940 synchronized (mPackages) { 9941 return mSettings.getIntentFilterVerificationsLPr(packageName); 9942 } 9943 } 9944 9945 @Override 9946 public List<IntentFilter> getAllIntentFilters(String packageName) { 9947 if (TextUtils.isEmpty(packageName)) { 9948 return Collections.<IntentFilter>emptyList(); 9949 } 9950 synchronized (mPackages) { 9951 PackageParser.Package pkg = mPackages.get(packageName); 9952 if (pkg == null || pkg.activities == null) { 9953 return Collections.<IntentFilter>emptyList(); 9954 } 9955 final int count = pkg.activities.size(); 9956 ArrayList<IntentFilter> result = new ArrayList<>(); 9957 for (int n=0; n<count; n++) { 9958 PackageParser.Activity activity = pkg.activities.get(n); 9959 if (activity.intents != null || activity.intents.size() > 0) { 9960 result.addAll(activity.intents); 9961 } 9962 } 9963 return result; 9964 } 9965 } 9966 9967 @Override 9968 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9969 mContext.enforceCallingOrSelfPermission( 9970 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9971 9972 synchronized (mPackages) { 9973 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9974 if (packageName != null) { 9975 result |= updateIntentVerificationStatus(packageName, 9976 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9977 userId); 9978 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9979 packageName, userId); 9980 } 9981 return result; 9982 } 9983 } 9984 9985 @Override 9986 public String getDefaultBrowserPackageName(int userId) { 9987 synchronized (mPackages) { 9988 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9989 } 9990 } 9991 9992 /** 9993 * Get the "allow unknown sources" setting. 9994 * 9995 * @return the current "allow unknown sources" setting 9996 */ 9997 private int getUnknownSourcesSettings() { 9998 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9999 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10000 -1); 10001 } 10002 10003 @Override 10004 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10005 final int uid = Binder.getCallingUid(); 10006 // writer 10007 synchronized (mPackages) { 10008 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10009 if (targetPackageSetting == null) { 10010 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10011 } 10012 10013 PackageSetting installerPackageSetting; 10014 if (installerPackageName != null) { 10015 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10016 if (installerPackageSetting == null) { 10017 throw new IllegalArgumentException("Unknown installer package: " 10018 + installerPackageName); 10019 } 10020 } else { 10021 installerPackageSetting = null; 10022 } 10023 10024 Signature[] callerSignature; 10025 Object obj = mSettings.getUserIdLPr(uid); 10026 if (obj != null) { 10027 if (obj instanceof SharedUserSetting) { 10028 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10029 } else if (obj instanceof PackageSetting) { 10030 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10031 } else { 10032 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10033 } 10034 } else { 10035 throw new SecurityException("Unknown calling uid " + uid); 10036 } 10037 10038 // Verify: can't set installerPackageName to a package that is 10039 // not signed with the same cert as the caller. 10040 if (installerPackageSetting != null) { 10041 if (compareSignatures(callerSignature, 10042 installerPackageSetting.signatures.mSignatures) 10043 != PackageManager.SIGNATURE_MATCH) { 10044 throw new SecurityException( 10045 "Caller does not have same cert as new installer package " 10046 + installerPackageName); 10047 } 10048 } 10049 10050 // Verify: if target already has an installer package, it must 10051 // be signed with the same cert as the caller. 10052 if (targetPackageSetting.installerPackageName != null) { 10053 PackageSetting setting = mSettings.mPackages.get( 10054 targetPackageSetting.installerPackageName); 10055 // If the currently set package isn't valid, then it's always 10056 // okay to change it. 10057 if (setting != null) { 10058 if (compareSignatures(callerSignature, 10059 setting.signatures.mSignatures) 10060 != PackageManager.SIGNATURE_MATCH) { 10061 throw new SecurityException( 10062 "Caller does not have same cert as old installer package " 10063 + targetPackageSetting.installerPackageName); 10064 } 10065 } 10066 } 10067 10068 // Okay! 10069 targetPackageSetting.installerPackageName = installerPackageName; 10070 scheduleWriteSettingsLocked(); 10071 } 10072 } 10073 10074 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10075 // Queue up an async operation since the package installation may take a little while. 10076 mHandler.post(new Runnable() { 10077 public void run() { 10078 mHandler.removeCallbacks(this); 10079 // Result object to be returned 10080 PackageInstalledInfo res = new PackageInstalledInfo(); 10081 res.returnCode = currentStatus; 10082 res.uid = -1; 10083 res.pkg = null; 10084 res.removedInfo = new PackageRemovedInfo(); 10085 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10086 args.doPreInstall(res.returnCode); 10087 synchronized (mInstallLock) { 10088 installPackageLI(args, res); 10089 } 10090 args.doPostInstall(res.returnCode, res.uid); 10091 } 10092 10093 // A restore should be performed at this point if (a) the install 10094 // succeeded, (b) the operation is not an update, and (c) the new 10095 // package has not opted out of backup participation. 10096 final boolean update = res.removedInfo.removedPackage != null; 10097 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10098 boolean doRestore = !update 10099 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10100 10101 // Set up the post-install work request bookkeeping. This will be used 10102 // and cleaned up by the post-install event handling regardless of whether 10103 // there's a restore pass performed. Token values are >= 1. 10104 int token; 10105 if (mNextInstallToken < 0) mNextInstallToken = 1; 10106 token = mNextInstallToken++; 10107 10108 PostInstallData data = new PostInstallData(args, res); 10109 mRunningInstalls.put(token, data); 10110 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10111 10112 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10113 // Pass responsibility to the Backup Manager. It will perform a 10114 // restore if appropriate, then pass responsibility back to the 10115 // Package Manager to run the post-install observer callbacks 10116 // and broadcasts. 10117 IBackupManager bm = IBackupManager.Stub.asInterface( 10118 ServiceManager.getService(Context.BACKUP_SERVICE)); 10119 if (bm != null) { 10120 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10121 + " to BM for possible restore"); 10122 try { 10123 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10124 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10125 } else { 10126 doRestore = false; 10127 } 10128 } catch (RemoteException e) { 10129 // can't happen; the backup manager is local 10130 } catch (Exception e) { 10131 Slog.e(TAG, "Exception trying to enqueue restore", e); 10132 doRestore = false; 10133 } 10134 } else { 10135 Slog.e(TAG, "Backup Manager not found!"); 10136 doRestore = false; 10137 } 10138 } 10139 10140 if (!doRestore) { 10141 // No restore possible, or the Backup Manager was mysteriously not 10142 // available -- just fire the post-install work request directly. 10143 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10144 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10145 mHandler.sendMessage(msg); 10146 } 10147 } 10148 }); 10149 } 10150 10151 private abstract class HandlerParams { 10152 private static final int MAX_RETRIES = 4; 10153 10154 /** 10155 * Number of times startCopy() has been attempted and had a non-fatal 10156 * error. 10157 */ 10158 private int mRetries = 0; 10159 10160 /** User handle for the user requesting the information or installation. */ 10161 private final UserHandle mUser; 10162 10163 HandlerParams(UserHandle user) { 10164 mUser = user; 10165 } 10166 10167 UserHandle getUser() { 10168 return mUser; 10169 } 10170 10171 final boolean startCopy() { 10172 boolean res; 10173 try { 10174 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10175 10176 if (++mRetries > MAX_RETRIES) { 10177 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10178 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10179 handleServiceError(); 10180 return false; 10181 } else { 10182 handleStartCopy(); 10183 res = true; 10184 } 10185 } catch (RemoteException e) { 10186 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10187 mHandler.sendEmptyMessage(MCS_RECONNECT); 10188 res = false; 10189 } 10190 handleReturnCode(); 10191 return res; 10192 } 10193 10194 final void serviceError() { 10195 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10196 handleServiceError(); 10197 handleReturnCode(); 10198 } 10199 10200 abstract void handleStartCopy() throws RemoteException; 10201 abstract void handleServiceError(); 10202 abstract void handleReturnCode(); 10203 } 10204 10205 class MeasureParams extends HandlerParams { 10206 private final PackageStats mStats; 10207 private boolean mSuccess; 10208 10209 private final IPackageStatsObserver mObserver; 10210 10211 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10212 super(new UserHandle(stats.userHandle)); 10213 mObserver = observer; 10214 mStats = stats; 10215 } 10216 10217 @Override 10218 public String toString() { 10219 return "MeasureParams{" 10220 + Integer.toHexString(System.identityHashCode(this)) 10221 + " " + mStats.packageName + "}"; 10222 } 10223 10224 @Override 10225 void handleStartCopy() throws RemoteException { 10226 synchronized (mInstallLock) { 10227 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10228 } 10229 10230 if (mSuccess) { 10231 final boolean mounted; 10232 if (Environment.isExternalStorageEmulated()) { 10233 mounted = true; 10234 } else { 10235 final String status = Environment.getExternalStorageState(); 10236 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10237 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10238 } 10239 10240 if (mounted) { 10241 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10242 10243 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10244 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10245 10246 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10247 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10248 10249 // Always subtract cache size, since it's a subdirectory 10250 mStats.externalDataSize -= mStats.externalCacheSize; 10251 10252 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10253 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10254 10255 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10256 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10257 } 10258 } 10259 } 10260 10261 @Override 10262 void handleReturnCode() { 10263 if (mObserver != null) { 10264 try { 10265 mObserver.onGetStatsCompleted(mStats, mSuccess); 10266 } catch (RemoteException e) { 10267 Slog.i(TAG, "Observer no longer exists."); 10268 } 10269 } 10270 } 10271 10272 @Override 10273 void handleServiceError() { 10274 Slog.e(TAG, "Could not measure application " + mStats.packageName 10275 + " external storage"); 10276 } 10277 } 10278 10279 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10280 throws RemoteException { 10281 long result = 0; 10282 for (File path : paths) { 10283 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10284 } 10285 return result; 10286 } 10287 10288 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10289 for (File path : paths) { 10290 try { 10291 mcs.clearDirectory(path.getAbsolutePath()); 10292 } catch (RemoteException e) { 10293 } 10294 } 10295 } 10296 10297 static class OriginInfo { 10298 /** 10299 * Location where install is coming from, before it has been 10300 * copied/renamed into place. This could be a single monolithic APK 10301 * file, or a cluster directory. This location may be untrusted. 10302 */ 10303 final File file; 10304 final String cid; 10305 10306 /** 10307 * Flag indicating that {@link #file} or {@link #cid} has already been 10308 * staged, meaning downstream users don't need to defensively copy the 10309 * contents. 10310 */ 10311 final boolean staged; 10312 10313 /** 10314 * Flag indicating that {@link #file} or {@link #cid} is an already 10315 * installed app that is being moved. 10316 */ 10317 final boolean existing; 10318 10319 final String resolvedPath; 10320 final File resolvedFile; 10321 10322 static OriginInfo fromNothing() { 10323 return new OriginInfo(null, null, false, false); 10324 } 10325 10326 static OriginInfo fromUntrustedFile(File file) { 10327 return new OriginInfo(file, null, false, false); 10328 } 10329 10330 static OriginInfo fromExistingFile(File file) { 10331 return new OriginInfo(file, null, false, true); 10332 } 10333 10334 static OriginInfo fromStagedFile(File file) { 10335 return new OriginInfo(file, null, true, false); 10336 } 10337 10338 static OriginInfo fromStagedContainer(String cid) { 10339 return new OriginInfo(null, cid, true, false); 10340 } 10341 10342 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10343 this.file = file; 10344 this.cid = cid; 10345 this.staged = staged; 10346 this.existing = existing; 10347 10348 if (cid != null) { 10349 resolvedPath = PackageHelper.getSdDir(cid); 10350 resolvedFile = new File(resolvedPath); 10351 } else if (file != null) { 10352 resolvedPath = file.getAbsolutePath(); 10353 resolvedFile = file; 10354 } else { 10355 resolvedPath = null; 10356 resolvedFile = null; 10357 } 10358 } 10359 } 10360 10361 class MoveInfo { 10362 final int moveId; 10363 final String fromUuid; 10364 final String toUuid; 10365 final String packageName; 10366 final String dataAppName; 10367 final int appId; 10368 final String seinfo; 10369 10370 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10371 String dataAppName, int appId, String seinfo) { 10372 this.moveId = moveId; 10373 this.fromUuid = fromUuid; 10374 this.toUuid = toUuid; 10375 this.packageName = packageName; 10376 this.dataAppName = dataAppName; 10377 this.appId = appId; 10378 this.seinfo = seinfo; 10379 } 10380 } 10381 10382 class InstallParams extends HandlerParams { 10383 final OriginInfo origin; 10384 final MoveInfo move; 10385 final IPackageInstallObserver2 observer; 10386 int installFlags; 10387 final String installerPackageName; 10388 final String volumeUuid; 10389 final VerificationParams verificationParams; 10390 private InstallArgs mArgs; 10391 private int mRet; 10392 final String packageAbiOverride; 10393 final String[] grantedRuntimePermissions; 10394 10395 10396 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10397 int installFlags, String installerPackageName, String volumeUuid, 10398 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10399 String[] grantedPermissions) { 10400 super(user); 10401 this.origin = origin; 10402 this.move = move; 10403 this.observer = observer; 10404 this.installFlags = installFlags; 10405 this.installerPackageName = installerPackageName; 10406 this.volumeUuid = volumeUuid; 10407 this.verificationParams = verificationParams; 10408 this.packageAbiOverride = packageAbiOverride; 10409 this.grantedRuntimePermissions = grantedPermissions; 10410 } 10411 10412 @Override 10413 public String toString() { 10414 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10415 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10416 } 10417 10418 public ManifestDigest getManifestDigest() { 10419 if (verificationParams == null) { 10420 return null; 10421 } 10422 return verificationParams.getManifestDigest(); 10423 } 10424 10425 private int installLocationPolicy(PackageInfoLite pkgLite) { 10426 String packageName = pkgLite.packageName; 10427 int installLocation = pkgLite.installLocation; 10428 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10429 // reader 10430 synchronized (mPackages) { 10431 PackageParser.Package pkg = mPackages.get(packageName); 10432 if (pkg != null) { 10433 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10434 // Check for downgrading. 10435 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10436 try { 10437 checkDowngrade(pkg, pkgLite); 10438 } catch (PackageManagerException e) { 10439 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10440 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10441 } 10442 } 10443 // Check for updated system application. 10444 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10445 if (onSd) { 10446 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10447 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10448 } 10449 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10450 } else { 10451 if (onSd) { 10452 // Install flag overrides everything. 10453 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10454 } 10455 // If current upgrade specifies particular preference 10456 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10457 // Application explicitly specified internal. 10458 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10459 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10460 // App explictly prefers external. Let policy decide 10461 } else { 10462 // Prefer previous location 10463 if (isExternal(pkg)) { 10464 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10465 } 10466 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10467 } 10468 } 10469 } else { 10470 // Invalid install. Return error code 10471 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10472 } 10473 } 10474 } 10475 // All the special cases have been taken care of. 10476 // Return result based on recommended install location. 10477 if (onSd) { 10478 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10479 } 10480 return pkgLite.recommendedInstallLocation; 10481 } 10482 10483 /* 10484 * Invoke remote method to get package information and install 10485 * location values. Override install location based on default 10486 * policy if needed and then create install arguments based 10487 * on the install location. 10488 */ 10489 public void handleStartCopy() throws RemoteException { 10490 int ret = PackageManager.INSTALL_SUCCEEDED; 10491 10492 // If we're already staged, we've firmly committed to an install location 10493 if (origin.staged) { 10494 if (origin.file != null) { 10495 installFlags |= PackageManager.INSTALL_INTERNAL; 10496 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10497 } else if (origin.cid != null) { 10498 installFlags |= PackageManager.INSTALL_EXTERNAL; 10499 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10500 } else { 10501 throw new IllegalStateException("Invalid stage location"); 10502 } 10503 } 10504 10505 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10506 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10507 10508 PackageInfoLite pkgLite = null; 10509 10510 if (onInt && onSd) { 10511 // Check if both bits are set. 10512 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10513 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10514 } else { 10515 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10516 packageAbiOverride); 10517 10518 /* 10519 * If we have too little free space, try to free cache 10520 * before giving up. 10521 */ 10522 if (!origin.staged && pkgLite.recommendedInstallLocation 10523 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10524 // TODO: focus freeing disk space on the target device 10525 final StorageManager storage = StorageManager.from(mContext); 10526 final long lowThreshold = storage.getStorageLowBytes( 10527 Environment.getDataDirectory()); 10528 10529 final long sizeBytes = mContainerService.calculateInstalledSize( 10530 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10531 10532 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10533 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10534 installFlags, packageAbiOverride); 10535 } 10536 10537 /* 10538 * The cache free must have deleted the file we 10539 * downloaded to install. 10540 * 10541 * TODO: fix the "freeCache" call to not delete 10542 * the file we care about. 10543 */ 10544 if (pkgLite.recommendedInstallLocation 10545 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10546 pkgLite.recommendedInstallLocation 10547 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10548 } 10549 } 10550 } 10551 10552 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10553 int loc = pkgLite.recommendedInstallLocation; 10554 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10555 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10556 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10557 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10558 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10559 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10560 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10561 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10562 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10563 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10564 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10565 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10566 } else { 10567 // Override with defaults if needed. 10568 loc = installLocationPolicy(pkgLite); 10569 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10570 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10571 } else if (!onSd && !onInt) { 10572 // Override install location with flags 10573 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10574 // Set the flag to install on external media. 10575 installFlags |= PackageManager.INSTALL_EXTERNAL; 10576 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10577 } else { 10578 // Make sure the flag for installing on external 10579 // media is unset 10580 installFlags |= PackageManager.INSTALL_INTERNAL; 10581 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10582 } 10583 } 10584 } 10585 } 10586 10587 final InstallArgs args = createInstallArgs(this); 10588 mArgs = args; 10589 10590 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10591 /* 10592 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10593 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10594 */ 10595 int userIdentifier = getUser().getIdentifier(); 10596 if (userIdentifier == UserHandle.USER_ALL 10597 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10598 userIdentifier = UserHandle.USER_OWNER; 10599 } 10600 10601 /* 10602 * Determine if we have any installed package verifiers. If we 10603 * do, then we'll defer to them to verify the packages. 10604 */ 10605 final int requiredUid = mRequiredVerifierPackage == null ? -1 10606 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10607 if (!origin.existing && requiredUid != -1 10608 && isVerificationEnabled(userIdentifier, installFlags)) { 10609 final Intent verification = new Intent( 10610 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10611 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10612 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10613 PACKAGE_MIME_TYPE); 10614 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10615 10616 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10617 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10618 0 /* TODO: Which userId? */); 10619 10620 if (DEBUG_VERIFY) { 10621 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10622 + verification.toString() + " with " + pkgLite.verifiers.length 10623 + " optional verifiers"); 10624 } 10625 10626 final int verificationId = mPendingVerificationToken++; 10627 10628 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10629 10630 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10631 installerPackageName); 10632 10633 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10634 installFlags); 10635 10636 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10637 pkgLite.packageName); 10638 10639 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10640 pkgLite.versionCode); 10641 10642 if (verificationParams != null) { 10643 if (verificationParams.getVerificationURI() != null) { 10644 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10645 verificationParams.getVerificationURI()); 10646 } 10647 if (verificationParams.getOriginatingURI() != null) { 10648 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10649 verificationParams.getOriginatingURI()); 10650 } 10651 if (verificationParams.getReferrer() != null) { 10652 verification.putExtra(Intent.EXTRA_REFERRER, 10653 verificationParams.getReferrer()); 10654 } 10655 if (verificationParams.getOriginatingUid() >= 0) { 10656 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10657 verificationParams.getOriginatingUid()); 10658 } 10659 if (verificationParams.getInstallerUid() >= 0) { 10660 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10661 verificationParams.getInstallerUid()); 10662 } 10663 } 10664 10665 final PackageVerificationState verificationState = new PackageVerificationState( 10666 requiredUid, args); 10667 10668 mPendingVerification.append(verificationId, verificationState); 10669 10670 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10671 receivers, verificationState); 10672 10673 // Apps installed for "all" users use the device owner to verify the app 10674 UserHandle verifierUser = getUser(); 10675 if (verifierUser == UserHandle.ALL) { 10676 verifierUser = UserHandle.OWNER; 10677 } 10678 10679 /* 10680 * If any sufficient verifiers were listed in the package 10681 * manifest, attempt to ask them. 10682 */ 10683 if (sufficientVerifiers != null) { 10684 final int N = sufficientVerifiers.size(); 10685 if (N == 0) { 10686 Slog.i(TAG, "Additional verifiers required, but none installed."); 10687 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10688 } else { 10689 for (int i = 0; i < N; i++) { 10690 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10691 10692 final Intent sufficientIntent = new Intent(verification); 10693 sufficientIntent.setComponent(verifierComponent); 10694 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10695 } 10696 } 10697 } 10698 10699 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10700 mRequiredVerifierPackage, receivers); 10701 if (ret == PackageManager.INSTALL_SUCCEEDED 10702 && mRequiredVerifierPackage != null) { 10703 /* 10704 * Send the intent to the required verification agent, 10705 * but only start the verification timeout after the 10706 * target BroadcastReceivers have run. 10707 */ 10708 verification.setComponent(requiredVerifierComponent); 10709 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10710 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10711 new BroadcastReceiver() { 10712 @Override 10713 public void onReceive(Context context, Intent intent) { 10714 final Message msg = mHandler 10715 .obtainMessage(CHECK_PENDING_VERIFICATION); 10716 msg.arg1 = verificationId; 10717 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10718 } 10719 }, null, 0, null, null); 10720 10721 /* 10722 * We don't want the copy to proceed until verification 10723 * succeeds, so null out this field. 10724 */ 10725 mArgs = null; 10726 } 10727 } else { 10728 /* 10729 * No package verification is enabled, so immediately start 10730 * the remote call to initiate copy using temporary file. 10731 */ 10732 ret = args.copyApk(mContainerService, true); 10733 } 10734 } 10735 10736 mRet = ret; 10737 } 10738 10739 @Override 10740 void handleReturnCode() { 10741 // If mArgs is null, then MCS couldn't be reached. When it 10742 // reconnects, it will try again to install. At that point, this 10743 // will succeed. 10744 if (mArgs != null) { 10745 processPendingInstall(mArgs, mRet); 10746 } 10747 } 10748 10749 @Override 10750 void handleServiceError() { 10751 mArgs = createInstallArgs(this); 10752 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10753 } 10754 10755 public boolean isForwardLocked() { 10756 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10757 } 10758 } 10759 10760 /** 10761 * Used during creation of InstallArgs 10762 * 10763 * @param installFlags package installation flags 10764 * @return true if should be installed on external storage 10765 */ 10766 private static boolean installOnExternalAsec(int installFlags) { 10767 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10768 return false; 10769 } 10770 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10771 return true; 10772 } 10773 return false; 10774 } 10775 10776 /** 10777 * Used during creation of InstallArgs 10778 * 10779 * @param installFlags package installation flags 10780 * @return true if should be installed as forward locked 10781 */ 10782 private static boolean installForwardLocked(int installFlags) { 10783 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10784 } 10785 10786 private InstallArgs createInstallArgs(InstallParams params) { 10787 if (params.move != null) { 10788 return new MoveInstallArgs(params); 10789 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10790 return new AsecInstallArgs(params); 10791 } else { 10792 return new FileInstallArgs(params); 10793 } 10794 } 10795 10796 /** 10797 * Create args that describe an existing installed package. Typically used 10798 * when cleaning up old installs, or used as a move source. 10799 */ 10800 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10801 String resourcePath, String[] instructionSets) { 10802 final boolean isInAsec; 10803 if (installOnExternalAsec(installFlags)) { 10804 /* Apps on SD card are always in ASEC containers. */ 10805 isInAsec = true; 10806 } else if (installForwardLocked(installFlags) 10807 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10808 /* 10809 * Forward-locked apps are only in ASEC containers if they're the 10810 * new style 10811 */ 10812 isInAsec = true; 10813 } else { 10814 isInAsec = false; 10815 } 10816 10817 if (isInAsec) { 10818 return new AsecInstallArgs(codePath, instructionSets, 10819 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10820 } else { 10821 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10822 } 10823 } 10824 10825 static abstract class InstallArgs { 10826 /** @see InstallParams#origin */ 10827 final OriginInfo origin; 10828 /** @see InstallParams#move */ 10829 final MoveInfo move; 10830 10831 final IPackageInstallObserver2 observer; 10832 // Always refers to PackageManager flags only 10833 final int installFlags; 10834 final String installerPackageName; 10835 final String volumeUuid; 10836 final ManifestDigest manifestDigest; 10837 final UserHandle user; 10838 final String abiOverride; 10839 final String[] installGrantPermissions; 10840 10841 // The list of instruction sets supported by this app. This is currently 10842 // only used during the rmdex() phase to clean up resources. We can get rid of this 10843 // if we move dex files under the common app path. 10844 /* nullable */ String[] instructionSets; 10845 10846 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10847 int installFlags, String installerPackageName, String volumeUuid, 10848 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10849 String abiOverride, String[] installGrantPermissions) { 10850 this.origin = origin; 10851 this.move = move; 10852 this.installFlags = installFlags; 10853 this.observer = observer; 10854 this.installerPackageName = installerPackageName; 10855 this.volumeUuid = volumeUuid; 10856 this.manifestDigest = manifestDigest; 10857 this.user = user; 10858 this.instructionSets = instructionSets; 10859 this.abiOverride = abiOverride; 10860 this.installGrantPermissions = installGrantPermissions; 10861 } 10862 10863 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10864 abstract int doPreInstall(int status); 10865 10866 /** 10867 * Rename package into final resting place. All paths on the given 10868 * scanned package should be updated to reflect the rename. 10869 */ 10870 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10871 abstract int doPostInstall(int status, int uid); 10872 10873 /** @see PackageSettingBase#codePathString */ 10874 abstract String getCodePath(); 10875 /** @see PackageSettingBase#resourcePathString */ 10876 abstract String getResourcePath(); 10877 10878 // Need installer lock especially for dex file removal. 10879 abstract void cleanUpResourcesLI(); 10880 abstract boolean doPostDeleteLI(boolean delete); 10881 10882 /** 10883 * Called before the source arguments are copied. This is used mostly 10884 * for MoveParams when it needs to read the source file to put it in the 10885 * destination. 10886 */ 10887 int doPreCopy() { 10888 return PackageManager.INSTALL_SUCCEEDED; 10889 } 10890 10891 /** 10892 * Called after the source arguments are copied. This is used mostly for 10893 * MoveParams when it needs to read the source file to put it in the 10894 * destination. 10895 * 10896 * @return 10897 */ 10898 int doPostCopy(int uid) { 10899 return PackageManager.INSTALL_SUCCEEDED; 10900 } 10901 10902 protected boolean isFwdLocked() { 10903 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10904 } 10905 10906 protected boolean isExternalAsec() { 10907 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10908 } 10909 10910 UserHandle getUser() { 10911 return user; 10912 } 10913 } 10914 10915 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10916 if (!allCodePaths.isEmpty()) { 10917 if (instructionSets == null) { 10918 throw new IllegalStateException("instructionSet == null"); 10919 } 10920 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10921 for (String codePath : allCodePaths) { 10922 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10923 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10924 if (retCode < 0) { 10925 Slog.w(TAG, "Couldn't remove dex file for package: " 10926 + " at location " + codePath + ", retcode=" + retCode); 10927 // we don't consider this to be a failure of the core package deletion 10928 } 10929 } 10930 } 10931 } 10932 } 10933 10934 /** 10935 * Logic to handle installation of non-ASEC applications, including copying 10936 * and renaming logic. 10937 */ 10938 class FileInstallArgs extends InstallArgs { 10939 private File codeFile; 10940 private File resourceFile; 10941 10942 // Example topology: 10943 // /data/app/com.example/base.apk 10944 // /data/app/com.example/split_foo.apk 10945 // /data/app/com.example/lib/arm/libfoo.so 10946 // /data/app/com.example/lib/arm64/libfoo.so 10947 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10948 10949 /** New install */ 10950 FileInstallArgs(InstallParams params) { 10951 super(params.origin, params.move, params.observer, params.installFlags, 10952 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10953 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 10954 params.grantedRuntimePermissions); 10955 if (isFwdLocked()) { 10956 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10957 } 10958 } 10959 10960 /** Existing install */ 10961 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10962 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10963 null, null); 10964 this.codeFile = (codePath != null) ? new File(codePath) : null; 10965 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10966 } 10967 10968 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10969 if (origin.staged) { 10970 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10971 codeFile = origin.file; 10972 resourceFile = origin.file; 10973 return PackageManager.INSTALL_SUCCEEDED; 10974 } 10975 10976 try { 10977 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10978 codeFile = tempDir; 10979 resourceFile = tempDir; 10980 } catch (IOException e) { 10981 Slog.w(TAG, "Failed to create copy file: " + e); 10982 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10983 } 10984 10985 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10986 @Override 10987 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10988 if (!FileUtils.isValidExtFilename(name)) { 10989 throw new IllegalArgumentException("Invalid filename: " + name); 10990 } 10991 try { 10992 final File file = new File(codeFile, name); 10993 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10994 O_RDWR | O_CREAT, 0644); 10995 Os.chmod(file.getAbsolutePath(), 0644); 10996 return new ParcelFileDescriptor(fd); 10997 } catch (ErrnoException e) { 10998 throw new RemoteException("Failed to open: " + e.getMessage()); 10999 } 11000 } 11001 }; 11002 11003 int ret = PackageManager.INSTALL_SUCCEEDED; 11004 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11005 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11006 Slog.e(TAG, "Failed to copy package"); 11007 return ret; 11008 } 11009 11010 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11011 NativeLibraryHelper.Handle handle = null; 11012 try { 11013 handle = NativeLibraryHelper.Handle.create(codeFile); 11014 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11015 abiOverride); 11016 } catch (IOException e) { 11017 Slog.e(TAG, "Copying native libraries failed", e); 11018 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11019 } finally { 11020 IoUtils.closeQuietly(handle); 11021 } 11022 11023 return ret; 11024 } 11025 11026 int doPreInstall(int status) { 11027 if (status != PackageManager.INSTALL_SUCCEEDED) { 11028 cleanUp(); 11029 } 11030 return status; 11031 } 11032 11033 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11034 if (status != PackageManager.INSTALL_SUCCEEDED) { 11035 cleanUp(); 11036 return false; 11037 } 11038 11039 final File targetDir = codeFile.getParentFile(); 11040 final File beforeCodeFile = codeFile; 11041 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11042 11043 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11044 try { 11045 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11046 } catch (ErrnoException e) { 11047 Slog.w(TAG, "Failed to rename", e); 11048 return false; 11049 } 11050 11051 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11052 Slog.w(TAG, "Failed to restorecon"); 11053 return false; 11054 } 11055 11056 // Reflect the rename internally 11057 codeFile = afterCodeFile; 11058 resourceFile = afterCodeFile; 11059 11060 // Reflect the rename in scanned details 11061 pkg.codePath = afterCodeFile.getAbsolutePath(); 11062 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11063 pkg.baseCodePath); 11064 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11065 pkg.splitCodePaths); 11066 11067 // Reflect the rename in app info 11068 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11069 pkg.applicationInfo.setCodePath(pkg.codePath); 11070 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11071 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11072 pkg.applicationInfo.setResourcePath(pkg.codePath); 11073 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11074 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11075 11076 return true; 11077 } 11078 11079 int doPostInstall(int status, int uid) { 11080 if (status != PackageManager.INSTALL_SUCCEEDED) { 11081 cleanUp(); 11082 } 11083 return status; 11084 } 11085 11086 @Override 11087 String getCodePath() { 11088 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11089 } 11090 11091 @Override 11092 String getResourcePath() { 11093 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11094 } 11095 11096 private boolean cleanUp() { 11097 if (codeFile == null || !codeFile.exists()) { 11098 return false; 11099 } 11100 11101 if (codeFile.isDirectory()) { 11102 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11103 } else { 11104 codeFile.delete(); 11105 } 11106 11107 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11108 resourceFile.delete(); 11109 } 11110 11111 return true; 11112 } 11113 11114 void cleanUpResourcesLI() { 11115 // Try enumerating all code paths before deleting 11116 List<String> allCodePaths = Collections.EMPTY_LIST; 11117 if (codeFile != null && codeFile.exists()) { 11118 try { 11119 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11120 allCodePaths = pkg.getAllCodePaths(); 11121 } catch (PackageParserException e) { 11122 // Ignored; we tried our best 11123 } 11124 } 11125 11126 cleanUp(); 11127 removeDexFiles(allCodePaths, instructionSets); 11128 } 11129 11130 boolean doPostDeleteLI(boolean delete) { 11131 // XXX err, shouldn't we respect the delete flag? 11132 cleanUpResourcesLI(); 11133 return true; 11134 } 11135 } 11136 11137 private boolean isAsecExternal(String cid) { 11138 final String asecPath = PackageHelper.getSdFilesystem(cid); 11139 return !asecPath.startsWith(mAsecInternalPath); 11140 } 11141 11142 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11143 PackageManagerException { 11144 if (copyRet < 0) { 11145 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11146 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11147 throw new PackageManagerException(copyRet, message); 11148 } 11149 } 11150 } 11151 11152 /** 11153 * Extract the MountService "container ID" from the full code path of an 11154 * .apk. 11155 */ 11156 static String cidFromCodePath(String fullCodePath) { 11157 int eidx = fullCodePath.lastIndexOf("/"); 11158 String subStr1 = fullCodePath.substring(0, eidx); 11159 int sidx = subStr1.lastIndexOf("/"); 11160 return subStr1.substring(sidx+1, eidx); 11161 } 11162 11163 /** 11164 * Logic to handle installation of ASEC applications, including copying and 11165 * renaming logic. 11166 */ 11167 class AsecInstallArgs extends InstallArgs { 11168 static final String RES_FILE_NAME = "pkg.apk"; 11169 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11170 11171 String cid; 11172 String packagePath; 11173 String resourcePath; 11174 11175 /** New install */ 11176 AsecInstallArgs(InstallParams params) { 11177 super(params.origin, params.move, params.observer, params.installFlags, 11178 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11179 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11180 params.grantedRuntimePermissions); 11181 } 11182 11183 /** Existing install */ 11184 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11185 boolean isExternal, boolean isForwardLocked) { 11186 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11187 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11188 instructionSets, null, null); 11189 // Hackily pretend we're still looking at a full code path 11190 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11191 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11192 } 11193 11194 // Extract cid from fullCodePath 11195 int eidx = fullCodePath.lastIndexOf("/"); 11196 String subStr1 = fullCodePath.substring(0, eidx); 11197 int sidx = subStr1.lastIndexOf("/"); 11198 cid = subStr1.substring(sidx+1, eidx); 11199 setMountPath(subStr1); 11200 } 11201 11202 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11203 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11204 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11205 instructionSets, null, null); 11206 this.cid = cid; 11207 setMountPath(PackageHelper.getSdDir(cid)); 11208 } 11209 11210 void createCopyFile() { 11211 cid = mInstallerService.allocateExternalStageCidLegacy(); 11212 } 11213 11214 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11215 if (origin.staged) { 11216 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11217 cid = origin.cid; 11218 setMountPath(PackageHelper.getSdDir(cid)); 11219 return PackageManager.INSTALL_SUCCEEDED; 11220 } 11221 11222 if (temp) { 11223 createCopyFile(); 11224 } else { 11225 /* 11226 * Pre-emptively destroy the container since it's destroyed if 11227 * copying fails due to it existing anyway. 11228 */ 11229 PackageHelper.destroySdDir(cid); 11230 } 11231 11232 final String newMountPath = imcs.copyPackageToContainer( 11233 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11234 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11235 11236 if (newMountPath != null) { 11237 setMountPath(newMountPath); 11238 return PackageManager.INSTALL_SUCCEEDED; 11239 } else { 11240 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11241 } 11242 } 11243 11244 @Override 11245 String getCodePath() { 11246 return packagePath; 11247 } 11248 11249 @Override 11250 String getResourcePath() { 11251 return resourcePath; 11252 } 11253 11254 int doPreInstall(int status) { 11255 if (status != PackageManager.INSTALL_SUCCEEDED) { 11256 // Destroy container 11257 PackageHelper.destroySdDir(cid); 11258 } else { 11259 boolean mounted = PackageHelper.isContainerMounted(cid); 11260 if (!mounted) { 11261 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11262 Process.SYSTEM_UID); 11263 if (newMountPath != null) { 11264 setMountPath(newMountPath); 11265 } else { 11266 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11267 } 11268 } 11269 } 11270 return status; 11271 } 11272 11273 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11274 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11275 String newMountPath = null; 11276 if (PackageHelper.isContainerMounted(cid)) { 11277 // Unmount the container 11278 if (!PackageHelper.unMountSdDir(cid)) { 11279 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11280 return false; 11281 } 11282 } 11283 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11284 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11285 " which might be stale. Will try to clean up."); 11286 // Clean up the stale container and proceed to recreate. 11287 if (!PackageHelper.destroySdDir(newCacheId)) { 11288 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11289 return false; 11290 } 11291 // Successfully cleaned up stale container. Try to rename again. 11292 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11293 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11294 + " inspite of cleaning it up."); 11295 return false; 11296 } 11297 } 11298 if (!PackageHelper.isContainerMounted(newCacheId)) { 11299 Slog.w(TAG, "Mounting container " + newCacheId); 11300 newMountPath = PackageHelper.mountSdDir(newCacheId, 11301 getEncryptKey(), Process.SYSTEM_UID); 11302 } else { 11303 newMountPath = PackageHelper.getSdDir(newCacheId); 11304 } 11305 if (newMountPath == null) { 11306 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11307 return false; 11308 } 11309 Log.i(TAG, "Succesfully renamed " + cid + 11310 " to " + newCacheId + 11311 " at new path: " + newMountPath); 11312 cid = newCacheId; 11313 11314 final File beforeCodeFile = new File(packagePath); 11315 setMountPath(newMountPath); 11316 final File afterCodeFile = new File(packagePath); 11317 11318 // Reflect the rename in scanned details 11319 pkg.codePath = afterCodeFile.getAbsolutePath(); 11320 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11321 pkg.baseCodePath); 11322 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11323 pkg.splitCodePaths); 11324 11325 // Reflect the rename in app info 11326 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11327 pkg.applicationInfo.setCodePath(pkg.codePath); 11328 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11329 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11330 pkg.applicationInfo.setResourcePath(pkg.codePath); 11331 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11332 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11333 11334 return true; 11335 } 11336 11337 private void setMountPath(String mountPath) { 11338 final File mountFile = new File(mountPath); 11339 11340 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11341 if (monolithicFile.exists()) { 11342 packagePath = monolithicFile.getAbsolutePath(); 11343 if (isFwdLocked()) { 11344 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11345 } else { 11346 resourcePath = packagePath; 11347 } 11348 } else { 11349 packagePath = mountFile.getAbsolutePath(); 11350 resourcePath = packagePath; 11351 } 11352 } 11353 11354 int doPostInstall(int status, int uid) { 11355 if (status != PackageManager.INSTALL_SUCCEEDED) { 11356 cleanUp(); 11357 } else { 11358 final int groupOwner; 11359 final String protectedFile; 11360 if (isFwdLocked()) { 11361 groupOwner = UserHandle.getSharedAppGid(uid); 11362 protectedFile = RES_FILE_NAME; 11363 } else { 11364 groupOwner = -1; 11365 protectedFile = null; 11366 } 11367 11368 if (uid < Process.FIRST_APPLICATION_UID 11369 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11370 Slog.e(TAG, "Failed to finalize " + cid); 11371 PackageHelper.destroySdDir(cid); 11372 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11373 } 11374 11375 boolean mounted = PackageHelper.isContainerMounted(cid); 11376 if (!mounted) { 11377 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11378 } 11379 } 11380 return status; 11381 } 11382 11383 private void cleanUp() { 11384 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11385 11386 // Destroy secure container 11387 PackageHelper.destroySdDir(cid); 11388 } 11389 11390 private List<String> getAllCodePaths() { 11391 final File codeFile = new File(getCodePath()); 11392 if (codeFile != null && codeFile.exists()) { 11393 try { 11394 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11395 return pkg.getAllCodePaths(); 11396 } catch (PackageParserException e) { 11397 // Ignored; we tried our best 11398 } 11399 } 11400 return Collections.EMPTY_LIST; 11401 } 11402 11403 void cleanUpResourcesLI() { 11404 // Enumerate all code paths before deleting 11405 cleanUpResourcesLI(getAllCodePaths()); 11406 } 11407 11408 private void cleanUpResourcesLI(List<String> allCodePaths) { 11409 cleanUp(); 11410 removeDexFiles(allCodePaths, instructionSets); 11411 } 11412 11413 String getPackageName() { 11414 return getAsecPackageName(cid); 11415 } 11416 11417 boolean doPostDeleteLI(boolean delete) { 11418 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11419 final List<String> allCodePaths = getAllCodePaths(); 11420 boolean mounted = PackageHelper.isContainerMounted(cid); 11421 if (mounted) { 11422 // Unmount first 11423 if (PackageHelper.unMountSdDir(cid)) { 11424 mounted = false; 11425 } 11426 } 11427 if (!mounted && delete) { 11428 cleanUpResourcesLI(allCodePaths); 11429 } 11430 return !mounted; 11431 } 11432 11433 @Override 11434 int doPreCopy() { 11435 if (isFwdLocked()) { 11436 if (!PackageHelper.fixSdPermissions(cid, 11437 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11438 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11439 } 11440 } 11441 11442 return PackageManager.INSTALL_SUCCEEDED; 11443 } 11444 11445 @Override 11446 int doPostCopy(int uid) { 11447 if (isFwdLocked()) { 11448 if (uid < Process.FIRST_APPLICATION_UID 11449 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11450 RES_FILE_NAME)) { 11451 Slog.e(TAG, "Failed to finalize " + cid); 11452 PackageHelper.destroySdDir(cid); 11453 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11454 } 11455 } 11456 11457 return PackageManager.INSTALL_SUCCEEDED; 11458 } 11459 } 11460 11461 /** 11462 * Logic to handle movement of existing installed applications. 11463 */ 11464 class MoveInstallArgs extends InstallArgs { 11465 private File codeFile; 11466 private File resourceFile; 11467 11468 /** New install */ 11469 MoveInstallArgs(InstallParams params) { 11470 super(params.origin, params.move, params.observer, params.installFlags, 11471 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11472 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11473 params.grantedRuntimePermissions); 11474 } 11475 11476 int copyApk(IMediaContainerService imcs, boolean temp) { 11477 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11478 + move.fromUuid + " to " + move.toUuid); 11479 synchronized (mInstaller) { 11480 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11481 move.dataAppName, move.appId, move.seinfo) != 0) { 11482 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11483 } 11484 } 11485 11486 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11487 resourceFile = codeFile; 11488 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11489 11490 return PackageManager.INSTALL_SUCCEEDED; 11491 } 11492 11493 int doPreInstall(int status) { 11494 if (status != PackageManager.INSTALL_SUCCEEDED) { 11495 cleanUp(move.toUuid); 11496 } 11497 return status; 11498 } 11499 11500 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11501 if (status != PackageManager.INSTALL_SUCCEEDED) { 11502 cleanUp(move.toUuid); 11503 return false; 11504 } 11505 11506 // Reflect the move in app info 11507 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11508 pkg.applicationInfo.setCodePath(pkg.codePath); 11509 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11510 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11511 pkg.applicationInfo.setResourcePath(pkg.codePath); 11512 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11513 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11514 11515 return true; 11516 } 11517 11518 int doPostInstall(int status, int uid) { 11519 if (status == PackageManager.INSTALL_SUCCEEDED) { 11520 cleanUp(move.fromUuid); 11521 } else { 11522 cleanUp(move.toUuid); 11523 } 11524 return status; 11525 } 11526 11527 @Override 11528 String getCodePath() { 11529 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11530 } 11531 11532 @Override 11533 String getResourcePath() { 11534 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11535 } 11536 11537 private boolean cleanUp(String volumeUuid) { 11538 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11539 move.dataAppName); 11540 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11541 synchronized (mInstallLock) { 11542 // Clean up both app data and code 11543 removeDataDirsLI(volumeUuid, move.packageName); 11544 if (codeFile.isDirectory()) { 11545 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11546 } else { 11547 codeFile.delete(); 11548 } 11549 } 11550 return true; 11551 } 11552 11553 void cleanUpResourcesLI() { 11554 throw new UnsupportedOperationException(); 11555 } 11556 11557 boolean doPostDeleteLI(boolean delete) { 11558 throw new UnsupportedOperationException(); 11559 } 11560 } 11561 11562 static String getAsecPackageName(String packageCid) { 11563 int idx = packageCid.lastIndexOf("-"); 11564 if (idx == -1) { 11565 return packageCid; 11566 } 11567 return packageCid.substring(0, idx); 11568 } 11569 11570 // Utility method used to create code paths based on package name and available index. 11571 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11572 String idxStr = ""; 11573 int idx = 1; 11574 // Fall back to default value of idx=1 if prefix is not 11575 // part of oldCodePath 11576 if (oldCodePath != null) { 11577 String subStr = oldCodePath; 11578 // Drop the suffix right away 11579 if (suffix != null && subStr.endsWith(suffix)) { 11580 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11581 } 11582 // If oldCodePath already contains prefix find out the 11583 // ending index to either increment or decrement. 11584 int sidx = subStr.lastIndexOf(prefix); 11585 if (sidx != -1) { 11586 subStr = subStr.substring(sidx + prefix.length()); 11587 if (subStr != null) { 11588 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11589 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11590 } 11591 try { 11592 idx = Integer.parseInt(subStr); 11593 if (idx <= 1) { 11594 idx++; 11595 } else { 11596 idx--; 11597 } 11598 } catch(NumberFormatException e) { 11599 } 11600 } 11601 } 11602 } 11603 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11604 return prefix + idxStr; 11605 } 11606 11607 private File getNextCodePath(File targetDir, String packageName) { 11608 int suffix = 1; 11609 File result; 11610 do { 11611 result = new File(targetDir, packageName + "-" + suffix); 11612 suffix++; 11613 } while (result.exists()); 11614 return result; 11615 } 11616 11617 // Utility method that returns the relative package path with respect 11618 // to the installation directory. Like say for /data/data/com.test-1.apk 11619 // string com.test-1 is returned. 11620 static String deriveCodePathName(String codePath) { 11621 if (codePath == null) { 11622 return null; 11623 } 11624 final File codeFile = new File(codePath); 11625 final String name = codeFile.getName(); 11626 if (codeFile.isDirectory()) { 11627 return name; 11628 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11629 final int lastDot = name.lastIndexOf('.'); 11630 return name.substring(0, lastDot); 11631 } else { 11632 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11633 return null; 11634 } 11635 } 11636 11637 class PackageInstalledInfo { 11638 String name; 11639 int uid; 11640 // The set of users that originally had this package installed. 11641 int[] origUsers; 11642 // The set of users that now have this package installed. 11643 int[] newUsers; 11644 PackageParser.Package pkg; 11645 int returnCode; 11646 String returnMsg; 11647 PackageRemovedInfo removedInfo; 11648 11649 public void setError(int code, String msg) { 11650 returnCode = code; 11651 returnMsg = msg; 11652 Slog.w(TAG, msg); 11653 } 11654 11655 public void setError(String msg, PackageParserException e) { 11656 returnCode = e.error; 11657 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11658 Slog.w(TAG, msg, e); 11659 } 11660 11661 public void setError(String msg, PackageManagerException e) { 11662 returnCode = e.error; 11663 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11664 Slog.w(TAG, msg, e); 11665 } 11666 11667 // In some error cases we want to convey more info back to the observer 11668 String origPackage; 11669 String origPermission; 11670 } 11671 11672 /* 11673 * Install a non-existing package. 11674 */ 11675 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11676 UserHandle user, String installerPackageName, String volumeUuid, 11677 PackageInstalledInfo res) { 11678 // Remember this for later, in case we need to rollback this install 11679 String pkgName = pkg.packageName; 11680 11681 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11682 final boolean dataDirExists = Environment 11683 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11684 synchronized(mPackages) { 11685 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11686 // A package with the same name is already installed, though 11687 // it has been renamed to an older name. The package we 11688 // are trying to install should be installed as an update to 11689 // the existing one, but that has not been requested, so bail. 11690 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11691 + " without first uninstalling package running as " 11692 + mSettings.mRenamedPackages.get(pkgName)); 11693 return; 11694 } 11695 if (mPackages.containsKey(pkgName)) { 11696 // Don't allow installation over an existing package with the same name. 11697 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11698 + " without first uninstalling."); 11699 return; 11700 } 11701 } 11702 11703 try { 11704 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11705 System.currentTimeMillis(), user); 11706 11707 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11708 // delete the partially installed application. the data directory will have to be 11709 // restored if it was already existing 11710 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11711 // remove package from internal structures. Note that we want deletePackageX to 11712 // delete the package data and cache directories that it created in 11713 // scanPackageLocked, unless those directories existed before we even tried to 11714 // install. 11715 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11716 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11717 res.removedInfo, true); 11718 } 11719 11720 } catch (PackageManagerException e) { 11721 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11722 } 11723 } 11724 11725 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11726 // Can't rotate keys during boot or if sharedUser. 11727 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11728 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11729 return false; 11730 } 11731 // app is using upgradeKeySets; make sure all are valid 11732 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11733 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11734 for (int i = 0; i < upgradeKeySets.length; i++) { 11735 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11736 Slog.wtf(TAG, "Package " 11737 + (oldPs.name != null ? oldPs.name : "<null>") 11738 + " contains upgrade-key-set reference to unknown key-set: " 11739 + upgradeKeySets[i] 11740 + " reverting to signatures check."); 11741 return false; 11742 } 11743 } 11744 return true; 11745 } 11746 11747 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11748 // Upgrade keysets are being used. Determine if new package has a superset of the 11749 // required keys. 11750 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11751 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11752 for (int i = 0; i < upgradeKeySets.length; i++) { 11753 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11754 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11755 return true; 11756 } 11757 } 11758 return false; 11759 } 11760 11761 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11762 UserHandle user, String installerPackageName, String volumeUuid, 11763 PackageInstalledInfo res) { 11764 final PackageParser.Package oldPackage; 11765 final String pkgName = pkg.packageName; 11766 final int[] allUsers; 11767 final boolean[] perUserInstalled; 11768 11769 // First find the old package info and check signatures 11770 synchronized(mPackages) { 11771 oldPackage = mPackages.get(pkgName); 11772 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11773 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11774 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11775 if(!checkUpgradeKeySetLP(ps, pkg)) { 11776 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11777 "New package not signed by keys specified by upgrade-keysets: " 11778 + pkgName); 11779 return; 11780 } 11781 } else { 11782 // default to original signature matching 11783 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11784 != PackageManager.SIGNATURE_MATCH) { 11785 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11786 "New package has a different signature: " + pkgName); 11787 return; 11788 } 11789 } 11790 11791 // In case of rollback, remember per-user/profile install state 11792 allUsers = sUserManager.getUserIds(); 11793 perUserInstalled = new boolean[allUsers.length]; 11794 for (int i = 0; i < allUsers.length; i++) { 11795 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11796 } 11797 } 11798 11799 boolean sysPkg = (isSystemApp(oldPackage)); 11800 if (sysPkg) { 11801 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11802 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11803 } else { 11804 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11805 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11806 } 11807 } 11808 11809 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11810 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11811 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11812 String volumeUuid, PackageInstalledInfo res) { 11813 String pkgName = deletedPackage.packageName; 11814 boolean deletedPkg = true; 11815 boolean updatedSettings = false; 11816 11817 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11818 + deletedPackage); 11819 long origUpdateTime; 11820 if (pkg.mExtras != null) { 11821 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11822 } else { 11823 origUpdateTime = 0; 11824 } 11825 11826 // First delete the existing package while retaining the data directory 11827 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11828 res.removedInfo, true)) { 11829 // If the existing package wasn't successfully deleted 11830 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11831 deletedPkg = false; 11832 } else { 11833 // Successfully deleted the old package; proceed with replace. 11834 11835 // If deleted package lived in a container, give users a chance to 11836 // relinquish resources before killing. 11837 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11838 if (DEBUG_INSTALL) { 11839 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11840 } 11841 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11842 final ArrayList<String> pkgList = new ArrayList<String>(1); 11843 pkgList.add(deletedPackage.applicationInfo.packageName); 11844 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11845 } 11846 11847 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11848 try { 11849 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11850 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11851 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11852 perUserInstalled, res, user); 11853 updatedSettings = true; 11854 } catch (PackageManagerException e) { 11855 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11856 } 11857 } 11858 11859 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11860 // remove package from internal structures. Note that we want deletePackageX to 11861 // delete the package data and cache directories that it created in 11862 // scanPackageLocked, unless those directories existed before we even tried to 11863 // install. 11864 if(updatedSettings) { 11865 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11866 deletePackageLI( 11867 pkgName, null, true, allUsers, perUserInstalled, 11868 PackageManager.DELETE_KEEP_DATA, 11869 res.removedInfo, true); 11870 } 11871 // Since we failed to install the new package we need to restore the old 11872 // package that we deleted. 11873 if (deletedPkg) { 11874 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11875 File restoreFile = new File(deletedPackage.codePath); 11876 // Parse old package 11877 boolean oldExternal = isExternal(deletedPackage); 11878 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11879 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11880 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11881 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11882 try { 11883 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11884 } catch (PackageManagerException e) { 11885 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11886 + e.getMessage()); 11887 return; 11888 } 11889 // Restore of old package succeeded. Update permissions. 11890 // writer 11891 synchronized (mPackages) { 11892 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11893 UPDATE_PERMISSIONS_ALL); 11894 // can downgrade to reader 11895 mSettings.writeLPr(); 11896 } 11897 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11898 } 11899 } 11900 } 11901 11902 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11903 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11904 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11905 String volumeUuid, PackageInstalledInfo res) { 11906 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11907 + ", old=" + deletedPackage); 11908 boolean disabledSystem = false; 11909 boolean updatedSettings = false; 11910 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11911 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11912 != 0) { 11913 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11914 } 11915 String packageName = deletedPackage.packageName; 11916 if (packageName == null) { 11917 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11918 "Attempt to delete null packageName."); 11919 return; 11920 } 11921 PackageParser.Package oldPkg; 11922 PackageSetting oldPkgSetting; 11923 // reader 11924 synchronized (mPackages) { 11925 oldPkg = mPackages.get(packageName); 11926 oldPkgSetting = mSettings.mPackages.get(packageName); 11927 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11928 (oldPkgSetting == null)) { 11929 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11930 "Couldn't find package:" + packageName + " information"); 11931 return; 11932 } 11933 } 11934 11935 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 11936 11937 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11938 res.removedInfo.removedPackage = packageName; 11939 // Remove existing system package 11940 removePackageLI(oldPkgSetting, true); 11941 // writer 11942 synchronized (mPackages) { 11943 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11944 if (!disabledSystem && deletedPackage != null) { 11945 // We didn't need to disable the .apk as a current system package, 11946 // which means we are replacing another update that is already 11947 // installed. We need to make sure to delete the older one's .apk. 11948 res.removedInfo.args = createInstallArgsForExisting(0, 11949 deletedPackage.applicationInfo.getCodePath(), 11950 deletedPackage.applicationInfo.getResourcePath(), 11951 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11952 } else { 11953 res.removedInfo.args = null; 11954 } 11955 } 11956 11957 // Successfully disabled the old package. Now proceed with re-installation 11958 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11959 11960 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11961 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11962 11963 PackageParser.Package newPackage = null; 11964 try { 11965 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11966 if (newPackage.mExtras != null) { 11967 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11968 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11969 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11970 11971 // is the update attempting to change shared user? that isn't going to work... 11972 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11973 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11974 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11975 + " to " + newPkgSetting.sharedUser); 11976 updatedSettings = true; 11977 } 11978 } 11979 11980 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11981 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11982 perUserInstalled, res, user); 11983 updatedSettings = true; 11984 } 11985 11986 } catch (PackageManagerException e) { 11987 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11988 } 11989 11990 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11991 // Re installation failed. Restore old information 11992 // Remove new pkg information 11993 if (newPackage != null) { 11994 removeInstalledPackageLI(newPackage, true); 11995 } 11996 // Add back the old system package 11997 try { 11998 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11999 } catch (PackageManagerException e) { 12000 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12001 } 12002 // Restore the old system information in Settings 12003 synchronized (mPackages) { 12004 if (disabledSystem) { 12005 mSettings.enableSystemPackageLPw(packageName); 12006 } 12007 if (updatedSettings) { 12008 mSettings.setInstallerPackageName(packageName, 12009 oldPkgSetting.installerPackageName); 12010 } 12011 mSettings.writeLPr(); 12012 } 12013 } 12014 } 12015 12016 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12017 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12018 UserHandle user) { 12019 String pkgName = newPackage.packageName; 12020 synchronized (mPackages) { 12021 //write settings. the installStatus will be incomplete at this stage. 12022 //note that the new package setting would have already been 12023 //added to mPackages. It hasn't been persisted yet. 12024 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12025 mSettings.writeLPr(); 12026 } 12027 12028 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12029 12030 synchronized (mPackages) { 12031 updatePermissionsLPw(newPackage.packageName, newPackage, 12032 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12033 ? UPDATE_PERMISSIONS_ALL : 0)); 12034 // For system-bundled packages, we assume that installing an upgraded version 12035 // of the package implies that the user actually wants to run that new code, 12036 // so we enable the package. 12037 PackageSetting ps = mSettings.mPackages.get(pkgName); 12038 if (ps != null) { 12039 if (isSystemApp(newPackage)) { 12040 // NB: implicit assumption that system package upgrades apply to all users 12041 if (DEBUG_INSTALL) { 12042 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12043 } 12044 if (res.origUsers != null) { 12045 for (int userHandle : res.origUsers) { 12046 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12047 userHandle, installerPackageName); 12048 } 12049 } 12050 // Also convey the prior install/uninstall state 12051 if (allUsers != null && perUserInstalled != null) { 12052 for (int i = 0; i < allUsers.length; i++) { 12053 if (DEBUG_INSTALL) { 12054 Slog.d(TAG, " user " + allUsers[i] 12055 + " => " + perUserInstalled[i]); 12056 } 12057 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12058 } 12059 // these install state changes will be persisted in the 12060 // upcoming call to mSettings.writeLPr(). 12061 } 12062 } 12063 // It's implied that when a user requests installation, they want the app to be 12064 // installed and enabled. 12065 int userId = user.getIdentifier(); 12066 if (userId != UserHandle.USER_ALL) { 12067 ps.setInstalled(true, userId); 12068 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12069 } 12070 } 12071 res.name = pkgName; 12072 res.uid = newPackage.applicationInfo.uid; 12073 res.pkg = newPackage; 12074 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12075 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12076 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12077 //to update install status 12078 mSettings.writeLPr(); 12079 } 12080 } 12081 12082 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12083 final int installFlags = args.installFlags; 12084 final String installerPackageName = args.installerPackageName; 12085 final String volumeUuid = args.volumeUuid; 12086 final File tmpPackageFile = new File(args.getCodePath()); 12087 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12088 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12089 || (args.volumeUuid != null)); 12090 boolean replace = false; 12091 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12092 if (args.move != null) { 12093 // moving a complete application; perfom an initial scan on the new install location 12094 scanFlags |= SCAN_INITIAL; 12095 } 12096 // Result object to be returned 12097 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12098 12099 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12100 // Retrieve PackageSettings and parse package 12101 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12102 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12103 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12104 PackageParser pp = new PackageParser(); 12105 pp.setSeparateProcesses(mSeparateProcesses); 12106 pp.setDisplayMetrics(mMetrics); 12107 12108 final PackageParser.Package pkg; 12109 try { 12110 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12111 } catch (PackageParserException e) { 12112 res.setError("Failed parse during installPackageLI", e); 12113 return; 12114 } 12115 12116 // Mark that we have an install time CPU ABI override. 12117 pkg.cpuAbiOverride = args.abiOverride; 12118 12119 String pkgName = res.name = pkg.packageName; 12120 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12121 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12122 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12123 return; 12124 } 12125 } 12126 12127 try { 12128 pp.collectCertificates(pkg, parseFlags); 12129 pp.collectManifestDigest(pkg); 12130 } catch (PackageParserException e) { 12131 res.setError("Failed collect during installPackageLI", e); 12132 return; 12133 } 12134 12135 /* If the installer passed in a manifest digest, compare it now. */ 12136 if (args.manifestDigest != null) { 12137 if (DEBUG_INSTALL) { 12138 final String parsedManifest = pkg.manifestDigest == null ? "null" 12139 : pkg.manifestDigest.toString(); 12140 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12141 + parsedManifest); 12142 } 12143 12144 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12145 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12146 return; 12147 } 12148 } else if (DEBUG_INSTALL) { 12149 final String parsedManifest = pkg.manifestDigest == null 12150 ? "null" : pkg.manifestDigest.toString(); 12151 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12152 } 12153 12154 // Get rid of all references to package scan path via parser. 12155 pp = null; 12156 String oldCodePath = null; 12157 boolean systemApp = false; 12158 synchronized (mPackages) { 12159 // Check if installing already existing package 12160 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12161 String oldName = mSettings.mRenamedPackages.get(pkgName); 12162 if (pkg.mOriginalPackages != null 12163 && pkg.mOriginalPackages.contains(oldName) 12164 && mPackages.containsKey(oldName)) { 12165 // This package is derived from an original package, 12166 // and this device has been updating from that original 12167 // name. We must continue using the original name, so 12168 // rename the new package here. 12169 pkg.setPackageName(oldName); 12170 pkgName = pkg.packageName; 12171 replace = true; 12172 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12173 + oldName + " pkgName=" + pkgName); 12174 } else if (mPackages.containsKey(pkgName)) { 12175 // This package, under its official name, already exists 12176 // on the device; we should replace it. 12177 replace = true; 12178 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12179 } 12180 12181 // Prevent apps opting out from runtime permissions 12182 if (replace) { 12183 PackageParser.Package oldPackage = mPackages.get(pkgName); 12184 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12185 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12186 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12187 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12188 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12189 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12190 + " doesn't support runtime permissions but the old" 12191 + " target SDK " + oldTargetSdk + " does."); 12192 return; 12193 } 12194 } 12195 } 12196 12197 PackageSetting ps = mSettings.mPackages.get(pkgName); 12198 if (ps != null) { 12199 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12200 12201 // Quick sanity check that we're signed correctly if updating; 12202 // we'll check this again later when scanning, but we want to 12203 // bail early here before tripping over redefined permissions. 12204 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12205 if (!checkUpgradeKeySetLP(ps, pkg)) { 12206 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12207 + pkg.packageName + " upgrade keys do not match the " 12208 + "previously installed version"); 12209 return; 12210 } 12211 } else { 12212 try { 12213 verifySignaturesLP(ps, pkg); 12214 } catch (PackageManagerException e) { 12215 res.setError(e.error, e.getMessage()); 12216 return; 12217 } 12218 } 12219 12220 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12221 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12222 systemApp = (ps.pkg.applicationInfo.flags & 12223 ApplicationInfo.FLAG_SYSTEM) != 0; 12224 } 12225 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12226 } 12227 12228 // Check whether the newly-scanned package wants to define an already-defined perm 12229 int N = pkg.permissions.size(); 12230 for (int i = N-1; i >= 0; i--) { 12231 PackageParser.Permission perm = pkg.permissions.get(i); 12232 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12233 if (bp != null) { 12234 // If the defining package is signed with our cert, it's okay. This 12235 // also includes the "updating the same package" case, of course. 12236 // "updating same package" could also involve key-rotation. 12237 final boolean sigsOk; 12238 if (bp.sourcePackage.equals(pkg.packageName) 12239 && (bp.packageSetting instanceof PackageSetting) 12240 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12241 scanFlags))) { 12242 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12243 } else { 12244 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12245 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12246 } 12247 if (!sigsOk) { 12248 // If the owning package is the system itself, we log but allow 12249 // install to proceed; we fail the install on all other permission 12250 // redefinitions. 12251 if (!bp.sourcePackage.equals("android")) { 12252 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12253 + pkg.packageName + " attempting to redeclare permission " 12254 + perm.info.name + " already owned by " + bp.sourcePackage); 12255 res.origPermission = perm.info.name; 12256 res.origPackage = bp.sourcePackage; 12257 return; 12258 } else { 12259 Slog.w(TAG, "Package " + pkg.packageName 12260 + " attempting to redeclare system permission " 12261 + perm.info.name + "; ignoring new declaration"); 12262 pkg.permissions.remove(i); 12263 } 12264 } 12265 } 12266 } 12267 12268 } 12269 12270 if (systemApp && onExternal) { 12271 // Disable updates to system apps on sdcard 12272 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12273 "Cannot install updates to system apps on sdcard"); 12274 return; 12275 } 12276 12277 if (args.move != null) { 12278 // We did an in-place move, so dex is ready to roll 12279 scanFlags |= SCAN_NO_DEX; 12280 scanFlags |= SCAN_MOVE; 12281 12282 synchronized (mPackages) { 12283 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12284 if (ps == null) { 12285 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12286 "Missing settings for moved package " + pkgName); 12287 } 12288 12289 // We moved the entire application as-is, so bring over the 12290 // previously derived ABI information. 12291 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12292 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12293 } 12294 12295 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12296 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12297 scanFlags |= SCAN_NO_DEX; 12298 12299 try { 12300 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12301 true /* extract libs */); 12302 } catch (PackageManagerException pme) { 12303 Slog.e(TAG, "Error deriving application ABI", pme); 12304 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12305 return; 12306 } 12307 12308 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12309 int result = mPackageDexOptimizer 12310 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12311 false /* defer */, false /* inclDependencies */); 12312 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12313 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12314 return; 12315 } 12316 } 12317 12318 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12319 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12320 return; 12321 } 12322 12323 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12324 12325 if (replace) { 12326 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12327 installerPackageName, volumeUuid, res); 12328 } else { 12329 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12330 args.user, installerPackageName, volumeUuid, res); 12331 } 12332 synchronized (mPackages) { 12333 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12334 if (ps != null) { 12335 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12336 } 12337 } 12338 } 12339 12340 private void startIntentFilterVerifications(int userId, boolean replacing, 12341 PackageParser.Package pkg) { 12342 if (mIntentFilterVerifierComponent == null) { 12343 Slog.w(TAG, "No IntentFilter verification will not be done as " 12344 + "there is no IntentFilterVerifier available!"); 12345 return; 12346 } 12347 12348 final int verifierUid = getPackageUid( 12349 mIntentFilterVerifierComponent.getPackageName(), 12350 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12351 12352 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12353 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12354 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12355 mHandler.sendMessage(msg); 12356 } 12357 12358 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12359 PackageParser.Package pkg) { 12360 int size = pkg.activities.size(); 12361 if (size == 0) { 12362 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12363 "No activity, so no need to verify any IntentFilter!"); 12364 return; 12365 } 12366 12367 final boolean hasDomainURLs = hasDomainURLs(pkg); 12368 if (!hasDomainURLs) { 12369 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12370 "No domain URLs, so no need to verify any IntentFilter!"); 12371 return; 12372 } 12373 12374 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12375 + " if any IntentFilter from the " + size 12376 + " Activities needs verification ..."); 12377 12378 int count = 0; 12379 final String packageName = pkg.packageName; 12380 12381 synchronized (mPackages) { 12382 // If this is a new install and we see that we've already run verification for this 12383 // package, we have nothing to do: it means the state was restored from backup. 12384 if (!replacing) { 12385 IntentFilterVerificationInfo ivi = 12386 mSettings.getIntentFilterVerificationLPr(packageName); 12387 if (ivi != null) { 12388 if (DEBUG_DOMAIN_VERIFICATION) { 12389 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12390 + ivi.getStatusString()); 12391 } 12392 return; 12393 } 12394 } 12395 12396 // If any filters need to be verified, then all need to be. 12397 boolean needToVerify = false; 12398 for (PackageParser.Activity a : pkg.activities) { 12399 for (ActivityIntentInfo filter : a.intents) { 12400 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12401 if (DEBUG_DOMAIN_VERIFICATION) { 12402 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12403 } 12404 needToVerify = true; 12405 break; 12406 } 12407 } 12408 } 12409 12410 if (needToVerify) { 12411 final int verificationId = mIntentFilterVerificationToken++; 12412 for (PackageParser.Activity a : pkg.activities) { 12413 for (ActivityIntentInfo filter : a.intents) { 12414 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12415 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12416 "Verification needed for IntentFilter:" + filter.toString()); 12417 mIntentFilterVerifier.addOneIntentFilterVerification( 12418 verifierUid, userId, verificationId, filter, packageName); 12419 count++; 12420 } 12421 } 12422 } 12423 } 12424 } 12425 12426 if (count > 0) { 12427 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12428 + " IntentFilter verification" + (count > 1 ? "s" : "") 12429 + " for userId:" + userId); 12430 mIntentFilterVerifier.startVerifications(userId); 12431 } else { 12432 if (DEBUG_DOMAIN_VERIFICATION) { 12433 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12434 } 12435 } 12436 } 12437 12438 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12439 final ComponentName cn = filter.activity.getComponentName(); 12440 final String packageName = cn.getPackageName(); 12441 12442 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12443 packageName); 12444 if (ivi == null) { 12445 return true; 12446 } 12447 int status = ivi.getStatus(); 12448 switch (status) { 12449 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12450 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12451 return true; 12452 12453 default: 12454 // Nothing to do 12455 return false; 12456 } 12457 } 12458 12459 private static boolean isMultiArch(PackageSetting ps) { 12460 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12461 } 12462 12463 private static boolean isMultiArch(ApplicationInfo info) { 12464 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12465 } 12466 12467 private static boolean isExternal(PackageParser.Package pkg) { 12468 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12469 } 12470 12471 private static boolean isExternal(PackageSetting ps) { 12472 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12473 } 12474 12475 private static boolean isExternal(ApplicationInfo info) { 12476 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12477 } 12478 12479 private static boolean isSystemApp(PackageParser.Package pkg) { 12480 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12481 } 12482 12483 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12484 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12485 } 12486 12487 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12488 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12489 } 12490 12491 private static boolean isSystemApp(PackageSetting ps) { 12492 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12493 } 12494 12495 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12496 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12497 } 12498 12499 private int packageFlagsToInstallFlags(PackageSetting ps) { 12500 int installFlags = 0; 12501 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12502 // This existing package was an external ASEC install when we have 12503 // the external flag without a UUID 12504 installFlags |= PackageManager.INSTALL_EXTERNAL; 12505 } 12506 if (ps.isForwardLocked()) { 12507 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12508 } 12509 return installFlags; 12510 } 12511 12512 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12513 if (isExternal(pkg)) { 12514 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12515 return mSettings.getExternalVersion(); 12516 } else { 12517 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12518 } 12519 } else { 12520 return mSettings.getInternalVersion(); 12521 } 12522 } 12523 12524 private void deleteTempPackageFiles() { 12525 final FilenameFilter filter = new FilenameFilter() { 12526 public boolean accept(File dir, String name) { 12527 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12528 } 12529 }; 12530 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12531 file.delete(); 12532 } 12533 } 12534 12535 @Override 12536 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12537 int flags) { 12538 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12539 flags); 12540 } 12541 12542 @Override 12543 public void deletePackage(final String packageName, 12544 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12545 mContext.enforceCallingOrSelfPermission( 12546 android.Manifest.permission.DELETE_PACKAGES, null); 12547 Preconditions.checkNotNull(packageName); 12548 Preconditions.checkNotNull(observer); 12549 final int uid = Binder.getCallingUid(); 12550 if (UserHandle.getUserId(uid) != userId) { 12551 mContext.enforceCallingPermission( 12552 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12553 "deletePackage for user " + userId); 12554 } 12555 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12556 try { 12557 observer.onPackageDeleted(packageName, 12558 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12559 } catch (RemoteException re) { 12560 } 12561 return; 12562 } 12563 12564 boolean uninstallBlocked = false; 12565 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12566 int[] users = sUserManager.getUserIds(); 12567 for (int i = 0; i < users.length; ++i) { 12568 if (getBlockUninstallForUser(packageName, users[i])) { 12569 uninstallBlocked = true; 12570 break; 12571 } 12572 } 12573 } else { 12574 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12575 } 12576 if (uninstallBlocked) { 12577 try { 12578 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12579 null); 12580 } catch (RemoteException re) { 12581 } 12582 return; 12583 } 12584 12585 if (DEBUG_REMOVE) { 12586 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12587 } 12588 // Queue up an async operation since the package deletion may take a little while. 12589 mHandler.post(new Runnable() { 12590 public void run() { 12591 mHandler.removeCallbacks(this); 12592 final int returnCode = deletePackageX(packageName, userId, flags); 12593 if (observer != null) { 12594 try { 12595 observer.onPackageDeleted(packageName, returnCode, null); 12596 } catch (RemoteException e) { 12597 Log.i(TAG, "Observer no longer exists."); 12598 } //end catch 12599 } //end if 12600 } //end run 12601 }); 12602 } 12603 12604 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12605 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12606 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12607 try { 12608 if (dpm != null) { 12609 if (dpm.isDeviceOwner(packageName)) { 12610 return true; 12611 } 12612 int[] users; 12613 if (userId == UserHandle.USER_ALL) { 12614 users = sUserManager.getUserIds(); 12615 } else { 12616 users = new int[]{userId}; 12617 } 12618 for (int i = 0; i < users.length; ++i) { 12619 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12620 return true; 12621 } 12622 } 12623 } 12624 } catch (RemoteException e) { 12625 } 12626 return false; 12627 } 12628 12629 /** 12630 * This method is an internal method that could be get invoked either 12631 * to delete an installed package or to clean up a failed installation. 12632 * After deleting an installed package, a broadcast is sent to notify any 12633 * listeners that the package has been installed. For cleaning up a failed 12634 * installation, the broadcast is not necessary since the package's 12635 * installation wouldn't have sent the initial broadcast either 12636 * The key steps in deleting a package are 12637 * deleting the package information in internal structures like mPackages, 12638 * deleting the packages base directories through installd 12639 * updating mSettings to reflect current status 12640 * persisting settings for later use 12641 * sending a broadcast if necessary 12642 */ 12643 private int deletePackageX(String packageName, int userId, int flags) { 12644 final PackageRemovedInfo info = new PackageRemovedInfo(); 12645 final boolean res; 12646 12647 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12648 ? UserHandle.ALL : new UserHandle(userId); 12649 12650 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12651 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12652 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12653 } 12654 12655 boolean removedForAllUsers = false; 12656 boolean systemUpdate = false; 12657 12658 // for the uninstall-updates case and restricted profiles, remember the per- 12659 // userhandle installed state 12660 int[] allUsers; 12661 boolean[] perUserInstalled; 12662 synchronized (mPackages) { 12663 PackageSetting ps = mSettings.mPackages.get(packageName); 12664 allUsers = sUserManager.getUserIds(); 12665 perUserInstalled = new boolean[allUsers.length]; 12666 for (int i = 0; i < allUsers.length; i++) { 12667 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12668 } 12669 } 12670 12671 synchronized (mInstallLock) { 12672 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12673 res = deletePackageLI(packageName, removeForUser, 12674 true, allUsers, perUserInstalled, 12675 flags | REMOVE_CHATTY, info, true); 12676 systemUpdate = info.isRemovedPackageSystemUpdate; 12677 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12678 removedForAllUsers = true; 12679 } 12680 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12681 + " removedForAllUsers=" + removedForAllUsers); 12682 } 12683 12684 if (res) { 12685 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12686 12687 // If the removed package was a system update, the old system package 12688 // was re-enabled; we need to broadcast this information 12689 if (systemUpdate) { 12690 Bundle extras = new Bundle(1); 12691 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12692 ? info.removedAppId : info.uid); 12693 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12694 12695 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12696 extras, null, null, null); 12697 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12698 extras, null, null, null); 12699 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12700 null, packageName, null, null); 12701 } 12702 } 12703 // Force a gc here. 12704 Runtime.getRuntime().gc(); 12705 // Delete the resources here after sending the broadcast to let 12706 // other processes clean up before deleting resources. 12707 if (info.args != null) { 12708 synchronized (mInstallLock) { 12709 info.args.doPostDeleteLI(true); 12710 } 12711 } 12712 12713 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12714 } 12715 12716 class PackageRemovedInfo { 12717 String removedPackage; 12718 int uid = -1; 12719 int removedAppId = -1; 12720 int[] removedUsers = null; 12721 boolean isRemovedPackageSystemUpdate = false; 12722 // Clean up resources deleted packages. 12723 InstallArgs args = null; 12724 12725 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12726 Bundle extras = new Bundle(1); 12727 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12728 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12729 if (replacing) { 12730 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12731 } 12732 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12733 if (removedPackage != null) { 12734 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12735 extras, null, null, removedUsers); 12736 if (fullRemove && !replacing) { 12737 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12738 extras, null, null, removedUsers); 12739 } 12740 } 12741 if (removedAppId >= 0) { 12742 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12743 removedUsers); 12744 } 12745 } 12746 } 12747 12748 /* 12749 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12750 * flag is not set, the data directory is removed as well. 12751 * make sure this flag is set for partially installed apps. If not its meaningless to 12752 * delete a partially installed application. 12753 */ 12754 private void removePackageDataLI(PackageSetting ps, 12755 int[] allUserHandles, boolean[] perUserInstalled, 12756 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12757 String packageName = ps.name; 12758 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12759 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12760 // Retrieve object to delete permissions for shared user later on 12761 final PackageSetting deletedPs; 12762 // reader 12763 synchronized (mPackages) { 12764 deletedPs = mSettings.mPackages.get(packageName); 12765 if (outInfo != null) { 12766 outInfo.removedPackage = packageName; 12767 outInfo.removedUsers = deletedPs != null 12768 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12769 : null; 12770 } 12771 } 12772 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12773 removeDataDirsLI(ps.volumeUuid, packageName); 12774 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12775 } 12776 // writer 12777 synchronized (mPackages) { 12778 if (deletedPs != null) { 12779 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12780 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12781 clearDefaultBrowserIfNeeded(packageName); 12782 if (outInfo != null) { 12783 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12784 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12785 } 12786 updatePermissionsLPw(deletedPs.name, null, 0); 12787 if (deletedPs.sharedUser != null) { 12788 // Remove permissions associated with package. Since runtime 12789 // permissions are per user we have to kill the removed package 12790 // or packages running under the shared user of the removed 12791 // package if revoking the permissions requested only by the removed 12792 // package is successful and this causes a change in gids. 12793 for (int userId : UserManagerService.getInstance().getUserIds()) { 12794 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12795 userId); 12796 if (userIdToKill == UserHandle.USER_ALL 12797 || userIdToKill >= UserHandle.USER_OWNER) { 12798 // If gids changed for this user, kill all affected packages. 12799 mHandler.post(new Runnable() { 12800 @Override 12801 public void run() { 12802 // This has to happen with no lock held. 12803 killApplication(deletedPs.name, deletedPs.appId, 12804 KILL_APP_REASON_GIDS_CHANGED); 12805 } 12806 }); 12807 break; 12808 } 12809 } 12810 } 12811 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12812 } 12813 // make sure to preserve per-user disabled state if this removal was just 12814 // a downgrade of a system app to the factory package 12815 if (allUserHandles != null && perUserInstalled != null) { 12816 if (DEBUG_REMOVE) { 12817 Slog.d(TAG, "Propagating install state across downgrade"); 12818 } 12819 for (int i = 0; i < allUserHandles.length; i++) { 12820 if (DEBUG_REMOVE) { 12821 Slog.d(TAG, " user " + allUserHandles[i] 12822 + " => " + perUserInstalled[i]); 12823 } 12824 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12825 } 12826 } 12827 } 12828 // can downgrade to reader 12829 if (writeSettings) { 12830 // Save settings now 12831 mSettings.writeLPr(); 12832 } 12833 } 12834 if (outInfo != null) { 12835 // A user ID was deleted here. Go through all users and remove it 12836 // from KeyStore. 12837 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12838 } 12839 } 12840 12841 static boolean locationIsPrivileged(File path) { 12842 try { 12843 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12844 .getCanonicalPath(); 12845 return path.getCanonicalPath().startsWith(privilegedAppDir); 12846 } catch (IOException e) { 12847 Slog.e(TAG, "Unable to access code path " + path); 12848 } 12849 return false; 12850 } 12851 12852 /* 12853 * Tries to delete system package. 12854 */ 12855 private boolean deleteSystemPackageLI(PackageSetting newPs, 12856 int[] allUserHandles, boolean[] perUserInstalled, 12857 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12858 final boolean applyUserRestrictions 12859 = (allUserHandles != null) && (perUserInstalled != null); 12860 PackageSetting disabledPs = null; 12861 // Confirm if the system package has been updated 12862 // An updated system app can be deleted. This will also have to restore 12863 // the system pkg from system partition 12864 // reader 12865 synchronized (mPackages) { 12866 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12867 } 12868 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12869 + " disabledPs=" + disabledPs); 12870 if (disabledPs == null) { 12871 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12872 return false; 12873 } else if (DEBUG_REMOVE) { 12874 Slog.d(TAG, "Deleting system pkg from data partition"); 12875 } 12876 if (DEBUG_REMOVE) { 12877 if (applyUserRestrictions) { 12878 Slog.d(TAG, "Remembering install states:"); 12879 for (int i = 0; i < allUserHandles.length; i++) { 12880 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12881 } 12882 } 12883 } 12884 // Delete the updated package 12885 outInfo.isRemovedPackageSystemUpdate = true; 12886 if (disabledPs.versionCode < newPs.versionCode) { 12887 // Delete data for downgrades 12888 flags &= ~PackageManager.DELETE_KEEP_DATA; 12889 } else { 12890 // Preserve data by setting flag 12891 flags |= PackageManager.DELETE_KEEP_DATA; 12892 } 12893 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12894 allUserHandles, perUserInstalled, outInfo, writeSettings); 12895 if (!ret) { 12896 return false; 12897 } 12898 // writer 12899 synchronized (mPackages) { 12900 // Reinstate the old system package 12901 mSettings.enableSystemPackageLPw(newPs.name); 12902 // Remove any native libraries from the upgraded package. 12903 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12904 } 12905 // Install the system package 12906 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12907 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12908 if (locationIsPrivileged(disabledPs.codePath)) { 12909 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12910 } 12911 12912 final PackageParser.Package newPkg; 12913 try { 12914 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12915 } catch (PackageManagerException e) { 12916 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12917 return false; 12918 } 12919 12920 // writer 12921 synchronized (mPackages) { 12922 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12923 12924 updatePermissionsLPw(newPkg.packageName, newPkg, 12925 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12926 12927 if (applyUserRestrictions) { 12928 if (DEBUG_REMOVE) { 12929 Slog.d(TAG, "Propagating install state across reinstall"); 12930 } 12931 for (int i = 0; i < allUserHandles.length; i++) { 12932 if (DEBUG_REMOVE) { 12933 Slog.d(TAG, " user " + allUserHandles[i] 12934 + " => " + perUserInstalled[i]); 12935 } 12936 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12937 12938 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 12939 } 12940 // Regardless of writeSettings we need to ensure that this restriction 12941 // state propagation is persisted 12942 mSettings.writeAllUsersPackageRestrictionsLPr(); 12943 } 12944 // can downgrade to reader here 12945 if (writeSettings) { 12946 mSettings.writeLPr(); 12947 } 12948 } 12949 return true; 12950 } 12951 12952 private boolean deleteInstalledPackageLI(PackageSetting ps, 12953 boolean deleteCodeAndResources, int flags, 12954 int[] allUserHandles, boolean[] perUserInstalled, 12955 PackageRemovedInfo outInfo, boolean writeSettings) { 12956 if (outInfo != null) { 12957 outInfo.uid = ps.appId; 12958 } 12959 12960 // Delete package data from internal structures and also remove data if flag is set 12961 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12962 12963 // Delete application code and resources 12964 if (deleteCodeAndResources && (outInfo != null)) { 12965 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12966 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12967 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12968 } 12969 return true; 12970 } 12971 12972 @Override 12973 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12974 int userId) { 12975 mContext.enforceCallingOrSelfPermission( 12976 android.Manifest.permission.DELETE_PACKAGES, null); 12977 synchronized (mPackages) { 12978 PackageSetting ps = mSettings.mPackages.get(packageName); 12979 if (ps == null) { 12980 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12981 return false; 12982 } 12983 if (!ps.getInstalled(userId)) { 12984 // Can't block uninstall for an app that is not installed or enabled. 12985 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12986 return false; 12987 } 12988 ps.setBlockUninstall(blockUninstall, userId); 12989 mSettings.writePackageRestrictionsLPr(userId); 12990 } 12991 return true; 12992 } 12993 12994 @Override 12995 public boolean getBlockUninstallForUser(String packageName, int userId) { 12996 synchronized (mPackages) { 12997 PackageSetting ps = mSettings.mPackages.get(packageName); 12998 if (ps == null) { 12999 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13000 return false; 13001 } 13002 return ps.getBlockUninstall(userId); 13003 } 13004 } 13005 13006 /* 13007 * This method handles package deletion in general 13008 */ 13009 private boolean deletePackageLI(String packageName, UserHandle user, 13010 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13011 int flags, PackageRemovedInfo outInfo, 13012 boolean writeSettings) { 13013 if (packageName == null) { 13014 Slog.w(TAG, "Attempt to delete null packageName."); 13015 return false; 13016 } 13017 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13018 PackageSetting ps; 13019 boolean dataOnly = false; 13020 int removeUser = -1; 13021 int appId = -1; 13022 synchronized (mPackages) { 13023 ps = mSettings.mPackages.get(packageName); 13024 if (ps == null) { 13025 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13026 return false; 13027 } 13028 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13029 && user.getIdentifier() != UserHandle.USER_ALL) { 13030 // The caller is asking that the package only be deleted for a single 13031 // user. To do this, we just mark its uninstalled state and delete 13032 // its data. If this is a system app, we only allow this to happen if 13033 // they have set the special DELETE_SYSTEM_APP which requests different 13034 // semantics than normal for uninstalling system apps. 13035 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13036 ps.setUserState(user.getIdentifier(), 13037 COMPONENT_ENABLED_STATE_DEFAULT, 13038 false, //installed 13039 true, //stopped 13040 true, //notLaunched 13041 false, //hidden 13042 null, null, null, 13043 false, // blockUninstall 13044 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0); 13045 if (!isSystemApp(ps)) { 13046 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13047 // Other user still have this package installed, so all 13048 // we need to do is clear this user's data and save that 13049 // it is uninstalled. 13050 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13051 removeUser = user.getIdentifier(); 13052 appId = ps.appId; 13053 scheduleWritePackageRestrictionsLocked(removeUser); 13054 } else { 13055 // We need to set it back to 'installed' so the uninstall 13056 // broadcasts will be sent correctly. 13057 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13058 ps.setInstalled(true, user.getIdentifier()); 13059 } 13060 } else { 13061 // This is a system app, so we assume that the 13062 // other users still have this package installed, so all 13063 // we need to do is clear this user's data and save that 13064 // it is uninstalled. 13065 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13066 removeUser = user.getIdentifier(); 13067 appId = ps.appId; 13068 scheduleWritePackageRestrictionsLocked(removeUser); 13069 } 13070 } 13071 } 13072 13073 if (removeUser >= 0) { 13074 // From above, we determined that we are deleting this only 13075 // for a single user. Continue the work here. 13076 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13077 if (outInfo != null) { 13078 outInfo.removedPackage = packageName; 13079 outInfo.removedAppId = appId; 13080 outInfo.removedUsers = new int[] {removeUser}; 13081 } 13082 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13083 removeKeystoreDataIfNeeded(removeUser, appId); 13084 schedulePackageCleaning(packageName, removeUser, false); 13085 synchronized (mPackages) { 13086 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13087 scheduleWritePackageRestrictionsLocked(removeUser); 13088 } 13089 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13090 } 13091 return true; 13092 } 13093 13094 if (dataOnly) { 13095 // Delete application data first 13096 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13097 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13098 return true; 13099 } 13100 13101 boolean ret = false; 13102 if (isSystemApp(ps)) { 13103 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13104 // When an updated system application is deleted we delete the existing resources as well and 13105 // fall back to existing code in system partition 13106 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13107 flags, outInfo, writeSettings); 13108 } else { 13109 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13110 // Kill application pre-emptively especially for apps on sd. 13111 killApplication(packageName, ps.appId, "uninstall pkg"); 13112 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13113 allUserHandles, perUserInstalled, 13114 outInfo, writeSettings); 13115 } 13116 13117 return ret; 13118 } 13119 13120 private final class ClearStorageConnection implements ServiceConnection { 13121 IMediaContainerService mContainerService; 13122 13123 @Override 13124 public void onServiceConnected(ComponentName name, IBinder service) { 13125 synchronized (this) { 13126 mContainerService = IMediaContainerService.Stub.asInterface(service); 13127 notifyAll(); 13128 } 13129 } 13130 13131 @Override 13132 public void onServiceDisconnected(ComponentName name) { 13133 } 13134 } 13135 13136 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13137 final boolean mounted; 13138 if (Environment.isExternalStorageEmulated()) { 13139 mounted = true; 13140 } else { 13141 final String status = Environment.getExternalStorageState(); 13142 13143 mounted = status.equals(Environment.MEDIA_MOUNTED) 13144 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13145 } 13146 13147 if (!mounted) { 13148 return; 13149 } 13150 13151 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13152 int[] users; 13153 if (userId == UserHandle.USER_ALL) { 13154 users = sUserManager.getUserIds(); 13155 } else { 13156 users = new int[] { userId }; 13157 } 13158 final ClearStorageConnection conn = new ClearStorageConnection(); 13159 if (mContext.bindServiceAsUser( 13160 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13161 try { 13162 for (int curUser : users) { 13163 long timeout = SystemClock.uptimeMillis() + 5000; 13164 synchronized (conn) { 13165 long now = SystemClock.uptimeMillis(); 13166 while (conn.mContainerService == null && now < timeout) { 13167 try { 13168 conn.wait(timeout - now); 13169 } catch (InterruptedException e) { 13170 } 13171 } 13172 } 13173 if (conn.mContainerService == null) { 13174 return; 13175 } 13176 13177 final UserEnvironment userEnv = new UserEnvironment(curUser); 13178 clearDirectory(conn.mContainerService, 13179 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13180 if (allData) { 13181 clearDirectory(conn.mContainerService, 13182 userEnv.buildExternalStorageAppDataDirs(packageName)); 13183 clearDirectory(conn.mContainerService, 13184 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13185 } 13186 } 13187 } finally { 13188 mContext.unbindService(conn); 13189 } 13190 } 13191 } 13192 13193 @Override 13194 public void clearApplicationUserData(final String packageName, 13195 final IPackageDataObserver observer, final int userId) { 13196 mContext.enforceCallingOrSelfPermission( 13197 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13198 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13199 // Queue up an async operation since the package deletion may take a little while. 13200 mHandler.post(new Runnable() { 13201 public void run() { 13202 mHandler.removeCallbacks(this); 13203 final boolean succeeded; 13204 synchronized (mInstallLock) { 13205 succeeded = clearApplicationUserDataLI(packageName, userId); 13206 } 13207 clearExternalStorageDataSync(packageName, userId, true); 13208 if (succeeded) { 13209 // invoke DeviceStorageMonitor's update method to clear any notifications 13210 DeviceStorageMonitorInternal 13211 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13212 if (dsm != null) { 13213 dsm.checkMemory(); 13214 } 13215 } 13216 if(observer != null) { 13217 try { 13218 observer.onRemoveCompleted(packageName, succeeded); 13219 } catch (RemoteException e) { 13220 Log.i(TAG, "Observer no longer exists."); 13221 } 13222 } //end if observer 13223 } //end run 13224 }); 13225 } 13226 13227 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13228 if (packageName == null) { 13229 Slog.w(TAG, "Attempt to delete null packageName."); 13230 return false; 13231 } 13232 13233 // Try finding details about the requested package 13234 PackageParser.Package pkg; 13235 synchronized (mPackages) { 13236 pkg = mPackages.get(packageName); 13237 if (pkg == null) { 13238 final PackageSetting ps = mSettings.mPackages.get(packageName); 13239 if (ps != null) { 13240 pkg = ps.pkg; 13241 } 13242 } 13243 13244 if (pkg == null) { 13245 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13246 return false; 13247 } 13248 13249 PackageSetting ps = (PackageSetting) pkg.mExtras; 13250 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13251 } 13252 13253 // Always delete data directories for package, even if we found no other 13254 // record of app. This helps users recover from UID mismatches without 13255 // resorting to a full data wipe. 13256 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13257 if (retCode < 0) { 13258 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13259 return false; 13260 } 13261 13262 final int appId = pkg.applicationInfo.uid; 13263 removeKeystoreDataIfNeeded(userId, appId); 13264 13265 // Create a native library symlink only if we have native libraries 13266 // and if the native libraries are 32 bit libraries. We do not provide 13267 // this symlink for 64 bit libraries. 13268 if (pkg.applicationInfo.primaryCpuAbi != null && 13269 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13270 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13271 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13272 nativeLibPath, userId) < 0) { 13273 Slog.w(TAG, "Failed linking native library dir"); 13274 return false; 13275 } 13276 } 13277 13278 return true; 13279 } 13280 13281 /** 13282 * Reverts user permission state changes (permissions and flags) in 13283 * all packages for a given user. 13284 * 13285 * @param userId The device user for which to do a reset. 13286 */ 13287 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13288 final int packageCount = mPackages.size(); 13289 for (int i = 0; i < packageCount; i++) { 13290 PackageParser.Package pkg = mPackages.valueAt(i); 13291 PackageSetting ps = (PackageSetting) pkg.mExtras; 13292 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13293 } 13294 } 13295 13296 /** 13297 * Reverts user permission state changes (permissions and flags). 13298 * 13299 * @param ps The package for which to reset. 13300 * @param userId The device user for which to do a reset. 13301 */ 13302 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13303 final PackageSetting ps, final int userId) { 13304 if (ps.pkg == null) { 13305 return; 13306 } 13307 13308 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13309 | FLAG_PERMISSION_USER_FIXED 13310 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13311 13312 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13313 | FLAG_PERMISSION_POLICY_FIXED; 13314 13315 boolean writeInstallPermissions = false; 13316 boolean writeRuntimePermissions = false; 13317 13318 final int permissionCount = ps.pkg.requestedPermissions.size(); 13319 for (int i = 0; i < permissionCount; i++) { 13320 String permission = ps.pkg.requestedPermissions.get(i); 13321 13322 BasePermission bp = mSettings.mPermissions.get(permission); 13323 if (bp == null) { 13324 continue; 13325 } 13326 13327 // If shared user we just reset the state to which only this app contributed. 13328 if (ps.sharedUser != null) { 13329 boolean used = false; 13330 final int packageCount = ps.sharedUser.packages.size(); 13331 for (int j = 0; j < packageCount; j++) { 13332 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13333 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13334 && pkg.pkg.requestedPermissions.contains(permission)) { 13335 used = true; 13336 break; 13337 } 13338 } 13339 if (used) { 13340 continue; 13341 } 13342 } 13343 13344 PermissionsState permissionsState = ps.getPermissionsState(); 13345 13346 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13347 13348 // Always clear the user settable flags. 13349 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13350 bp.name) != null; 13351 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13352 if (hasInstallState) { 13353 writeInstallPermissions = true; 13354 } else { 13355 writeRuntimePermissions = true; 13356 } 13357 } 13358 13359 // Below is only runtime permission handling. 13360 if (!bp.isRuntime()) { 13361 continue; 13362 } 13363 13364 // Never clobber system or policy. 13365 if ((oldFlags & policyOrSystemFlags) != 0) { 13366 continue; 13367 } 13368 13369 // If this permission was granted by default, make sure it is. 13370 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13371 if (permissionsState.grantRuntimePermission(bp, userId) 13372 != PERMISSION_OPERATION_FAILURE) { 13373 writeRuntimePermissions = true; 13374 } 13375 } else { 13376 // Otherwise, reset the permission. 13377 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13378 switch (revokeResult) { 13379 case PERMISSION_OPERATION_SUCCESS: { 13380 writeRuntimePermissions = true; 13381 } break; 13382 13383 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13384 writeRuntimePermissions = true; 13385 final int appId = ps.appId; 13386 mHandler.post(new Runnable() { 13387 @Override 13388 public void run() { 13389 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13390 } 13391 }); 13392 } break; 13393 } 13394 } 13395 } 13396 13397 // Synchronously write as we are taking permissions away. 13398 if (writeRuntimePermissions) { 13399 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13400 } 13401 13402 // Synchronously write as we are taking permissions away. 13403 if (writeInstallPermissions) { 13404 mSettings.writeLPr(); 13405 } 13406 } 13407 13408 /** 13409 * Remove entries from the keystore daemon. Will only remove it if the 13410 * {@code appId} is valid. 13411 */ 13412 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13413 if (appId < 0) { 13414 return; 13415 } 13416 13417 final KeyStore keyStore = KeyStore.getInstance(); 13418 if (keyStore != null) { 13419 if (userId == UserHandle.USER_ALL) { 13420 for (final int individual : sUserManager.getUserIds()) { 13421 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13422 } 13423 } else { 13424 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13425 } 13426 } else { 13427 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13428 } 13429 } 13430 13431 @Override 13432 public void deleteApplicationCacheFiles(final String packageName, 13433 final IPackageDataObserver observer) { 13434 mContext.enforceCallingOrSelfPermission( 13435 android.Manifest.permission.DELETE_CACHE_FILES, null); 13436 // Queue up an async operation since the package deletion may take a little while. 13437 final int userId = UserHandle.getCallingUserId(); 13438 mHandler.post(new Runnable() { 13439 public void run() { 13440 mHandler.removeCallbacks(this); 13441 final boolean succeded; 13442 synchronized (mInstallLock) { 13443 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13444 } 13445 clearExternalStorageDataSync(packageName, userId, false); 13446 if (observer != null) { 13447 try { 13448 observer.onRemoveCompleted(packageName, succeded); 13449 } catch (RemoteException e) { 13450 Log.i(TAG, "Observer no longer exists."); 13451 } 13452 } //end if observer 13453 } //end run 13454 }); 13455 } 13456 13457 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13458 if (packageName == null) { 13459 Slog.w(TAG, "Attempt to delete null packageName."); 13460 return false; 13461 } 13462 PackageParser.Package p; 13463 synchronized (mPackages) { 13464 p = mPackages.get(packageName); 13465 } 13466 if (p == null) { 13467 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13468 return false; 13469 } 13470 final ApplicationInfo applicationInfo = p.applicationInfo; 13471 if (applicationInfo == null) { 13472 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13473 return false; 13474 } 13475 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13476 if (retCode < 0) { 13477 Slog.w(TAG, "Couldn't remove cache files for package: " 13478 + packageName + " u" + userId); 13479 return false; 13480 } 13481 return true; 13482 } 13483 13484 @Override 13485 public void getPackageSizeInfo(final String packageName, int userHandle, 13486 final IPackageStatsObserver observer) { 13487 mContext.enforceCallingOrSelfPermission( 13488 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13489 if (packageName == null) { 13490 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13491 } 13492 13493 PackageStats stats = new PackageStats(packageName, userHandle); 13494 13495 /* 13496 * Queue up an async operation since the package measurement may take a 13497 * little while. 13498 */ 13499 Message msg = mHandler.obtainMessage(INIT_COPY); 13500 msg.obj = new MeasureParams(stats, observer); 13501 mHandler.sendMessage(msg); 13502 } 13503 13504 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13505 PackageStats pStats) { 13506 if (packageName == null) { 13507 Slog.w(TAG, "Attempt to get size of null packageName."); 13508 return false; 13509 } 13510 PackageParser.Package p; 13511 boolean dataOnly = false; 13512 String libDirRoot = null; 13513 String asecPath = null; 13514 PackageSetting ps = null; 13515 synchronized (mPackages) { 13516 p = mPackages.get(packageName); 13517 ps = mSettings.mPackages.get(packageName); 13518 if(p == null) { 13519 dataOnly = true; 13520 if((ps == null) || (ps.pkg == null)) { 13521 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13522 return false; 13523 } 13524 p = ps.pkg; 13525 } 13526 if (ps != null) { 13527 libDirRoot = ps.legacyNativeLibraryPathString; 13528 } 13529 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13530 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13531 if (secureContainerId != null) { 13532 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13533 } 13534 } 13535 } 13536 String publicSrcDir = null; 13537 if(!dataOnly) { 13538 final ApplicationInfo applicationInfo = p.applicationInfo; 13539 if (applicationInfo == null) { 13540 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13541 return false; 13542 } 13543 if (p.isForwardLocked()) { 13544 publicSrcDir = applicationInfo.getBaseResourcePath(); 13545 } 13546 } 13547 // TODO: extend to measure size of split APKs 13548 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13549 // not just the first level. 13550 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13551 // just the primary. 13552 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13553 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13554 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13555 if (res < 0) { 13556 return false; 13557 } 13558 13559 // Fix-up for forward-locked applications in ASEC containers. 13560 if (!isExternal(p)) { 13561 pStats.codeSize += pStats.externalCodeSize; 13562 pStats.externalCodeSize = 0L; 13563 } 13564 13565 return true; 13566 } 13567 13568 13569 @Override 13570 public void addPackageToPreferred(String packageName) { 13571 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13572 } 13573 13574 @Override 13575 public void removePackageFromPreferred(String packageName) { 13576 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13577 } 13578 13579 @Override 13580 public List<PackageInfo> getPreferredPackages(int flags) { 13581 return new ArrayList<PackageInfo>(); 13582 } 13583 13584 private int getUidTargetSdkVersionLockedLPr(int uid) { 13585 Object obj = mSettings.getUserIdLPr(uid); 13586 if (obj instanceof SharedUserSetting) { 13587 final SharedUserSetting sus = (SharedUserSetting) obj; 13588 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13589 final Iterator<PackageSetting> it = sus.packages.iterator(); 13590 while (it.hasNext()) { 13591 final PackageSetting ps = it.next(); 13592 if (ps.pkg != null) { 13593 int v = ps.pkg.applicationInfo.targetSdkVersion; 13594 if (v < vers) vers = v; 13595 } 13596 } 13597 return vers; 13598 } else if (obj instanceof PackageSetting) { 13599 final PackageSetting ps = (PackageSetting) obj; 13600 if (ps.pkg != null) { 13601 return ps.pkg.applicationInfo.targetSdkVersion; 13602 } 13603 } 13604 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13605 } 13606 13607 @Override 13608 public void addPreferredActivity(IntentFilter filter, int match, 13609 ComponentName[] set, ComponentName activity, int userId) { 13610 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13611 "Adding preferred"); 13612 } 13613 13614 private void addPreferredActivityInternal(IntentFilter filter, int match, 13615 ComponentName[] set, ComponentName activity, boolean always, int userId, 13616 String opname) { 13617 // writer 13618 int callingUid = Binder.getCallingUid(); 13619 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13620 if (filter.countActions() == 0) { 13621 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13622 return; 13623 } 13624 synchronized (mPackages) { 13625 if (mContext.checkCallingOrSelfPermission( 13626 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13627 != PackageManager.PERMISSION_GRANTED) { 13628 if (getUidTargetSdkVersionLockedLPr(callingUid) 13629 < Build.VERSION_CODES.FROYO) { 13630 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13631 + callingUid); 13632 return; 13633 } 13634 mContext.enforceCallingOrSelfPermission( 13635 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13636 } 13637 13638 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13639 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13640 + userId + ":"); 13641 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13642 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13643 scheduleWritePackageRestrictionsLocked(userId); 13644 } 13645 } 13646 13647 @Override 13648 public void replacePreferredActivity(IntentFilter filter, int match, 13649 ComponentName[] set, ComponentName activity, int userId) { 13650 if (filter.countActions() != 1) { 13651 throw new IllegalArgumentException( 13652 "replacePreferredActivity expects filter to have only 1 action."); 13653 } 13654 if (filter.countDataAuthorities() != 0 13655 || filter.countDataPaths() != 0 13656 || filter.countDataSchemes() > 1 13657 || filter.countDataTypes() != 0) { 13658 throw new IllegalArgumentException( 13659 "replacePreferredActivity expects filter to have no data authorities, " + 13660 "paths, or types; and at most one scheme."); 13661 } 13662 13663 final int callingUid = Binder.getCallingUid(); 13664 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13665 synchronized (mPackages) { 13666 if (mContext.checkCallingOrSelfPermission( 13667 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13668 != PackageManager.PERMISSION_GRANTED) { 13669 if (getUidTargetSdkVersionLockedLPr(callingUid) 13670 < Build.VERSION_CODES.FROYO) { 13671 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13672 + Binder.getCallingUid()); 13673 return; 13674 } 13675 mContext.enforceCallingOrSelfPermission( 13676 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13677 } 13678 13679 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13680 if (pir != null) { 13681 // Get all of the existing entries that exactly match this filter. 13682 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13683 if (existing != null && existing.size() == 1) { 13684 PreferredActivity cur = existing.get(0); 13685 if (DEBUG_PREFERRED) { 13686 Slog.i(TAG, "Checking replace of preferred:"); 13687 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13688 if (!cur.mPref.mAlways) { 13689 Slog.i(TAG, " -- CUR; not mAlways!"); 13690 } else { 13691 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13692 Slog.i(TAG, " -- CUR: mSet=" 13693 + Arrays.toString(cur.mPref.mSetComponents)); 13694 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13695 Slog.i(TAG, " -- NEW: mMatch=" 13696 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13697 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13698 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13699 } 13700 } 13701 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13702 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13703 && cur.mPref.sameSet(set)) { 13704 // Setting the preferred activity to what it happens to be already 13705 if (DEBUG_PREFERRED) { 13706 Slog.i(TAG, "Replacing with same preferred activity " 13707 + cur.mPref.mShortComponent + " for user " 13708 + userId + ":"); 13709 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13710 } 13711 return; 13712 } 13713 } 13714 13715 if (existing != null) { 13716 if (DEBUG_PREFERRED) { 13717 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13718 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13719 } 13720 for (int i = 0; i < existing.size(); i++) { 13721 PreferredActivity pa = existing.get(i); 13722 if (DEBUG_PREFERRED) { 13723 Slog.i(TAG, "Removing existing preferred activity " 13724 + pa.mPref.mComponent + ":"); 13725 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13726 } 13727 pir.removeFilter(pa); 13728 } 13729 } 13730 } 13731 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13732 "Replacing preferred"); 13733 } 13734 } 13735 13736 @Override 13737 public void clearPackagePreferredActivities(String packageName) { 13738 final int uid = Binder.getCallingUid(); 13739 // writer 13740 synchronized (mPackages) { 13741 PackageParser.Package pkg = mPackages.get(packageName); 13742 if (pkg == null || pkg.applicationInfo.uid != uid) { 13743 if (mContext.checkCallingOrSelfPermission( 13744 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13745 != PackageManager.PERMISSION_GRANTED) { 13746 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13747 < Build.VERSION_CODES.FROYO) { 13748 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13749 + Binder.getCallingUid()); 13750 return; 13751 } 13752 mContext.enforceCallingOrSelfPermission( 13753 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13754 } 13755 } 13756 13757 int user = UserHandle.getCallingUserId(); 13758 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13759 scheduleWritePackageRestrictionsLocked(user); 13760 } 13761 } 13762 } 13763 13764 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13765 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13766 ArrayList<PreferredActivity> removed = null; 13767 boolean changed = false; 13768 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13769 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13770 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13771 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13772 continue; 13773 } 13774 Iterator<PreferredActivity> it = pir.filterIterator(); 13775 while (it.hasNext()) { 13776 PreferredActivity pa = it.next(); 13777 // Mark entry for removal only if it matches the package name 13778 // and the entry is of type "always". 13779 if (packageName == null || 13780 (pa.mPref.mComponent.getPackageName().equals(packageName) 13781 && pa.mPref.mAlways)) { 13782 if (removed == null) { 13783 removed = new ArrayList<PreferredActivity>(); 13784 } 13785 removed.add(pa); 13786 } 13787 } 13788 if (removed != null) { 13789 for (int j=0; j<removed.size(); j++) { 13790 PreferredActivity pa = removed.get(j); 13791 pir.removeFilter(pa); 13792 } 13793 changed = true; 13794 } 13795 } 13796 return changed; 13797 } 13798 13799 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13800 private void clearIntentFilterVerificationsLPw(int userId) { 13801 final int packageCount = mPackages.size(); 13802 for (int i = 0; i < packageCount; i++) { 13803 PackageParser.Package pkg = mPackages.valueAt(i); 13804 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13805 } 13806 } 13807 13808 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13809 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13810 if (userId == UserHandle.USER_ALL) { 13811 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13812 sUserManager.getUserIds())) { 13813 for (int oneUserId : sUserManager.getUserIds()) { 13814 scheduleWritePackageRestrictionsLocked(oneUserId); 13815 } 13816 } 13817 } else { 13818 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13819 scheduleWritePackageRestrictionsLocked(userId); 13820 } 13821 } 13822 } 13823 13824 void clearDefaultBrowserIfNeeded(String packageName) { 13825 for (int oneUserId : sUserManager.getUserIds()) { 13826 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13827 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13828 if (packageName.equals(defaultBrowserPackageName)) { 13829 setDefaultBrowserPackageName(null, oneUserId); 13830 } 13831 } 13832 } 13833 13834 @Override 13835 public void resetApplicationPreferences(int userId) { 13836 mContext.enforceCallingOrSelfPermission( 13837 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13838 // writer 13839 synchronized (mPackages) { 13840 final long identity = Binder.clearCallingIdentity(); 13841 try { 13842 clearPackagePreferredActivitiesLPw(null, userId); 13843 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13844 // TODO: We have to reset the default SMS and Phone. This requires 13845 // significant refactoring to keep all default apps in the package 13846 // manager (cleaner but more work) or have the services provide 13847 // callbacks to the package manager to request a default app reset. 13848 applyFactoryDefaultBrowserLPw(userId); 13849 clearIntentFilterVerificationsLPw(userId); 13850 primeDomainVerificationsLPw(userId); 13851 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 13852 scheduleWritePackageRestrictionsLocked(userId); 13853 } finally { 13854 Binder.restoreCallingIdentity(identity); 13855 } 13856 } 13857 } 13858 13859 @Override 13860 public int getPreferredActivities(List<IntentFilter> outFilters, 13861 List<ComponentName> outActivities, String packageName) { 13862 13863 int num = 0; 13864 final int userId = UserHandle.getCallingUserId(); 13865 // reader 13866 synchronized (mPackages) { 13867 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13868 if (pir != null) { 13869 final Iterator<PreferredActivity> it = pir.filterIterator(); 13870 while (it.hasNext()) { 13871 final PreferredActivity pa = it.next(); 13872 if (packageName == null 13873 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13874 && pa.mPref.mAlways)) { 13875 if (outFilters != null) { 13876 outFilters.add(new IntentFilter(pa)); 13877 } 13878 if (outActivities != null) { 13879 outActivities.add(pa.mPref.mComponent); 13880 } 13881 } 13882 } 13883 } 13884 } 13885 13886 return num; 13887 } 13888 13889 @Override 13890 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13891 int userId) { 13892 int callingUid = Binder.getCallingUid(); 13893 if (callingUid != Process.SYSTEM_UID) { 13894 throw new SecurityException( 13895 "addPersistentPreferredActivity can only be run by the system"); 13896 } 13897 if (filter.countActions() == 0) { 13898 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13899 return; 13900 } 13901 synchronized (mPackages) { 13902 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13903 " :"); 13904 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13905 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13906 new PersistentPreferredActivity(filter, activity)); 13907 scheduleWritePackageRestrictionsLocked(userId); 13908 } 13909 } 13910 13911 @Override 13912 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13913 int callingUid = Binder.getCallingUid(); 13914 if (callingUid != Process.SYSTEM_UID) { 13915 throw new SecurityException( 13916 "clearPackagePersistentPreferredActivities can only be run by the system"); 13917 } 13918 ArrayList<PersistentPreferredActivity> removed = null; 13919 boolean changed = false; 13920 synchronized (mPackages) { 13921 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13922 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13923 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13924 .valueAt(i); 13925 if (userId != thisUserId) { 13926 continue; 13927 } 13928 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13929 while (it.hasNext()) { 13930 PersistentPreferredActivity ppa = it.next(); 13931 // Mark entry for removal only if it matches the package name. 13932 if (ppa.mComponent.getPackageName().equals(packageName)) { 13933 if (removed == null) { 13934 removed = new ArrayList<PersistentPreferredActivity>(); 13935 } 13936 removed.add(ppa); 13937 } 13938 } 13939 if (removed != null) { 13940 for (int j=0; j<removed.size(); j++) { 13941 PersistentPreferredActivity ppa = removed.get(j); 13942 ppir.removeFilter(ppa); 13943 } 13944 changed = true; 13945 } 13946 } 13947 13948 if (changed) { 13949 scheduleWritePackageRestrictionsLocked(userId); 13950 } 13951 } 13952 } 13953 13954 /** 13955 * Common machinery for picking apart a restored XML blob and passing 13956 * it to a caller-supplied functor to be applied to the running system. 13957 */ 13958 private void restoreFromXml(XmlPullParser parser, int userId, 13959 String expectedStartTag, BlobXmlRestorer functor) 13960 throws IOException, XmlPullParserException { 13961 int type; 13962 while ((type = parser.next()) != XmlPullParser.START_TAG 13963 && type != XmlPullParser.END_DOCUMENT) { 13964 } 13965 if (type != XmlPullParser.START_TAG) { 13966 // oops didn't find a start tag?! 13967 if (DEBUG_BACKUP) { 13968 Slog.e(TAG, "Didn't find start tag during restore"); 13969 } 13970 return; 13971 } 13972 13973 // this is supposed to be TAG_PREFERRED_BACKUP 13974 if (!expectedStartTag.equals(parser.getName())) { 13975 if (DEBUG_BACKUP) { 13976 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13977 } 13978 return; 13979 } 13980 13981 // skip interfering stuff, then we're aligned with the backing implementation 13982 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13983 functor.apply(parser, userId); 13984 } 13985 13986 private interface BlobXmlRestorer { 13987 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13988 } 13989 13990 /** 13991 * Non-Binder method, support for the backup/restore mechanism: write the 13992 * full set of preferred activities in its canonical XML format. Returns the 13993 * XML output as a byte array, or null if there is none. 13994 */ 13995 @Override 13996 public byte[] getPreferredActivityBackup(int userId) { 13997 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13998 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13999 } 14000 14001 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14002 try { 14003 final XmlSerializer serializer = new FastXmlSerializer(); 14004 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14005 serializer.startDocument(null, true); 14006 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14007 14008 synchronized (mPackages) { 14009 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14010 } 14011 14012 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14013 serializer.endDocument(); 14014 serializer.flush(); 14015 } catch (Exception e) { 14016 if (DEBUG_BACKUP) { 14017 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14018 } 14019 return null; 14020 } 14021 14022 return dataStream.toByteArray(); 14023 } 14024 14025 @Override 14026 public void restorePreferredActivities(byte[] backup, int userId) { 14027 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14028 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14029 } 14030 14031 try { 14032 final XmlPullParser parser = Xml.newPullParser(); 14033 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14034 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14035 new BlobXmlRestorer() { 14036 @Override 14037 public void apply(XmlPullParser parser, int userId) 14038 throws XmlPullParserException, IOException { 14039 synchronized (mPackages) { 14040 mSettings.readPreferredActivitiesLPw(parser, userId); 14041 } 14042 } 14043 } ); 14044 } catch (Exception e) { 14045 if (DEBUG_BACKUP) { 14046 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14047 } 14048 } 14049 } 14050 14051 /** 14052 * Non-Binder method, support for the backup/restore mechanism: write the 14053 * default browser (etc) settings in its canonical XML format. Returns the default 14054 * browser XML representation as a byte array, or null if there is none. 14055 */ 14056 @Override 14057 public byte[] getDefaultAppsBackup(int userId) { 14058 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14059 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14060 } 14061 14062 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14063 try { 14064 final XmlSerializer serializer = new FastXmlSerializer(); 14065 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14066 serializer.startDocument(null, true); 14067 serializer.startTag(null, TAG_DEFAULT_APPS); 14068 14069 synchronized (mPackages) { 14070 mSettings.writeDefaultAppsLPr(serializer, userId); 14071 } 14072 14073 serializer.endTag(null, TAG_DEFAULT_APPS); 14074 serializer.endDocument(); 14075 serializer.flush(); 14076 } catch (Exception e) { 14077 if (DEBUG_BACKUP) { 14078 Slog.e(TAG, "Unable to write default apps for backup", e); 14079 } 14080 return null; 14081 } 14082 14083 return dataStream.toByteArray(); 14084 } 14085 14086 @Override 14087 public void restoreDefaultApps(byte[] backup, int userId) { 14088 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14089 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14090 } 14091 14092 try { 14093 final XmlPullParser parser = Xml.newPullParser(); 14094 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14095 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14096 new BlobXmlRestorer() { 14097 @Override 14098 public void apply(XmlPullParser parser, int userId) 14099 throws XmlPullParserException, IOException { 14100 synchronized (mPackages) { 14101 mSettings.readDefaultAppsLPw(parser, userId); 14102 } 14103 } 14104 } ); 14105 } catch (Exception e) { 14106 if (DEBUG_BACKUP) { 14107 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14108 } 14109 } 14110 } 14111 14112 @Override 14113 public byte[] getIntentFilterVerificationBackup(int userId) { 14114 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14115 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14116 } 14117 14118 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14119 try { 14120 final XmlSerializer serializer = new FastXmlSerializer(); 14121 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14122 serializer.startDocument(null, true); 14123 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14124 14125 synchronized (mPackages) { 14126 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14127 } 14128 14129 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14130 serializer.endDocument(); 14131 serializer.flush(); 14132 } catch (Exception e) { 14133 if (DEBUG_BACKUP) { 14134 Slog.e(TAG, "Unable to write default apps for backup", e); 14135 } 14136 return null; 14137 } 14138 14139 return dataStream.toByteArray(); 14140 } 14141 14142 @Override 14143 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14144 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14145 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14146 } 14147 14148 try { 14149 final XmlPullParser parser = Xml.newPullParser(); 14150 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14151 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14152 new BlobXmlRestorer() { 14153 @Override 14154 public void apply(XmlPullParser parser, int userId) 14155 throws XmlPullParserException, IOException { 14156 synchronized (mPackages) { 14157 mSettings.readAllDomainVerificationsLPr(parser, userId); 14158 mSettings.writeLPr(); 14159 } 14160 } 14161 } ); 14162 } catch (Exception e) { 14163 if (DEBUG_BACKUP) { 14164 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14165 } 14166 } 14167 } 14168 14169 @Override 14170 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14171 int sourceUserId, int targetUserId, int flags) { 14172 mContext.enforceCallingOrSelfPermission( 14173 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14174 int callingUid = Binder.getCallingUid(); 14175 enforceOwnerRights(ownerPackage, callingUid); 14176 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14177 if (intentFilter.countActions() == 0) { 14178 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14179 return; 14180 } 14181 synchronized (mPackages) { 14182 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14183 ownerPackage, targetUserId, flags); 14184 CrossProfileIntentResolver resolver = 14185 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14186 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14187 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14188 if (existing != null) { 14189 int size = existing.size(); 14190 for (int i = 0; i < size; i++) { 14191 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14192 return; 14193 } 14194 } 14195 } 14196 resolver.addFilter(newFilter); 14197 scheduleWritePackageRestrictionsLocked(sourceUserId); 14198 } 14199 } 14200 14201 @Override 14202 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14203 mContext.enforceCallingOrSelfPermission( 14204 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14205 int callingUid = Binder.getCallingUid(); 14206 enforceOwnerRights(ownerPackage, callingUid); 14207 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14208 synchronized (mPackages) { 14209 CrossProfileIntentResolver resolver = 14210 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14211 ArraySet<CrossProfileIntentFilter> set = 14212 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14213 for (CrossProfileIntentFilter filter : set) { 14214 if (filter.getOwnerPackage().equals(ownerPackage)) { 14215 resolver.removeFilter(filter); 14216 } 14217 } 14218 scheduleWritePackageRestrictionsLocked(sourceUserId); 14219 } 14220 } 14221 14222 // Enforcing that callingUid is owning pkg on userId 14223 private void enforceOwnerRights(String pkg, int callingUid) { 14224 // The system owns everything. 14225 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14226 return; 14227 } 14228 int callingUserId = UserHandle.getUserId(callingUid); 14229 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14230 if (pi == null) { 14231 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14232 + callingUserId); 14233 } 14234 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14235 throw new SecurityException("Calling uid " + callingUid 14236 + " does not own package " + pkg); 14237 } 14238 } 14239 14240 @Override 14241 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14242 Intent intent = new Intent(Intent.ACTION_MAIN); 14243 intent.addCategory(Intent.CATEGORY_HOME); 14244 14245 final int callingUserId = UserHandle.getCallingUserId(); 14246 List<ResolveInfo> list = queryIntentActivities(intent, null, 14247 PackageManager.GET_META_DATA, callingUserId); 14248 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14249 true, false, false, callingUserId); 14250 14251 allHomeCandidates.clear(); 14252 if (list != null) { 14253 for (ResolveInfo ri : list) { 14254 allHomeCandidates.add(ri); 14255 } 14256 } 14257 return (preferred == null || preferred.activityInfo == null) 14258 ? null 14259 : new ComponentName(preferred.activityInfo.packageName, 14260 preferred.activityInfo.name); 14261 } 14262 14263 @Override 14264 public void setApplicationEnabledSetting(String appPackageName, 14265 int newState, int flags, int userId, String callingPackage) { 14266 if (!sUserManager.exists(userId)) return; 14267 if (callingPackage == null) { 14268 callingPackage = Integer.toString(Binder.getCallingUid()); 14269 } 14270 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14271 } 14272 14273 @Override 14274 public void setComponentEnabledSetting(ComponentName componentName, 14275 int newState, int flags, int userId) { 14276 if (!sUserManager.exists(userId)) return; 14277 setEnabledSetting(componentName.getPackageName(), 14278 componentName.getClassName(), newState, flags, userId, null); 14279 } 14280 14281 private void setEnabledSetting(final String packageName, String className, int newState, 14282 final int flags, int userId, String callingPackage) { 14283 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14284 || newState == COMPONENT_ENABLED_STATE_ENABLED 14285 || newState == COMPONENT_ENABLED_STATE_DISABLED 14286 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14287 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14288 throw new IllegalArgumentException("Invalid new component state: " 14289 + newState); 14290 } 14291 PackageSetting pkgSetting; 14292 final int uid = Binder.getCallingUid(); 14293 final int permission = mContext.checkCallingOrSelfPermission( 14294 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14295 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14296 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14297 boolean sendNow = false; 14298 boolean isApp = (className == null); 14299 String componentName = isApp ? packageName : className; 14300 int packageUid = -1; 14301 ArrayList<String> components; 14302 14303 // writer 14304 synchronized (mPackages) { 14305 pkgSetting = mSettings.mPackages.get(packageName); 14306 if (pkgSetting == null) { 14307 if (className == null) { 14308 throw new IllegalArgumentException( 14309 "Unknown package: " + packageName); 14310 } 14311 throw new IllegalArgumentException( 14312 "Unknown component: " + packageName 14313 + "/" + className); 14314 } 14315 // Allow root and verify that userId is not being specified by a different user 14316 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14317 throw new SecurityException( 14318 "Permission Denial: attempt to change component state from pid=" 14319 + Binder.getCallingPid() 14320 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14321 } 14322 if (className == null) { 14323 // We're dealing with an application/package level state change 14324 if (pkgSetting.getEnabled(userId) == newState) { 14325 // Nothing to do 14326 return; 14327 } 14328 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14329 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14330 // Don't care about who enables an app. 14331 callingPackage = null; 14332 } 14333 pkgSetting.setEnabled(newState, userId, callingPackage); 14334 // pkgSetting.pkg.mSetEnabled = newState; 14335 } else { 14336 // We're dealing with a component level state change 14337 // First, verify that this is a valid class name. 14338 PackageParser.Package pkg = pkgSetting.pkg; 14339 if (pkg == null || !pkg.hasComponentClassName(className)) { 14340 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14341 throw new IllegalArgumentException("Component class " + className 14342 + " does not exist in " + packageName); 14343 } else { 14344 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14345 + className + " does not exist in " + packageName); 14346 } 14347 } 14348 switch (newState) { 14349 case COMPONENT_ENABLED_STATE_ENABLED: 14350 if (!pkgSetting.enableComponentLPw(className, userId)) { 14351 return; 14352 } 14353 break; 14354 case COMPONENT_ENABLED_STATE_DISABLED: 14355 if (!pkgSetting.disableComponentLPw(className, userId)) { 14356 return; 14357 } 14358 break; 14359 case COMPONENT_ENABLED_STATE_DEFAULT: 14360 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14361 return; 14362 } 14363 break; 14364 default: 14365 Slog.e(TAG, "Invalid new component state: " + newState); 14366 return; 14367 } 14368 } 14369 scheduleWritePackageRestrictionsLocked(userId); 14370 components = mPendingBroadcasts.get(userId, packageName); 14371 final boolean newPackage = components == null; 14372 if (newPackage) { 14373 components = new ArrayList<String>(); 14374 } 14375 if (!components.contains(componentName)) { 14376 components.add(componentName); 14377 } 14378 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14379 sendNow = true; 14380 // Purge entry from pending broadcast list if another one exists already 14381 // since we are sending one right away. 14382 mPendingBroadcasts.remove(userId, packageName); 14383 } else { 14384 if (newPackage) { 14385 mPendingBroadcasts.put(userId, packageName, components); 14386 } 14387 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14388 // Schedule a message 14389 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14390 } 14391 } 14392 } 14393 14394 long callingId = Binder.clearCallingIdentity(); 14395 try { 14396 if (sendNow) { 14397 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14398 sendPackageChangedBroadcast(packageName, 14399 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14400 } 14401 } finally { 14402 Binder.restoreCallingIdentity(callingId); 14403 } 14404 } 14405 14406 private void sendPackageChangedBroadcast(String packageName, 14407 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14408 if (DEBUG_INSTALL) 14409 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14410 + componentNames); 14411 Bundle extras = new Bundle(4); 14412 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14413 String nameList[] = new String[componentNames.size()]; 14414 componentNames.toArray(nameList); 14415 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14416 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14417 extras.putInt(Intent.EXTRA_UID, packageUid); 14418 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14419 new int[] {UserHandle.getUserId(packageUid)}); 14420 } 14421 14422 @Override 14423 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14424 if (!sUserManager.exists(userId)) return; 14425 final int uid = Binder.getCallingUid(); 14426 final int permission = mContext.checkCallingOrSelfPermission( 14427 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14428 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14429 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14430 // writer 14431 synchronized (mPackages) { 14432 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14433 allowedByPermission, uid, userId)) { 14434 scheduleWritePackageRestrictionsLocked(userId); 14435 } 14436 } 14437 } 14438 14439 @Override 14440 public String getInstallerPackageName(String packageName) { 14441 // reader 14442 synchronized (mPackages) { 14443 return mSettings.getInstallerPackageNameLPr(packageName); 14444 } 14445 } 14446 14447 @Override 14448 public int getApplicationEnabledSetting(String packageName, int userId) { 14449 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14450 int uid = Binder.getCallingUid(); 14451 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14452 // reader 14453 synchronized (mPackages) { 14454 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14455 } 14456 } 14457 14458 @Override 14459 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14460 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14461 int uid = Binder.getCallingUid(); 14462 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14463 // reader 14464 synchronized (mPackages) { 14465 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14466 } 14467 } 14468 14469 @Override 14470 public void enterSafeMode() { 14471 enforceSystemOrRoot("Only the system can request entering safe mode"); 14472 14473 if (!mSystemReady) { 14474 mSafeMode = true; 14475 } 14476 } 14477 14478 @Override 14479 public void systemReady() { 14480 mSystemReady = true; 14481 14482 // Read the compatibilty setting when the system is ready. 14483 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14484 mContext.getContentResolver(), 14485 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14486 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14487 if (DEBUG_SETTINGS) { 14488 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14489 } 14490 14491 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14492 14493 synchronized (mPackages) { 14494 // Verify that all of the preferred activity components actually 14495 // exist. It is possible for applications to be updated and at 14496 // that point remove a previously declared activity component that 14497 // had been set as a preferred activity. We try to clean this up 14498 // the next time we encounter that preferred activity, but it is 14499 // possible for the user flow to never be able to return to that 14500 // situation so here we do a sanity check to make sure we haven't 14501 // left any junk around. 14502 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14503 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14504 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14505 removed.clear(); 14506 for (PreferredActivity pa : pir.filterSet()) { 14507 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14508 removed.add(pa); 14509 } 14510 } 14511 if (removed.size() > 0) { 14512 for (int r=0; r<removed.size(); r++) { 14513 PreferredActivity pa = removed.get(r); 14514 Slog.w(TAG, "Removing dangling preferred activity: " 14515 + pa.mPref.mComponent); 14516 pir.removeFilter(pa); 14517 } 14518 mSettings.writePackageRestrictionsLPr( 14519 mSettings.mPreferredActivities.keyAt(i)); 14520 } 14521 } 14522 14523 for (int userId : UserManagerService.getInstance().getUserIds()) { 14524 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14525 grantPermissionsUserIds = ArrayUtils.appendInt( 14526 grantPermissionsUserIds, userId); 14527 } 14528 } 14529 } 14530 sUserManager.systemReady(); 14531 14532 // If we upgraded grant all default permissions before kicking off. 14533 for (int userId : grantPermissionsUserIds) { 14534 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14535 } 14536 14537 // Kick off any messages waiting for system ready 14538 if (mPostSystemReadyMessages != null) { 14539 for (Message msg : mPostSystemReadyMessages) { 14540 msg.sendToTarget(); 14541 } 14542 mPostSystemReadyMessages = null; 14543 } 14544 14545 // Watch for external volumes that come and go over time 14546 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14547 storage.registerListener(mStorageListener); 14548 14549 mInstallerService.systemReady(); 14550 mPackageDexOptimizer.systemReady(); 14551 14552 MountServiceInternal mountServiceInternal = LocalServices.getService( 14553 MountServiceInternal.class); 14554 mountServiceInternal.addExternalStoragePolicy( 14555 new MountServiceInternal.ExternalStorageMountPolicy() { 14556 @Override 14557 public int getMountMode(int uid, String packageName) { 14558 if (Process.isIsolated(uid)) { 14559 return Zygote.MOUNT_EXTERNAL_NONE; 14560 } 14561 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14562 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14563 } 14564 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14565 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14566 } 14567 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14568 return Zygote.MOUNT_EXTERNAL_READ; 14569 } 14570 return Zygote.MOUNT_EXTERNAL_WRITE; 14571 } 14572 14573 @Override 14574 public boolean hasExternalStorage(int uid, String packageName) { 14575 return true; 14576 } 14577 }); 14578 } 14579 14580 @Override 14581 public boolean isSafeMode() { 14582 return mSafeMode; 14583 } 14584 14585 @Override 14586 public boolean hasSystemUidErrors() { 14587 return mHasSystemUidErrors; 14588 } 14589 14590 static String arrayToString(int[] array) { 14591 StringBuffer buf = new StringBuffer(128); 14592 buf.append('['); 14593 if (array != null) { 14594 for (int i=0; i<array.length; i++) { 14595 if (i > 0) buf.append(", "); 14596 buf.append(array[i]); 14597 } 14598 } 14599 buf.append(']'); 14600 return buf.toString(); 14601 } 14602 14603 static class DumpState { 14604 public static final int DUMP_LIBS = 1 << 0; 14605 public static final int DUMP_FEATURES = 1 << 1; 14606 public static final int DUMP_RESOLVERS = 1 << 2; 14607 public static final int DUMP_PERMISSIONS = 1 << 3; 14608 public static final int DUMP_PACKAGES = 1 << 4; 14609 public static final int DUMP_SHARED_USERS = 1 << 5; 14610 public static final int DUMP_MESSAGES = 1 << 6; 14611 public static final int DUMP_PROVIDERS = 1 << 7; 14612 public static final int DUMP_VERIFIERS = 1 << 8; 14613 public static final int DUMP_PREFERRED = 1 << 9; 14614 public static final int DUMP_PREFERRED_XML = 1 << 10; 14615 public static final int DUMP_KEYSETS = 1 << 11; 14616 public static final int DUMP_VERSION = 1 << 12; 14617 public static final int DUMP_INSTALLS = 1 << 13; 14618 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14619 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14620 14621 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14622 14623 private int mTypes; 14624 14625 private int mOptions; 14626 14627 private boolean mTitlePrinted; 14628 14629 private SharedUserSetting mSharedUser; 14630 14631 public boolean isDumping(int type) { 14632 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14633 return true; 14634 } 14635 14636 return (mTypes & type) != 0; 14637 } 14638 14639 public void setDump(int type) { 14640 mTypes |= type; 14641 } 14642 14643 public boolean isOptionEnabled(int option) { 14644 return (mOptions & option) != 0; 14645 } 14646 14647 public void setOptionEnabled(int option) { 14648 mOptions |= option; 14649 } 14650 14651 public boolean onTitlePrinted() { 14652 final boolean printed = mTitlePrinted; 14653 mTitlePrinted = true; 14654 return printed; 14655 } 14656 14657 public boolean getTitlePrinted() { 14658 return mTitlePrinted; 14659 } 14660 14661 public void setTitlePrinted(boolean enabled) { 14662 mTitlePrinted = enabled; 14663 } 14664 14665 public SharedUserSetting getSharedUser() { 14666 return mSharedUser; 14667 } 14668 14669 public void setSharedUser(SharedUserSetting user) { 14670 mSharedUser = user; 14671 } 14672 } 14673 14674 @Override 14675 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14676 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14677 != PackageManager.PERMISSION_GRANTED) { 14678 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14679 + Binder.getCallingPid() 14680 + ", uid=" + Binder.getCallingUid() 14681 + " without permission " 14682 + android.Manifest.permission.DUMP); 14683 return; 14684 } 14685 14686 DumpState dumpState = new DumpState(); 14687 boolean fullPreferred = false; 14688 boolean checkin = false; 14689 14690 String packageName = null; 14691 ArraySet<String> permissionNames = null; 14692 14693 int opti = 0; 14694 while (opti < args.length) { 14695 String opt = args[opti]; 14696 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14697 break; 14698 } 14699 opti++; 14700 14701 if ("-a".equals(opt)) { 14702 // Right now we only know how to print all. 14703 } else if ("-h".equals(opt)) { 14704 pw.println("Package manager dump options:"); 14705 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14706 pw.println(" --checkin: dump for a checkin"); 14707 pw.println(" -f: print details of intent filters"); 14708 pw.println(" -h: print this help"); 14709 pw.println(" cmd may be one of:"); 14710 pw.println(" l[ibraries]: list known shared libraries"); 14711 pw.println(" f[ibraries]: list device features"); 14712 pw.println(" k[eysets]: print known keysets"); 14713 pw.println(" r[esolvers]: dump intent resolvers"); 14714 pw.println(" perm[issions]: dump permissions"); 14715 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14716 pw.println(" pref[erred]: print preferred package settings"); 14717 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14718 pw.println(" prov[iders]: dump content providers"); 14719 pw.println(" p[ackages]: dump installed packages"); 14720 pw.println(" s[hared-users]: dump shared user IDs"); 14721 pw.println(" m[essages]: print collected runtime messages"); 14722 pw.println(" v[erifiers]: print package verifier info"); 14723 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14724 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14725 pw.println(" version: print database version info"); 14726 pw.println(" write: write current settings now"); 14727 pw.println(" installs: details about install sessions"); 14728 pw.println(" <package.name>: info about given package"); 14729 return; 14730 } else if ("--checkin".equals(opt)) { 14731 checkin = true; 14732 } else if ("-f".equals(opt)) { 14733 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14734 } else { 14735 pw.println("Unknown argument: " + opt + "; use -h for help"); 14736 } 14737 } 14738 14739 // Is the caller requesting to dump a particular piece of data? 14740 if (opti < args.length) { 14741 String cmd = args[opti]; 14742 opti++; 14743 // Is this a package name? 14744 if ("android".equals(cmd) || cmd.contains(".")) { 14745 packageName = cmd; 14746 // When dumping a single package, we always dump all of its 14747 // filter information since the amount of data will be reasonable. 14748 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14749 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14750 dumpState.setDump(DumpState.DUMP_LIBS); 14751 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14752 dumpState.setDump(DumpState.DUMP_FEATURES); 14753 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14754 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14755 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14756 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14757 } else if ("permission".equals(cmd)) { 14758 if (opti >= args.length) { 14759 pw.println("Error: permission requires permission name"); 14760 return; 14761 } 14762 permissionNames = new ArraySet<>(); 14763 while (opti < args.length) { 14764 permissionNames.add(args[opti]); 14765 opti++; 14766 } 14767 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14768 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14769 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14770 dumpState.setDump(DumpState.DUMP_PREFERRED); 14771 } else if ("preferred-xml".equals(cmd)) { 14772 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14773 if (opti < args.length && "--full".equals(args[opti])) { 14774 fullPreferred = true; 14775 opti++; 14776 } 14777 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14778 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14779 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14780 dumpState.setDump(DumpState.DUMP_PACKAGES); 14781 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14782 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14783 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14784 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14785 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14786 dumpState.setDump(DumpState.DUMP_MESSAGES); 14787 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14788 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14789 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14790 || "intent-filter-verifiers".equals(cmd)) { 14791 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14792 } else if ("version".equals(cmd)) { 14793 dumpState.setDump(DumpState.DUMP_VERSION); 14794 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14795 dumpState.setDump(DumpState.DUMP_KEYSETS); 14796 } else if ("installs".equals(cmd)) { 14797 dumpState.setDump(DumpState.DUMP_INSTALLS); 14798 } else if ("write".equals(cmd)) { 14799 synchronized (mPackages) { 14800 mSettings.writeLPr(); 14801 pw.println("Settings written."); 14802 return; 14803 } 14804 } 14805 } 14806 14807 if (checkin) { 14808 pw.println("vers,1"); 14809 } 14810 14811 // reader 14812 synchronized (mPackages) { 14813 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14814 if (!checkin) { 14815 if (dumpState.onTitlePrinted()) 14816 pw.println(); 14817 pw.println("Database versions:"); 14818 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 14819 } 14820 } 14821 14822 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14823 if (!checkin) { 14824 if (dumpState.onTitlePrinted()) 14825 pw.println(); 14826 pw.println("Verifiers:"); 14827 pw.print(" Required: "); 14828 pw.print(mRequiredVerifierPackage); 14829 pw.print(" (uid="); 14830 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14831 pw.println(")"); 14832 } else if (mRequiredVerifierPackage != null) { 14833 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14834 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14835 } 14836 } 14837 14838 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14839 packageName == null) { 14840 if (mIntentFilterVerifierComponent != null) { 14841 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14842 if (!checkin) { 14843 if (dumpState.onTitlePrinted()) 14844 pw.println(); 14845 pw.println("Intent Filter Verifier:"); 14846 pw.print(" Using: "); 14847 pw.print(verifierPackageName); 14848 pw.print(" (uid="); 14849 pw.print(getPackageUid(verifierPackageName, 0)); 14850 pw.println(")"); 14851 } else if (verifierPackageName != null) { 14852 pw.print("ifv,"); pw.print(verifierPackageName); 14853 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14854 } 14855 } else { 14856 pw.println(); 14857 pw.println("No Intent Filter Verifier available!"); 14858 } 14859 } 14860 14861 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14862 boolean printedHeader = false; 14863 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14864 while (it.hasNext()) { 14865 String name = it.next(); 14866 SharedLibraryEntry ent = mSharedLibraries.get(name); 14867 if (!checkin) { 14868 if (!printedHeader) { 14869 if (dumpState.onTitlePrinted()) 14870 pw.println(); 14871 pw.println("Libraries:"); 14872 printedHeader = true; 14873 } 14874 pw.print(" "); 14875 } else { 14876 pw.print("lib,"); 14877 } 14878 pw.print(name); 14879 if (!checkin) { 14880 pw.print(" -> "); 14881 } 14882 if (ent.path != null) { 14883 if (!checkin) { 14884 pw.print("(jar) "); 14885 pw.print(ent.path); 14886 } else { 14887 pw.print(",jar,"); 14888 pw.print(ent.path); 14889 } 14890 } else { 14891 if (!checkin) { 14892 pw.print("(apk) "); 14893 pw.print(ent.apk); 14894 } else { 14895 pw.print(",apk,"); 14896 pw.print(ent.apk); 14897 } 14898 } 14899 pw.println(); 14900 } 14901 } 14902 14903 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14904 if (dumpState.onTitlePrinted()) 14905 pw.println(); 14906 if (!checkin) { 14907 pw.println("Features:"); 14908 } 14909 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14910 while (it.hasNext()) { 14911 String name = it.next(); 14912 if (!checkin) { 14913 pw.print(" "); 14914 } else { 14915 pw.print("feat,"); 14916 } 14917 pw.println(name); 14918 } 14919 } 14920 14921 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14922 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14923 : "Activity Resolver Table:", " ", packageName, 14924 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14925 dumpState.setTitlePrinted(true); 14926 } 14927 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14928 : "Receiver Resolver Table:", " ", packageName, 14929 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14930 dumpState.setTitlePrinted(true); 14931 } 14932 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14933 : "Service Resolver Table:", " ", packageName, 14934 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14935 dumpState.setTitlePrinted(true); 14936 } 14937 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14938 : "Provider Resolver Table:", " ", packageName, 14939 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14940 dumpState.setTitlePrinted(true); 14941 } 14942 } 14943 14944 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14945 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14946 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14947 int user = mSettings.mPreferredActivities.keyAt(i); 14948 if (pir.dump(pw, 14949 dumpState.getTitlePrinted() 14950 ? "\nPreferred Activities User " + user + ":" 14951 : "Preferred Activities User " + user + ":", " ", 14952 packageName, true, false)) { 14953 dumpState.setTitlePrinted(true); 14954 } 14955 } 14956 } 14957 14958 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14959 pw.flush(); 14960 FileOutputStream fout = new FileOutputStream(fd); 14961 BufferedOutputStream str = new BufferedOutputStream(fout); 14962 XmlSerializer serializer = new FastXmlSerializer(); 14963 try { 14964 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14965 serializer.startDocument(null, true); 14966 serializer.setFeature( 14967 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14968 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14969 serializer.endDocument(); 14970 serializer.flush(); 14971 } catch (IllegalArgumentException e) { 14972 pw.println("Failed writing: " + e); 14973 } catch (IllegalStateException e) { 14974 pw.println("Failed writing: " + e); 14975 } catch (IOException e) { 14976 pw.println("Failed writing: " + e); 14977 } 14978 } 14979 14980 if (!checkin 14981 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14982 && packageName == null) { 14983 pw.println(); 14984 int count = mSettings.mPackages.size(); 14985 if (count == 0) { 14986 pw.println("No applications!"); 14987 pw.println(); 14988 } else { 14989 final String prefix = " "; 14990 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14991 if (allPackageSettings.size() == 0) { 14992 pw.println("No domain preferred apps!"); 14993 pw.println(); 14994 } else { 14995 pw.println("App verification status:"); 14996 pw.println(); 14997 count = 0; 14998 for (PackageSetting ps : allPackageSettings) { 14999 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15000 if (ivi == null || ivi.getPackageName() == null) continue; 15001 pw.println(prefix + "Package: " + ivi.getPackageName()); 15002 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15003 pw.println(prefix + "Status: " + ivi.getStatusString()); 15004 pw.println(); 15005 count++; 15006 } 15007 if (count == 0) { 15008 pw.println(prefix + "No app verification established."); 15009 pw.println(); 15010 } 15011 for (int userId : sUserManager.getUserIds()) { 15012 pw.println("App linkages for user " + userId + ":"); 15013 pw.println(); 15014 count = 0; 15015 for (PackageSetting ps : allPackageSettings) { 15016 final long status = ps.getDomainVerificationStatusForUser(userId); 15017 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15018 continue; 15019 } 15020 pw.println(prefix + "Package: " + ps.name); 15021 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15022 String statusStr = IntentFilterVerificationInfo. 15023 getStatusStringFromValue(status); 15024 pw.println(prefix + "Status: " + statusStr); 15025 pw.println(); 15026 count++; 15027 } 15028 if (count == 0) { 15029 pw.println(prefix + "No configured app linkages."); 15030 pw.println(); 15031 } 15032 } 15033 } 15034 } 15035 } 15036 15037 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15038 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15039 if (packageName == null && permissionNames == null) { 15040 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15041 if (iperm == 0) { 15042 if (dumpState.onTitlePrinted()) 15043 pw.println(); 15044 pw.println("AppOp Permissions:"); 15045 } 15046 pw.print(" AppOp Permission "); 15047 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15048 pw.println(":"); 15049 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15050 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15051 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15052 } 15053 } 15054 } 15055 } 15056 15057 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15058 boolean printedSomething = false; 15059 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15060 if (packageName != null && !packageName.equals(p.info.packageName)) { 15061 continue; 15062 } 15063 if (!printedSomething) { 15064 if (dumpState.onTitlePrinted()) 15065 pw.println(); 15066 pw.println("Registered ContentProviders:"); 15067 printedSomething = true; 15068 } 15069 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15070 pw.print(" "); pw.println(p.toString()); 15071 } 15072 printedSomething = false; 15073 for (Map.Entry<String, PackageParser.Provider> entry : 15074 mProvidersByAuthority.entrySet()) { 15075 PackageParser.Provider p = entry.getValue(); 15076 if (packageName != null && !packageName.equals(p.info.packageName)) { 15077 continue; 15078 } 15079 if (!printedSomething) { 15080 if (dumpState.onTitlePrinted()) 15081 pw.println(); 15082 pw.println("ContentProvider Authorities:"); 15083 printedSomething = true; 15084 } 15085 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15086 pw.print(" "); pw.println(p.toString()); 15087 if (p.info != null && p.info.applicationInfo != null) { 15088 final String appInfo = p.info.applicationInfo.toString(); 15089 pw.print(" applicationInfo="); pw.println(appInfo); 15090 } 15091 } 15092 } 15093 15094 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15095 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15096 } 15097 15098 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15099 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15100 } 15101 15102 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15103 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15104 } 15105 15106 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15107 // XXX should handle packageName != null by dumping only install data that 15108 // the given package is involved with. 15109 if (dumpState.onTitlePrinted()) pw.println(); 15110 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15111 } 15112 15113 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15114 if (dumpState.onTitlePrinted()) pw.println(); 15115 mSettings.dumpReadMessagesLPr(pw, dumpState); 15116 15117 pw.println(); 15118 pw.println("Package warning messages:"); 15119 BufferedReader in = null; 15120 String line = null; 15121 try { 15122 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15123 while ((line = in.readLine()) != null) { 15124 if (line.contains("ignored: updated version")) continue; 15125 pw.println(line); 15126 } 15127 } catch (IOException ignored) { 15128 } finally { 15129 IoUtils.closeQuietly(in); 15130 } 15131 } 15132 15133 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15134 BufferedReader in = null; 15135 String line = null; 15136 try { 15137 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15138 while ((line = in.readLine()) != null) { 15139 if (line.contains("ignored: updated version")) continue; 15140 pw.print("msg,"); 15141 pw.println(line); 15142 } 15143 } catch (IOException ignored) { 15144 } finally { 15145 IoUtils.closeQuietly(in); 15146 } 15147 } 15148 } 15149 } 15150 15151 private String dumpDomainString(String packageName) { 15152 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15153 List<IntentFilter> filters = getAllIntentFilters(packageName); 15154 15155 ArraySet<String> result = new ArraySet<>(); 15156 if (iviList.size() > 0) { 15157 for (IntentFilterVerificationInfo ivi : iviList) { 15158 for (String host : ivi.getDomains()) { 15159 result.add(host); 15160 } 15161 } 15162 } 15163 if (filters != null && filters.size() > 0) { 15164 for (IntentFilter filter : filters) { 15165 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15166 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15167 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15168 result.addAll(filter.getHostsList()); 15169 } 15170 } 15171 } 15172 15173 StringBuilder sb = new StringBuilder(result.size() * 16); 15174 for (String domain : result) { 15175 if (sb.length() > 0) sb.append(" "); 15176 sb.append(domain); 15177 } 15178 return sb.toString(); 15179 } 15180 15181 // ------- apps on sdcard specific code ------- 15182 static final boolean DEBUG_SD_INSTALL = false; 15183 15184 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15185 15186 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15187 15188 private boolean mMediaMounted = false; 15189 15190 static String getEncryptKey() { 15191 try { 15192 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15193 SD_ENCRYPTION_KEYSTORE_NAME); 15194 if (sdEncKey == null) { 15195 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15196 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15197 if (sdEncKey == null) { 15198 Slog.e(TAG, "Failed to create encryption keys"); 15199 return null; 15200 } 15201 } 15202 return sdEncKey; 15203 } catch (NoSuchAlgorithmException nsae) { 15204 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15205 return null; 15206 } catch (IOException ioe) { 15207 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15208 return null; 15209 } 15210 } 15211 15212 /* 15213 * Update media status on PackageManager. 15214 */ 15215 @Override 15216 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15217 int callingUid = Binder.getCallingUid(); 15218 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15219 throw new SecurityException("Media status can only be updated by the system"); 15220 } 15221 // reader; this apparently protects mMediaMounted, but should probably 15222 // be a different lock in that case. 15223 synchronized (mPackages) { 15224 Log.i(TAG, "Updating external media status from " 15225 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15226 + (mediaStatus ? "mounted" : "unmounted")); 15227 if (DEBUG_SD_INSTALL) 15228 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15229 + ", mMediaMounted=" + mMediaMounted); 15230 if (mediaStatus == mMediaMounted) { 15231 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15232 : 0, -1); 15233 mHandler.sendMessage(msg); 15234 return; 15235 } 15236 mMediaMounted = mediaStatus; 15237 } 15238 // Queue up an async operation since the package installation may take a 15239 // little while. 15240 mHandler.post(new Runnable() { 15241 public void run() { 15242 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15243 } 15244 }); 15245 } 15246 15247 /** 15248 * Called by MountService when the initial ASECs to scan are available. 15249 * Should block until all the ASEC containers are finished being scanned. 15250 */ 15251 public void scanAvailableAsecs() { 15252 updateExternalMediaStatusInner(true, false, false); 15253 if (mShouldRestoreconData) { 15254 SELinuxMMAC.setRestoreconDone(); 15255 mShouldRestoreconData = false; 15256 } 15257 } 15258 15259 /* 15260 * Collect information of applications on external media, map them against 15261 * existing containers and update information based on current mount status. 15262 * Please note that we always have to report status if reportStatus has been 15263 * set to true especially when unloading packages. 15264 */ 15265 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15266 boolean externalStorage) { 15267 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15268 int[] uidArr = EmptyArray.INT; 15269 15270 final String[] list = PackageHelper.getSecureContainerList(); 15271 if (ArrayUtils.isEmpty(list)) { 15272 Log.i(TAG, "No secure containers found"); 15273 } else { 15274 // Process list of secure containers and categorize them 15275 // as active or stale based on their package internal state. 15276 15277 // reader 15278 synchronized (mPackages) { 15279 for (String cid : list) { 15280 // Leave stages untouched for now; installer service owns them 15281 if (PackageInstallerService.isStageName(cid)) continue; 15282 15283 if (DEBUG_SD_INSTALL) 15284 Log.i(TAG, "Processing container " + cid); 15285 String pkgName = getAsecPackageName(cid); 15286 if (pkgName == null) { 15287 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15288 continue; 15289 } 15290 if (DEBUG_SD_INSTALL) 15291 Log.i(TAG, "Looking for pkg : " + pkgName); 15292 15293 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15294 if (ps == null) { 15295 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15296 continue; 15297 } 15298 15299 /* 15300 * Skip packages that are not external if we're unmounting 15301 * external storage. 15302 */ 15303 if (externalStorage && !isMounted && !isExternal(ps)) { 15304 continue; 15305 } 15306 15307 final AsecInstallArgs args = new AsecInstallArgs(cid, 15308 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15309 // The package status is changed only if the code path 15310 // matches between settings and the container id. 15311 if (ps.codePathString != null 15312 && ps.codePathString.startsWith(args.getCodePath())) { 15313 if (DEBUG_SD_INSTALL) { 15314 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15315 + " at code path: " + ps.codePathString); 15316 } 15317 15318 // We do have a valid package installed on sdcard 15319 processCids.put(args, ps.codePathString); 15320 final int uid = ps.appId; 15321 if (uid != -1) { 15322 uidArr = ArrayUtils.appendInt(uidArr, uid); 15323 } 15324 } else { 15325 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15326 + ps.codePathString); 15327 } 15328 } 15329 } 15330 15331 Arrays.sort(uidArr); 15332 } 15333 15334 // Process packages with valid entries. 15335 if (isMounted) { 15336 if (DEBUG_SD_INSTALL) 15337 Log.i(TAG, "Loading packages"); 15338 loadMediaPackages(processCids, uidArr); 15339 startCleaningPackages(); 15340 mInstallerService.onSecureContainersAvailable(); 15341 } else { 15342 if (DEBUG_SD_INSTALL) 15343 Log.i(TAG, "Unloading packages"); 15344 unloadMediaPackages(processCids, uidArr, reportStatus); 15345 } 15346 } 15347 15348 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15349 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15350 final int size = infos.size(); 15351 final String[] packageNames = new String[size]; 15352 final int[] packageUids = new int[size]; 15353 for (int i = 0; i < size; i++) { 15354 final ApplicationInfo info = infos.get(i); 15355 packageNames[i] = info.packageName; 15356 packageUids[i] = info.uid; 15357 } 15358 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15359 finishedReceiver); 15360 } 15361 15362 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15363 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15364 sendResourcesChangedBroadcast(mediaStatus, replacing, 15365 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15366 } 15367 15368 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15369 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15370 int size = pkgList.length; 15371 if (size > 0) { 15372 // Send broadcasts here 15373 Bundle extras = new Bundle(); 15374 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15375 if (uidArr != null) { 15376 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15377 } 15378 if (replacing) { 15379 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15380 } 15381 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15382 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15383 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15384 } 15385 } 15386 15387 /* 15388 * Look at potentially valid container ids from processCids If package 15389 * information doesn't match the one on record or package scanning fails, 15390 * the cid is added to list of removeCids. We currently don't delete stale 15391 * containers. 15392 */ 15393 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15394 ArrayList<String> pkgList = new ArrayList<String>(); 15395 Set<AsecInstallArgs> keys = processCids.keySet(); 15396 15397 for (AsecInstallArgs args : keys) { 15398 String codePath = processCids.get(args); 15399 if (DEBUG_SD_INSTALL) 15400 Log.i(TAG, "Loading container : " + args.cid); 15401 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15402 try { 15403 // Make sure there are no container errors first. 15404 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15405 Slog.e(TAG, "Failed to mount cid : " + args.cid 15406 + " when installing from sdcard"); 15407 continue; 15408 } 15409 // Check code path here. 15410 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15411 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15412 + " does not match one in settings " + codePath); 15413 continue; 15414 } 15415 // Parse package 15416 int parseFlags = mDefParseFlags; 15417 if (args.isExternalAsec()) { 15418 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15419 } 15420 if (args.isFwdLocked()) { 15421 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15422 } 15423 15424 synchronized (mInstallLock) { 15425 PackageParser.Package pkg = null; 15426 try { 15427 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15428 } catch (PackageManagerException e) { 15429 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15430 } 15431 // Scan the package 15432 if (pkg != null) { 15433 /* 15434 * TODO why is the lock being held? doPostInstall is 15435 * called in other places without the lock. This needs 15436 * to be straightened out. 15437 */ 15438 // writer 15439 synchronized (mPackages) { 15440 retCode = PackageManager.INSTALL_SUCCEEDED; 15441 pkgList.add(pkg.packageName); 15442 // Post process args 15443 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15444 pkg.applicationInfo.uid); 15445 } 15446 } else { 15447 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15448 } 15449 } 15450 15451 } finally { 15452 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15453 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15454 } 15455 } 15456 } 15457 // writer 15458 synchronized (mPackages) { 15459 // If the platform SDK has changed since the last time we booted, 15460 // we need to re-grant app permission to catch any new ones that 15461 // appear. This is really a hack, and means that apps can in some 15462 // cases get permissions that the user didn't initially explicitly 15463 // allow... it would be nice to have some better way to handle 15464 // this situation. 15465 final VersionInfo ver = mSettings.getExternalVersion(); 15466 15467 int updateFlags = UPDATE_PERMISSIONS_ALL; 15468 if (ver.sdkVersion != mSdkVersion) { 15469 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15470 + mSdkVersion + "; regranting permissions for external"); 15471 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15472 } 15473 updatePermissionsLPw(null, null, updateFlags); 15474 15475 // Yay, everything is now upgraded 15476 ver.forceCurrent(); 15477 15478 // can downgrade to reader 15479 // Persist settings 15480 mSettings.writeLPr(); 15481 } 15482 // Send a broadcast to let everyone know we are done processing 15483 if (pkgList.size() > 0) { 15484 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15485 } 15486 } 15487 15488 /* 15489 * Utility method to unload a list of specified containers 15490 */ 15491 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15492 // Just unmount all valid containers. 15493 for (AsecInstallArgs arg : cidArgs) { 15494 synchronized (mInstallLock) { 15495 arg.doPostDeleteLI(false); 15496 } 15497 } 15498 } 15499 15500 /* 15501 * Unload packages mounted on external media. This involves deleting package 15502 * data from internal structures, sending broadcasts about diabled packages, 15503 * gc'ing to free up references, unmounting all secure containers 15504 * corresponding to packages on external media, and posting a 15505 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15506 * that we always have to post this message if status has been requested no 15507 * matter what. 15508 */ 15509 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15510 final boolean reportStatus) { 15511 if (DEBUG_SD_INSTALL) 15512 Log.i(TAG, "unloading media packages"); 15513 ArrayList<String> pkgList = new ArrayList<String>(); 15514 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15515 final Set<AsecInstallArgs> keys = processCids.keySet(); 15516 for (AsecInstallArgs args : keys) { 15517 String pkgName = args.getPackageName(); 15518 if (DEBUG_SD_INSTALL) 15519 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15520 // Delete package internally 15521 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15522 synchronized (mInstallLock) { 15523 boolean res = deletePackageLI(pkgName, null, false, null, null, 15524 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15525 if (res) { 15526 pkgList.add(pkgName); 15527 } else { 15528 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15529 failedList.add(args); 15530 } 15531 } 15532 } 15533 15534 // reader 15535 synchronized (mPackages) { 15536 // We didn't update the settings after removing each package; 15537 // write them now for all packages. 15538 mSettings.writeLPr(); 15539 } 15540 15541 // We have to absolutely send UPDATED_MEDIA_STATUS only 15542 // after confirming that all the receivers processed the ordered 15543 // broadcast when packages get disabled, force a gc to clean things up. 15544 // and unload all the containers. 15545 if (pkgList.size() > 0) { 15546 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15547 new IIntentReceiver.Stub() { 15548 public void performReceive(Intent intent, int resultCode, String data, 15549 Bundle extras, boolean ordered, boolean sticky, 15550 int sendingUser) throws RemoteException { 15551 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15552 reportStatus ? 1 : 0, 1, keys); 15553 mHandler.sendMessage(msg); 15554 } 15555 }); 15556 } else { 15557 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15558 keys); 15559 mHandler.sendMessage(msg); 15560 } 15561 } 15562 15563 private void loadPrivatePackages(VolumeInfo vol) { 15564 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15565 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15566 synchronized (mInstallLock) { 15567 synchronized (mPackages) { 15568 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15569 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15570 for (PackageSetting ps : packages) { 15571 final PackageParser.Package pkg; 15572 try { 15573 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15574 loaded.add(pkg.applicationInfo); 15575 } catch (PackageManagerException e) { 15576 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15577 } 15578 15579 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15580 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15581 } 15582 } 15583 15584 int updateFlags = UPDATE_PERMISSIONS_ALL; 15585 if (ver.sdkVersion != mSdkVersion) { 15586 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15587 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15588 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15589 } 15590 updatePermissionsLPw(null, null, updateFlags); 15591 15592 // Yay, everything is now upgraded 15593 ver.forceCurrent(); 15594 15595 mSettings.writeLPr(); 15596 } 15597 } 15598 15599 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15600 sendResourcesChangedBroadcast(true, false, loaded, null); 15601 } 15602 15603 private void unloadPrivatePackages(VolumeInfo vol) { 15604 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15605 synchronized (mInstallLock) { 15606 synchronized (mPackages) { 15607 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15608 for (PackageSetting ps : packages) { 15609 if (ps.pkg == null) continue; 15610 15611 final ApplicationInfo info = ps.pkg.applicationInfo; 15612 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15613 if (deletePackageLI(ps.name, null, false, null, null, 15614 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15615 unloaded.add(info); 15616 } else { 15617 Slog.w(TAG, "Failed to unload " + ps.codePath); 15618 } 15619 } 15620 15621 mSettings.writeLPr(); 15622 } 15623 } 15624 15625 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15626 sendResourcesChangedBroadcast(false, false, unloaded, null); 15627 } 15628 15629 /** 15630 * Examine all users present on given mounted volume, and destroy data 15631 * belonging to users that are no longer valid, or whose user ID has been 15632 * recycled. 15633 */ 15634 private void reconcileUsers(String volumeUuid) { 15635 final File[] files = FileUtils 15636 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15637 for (File file : files) { 15638 if (!file.isDirectory()) continue; 15639 15640 final int userId; 15641 final UserInfo info; 15642 try { 15643 userId = Integer.parseInt(file.getName()); 15644 info = sUserManager.getUserInfo(userId); 15645 } catch (NumberFormatException e) { 15646 Slog.w(TAG, "Invalid user directory " + file); 15647 continue; 15648 } 15649 15650 boolean destroyUser = false; 15651 if (info == null) { 15652 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15653 + " because no matching user was found"); 15654 destroyUser = true; 15655 } else { 15656 try { 15657 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15658 } catch (IOException e) { 15659 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15660 + " because we failed to enforce serial number: " + e); 15661 destroyUser = true; 15662 } 15663 } 15664 15665 if (destroyUser) { 15666 synchronized (mInstallLock) { 15667 mInstaller.removeUserDataDirs(volumeUuid, userId); 15668 } 15669 } 15670 } 15671 15672 final UserManager um = mContext.getSystemService(UserManager.class); 15673 for (UserInfo user : um.getUsers()) { 15674 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15675 if (userDir.exists()) continue; 15676 15677 try { 15678 UserManagerService.prepareUserDirectory(userDir); 15679 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15680 } catch (IOException e) { 15681 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15682 } 15683 } 15684 } 15685 15686 /** 15687 * Examine all apps present on given mounted volume, and destroy apps that 15688 * aren't expected, either due to uninstallation or reinstallation on 15689 * another volume. 15690 */ 15691 private void reconcileApps(String volumeUuid) { 15692 final File[] files = FileUtils 15693 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15694 for (File file : files) { 15695 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15696 && !PackageInstallerService.isStageName(file.getName()); 15697 if (!isPackage) { 15698 // Ignore entries which are not packages 15699 continue; 15700 } 15701 15702 boolean destroyApp = false; 15703 String packageName = null; 15704 try { 15705 final PackageLite pkg = PackageParser.parsePackageLite(file, 15706 PackageParser.PARSE_MUST_BE_APK); 15707 packageName = pkg.packageName; 15708 15709 synchronized (mPackages) { 15710 final PackageSetting ps = mSettings.mPackages.get(packageName); 15711 if (ps == null) { 15712 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15713 + volumeUuid + " because we found no install record"); 15714 destroyApp = true; 15715 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15716 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15717 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15718 destroyApp = true; 15719 } 15720 } 15721 15722 } catch (PackageParserException e) { 15723 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15724 destroyApp = true; 15725 } 15726 15727 if (destroyApp) { 15728 synchronized (mInstallLock) { 15729 if (packageName != null) { 15730 removeDataDirsLI(volumeUuid, packageName); 15731 } 15732 if (file.isDirectory()) { 15733 mInstaller.rmPackageDir(file.getAbsolutePath()); 15734 } else { 15735 file.delete(); 15736 } 15737 } 15738 } 15739 } 15740 } 15741 15742 private void unfreezePackage(String packageName) { 15743 synchronized (mPackages) { 15744 final PackageSetting ps = mSettings.mPackages.get(packageName); 15745 if (ps != null) { 15746 ps.frozen = false; 15747 } 15748 } 15749 } 15750 15751 @Override 15752 public int movePackage(final String packageName, final String volumeUuid) { 15753 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15754 15755 final int moveId = mNextMoveId.getAndIncrement(); 15756 try { 15757 movePackageInternal(packageName, volumeUuid, moveId); 15758 } catch (PackageManagerException e) { 15759 Slog.w(TAG, "Failed to move " + packageName, e); 15760 mMoveCallbacks.notifyStatusChanged(moveId, 15761 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15762 } 15763 return moveId; 15764 } 15765 15766 private void movePackageInternal(final String packageName, final String volumeUuid, 15767 final int moveId) throws PackageManagerException { 15768 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15769 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15770 final PackageManager pm = mContext.getPackageManager(); 15771 15772 final boolean currentAsec; 15773 final String currentVolumeUuid; 15774 final File codeFile; 15775 final String installerPackageName; 15776 final String packageAbiOverride; 15777 final int appId; 15778 final String seinfo; 15779 final String label; 15780 15781 // reader 15782 synchronized (mPackages) { 15783 final PackageParser.Package pkg = mPackages.get(packageName); 15784 final PackageSetting ps = mSettings.mPackages.get(packageName); 15785 if (pkg == null || ps == null) { 15786 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15787 } 15788 15789 if (pkg.applicationInfo.isSystemApp()) { 15790 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15791 "Cannot move system application"); 15792 } 15793 15794 if (pkg.applicationInfo.isExternalAsec()) { 15795 currentAsec = true; 15796 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 15797 } else if (pkg.applicationInfo.isForwardLocked()) { 15798 currentAsec = true; 15799 currentVolumeUuid = "forward_locked"; 15800 } else { 15801 currentAsec = false; 15802 currentVolumeUuid = ps.volumeUuid; 15803 15804 final File probe = new File(pkg.codePath); 15805 final File probeOat = new File(probe, "oat"); 15806 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15807 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15808 "Move only supported for modern cluster style installs"); 15809 } 15810 } 15811 15812 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 15813 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15814 "Package already moved to " + volumeUuid); 15815 } 15816 15817 if (ps.frozen) { 15818 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15819 "Failed to move already frozen package"); 15820 } 15821 ps.frozen = true; 15822 15823 codeFile = new File(pkg.codePath); 15824 installerPackageName = ps.installerPackageName; 15825 packageAbiOverride = ps.cpuAbiOverrideString; 15826 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15827 seinfo = pkg.applicationInfo.seinfo; 15828 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15829 } 15830 15831 // Now that we're guarded by frozen state, kill app during move 15832 final long token = Binder.clearCallingIdentity(); 15833 try { 15834 killApplication(packageName, appId, "move pkg"); 15835 } finally { 15836 Binder.restoreCallingIdentity(token); 15837 } 15838 15839 final Bundle extras = new Bundle(); 15840 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15841 extras.putString(Intent.EXTRA_TITLE, label); 15842 mMoveCallbacks.notifyCreated(moveId, extras); 15843 15844 int installFlags; 15845 final boolean moveCompleteApp; 15846 final File measurePath; 15847 15848 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15849 installFlags = INSTALL_INTERNAL; 15850 moveCompleteApp = !currentAsec; 15851 measurePath = Environment.getDataAppDirectory(volumeUuid); 15852 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15853 installFlags = INSTALL_EXTERNAL; 15854 moveCompleteApp = false; 15855 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15856 } else { 15857 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15858 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15859 || !volume.isMountedWritable()) { 15860 unfreezePackage(packageName); 15861 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15862 "Move location not mounted private volume"); 15863 } 15864 15865 Preconditions.checkState(!currentAsec); 15866 15867 installFlags = INSTALL_INTERNAL; 15868 moveCompleteApp = true; 15869 measurePath = Environment.getDataAppDirectory(volumeUuid); 15870 } 15871 15872 final PackageStats stats = new PackageStats(null, -1); 15873 synchronized (mInstaller) { 15874 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15875 unfreezePackage(packageName); 15876 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15877 "Failed to measure package size"); 15878 } 15879 } 15880 15881 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15882 + stats.dataSize); 15883 15884 final long startFreeBytes = measurePath.getFreeSpace(); 15885 final long sizeBytes; 15886 if (moveCompleteApp) { 15887 sizeBytes = stats.codeSize + stats.dataSize; 15888 } else { 15889 sizeBytes = stats.codeSize; 15890 } 15891 15892 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15893 unfreezePackage(packageName); 15894 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15895 "Not enough free space to move"); 15896 } 15897 15898 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15899 15900 final CountDownLatch installedLatch = new CountDownLatch(1); 15901 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15902 @Override 15903 public void onUserActionRequired(Intent intent) throws RemoteException { 15904 throw new IllegalStateException(); 15905 } 15906 15907 @Override 15908 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15909 Bundle extras) throws RemoteException { 15910 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15911 + PackageManager.installStatusToString(returnCode, msg)); 15912 15913 installedLatch.countDown(); 15914 15915 // Regardless of success or failure of the move operation, 15916 // always unfreeze the package 15917 unfreezePackage(packageName); 15918 15919 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15920 switch (status) { 15921 case PackageInstaller.STATUS_SUCCESS: 15922 mMoveCallbacks.notifyStatusChanged(moveId, 15923 PackageManager.MOVE_SUCCEEDED); 15924 break; 15925 case PackageInstaller.STATUS_FAILURE_STORAGE: 15926 mMoveCallbacks.notifyStatusChanged(moveId, 15927 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15928 break; 15929 default: 15930 mMoveCallbacks.notifyStatusChanged(moveId, 15931 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15932 break; 15933 } 15934 } 15935 }; 15936 15937 final MoveInfo move; 15938 if (moveCompleteApp) { 15939 // Kick off a thread to report progress estimates 15940 new Thread() { 15941 @Override 15942 public void run() { 15943 while (true) { 15944 try { 15945 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15946 break; 15947 } 15948 } catch (InterruptedException ignored) { 15949 } 15950 15951 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15952 final int progress = 10 + (int) MathUtils.constrain( 15953 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15954 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15955 } 15956 } 15957 }.start(); 15958 15959 final String dataAppName = codeFile.getName(); 15960 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15961 dataAppName, appId, seinfo); 15962 } else { 15963 move = null; 15964 } 15965 15966 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15967 15968 final Message msg = mHandler.obtainMessage(INIT_COPY); 15969 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15970 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15971 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 15972 mHandler.sendMessage(msg); 15973 } 15974 15975 @Override 15976 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15977 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15978 15979 final int realMoveId = mNextMoveId.getAndIncrement(); 15980 final Bundle extras = new Bundle(); 15981 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15982 mMoveCallbacks.notifyCreated(realMoveId, extras); 15983 15984 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15985 @Override 15986 public void onCreated(int moveId, Bundle extras) { 15987 // Ignored 15988 } 15989 15990 @Override 15991 public void onStatusChanged(int moveId, int status, long estMillis) { 15992 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15993 } 15994 }; 15995 15996 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15997 storage.setPrimaryStorageUuid(volumeUuid, callback); 15998 return realMoveId; 15999 } 16000 16001 @Override 16002 public int getMoveStatus(int moveId) { 16003 mContext.enforceCallingOrSelfPermission( 16004 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16005 return mMoveCallbacks.mLastStatus.get(moveId); 16006 } 16007 16008 @Override 16009 public void registerMoveCallback(IPackageMoveObserver callback) { 16010 mContext.enforceCallingOrSelfPermission( 16011 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16012 mMoveCallbacks.register(callback); 16013 } 16014 16015 @Override 16016 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16017 mContext.enforceCallingOrSelfPermission( 16018 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16019 mMoveCallbacks.unregister(callback); 16020 } 16021 16022 @Override 16023 public boolean setInstallLocation(int loc) { 16024 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16025 null); 16026 if (getInstallLocation() == loc) { 16027 return true; 16028 } 16029 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16030 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16031 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16032 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16033 return true; 16034 } 16035 return false; 16036 } 16037 16038 @Override 16039 public int getInstallLocation() { 16040 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16041 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16042 PackageHelper.APP_INSTALL_AUTO); 16043 } 16044 16045 /** Called by UserManagerService */ 16046 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16047 mDirtyUsers.remove(userHandle); 16048 mSettings.removeUserLPw(userHandle); 16049 mPendingBroadcasts.remove(userHandle); 16050 if (mInstaller != null) { 16051 // Technically, we shouldn't be doing this with the package lock 16052 // held. However, this is very rare, and there is already so much 16053 // other disk I/O going on, that we'll let it slide for now. 16054 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16055 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16056 final String volumeUuid = vol.getFsUuid(); 16057 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16058 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16059 } 16060 } 16061 mUserNeedsBadging.delete(userHandle); 16062 removeUnusedPackagesLILPw(userManager, userHandle); 16063 } 16064 16065 /** 16066 * We're removing userHandle and would like to remove any downloaded packages 16067 * that are no longer in use by any other user. 16068 * @param userHandle the user being removed 16069 */ 16070 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16071 final boolean DEBUG_CLEAN_APKS = false; 16072 int [] users = userManager.getUserIdsLPr(); 16073 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16074 while (psit.hasNext()) { 16075 PackageSetting ps = psit.next(); 16076 if (ps.pkg == null) { 16077 continue; 16078 } 16079 final String packageName = ps.pkg.packageName; 16080 // Skip over if system app 16081 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16082 continue; 16083 } 16084 if (DEBUG_CLEAN_APKS) { 16085 Slog.i(TAG, "Checking package " + packageName); 16086 } 16087 boolean keep = false; 16088 for (int i = 0; i < users.length; i++) { 16089 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16090 keep = true; 16091 if (DEBUG_CLEAN_APKS) { 16092 Slog.i(TAG, " Keeping package " + packageName + " for user " 16093 + users[i]); 16094 } 16095 break; 16096 } 16097 } 16098 if (!keep) { 16099 if (DEBUG_CLEAN_APKS) { 16100 Slog.i(TAG, " Removing package " + packageName); 16101 } 16102 mHandler.post(new Runnable() { 16103 public void run() { 16104 deletePackageX(packageName, userHandle, 0); 16105 } //end run 16106 }); 16107 } 16108 } 16109 } 16110 16111 /** Called by UserManagerService */ 16112 void createNewUserLILPw(int userHandle) { 16113 if (mInstaller != null) { 16114 mInstaller.createUserConfig(userHandle); 16115 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16116 applyFactoryDefaultBrowserLPw(userHandle); 16117 primeDomainVerificationsLPw(userHandle); 16118 } 16119 } 16120 16121 void newUserCreated(final int userHandle) { 16122 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16123 } 16124 16125 @Override 16126 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16127 mContext.enforceCallingOrSelfPermission( 16128 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16129 "Only package verification agents can read the verifier device identity"); 16130 16131 synchronized (mPackages) { 16132 return mSettings.getVerifierDeviceIdentityLPw(); 16133 } 16134 } 16135 16136 @Override 16137 public void setPermissionEnforced(String permission, boolean enforced) { 16138 // TODO: Now that we no longer change GID for storage, this should to away. 16139 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16140 "setPermissionEnforced"); 16141 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16142 synchronized (mPackages) { 16143 if (mSettings.mReadExternalStorageEnforced == null 16144 || mSettings.mReadExternalStorageEnforced != enforced) { 16145 mSettings.mReadExternalStorageEnforced = enforced; 16146 mSettings.writeLPr(); 16147 } 16148 } 16149 // kill any non-foreground processes so we restart them and 16150 // grant/revoke the GID. 16151 final IActivityManager am = ActivityManagerNative.getDefault(); 16152 if (am != null) { 16153 final long token = Binder.clearCallingIdentity(); 16154 try { 16155 am.killProcessesBelowForeground("setPermissionEnforcement"); 16156 } catch (RemoteException e) { 16157 } finally { 16158 Binder.restoreCallingIdentity(token); 16159 } 16160 } 16161 } else { 16162 throw new IllegalArgumentException("No selective enforcement for " + permission); 16163 } 16164 } 16165 16166 @Override 16167 @Deprecated 16168 public boolean isPermissionEnforced(String permission) { 16169 return true; 16170 } 16171 16172 @Override 16173 public boolean isStorageLow() { 16174 final long token = Binder.clearCallingIdentity(); 16175 try { 16176 final DeviceStorageMonitorInternal 16177 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16178 if (dsm != null) { 16179 return dsm.isMemoryLow(); 16180 } else { 16181 return false; 16182 } 16183 } finally { 16184 Binder.restoreCallingIdentity(token); 16185 } 16186 } 16187 16188 @Override 16189 public IPackageInstaller getPackageInstaller() { 16190 return mInstallerService; 16191 } 16192 16193 private boolean userNeedsBadging(int userId) { 16194 int index = mUserNeedsBadging.indexOfKey(userId); 16195 if (index < 0) { 16196 final UserInfo userInfo; 16197 final long token = Binder.clearCallingIdentity(); 16198 try { 16199 userInfo = sUserManager.getUserInfo(userId); 16200 } finally { 16201 Binder.restoreCallingIdentity(token); 16202 } 16203 final boolean b; 16204 if (userInfo != null && userInfo.isManagedProfile()) { 16205 b = true; 16206 } else { 16207 b = false; 16208 } 16209 mUserNeedsBadging.put(userId, b); 16210 return b; 16211 } 16212 return mUserNeedsBadging.valueAt(index); 16213 } 16214 16215 @Override 16216 public KeySet getKeySetByAlias(String packageName, String alias) { 16217 if (packageName == null || alias == null) { 16218 return null; 16219 } 16220 synchronized(mPackages) { 16221 final PackageParser.Package pkg = mPackages.get(packageName); 16222 if (pkg == null) { 16223 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16224 throw new IllegalArgumentException("Unknown package: " + packageName); 16225 } 16226 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16227 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16228 } 16229 } 16230 16231 @Override 16232 public KeySet getSigningKeySet(String packageName) { 16233 if (packageName == null) { 16234 return null; 16235 } 16236 synchronized(mPackages) { 16237 final PackageParser.Package pkg = mPackages.get(packageName); 16238 if (pkg == null) { 16239 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16240 throw new IllegalArgumentException("Unknown package: " + packageName); 16241 } 16242 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16243 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16244 throw new SecurityException("May not access signing KeySet of other apps."); 16245 } 16246 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16247 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16248 } 16249 } 16250 16251 @Override 16252 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16253 if (packageName == null || ks == null) { 16254 return false; 16255 } 16256 synchronized(mPackages) { 16257 final PackageParser.Package pkg = mPackages.get(packageName); 16258 if (pkg == null) { 16259 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16260 throw new IllegalArgumentException("Unknown package: " + packageName); 16261 } 16262 IBinder ksh = ks.getToken(); 16263 if (ksh instanceof KeySetHandle) { 16264 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16265 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16266 } 16267 return false; 16268 } 16269 } 16270 16271 @Override 16272 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16273 if (packageName == null || ks == null) { 16274 return false; 16275 } 16276 synchronized(mPackages) { 16277 final PackageParser.Package pkg = mPackages.get(packageName); 16278 if (pkg == null) { 16279 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16280 throw new IllegalArgumentException("Unknown package: " + packageName); 16281 } 16282 IBinder ksh = ks.getToken(); 16283 if (ksh instanceof KeySetHandle) { 16284 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16285 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16286 } 16287 return false; 16288 } 16289 } 16290 16291 public void getUsageStatsIfNoPackageUsageInfo() { 16292 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16293 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16294 if (usm == null) { 16295 throw new IllegalStateException("UsageStatsManager must be initialized"); 16296 } 16297 long now = System.currentTimeMillis(); 16298 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16299 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16300 String packageName = entry.getKey(); 16301 PackageParser.Package pkg = mPackages.get(packageName); 16302 if (pkg == null) { 16303 continue; 16304 } 16305 UsageStats usage = entry.getValue(); 16306 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16307 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16308 } 16309 } 16310 } 16311 16312 /** 16313 * Check and throw if the given before/after packages would be considered a 16314 * downgrade. 16315 */ 16316 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16317 throws PackageManagerException { 16318 if (after.versionCode < before.mVersionCode) { 16319 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16320 "Update version code " + after.versionCode + " is older than current " 16321 + before.mVersionCode); 16322 } else if (after.versionCode == before.mVersionCode) { 16323 if (after.baseRevisionCode < before.baseRevisionCode) { 16324 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16325 "Update base revision code " + after.baseRevisionCode 16326 + " is older than current " + before.baseRevisionCode); 16327 } 16328 16329 if (!ArrayUtils.isEmpty(after.splitNames)) { 16330 for (int i = 0; i < after.splitNames.length; i++) { 16331 final String splitName = after.splitNames[i]; 16332 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16333 if (j != -1) { 16334 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16335 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16336 "Update split " + splitName + " revision code " 16337 + after.splitRevisionCodes[i] + " is older than current " 16338 + before.splitRevisionCodes[j]); 16339 } 16340 } 16341 } 16342 } 16343 } 16344 } 16345 16346 private static class MoveCallbacks extends Handler { 16347 private static final int MSG_CREATED = 1; 16348 private static final int MSG_STATUS_CHANGED = 2; 16349 16350 private final RemoteCallbackList<IPackageMoveObserver> 16351 mCallbacks = new RemoteCallbackList<>(); 16352 16353 private final SparseIntArray mLastStatus = new SparseIntArray(); 16354 16355 public MoveCallbacks(Looper looper) { 16356 super(looper); 16357 } 16358 16359 public void register(IPackageMoveObserver callback) { 16360 mCallbacks.register(callback); 16361 } 16362 16363 public void unregister(IPackageMoveObserver callback) { 16364 mCallbacks.unregister(callback); 16365 } 16366 16367 @Override 16368 public void handleMessage(Message msg) { 16369 final SomeArgs args = (SomeArgs) msg.obj; 16370 final int n = mCallbacks.beginBroadcast(); 16371 for (int i = 0; i < n; i++) { 16372 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16373 try { 16374 invokeCallback(callback, msg.what, args); 16375 } catch (RemoteException ignored) { 16376 } 16377 } 16378 mCallbacks.finishBroadcast(); 16379 args.recycle(); 16380 } 16381 16382 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16383 throws RemoteException { 16384 switch (what) { 16385 case MSG_CREATED: { 16386 callback.onCreated(args.argi1, (Bundle) args.arg2); 16387 break; 16388 } 16389 case MSG_STATUS_CHANGED: { 16390 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16391 break; 16392 } 16393 } 16394 } 16395 16396 private void notifyCreated(int moveId, Bundle extras) { 16397 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16398 16399 final SomeArgs args = SomeArgs.obtain(); 16400 args.argi1 = moveId; 16401 args.arg2 = extras; 16402 obtainMessage(MSG_CREATED, args).sendToTarget(); 16403 } 16404 16405 private void notifyStatusChanged(int moveId, int status) { 16406 notifyStatusChanged(moveId, status, -1); 16407 } 16408 16409 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16410 Slog.v(TAG, "Move " + moveId + " status " + status); 16411 16412 final SomeArgs args = SomeArgs.obtain(); 16413 args.argi1 = moveId; 16414 args.argi2 = status; 16415 args.arg3 = estMillis; 16416 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16417 16418 synchronized (mLastStatus) { 16419 mLastStatus.put(moveId, status); 16420 } 16421 } 16422 } 16423 16424 private final class OnPermissionChangeListeners extends Handler { 16425 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16426 16427 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16428 new RemoteCallbackList<>(); 16429 16430 public OnPermissionChangeListeners(Looper looper) { 16431 super(looper); 16432 } 16433 16434 @Override 16435 public void handleMessage(Message msg) { 16436 switch (msg.what) { 16437 case MSG_ON_PERMISSIONS_CHANGED: { 16438 final int uid = msg.arg1; 16439 handleOnPermissionsChanged(uid); 16440 } break; 16441 } 16442 } 16443 16444 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16445 mPermissionListeners.register(listener); 16446 16447 } 16448 16449 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16450 mPermissionListeners.unregister(listener); 16451 } 16452 16453 public void onPermissionsChanged(int uid) { 16454 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16455 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16456 } 16457 } 16458 16459 private void handleOnPermissionsChanged(int uid) { 16460 final int count = mPermissionListeners.beginBroadcast(); 16461 try { 16462 for (int i = 0; i < count; i++) { 16463 IOnPermissionsChangeListener callback = mPermissionListeners 16464 .getBroadcastItem(i); 16465 try { 16466 callback.onPermissionsChanged(uid); 16467 } catch (RemoteException e) { 16468 Log.e(TAG, "Permission listener is dead", e); 16469 } 16470 } 16471 } finally { 16472 mPermissionListeners.finishBroadcast(); 16473 } 16474 } 16475 } 16476 16477 private class PackageManagerInternalImpl extends PackageManagerInternal { 16478 @Override 16479 public void setLocationPackagesProvider(PackagesProvider provider) { 16480 synchronized (mPackages) { 16481 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16482 } 16483 } 16484 16485 @Override 16486 public void setImePackagesProvider(PackagesProvider provider) { 16487 synchronized (mPackages) { 16488 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16489 } 16490 } 16491 16492 @Override 16493 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16494 synchronized (mPackages) { 16495 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16496 } 16497 } 16498 16499 @Override 16500 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16501 synchronized (mPackages) { 16502 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16503 } 16504 } 16505 16506 @Override 16507 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16508 synchronized (mPackages) { 16509 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16510 } 16511 } 16512 16513 @Override 16514 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16515 synchronized (mPackages) { 16516 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16517 } 16518 } 16519 16520 @Override 16521 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16522 synchronized (mPackages) { 16523 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16524 } 16525 } 16526 16527 @Override 16528 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16529 synchronized (mPackages) { 16530 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16531 packageName, userId); 16532 } 16533 } 16534 16535 @Override 16536 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16537 synchronized (mPackages) { 16538 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16539 packageName, userId); 16540 } 16541 } 16542 @Override 16543 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16544 synchronized (mPackages) { 16545 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16546 packageName, userId); 16547 } 16548 } 16549 } 16550 16551 @Override 16552 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16553 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16554 synchronized (mPackages) { 16555 final long identity = Binder.clearCallingIdentity(); 16556 try { 16557 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16558 packageNames, userId); 16559 } finally { 16560 Binder.restoreCallingIdentity(identity); 16561 } 16562 } 16563 } 16564 16565 private static void enforceSystemOrPhoneCaller(String tag) { 16566 int callingUid = Binder.getCallingUid(); 16567 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16568 throw new SecurityException( 16569 "Cannot call " + tag + " from UID " + callingUid); 16570 } 16571 } 16572} 16573