PackageManagerService.java revision 4a5f4a2bc7a379a5b4174f78fefeefe745e6cd37
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.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 22import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 34import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 60import static android.content.pm.PackageManager.MATCH_ALL; 61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 65import static android.content.pm.PackageManager.PERMISSION_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.Binder; 147import android.os.Build; 148import android.os.Bundle; 149import android.os.Debug; 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.StorageEventListener; 170import android.os.storage.StorageManager; 171import android.os.storage.VolumeInfo; 172import android.os.storage.VolumeRecord; 173import android.security.KeyStore; 174import android.security.SystemKeyStore; 175import android.system.ErrnoException; 176import android.system.Os; 177import android.system.StructStat; 178import android.text.TextUtils; 179import android.text.format.DateUtils; 180import android.util.ArrayMap; 181import android.util.ArraySet; 182import android.util.AtomicFile; 183import android.util.DisplayMetrics; 184import android.util.EventLog; 185import android.util.ExceptionUtils; 186import android.util.Log; 187import android.util.LogPrinter; 188import android.util.MathUtils; 189import android.util.PrintStreamPrinter; 190import android.util.Slog; 191import android.util.SparseArray; 192import android.util.SparseBooleanArray; 193import android.util.SparseIntArray; 194import android.util.Xml; 195import android.view.Display; 196 197import dalvik.system.DexFile; 198import dalvik.system.VMRuntime; 199 200import libcore.io.IoUtils; 201import libcore.util.EmptyArray; 202 203import com.android.internal.R; 204import com.android.internal.annotations.GuardedBy; 205import com.android.internal.app.IMediaContainerService; 206import com.android.internal.app.ResolverActivity; 207import com.android.internal.content.NativeLibraryHelper; 208import com.android.internal.content.PackageHelper; 209import com.android.internal.os.IParcelFileDescriptorFactory; 210import com.android.internal.os.SomeArgs; 211import com.android.internal.os.Zygote; 212import com.android.internal.util.ArrayUtils; 213import com.android.internal.util.FastPrintWriter; 214import com.android.internal.util.FastXmlSerializer; 215import com.android.internal.util.IndentingPrintWriter; 216import com.android.internal.util.Preconditions; 217import com.android.server.EventLogTags; 218import com.android.server.FgThread; 219import com.android.server.IntentResolver; 220import com.android.server.LocalServices; 221import com.android.server.ServiceThread; 222import com.android.server.SystemConfig; 223import com.android.server.Watchdog; 224import com.android.server.pm.PermissionsState.PermissionState; 225import com.android.server.pm.Settings.DatabaseVersion; 226import com.android.server.storage.DeviceStorageMonitorInternal; 227 228import org.xmlpull.v1.XmlPullParser; 229import org.xmlpull.v1.XmlPullParserException; 230import org.xmlpull.v1.XmlSerializer; 231 232import java.io.BufferedInputStream; 233import java.io.BufferedOutputStream; 234import java.io.BufferedReader; 235import java.io.ByteArrayInputStream; 236import java.io.ByteArrayOutputStream; 237import java.io.File; 238import java.io.FileDescriptor; 239import java.io.FileNotFoundException; 240import java.io.FileOutputStream; 241import java.io.FileReader; 242import java.io.FilenameFilter; 243import java.io.IOException; 244import java.io.InputStream; 245import java.io.PrintWriter; 246import java.nio.charset.StandardCharsets; 247import java.security.NoSuchAlgorithmException; 248import java.security.PublicKey; 249import java.security.cert.CertificateEncodingException; 250import java.security.cert.CertificateException; 251import java.text.SimpleDateFormat; 252import java.util.ArrayList; 253import java.util.Arrays; 254import java.util.Collection; 255import java.util.Collections; 256import java.util.Comparator; 257import java.util.Date; 258import java.util.Iterator; 259import java.util.List; 260import java.util.Map; 261import java.util.Objects; 262import java.util.Set; 263import java.util.concurrent.CountDownLatch; 264import java.util.concurrent.TimeUnit; 265import java.util.concurrent.atomic.AtomicBoolean; 266import java.util.concurrent.atomic.AtomicInteger; 267import java.util.concurrent.atomic.AtomicLong; 268 269/** 270 * Keep track of all those .apks everywhere. 271 * 272 * This is very central to the platform's security; please run the unit 273 * tests whenever making modifications here: 274 * 275mmm frameworks/base/tests/AndroidTests 276adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 277adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 278 * 279 * {@hide} 280 */ 281public class PackageManagerService extends IPackageManager.Stub { 282 static final String TAG = "PackageManager"; 283 static final boolean DEBUG_SETTINGS = false; 284 static final boolean DEBUG_PREFERRED = false; 285 static final boolean DEBUG_UPGRADE = false; 286 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 287 private static final boolean DEBUG_BACKUP = true; 288 private static final boolean DEBUG_INSTALL = false; 289 private static final boolean DEBUG_REMOVE = false; 290 private static final boolean DEBUG_BROADCASTS = false; 291 private static final boolean DEBUG_SHOW_INFO = false; 292 private static final boolean DEBUG_PACKAGE_INFO = false; 293 private static final boolean DEBUG_INTENT_MATCHING = false; 294 private static final boolean DEBUG_PACKAGE_SCANNING = false; 295 private static final boolean DEBUG_VERIFY = false; 296 private static final boolean DEBUG_DEXOPT = false; 297 private static final boolean DEBUG_ABI_SELECTION = false; 298 299 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 300 301 private static final int RADIO_UID = Process.PHONE_UID; 302 private static final int LOG_UID = Process.LOG_UID; 303 private static final int NFC_UID = Process.NFC_UID; 304 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 305 private static final int SHELL_UID = Process.SHELL_UID; 306 307 // Cap the size of permission trees that 3rd party apps can define 308 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 309 310 // Suffix used during package installation when copying/moving 311 // package apks to install directory. 312 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 313 314 static final int SCAN_NO_DEX = 1<<1; 315 static final int SCAN_FORCE_DEX = 1<<2; 316 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 317 static final int SCAN_NEW_INSTALL = 1<<4; 318 static final int SCAN_NO_PATHS = 1<<5; 319 static final int SCAN_UPDATE_TIME = 1<<6; 320 static final int SCAN_DEFER_DEX = 1<<7; 321 static final int SCAN_BOOTING = 1<<8; 322 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 323 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 324 static final int SCAN_REQUIRE_KNOWN = 1<<12; 325 static final int SCAN_MOVE = 1<<13; 326 static final int SCAN_INITIAL = 1<<14; 327 328 static final int REMOVE_CHATTY = 1<<16; 329 330 private static final int[] EMPTY_INT_ARRAY = new int[0]; 331 332 /** 333 * Timeout (in milliseconds) after which the watchdog should declare that 334 * our handler thread is wedged. The usual default for such things is one 335 * minute but we sometimes do very lengthy I/O operations on this thread, 336 * such as installing multi-gigabyte applications, so ours needs to be longer. 337 */ 338 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 339 340 /** 341 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 342 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 343 * settings entry if available, otherwise we use the hardcoded default. If it's been 344 * more than this long since the last fstrim, we force one during the boot sequence. 345 * 346 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 347 * one gets run at the next available charging+idle time. This final mandatory 348 * no-fstrim check kicks in only of the other scheduling criteria is never met. 349 */ 350 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 351 352 /** 353 * Whether verification is enabled by default. 354 */ 355 private static final boolean DEFAULT_VERIFY_ENABLE = true; 356 357 /** 358 * The default maximum time to wait for the verification agent to return in 359 * milliseconds. 360 */ 361 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 362 363 /** 364 * The default response for package verification timeout. 365 * 366 * This can be either PackageManager.VERIFICATION_ALLOW or 367 * PackageManager.VERIFICATION_REJECT. 368 */ 369 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 370 371 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 372 373 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 374 DEFAULT_CONTAINER_PACKAGE, 375 "com.android.defcontainer.DefaultContainerService"); 376 377 private static final String KILL_APP_REASON_GIDS_CHANGED = 378 "permission grant or revoke changed gids"; 379 380 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 381 "permissions revoked"; 382 383 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 384 385 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 386 387 /** Permission grant: not grant the permission. */ 388 private static final int GRANT_DENIED = 1; 389 390 /** Permission grant: grant the permission as an install permission. */ 391 private static final int GRANT_INSTALL = 2; 392 393 /** Permission grant: grant the permission as an install permission for a legacy app. */ 394 private static final int GRANT_INSTALL_LEGACY = 3; 395 396 /** Permission grant: grant the permission as a runtime one. */ 397 private static final int GRANT_RUNTIME = 4; 398 399 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 400 private static final int GRANT_UPGRADE = 5; 401 402 /** Canonical intent used to identify what counts as a "web browser" app */ 403 private static final Intent sBrowserIntent; 404 static { 405 sBrowserIntent = new Intent(); 406 sBrowserIntent.setAction(Intent.ACTION_VIEW); 407 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 408 sBrowserIntent.setData(Uri.parse("http:")); 409 } 410 411 final ServiceThread mHandlerThread; 412 413 final PackageHandler mHandler; 414 415 /** 416 * Messages for {@link #mHandler} that need to wait for system ready before 417 * being dispatched. 418 */ 419 private ArrayList<Message> mPostSystemReadyMessages; 420 421 final int mSdkVersion = Build.VERSION.SDK_INT; 422 423 final Context mContext; 424 final boolean mFactoryTest; 425 final boolean mOnlyCore; 426 final boolean mLazyDexOpt; 427 final long mDexOptLRUThresholdInMills; 428 final DisplayMetrics mMetrics; 429 final int mDefParseFlags; 430 final String[] mSeparateProcesses; 431 final boolean mIsUpgrade; 432 433 // This is where all application persistent data goes. 434 final File mAppDataDir; 435 436 // This is where all application persistent data goes for secondary users. 437 final File mUserAppDataDir; 438 439 /** The location for ASEC container files on internal storage. */ 440 final String mAsecInternalPath; 441 442 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 443 // LOCK HELD. Can be called with mInstallLock held. 444 @GuardedBy("mInstallLock") 445 final Installer mInstaller; 446 447 /** Directory where installed third-party apps stored */ 448 final File mAppInstallDir; 449 450 /** 451 * Directory to which applications installed internally have their 452 * 32 bit native libraries copied. 453 */ 454 private File mAppLib32InstallDir; 455 456 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 457 // apps. 458 final File mDrmAppPrivateInstallDir; 459 460 // ---------------------------------------------------------------- 461 462 // Lock for state used when installing and doing other long running 463 // operations. Methods that must be called with this lock held have 464 // the suffix "LI". 465 final Object mInstallLock = new Object(); 466 467 // ---------------------------------------------------------------- 468 469 // Keys are String (package name), values are Package. This also serves 470 // as the lock for the global state. Methods that must be called with 471 // this lock held have the prefix "LP". 472 @GuardedBy("mPackages") 473 final ArrayMap<String, PackageParser.Package> mPackages = 474 new ArrayMap<String, PackageParser.Package>(); 475 476 // Tracks available target package names -> overlay package paths. 477 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 478 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 479 480 final Settings mSettings; 481 boolean mRestoredSettings; 482 483 // System configuration read by SystemConfig. 484 final int[] mGlobalGids; 485 final SparseArray<ArraySet<String>> mSystemPermissions; 486 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 487 488 // If mac_permissions.xml was found for seinfo labeling. 489 boolean mFoundPolicyFile; 490 491 // If a recursive restorecon of /data/data/<pkg> is needed. 492 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 493 494 public static final class SharedLibraryEntry { 495 public final String path; 496 public final String apk; 497 498 SharedLibraryEntry(String _path, String _apk) { 499 path = _path; 500 apk = _apk; 501 } 502 } 503 504 // Currently known shared libraries. 505 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 506 new ArrayMap<String, SharedLibraryEntry>(); 507 508 // All available activities, for your resolving pleasure. 509 final ActivityIntentResolver mActivities = 510 new ActivityIntentResolver(); 511 512 // All available receivers, for your resolving pleasure. 513 final ActivityIntentResolver mReceivers = 514 new ActivityIntentResolver(); 515 516 // All available services, for your resolving pleasure. 517 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 518 519 // All available providers, for your resolving pleasure. 520 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 521 522 // Mapping from provider base names (first directory in content URI codePath) 523 // to the provider information. 524 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 525 new ArrayMap<String, PackageParser.Provider>(); 526 527 // Mapping from instrumentation class names to info about them. 528 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 529 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 530 531 // Mapping from permission names to info about them. 532 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 533 new ArrayMap<String, PackageParser.PermissionGroup>(); 534 535 // Packages whose data we have transfered into another package, thus 536 // should no longer exist. 537 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 538 539 // Broadcast actions that are only available to the system. 540 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 541 542 /** List of packages waiting for verification. */ 543 final SparseArray<PackageVerificationState> mPendingVerification 544 = new SparseArray<PackageVerificationState>(); 545 546 /** Set of packages associated with each app op permission. */ 547 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 548 549 final PackageInstallerService mInstallerService; 550 551 private final PackageDexOptimizer mPackageDexOptimizer; 552 553 private AtomicInteger mNextMoveId = new AtomicInteger(); 554 private final MoveCallbacks mMoveCallbacks; 555 556 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 557 558 // Cache of users who need badging. 559 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 560 561 /** Token for keys in mPendingVerification. */ 562 private int mPendingVerificationToken = 0; 563 564 volatile boolean mSystemReady; 565 volatile boolean mSafeMode; 566 volatile boolean mHasSystemUidErrors; 567 568 ApplicationInfo mAndroidApplication; 569 final ActivityInfo mResolveActivity = new ActivityInfo(); 570 final ResolveInfo mResolveInfo = new ResolveInfo(); 571 ComponentName mResolveComponentName; 572 PackageParser.Package mPlatformPackage; 573 ComponentName mCustomResolverComponentName; 574 575 boolean mResolverReplaced = false; 576 577 private final ComponentName mIntentFilterVerifierComponent; 578 private int mIntentFilterVerificationToken = 0; 579 580 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 581 = new SparseArray<IntentFilterVerificationState>(); 582 583 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 584 new DefaultPermissionGrantPolicy(this); 585 586 private static class IFVerificationParams { 587 PackageParser.Package pkg; 588 boolean replacing; 589 int userId; 590 int verifierUid; 591 592 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 593 int _userId, int _verifierUid) { 594 pkg = _pkg; 595 replacing = _replacing; 596 userId = _userId; 597 replacing = _replacing; 598 verifierUid = _verifierUid; 599 } 600 } 601 602 private interface IntentFilterVerifier<T extends IntentFilter> { 603 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 604 T filter, String packageName); 605 void startVerifications(int userId); 606 void receiveVerificationResponse(int verificationId); 607 } 608 609 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 610 private Context mContext; 611 private ComponentName mIntentFilterVerifierComponent; 612 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 613 614 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 615 mContext = context; 616 mIntentFilterVerifierComponent = verifierComponent; 617 } 618 619 private String getDefaultScheme() { 620 return IntentFilter.SCHEME_HTTPS; 621 } 622 623 @Override 624 public void startVerifications(int userId) { 625 // Launch verifications requests 626 int count = mCurrentIntentFilterVerifications.size(); 627 for (int n=0; n<count; n++) { 628 int verificationId = mCurrentIntentFilterVerifications.get(n); 629 final IntentFilterVerificationState ivs = 630 mIntentFilterVerificationStates.get(verificationId); 631 632 String packageName = ivs.getPackageName(); 633 634 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 635 final int filterCount = filters.size(); 636 ArraySet<String> domainsSet = new ArraySet<>(); 637 for (int m=0; m<filterCount; m++) { 638 PackageParser.ActivityIntentInfo filter = filters.get(m); 639 domainsSet.addAll(filter.getHostsList()); 640 } 641 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 642 synchronized (mPackages) { 643 if (mSettings.createIntentFilterVerificationIfNeededLPw( 644 packageName, domainsList) != null) { 645 scheduleWriteSettingsLocked(); 646 } 647 } 648 sendVerificationRequest(userId, verificationId, ivs); 649 } 650 mCurrentIntentFilterVerifications.clear(); 651 } 652 653 private void sendVerificationRequest(int userId, int verificationId, 654 IntentFilterVerificationState ivs) { 655 656 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 657 verificationIntent.putExtra( 658 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 659 verificationId); 660 verificationIntent.putExtra( 661 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 662 getDefaultScheme()); 663 verificationIntent.putExtra( 664 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 665 ivs.getHostsString()); 666 verificationIntent.putExtra( 667 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 668 ivs.getPackageName()); 669 verificationIntent.setComponent(mIntentFilterVerifierComponent); 670 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 671 672 UserHandle user = new UserHandle(userId); 673 mContext.sendBroadcastAsUser(verificationIntent, user); 674 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 675 "Sending IntentFilter verification broadcast"); 676 } 677 678 public void receiveVerificationResponse(int verificationId) { 679 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 680 681 final boolean verified = ivs.isVerified(); 682 683 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 684 final int count = filters.size(); 685 if (DEBUG_DOMAIN_VERIFICATION) { 686 Slog.i(TAG, "Received verification response " + verificationId 687 + " for " + count + " filters, verified=" + verified); 688 } 689 for (int n=0; n<count; n++) { 690 PackageParser.ActivityIntentInfo filter = filters.get(n); 691 filter.setVerified(verified); 692 693 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 694 + " verified with result:" + verified + " and hosts:" 695 + ivs.getHostsString()); 696 } 697 698 mIntentFilterVerificationStates.remove(verificationId); 699 700 final String packageName = ivs.getPackageName(); 701 IntentFilterVerificationInfo ivi = null; 702 703 synchronized (mPackages) { 704 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 705 } 706 if (ivi == null) { 707 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 708 + verificationId + " packageName:" + packageName); 709 return; 710 } 711 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 712 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 713 714 synchronized (mPackages) { 715 if (verified) { 716 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 717 } else { 718 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 719 } 720 scheduleWriteSettingsLocked(); 721 722 final int userId = ivs.getUserId(); 723 if (userId != UserHandle.USER_ALL) { 724 final int userStatus = 725 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 726 727 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 728 boolean needUpdate = false; 729 730 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 731 // already been set by the User thru the Disambiguation dialog 732 switch (userStatus) { 733 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 734 if (verified) { 735 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 736 } else { 737 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 738 } 739 needUpdate = true; 740 break; 741 742 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 743 if (verified) { 744 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 745 needUpdate = true; 746 } 747 break; 748 749 default: 750 // Nothing to do 751 } 752 753 if (needUpdate) { 754 mSettings.updateIntentFilterVerificationStatusLPw( 755 packageName, updatedStatus, userId); 756 scheduleWritePackageRestrictionsLocked(userId); 757 } 758 } 759 } 760 } 761 762 @Override 763 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 764 ActivityIntentInfo filter, String packageName) { 765 if (!hasValidDomains(filter)) { 766 return false; 767 } 768 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 769 if (ivs == null) { 770 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 771 packageName); 772 } 773 if (DEBUG_DOMAIN_VERIFICATION) { 774 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 775 } 776 ivs.addFilter(filter); 777 return true; 778 } 779 780 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 781 int userId, int verificationId, String packageName) { 782 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 783 verifierUid, userId, packageName); 784 ivs.setPendingState(); 785 synchronized (mPackages) { 786 mIntentFilterVerificationStates.append(verificationId, ivs); 787 mCurrentIntentFilterVerifications.add(verificationId); 788 } 789 return ivs; 790 } 791 } 792 793 private static boolean hasValidDomains(ActivityIntentInfo filter) { 794 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 795 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 796 if (!hasHTTPorHTTPS) { 797 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 798 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 799 return false; 800 } 801 return true; 802 } 803 804 private IntentFilterVerifier mIntentFilterVerifier; 805 806 // Set of pending broadcasts for aggregating enable/disable of components. 807 static class PendingPackageBroadcasts { 808 // for each user id, a map of <package name -> components within that package> 809 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 810 811 public PendingPackageBroadcasts() { 812 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 813 } 814 815 public ArrayList<String> get(int userId, String packageName) { 816 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 817 return packages.get(packageName); 818 } 819 820 public void put(int userId, String packageName, ArrayList<String> components) { 821 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 822 packages.put(packageName, components); 823 } 824 825 public void remove(int userId, String packageName) { 826 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 827 if (packages != null) { 828 packages.remove(packageName); 829 } 830 } 831 832 public void remove(int userId) { 833 mUidMap.remove(userId); 834 } 835 836 public int userIdCount() { 837 return mUidMap.size(); 838 } 839 840 public int userIdAt(int n) { 841 return mUidMap.keyAt(n); 842 } 843 844 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 845 return mUidMap.get(userId); 846 } 847 848 public int size() { 849 // total number of pending broadcast entries across all userIds 850 int num = 0; 851 for (int i = 0; i< mUidMap.size(); i++) { 852 num += mUidMap.valueAt(i).size(); 853 } 854 return num; 855 } 856 857 public void clear() { 858 mUidMap.clear(); 859 } 860 861 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 862 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 863 if (map == null) { 864 map = new ArrayMap<String, ArrayList<String>>(); 865 mUidMap.put(userId, map); 866 } 867 return map; 868 } 869 } 870 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 871 872 // Service Connection to remote media container service to copy 873 // package uri's from external media onto secure containers 874 // or internal storage. 875 private IMediaContainerService mContainerService = null; 876 877 static final int SEND_PENDING_BROADCAST = 1; 878 static final int MCS_BOUND = 3; 879 static final int END_COPY = 4; 880 static final int INIT_COPY = 5; 881 static final int MCS_UNBIND = 6; 882 static final int START_CLEANING_PACKAGE = 7; 883 static final int FIND_INSTALL_LOC = 8; 884 static final int POST_INSTALL = 9; 885 static final int MCS_RECONNECT = 10; 886 static final int MCS_GIVE_UP = 11; 887 static final int UPDATED_MEDIA_STATUS = 12; 888 static final int WRITE_SETTINGS = 13; 889 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 890 static final int PACKAGE_VERIFIED = 15; 891 static final int CHECK_PENDING_VERIFICATION = 16; 892 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 893 static final int INTENT_FILTER_VERIFIED = 18; 894 895 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 896 897 // Delay time in millisecs 898 static final int BROADCAST_DELAY = 10 * 1000; 899 900 static UserManagerService sUserManager; 901 902 // Stores a list of users whose package restrictions file needs to be updated 903 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 904 905 final private DefaultContainerConnection mDefContainerConn = 906 new DefaultContainerConnection(); 907 class DefaultContainerConnection implements ServiceConnection { 908 public void onServiceConnected(ComponentName name, IBinder service) { 909 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 910 IMediaContainerService imcs = 911 IMediaContainerService.Stub.asInterface(service); 912 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 913 } 914 915 public void onServiceDisconnected(ComponentName name) { 916 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 917 } 918 } 919 920 // Recordkeeping of restore-after-install operations that are currently in flight 921 // between the Package Manager and the Backup Manager 922 class PostInstallData { 923 public InstallArgs args; 924 public PackageInstalledInfo res; 925 926 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 927 args = _a; 928 res = _r; 929 } 930 } 931 932 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 933 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 934 935 // XML tags for backup/restore of various bits of state 936 private static final String TAG_PREFERRED_BACKUP = "pa"; 937 private static final String TAG_DEFAULT_APPS = "da"; 938 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 939 940 final String mRequiredVerifierPackage; 941 final String mRequiredInstallerPackage; 942 943 private final PackageUsage mPackageUsage = new PackageUsage(); 944 945 private class PackageUsage { 946 private static final int WRITE_INTERVAL 947 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 948 949 private final Object mFileLock = new Object(); 950 private final AtomicLong mLastWritten = new AtomicLong(0); 951 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 952 953 private boolean mIsHistoricalPackageUsageAvailable = true; 954 955 boolean isHistoricalPackageUsageAvailable() { 956 return mIsHistoricalPackageUsageAvailable; 957 } 958 959 void write(boolean force) { 960 if (force) { 961 writeInternal(); 962 return; 963 } 964 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 965 && !DEBUG_DEXOPT) { 966 return; 967 } 968 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 969 new Thread("PackageUsage_DiskWriter") { 970 @Override 971 public void run() { 972 try { 973 writeInternal(); 974 } finally { 975 mBackgroundWriteRunning.set(false); 976 } 977 } 978 }.start(); 979 } 980 } 981 982 private void writeInternal() { 983 synchronized (mPackages) { 984 synchronized (mFileLock) { 985 AtomicFile file = getFile(); 986 FileOutputStream f = null; 987 try { 988 f = file.startWrite(); 989 BufferedOutputStream out = new BufferedOutputStream(f); 990 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 991 StringBuilder sb = new StringBuilder(); 992 for (PackageParser.Package pkg : mPackages.values()) { 993 if (pkg.mLastPackageUsageTimeInMills == 0) { 994 continue; 995 } 996 sb.setLength(0); 997 sb.append(pkg.packageName); 998 sb.append(' '); 999 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1000 sb.append('\n'); 1001 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1002 } 1003 out.flush(); 1004 file.finishWrite(f); 1005 } catch (IOException e) { 1006 if (f != null) { 1007 file.failWrite(f); 1008 } 1009 Log.e(TAG, "Failed to write package usage times", e); 1010 } 1011 } 1012 } 1013 mLastWritten.set(SystemClock.elapsedRealtime()); 1014 } 1015 1016 void readLP() { 1017 synchronized (mFileLock) { 1018 AtomicFile file = getFile(); 1019 BufferedInputStream in = null; 1020 try { 1021 in = new BufferedInputStream(file.openRead()); 1022 StringBuffer sb = new StringBuffer(); 1023 while (true) { 1024 String packageName = readToken(in, sb, ' '); 1025 if (packageName == null) { 1026 break; 1027 } 1028 String timeInMillisString = readToken(in, sb, '\n'); 1029 if (timeInMillisString == null) { 1030 throw new IOException("Failed to find last usage time for package " 1031 + packageName); 1032 } 1033 PackageParser.Package pkg = mPackages.get(packageName); 1034 if (pkg == null) { 1035 continue; 1036 } 1037 long timeInMillis; 1038 try { 1039 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1040 } catch (NumberFormatException e) { 1041 throw new IOException("Failed to parse " + timeInMillisString 1042 + " as a long.", e); 1043 } 1044 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1045 } 1046 } catch (FileNotFoundException expected) { 1047 mIsHistoricalPackageUsageAvailable = false; 1048 } catch (IOException e) { 1049 Log.w(TAG, "Failed to read package usage times", e); 1050 } finally { 1051 IoUtils.closeQuietly(in); 1052 } 1053 } 1054 mLastWritten.set(SystemClock.elapsedRealtime()); 1055 } 1056 1057 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1058 throws IOException { 1059 sb.setLength(0); 1060 while (true) { 1061 int ch = in.read(); 1062 if (ch == -1) { 1063 if (sb.length() == 0) { 1064 return null; 1065 } 1066 throw new IOException("Unexpected EOF"); 1067 } 1068 if (ch == endOfToken) { 1069 return sb.toString(); 1070 } 1071 sb.append((char)ch); 1072 } 1073 } 1074 1075 private AtomicFile getFile() { 1076 File dataDir = Environment.getDataDirectory(); 1077 File systemDir = new File(dataDir, "system"); 1078 File fname = new File(systemDir, "package-usage.list"); 1079 return new AtomicFile(fname); 1080 } 1081 } 1082 1083 class PackageHandler extends Handler { 1084 private boolean mBound = false; 1085 final ArrayList<HandlerParams> mPendingInstalls = 1086 new ArrayList<HandlerParams>(); 1087 1088 private boolean connectToService() { 1089 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1090 " DefaultContainerService"); 1091 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1092 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1093 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1094 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1095 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1096 mBound = true; 1097 return true; 1098 } 1099 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1100 return false; 1101 } 1102 1103 private void disconnectService() { 1104 mContainerService = null; 1105 mBound = false; 1106 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1107 mContext.unbindService(mDefContainerConn); 1108 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1109 } 1110 1111 PackageHandler(Looper looper) { 1112 super(looper); 1113 } 1114 1115 public void handleMessage(Message msg) { 1116 try { 1117 doHandleMessage(msg); 1118 } finally { 1119 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1120 } 1121 } 1122 1123 void doHandleMessage(Message msg) { 1124 switch (msg.what) { 1125 case INIT_COPY: { 1126 HandlerParams params = (HandlerParams) msg.obj; 1127 int idx = mPendingInstalls.size(); 1128 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1129 // If a bind was already initiated we dont really 1130 // need to do anything. The pending install 1131 // will be processed later on. 1132 if (!mBound) { 1133 // If this is the only one pending we might 1134 // have to bind to the service again. 1135 if (!connectToService()) { 1136 Slog.e(TAG, "Failed to bind to media container service"); 1137 params.serviceError(); 1138 return; 1139 } else { 1140 // Once we bind to the service, the first 1141 // pending request will be processed. 1142 mPendingInstalls.add(idx, params); 1143 } 1144 } else { 1145 mPendingInstalls.add(idx, params); 1146 // Already bound to the service. Just make 1147 // sure we trigger off processing the first request. 1148 if (idx == 0) { 1149 mHandler.sendEmptyMessage(MCS_BOUND); 1150 } 1151 } 1152 break; 1153 } 1154 case MCS_BOUND: { 1155 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1156 if (msg.obj != null) { 1157 mContainerService = (IMediaContainerService) msg.obj; 1158 } 1159 if (mContainerService == null) { 1160 if (!mBound) { 1161 // Something seriously wrong since we are not bound and we are not 1162 // waiting for connection. Bail out. 1163 Slog.e(TAG, "Cannot bind to media container service"); 1164 for (HandlerParams params : mPendingInstalls) { 1165 // Indicate service bind error 1166 params.serviceError(); 1167 } 1168 mPendingInstalls.clear(); 1169 } else { 1170 Slog.w(TAG, "Waiting to connect to media container service"); 1171 } 1172 } else if (mPendingInstalls.size() > 0) { 1173 HandlerParams params = mPendingInstalls.get(0); 1174 if (params != null) { 1175 if (params.startCopy()) { 1176 // We are done... look for more work or to 1177 // go idle. 1178 if (DEBUG_SD_INSTALL) Log.i(TAG, 1179 "Checking for more work or unbind..."); 1180 // Delete pending install 1181 if (mPendingInstalls.size() > 0) { 1182 mPendingInstalls.remove(0); 1183 } 1184 if (mPendingInstalls.size() == 0) { 1185 if (mBound) { 1186 if (DEBUG_SD_INSTALL) Log.i(TAG, 1187 "Posting delayed MCS_UNBIND"); 1188 removeMessages(MCS_UNBIND); 1189 Message ubmsg = obtainMessage(MCS_UNBIND); 1190 // Unbind after a little delay, to avoid 1191 // continual thrashing. 1192 sendMessageDelayed(ubmsg, 10000); 1193 } 1194 } else { 1195 // There are more pending requests in queue. 1196 // Just post MCS_BOUND message to trigger processing 1197 // of next pending install. 1198 if (DEBUG_SD_INSTALL) Log.i(TAG, 1199 "Posting MCS_BOUND for next work"); 1200 mHandler.sendEmptyMessage(MCS_BOUND); 1201 } 1202 } 1203 } 1204 } else { 1205 // Should never happen ideally. 1206 Slog.w(TAG, "Empty queue"); 1207 } 1208 break; 1209 } 1210 case MCS_RECONNECT: { 1211 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1212 if (mPendingInstalls.size() > 0) { 1213 if (mBound) { 1214 disconnectService(); 1215 } 1216 if (!connectToService()) { 1217 Slog.e(TAG, "Failed to bind to media container service"); 1218 for (HandlerParams params : mPendingInstalls) { 1219 // Indicate service bind error 1220 params.serviceError(); 1221 } 1222 mPendingInstalls.clear(); 1223 } 1224 } 1225 break; 1226 } 1227 case MCS_UNBIND: { 1228 // If there is no actual work left, then time to unbind. 1229 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1230 1231 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1232 if (mBound) { 1233 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1234 1235 disconnectService(); 1236 } 1237 } else if (mPendingInstalls.size() > 0) { 1238 // There are more pending requests in queue. 1239 // Just post MCS_BOUND message to trigger processing 1240 // of next pending install. 1241 mHandler.sendEmptyMessage(MCS_BOUND); 1242 } 1243 1244 break; 1245 } 1246 case MCS_GIVE_UP: { 1247 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1248 mPendingInstalls.remove(0); 1249 break; 1250 } 1251 case SEND_PENDING_BROADCAST: { 1252 String packages[]; 1253 ArrayList<String> components[]; 1254 int size = 0; 1255 int uids[]; 1256 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1257 synchronized (mPackages) { 1258 if (mPendingBroadcasts == null) { 1259 return; 1260 } 1261 size = mPendingBroadcasts.size(); 1262 if (size <= 0) { 1263 // Nothing to be done. Just return 1264 return; 1265 } 1266 packages = new String[size]; 1267 components = new ArrayList[size]; 1268 uids = new int[size]; 1269 int i = 0; // filling out the above arrays 1270 1271 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1272 int packageUserId = mPendingBroadcasts.userIdAt(n); 1273 Iterator<Map.Entry<String, ArrayList<String>>> it 1274 = mPendingBroadcasts.packagesForUserId(packageUserId) 1275 .entrySet().iterator(); 1276 while (it.hasNext() && i < size) { 1277 Map.Entry<String, ArrayList<String>> ent = it.next(); 1278 packages[i] = ent.getKey(); 1279 components[i] = ent.getValue(); 1280 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1281 uids[i] = (ps != null) 1282 ? UserHandle.getUid(packageUserId, ps.appId) 1283 : -1; 1284 i++; 1285 } 1286 } 1287 size = i; 1288 mPendingBroadcasts.clear(); 1289 } 1290 // Send broadcasts 1291 for (int i = 0; i < size; i++) { 1292 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1293 } 1294 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1295 break; 1296 } 1297 case START_CLEANING_PACKAGE: { 1298 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1299 final String packageName = (String)msg.obj; 1300 final int userId = msg.arg1; 1301 final boolean andCode = msg.arg2 != 0; 1302 synchronized (mPackages) { 1303 if (userId == UserHandle.USER_ALL) { 1304 int[] users = sUserManager.getUserIds(); 1305 for (int user : users) { 1306 mSettings.addPackageToCleanLPw( 1307 new PackageCleanItem(user, packageName, andCode)); 1308 } 1309 } else { 1310 mSettings.addPackageToCleanLPw( 1311 new PackageCleanItem(userId, packageName, andCode)); 1312 } 1313 } 1314 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1315 startCleaningPackages(); 1316 } break; 1317 case POST_INSTALL: { 1318 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1319 PostInstallData data = mRunningInstalls.get(msg.arg1); 1320 mRunningInstalls.delete(msg.arg1); 1321 boolean deleteOld = false; 1322 1323 if (data != null) { 1324 InstallArgs args = data.args; 1325 PackageInstalledInfo res = data.res; 1326 1327 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1328 final String packageName = res.pkg.applicationInfo.packageName; 1329 res.removedInfo.sendBroadcast(false, true, false); 1330 Bundle extras = new Bundle(1); 1331 extras.putInt(Intent.EXTRA_UID, res.uid); 1332 1333 // Now that we successfully installed the package, grant runtime 1334 // permissions if requested before broadcasting the install. 1335 if ((args.installFlags 1336 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1337 grantRequestedRuntimePermissions(res.pkg, 1338 args.user.getIdentifier()); 1339 } 1340 1341 // Determine the set of users who are adding this 1342 // package for the first time vs. those who are seeing 1343 // an update. 1344 int[] firstUsers; 1345 int[] updateUsers = new int[0]; 1346 if (res.origUsers == null || res.origUsers.length == 0) { 1347 firstUsers = res.newUsers; 1348 } else { 1349 firstUsers = new int[0]; 1350 for (int i=0; i<res.newUsers.length; i++) { 1351 int user = res.newUsers[i]; 1352 boolean isNew = true; 1353 for (int j=0; j<res.origUsers.length; j++) { 1354 if (res.origUsers[j] == user) { 1355 isNew = false; 1356 break; 1357 } 1358 } 1359 if (isNew) { 1360 int[] newFirst = new int[firstUsers.length+1]; 1361 System.arraycopy(firstUsers, 0, newFirst, 0, 1362 firstUsers.length); 1363 newFirst[firstUsers.length] = user; 1364 firstUsers = newFirst; 1365 } else { 1366 int[] newUpdate = new int[updateUsers.length+1]; 1367 System.arraycopy(updateUsers, 0, newUpdate, 0, 1368 updateUsers.length); 1369 newUpdate[updateUsers.length] = user; 1370 updateUsers = newUpdate; 1371 } 1372 } 1373 } 1374 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1375 packageName, extras, null, null, firstUsers); 1376 final boolean update = res.removedInfo.removedPackage != null; 1377 if (update) { 1378 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1379 } 1380 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1381 packageName, extras, null, null, updateUsers); 1382 if (update) { 1383 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1384 packageName, extras, null, null, updateUsers); 1385 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1386 null, null, packageName, null, updateUsers); 1387 1388 // treat asec-hosted packages like removable media on upgrade 1389 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1390 if (DEBUG_INSTALL) { 1391 Slog.i(TAG, "upgrading pkg " + res.pkg 1392 + " is ASEC-hosted -> AVAILABLE"); 1393 } 1394 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1395 ArrayList<String> pkgList = new ArrayList<String>(1); 1396 pkgList.add(packageName); 1397 sendResourcesChangedBroadcast(true, true, 1398 pkgList,uidArray, null); 1399 } 1400 } 1401 if (res.removedInfo.args != null) { 1402 // Remove the replaced package's older resources safely now 1403 deleteOld = true; 1404 } 1405 1406 // If this app is a browser and it's newly-installed for some 1407 // users, clear any default-browser state in those users 1408 if (firstUsers.length > 0) { 1409 // the app's nature doesn't depend on the user, so we can just 1410 // check its browser nature in any user and generalize. 1411 if (packageIsBrowser(packageName, firstUsers[0])) { 1412 synchronized (mPackages) { 1413 for (int userId : firstUsers) { 1414 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1415 } 1416 } 1417 } 1418 } 1419 // Log current value of "unknown sources" setting 1420 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1421 getUnknownSourcesSettings()); 1422 } 1423 // Force a gc to clear up things 1424 Runtime.getRuntime().gc(); 1425 // We delete after a gc for applications on sdcard. 1426 if (deleteOld) { 1427 synchronized (mInstallLock) { 1428 res.removedInfo.args.doPostDeleteLI(true); 1429 } 1430 } 1431 if (args.observer != null) { 1432 try { 1433 Bundle extras = extrasForInstallResult(res); 1434 args.observer.onPackageInstalled(res.name, res.returnCode, 1435 res.returnMsg, extras); 1436 } catch (RemoteException e) { 1437 Slog.i(TAG, "Observer no longer exists."); 1438 } 1439 } 1440 } else { 1441 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1442 } 1443 } break; 1444 case UPDATED_MEDIA_STATUS: { 1445 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1446 boolean reportStatus = msg.arg1 == 1; 1447 boolean doGc = msg.arg2 == 1; 1448 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1449 if (doGc) { 1450 // Force a gc to clear up stale containers. 1451 Runtime.getRuntime().gc(); 1452 } 1453 if (msg.obj != null) { 1454 @SuppressWarnings("unchecked") 1455 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1456 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1457 // Unload containers 1458 unloadAllContainers(args); 1459 } 1460 if (reportStatus) { 1461 try { 1462 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1463 PackageHelper.getMountService().finishMediaUpdate(); 1464 } catch (RemoteException e) { 1465 Log.e(TAG, "MountService not running?"); 1466 } 1467 } 1468 } break; 1469 case WRITE_SETTINGS: { 1470 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1471 synchronized (mPackages) { 1472 removeMessages(WRITE_SETTINGS); 1473 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1474 mSettings.writeLPr(); 1475 mDirtyUsers.clear(); 1476 } 1477 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1478 } break; 1479 case WRITE_PACKAGE_RESTRICTIONS: { 1480 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1481 synchronized (mPackages) { 1482 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1483 for (int userId : mDirtyUsers) { 1484 mSettings.writePackageRestrictionsLPr(userId); 1485 } 1486 mDirtyUsers.clear(); 1487 } 1488 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1489 } break; 1490 case CHECK_PENDING_VERIFICATION: { 1491 final int verificationId = msg.arg1; 1492 final PackageVerificationState state = mPendingVerification.get(verificationId); 1493 1494 if ((state != null) && !state.timeoutExtended()) { 1495 final InstallArgs args = state.getInstallArgs(); 1496 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1497 1498 Slog.i(TAG, "Verification timed out for " + originUri); 1499 mPendingVerification.remove(verificationId); 1500 1501 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1502 1503 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1504 Slog.i(TAG, "Continuing with installation of " + originUri); 1505 state.setVerifierResponse(Binder.getCallingUid(), 1506 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1507 broadcastPackageVerified(verificationId, originUri, 1508 PackageManager.VERIFICATION_ALLOW, 1509 state.getInstallArgs().getUser()); 1510 try { 1511 ret = args.copyApk(mContainerService, true); 1512 } catch (RemoteException e) { 1513 Slog.e(TAG, "Could not contact the ContainerService"); 1514 } 1515 } else { 1516 broadcastPackageVerified(verificationId, originUri, 1517 PackageManager.VERIFICATION_REJECT, 1518 state.getInstallArgs().getUser()); 1519 } 1520 1521 processPendingInstall(args, ret); 1522 mHandler.sendEmptyMessage(MCS_UNBIND); 1523 } 1524 break; 1525 } 1526 case PACKAGE_VERIFIED: { 1527 final int verificationId = msg.arg1; 1528 1529 final PackageVerificationState state = mPendingVerification.get(verificationId); 1530 if (state == null) { 1531 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1532 break; 1533 } 1534 1535 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1536 1537 state.setVerifierResponse(response.callerUid, response.code); 1538 1539 if (state.isVerificationComplete()) { 1540 mPendingVerification.remove(verificationId); 1541 1542 final InstallArgs args = state.getInstallArgs(); 1543 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1544 1545 int ret; 1546 if (state.isInstallAllowed()) { 1547 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1548 broadcastPackageVerified(verificationId, originUri, 1549 response.code, state.getInstallArgs().getUser()); 1550 try { 1551 ret = args.copyApk(mContainerService, true); 1552 } catch (RemoteException e) { 1553 Slog.e(TAG, "Could not contact the ContainerService"); 1554 } 1555 } else { 1556 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1557 } 1558 1559 processPendingInstall(args, ret); 1560 1561 mHandler.sendEmptyMessage(MCS_UNBIND); 1562 } 1563 1564 break; 1565 } 1566 case START_INTENT_FILTER_VERIFICATIONS: { 1567 IFVerificationParams params = (IFVerificationParams) msg.obj; 1568 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1569 params.replacing, params.pkg); 1570 break; 1571 } 1572 case INTENT_FILTER_VERIFIED: { 1573 final int verificationId = msg.arg1; 1574 1575 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1576 verificationId); 1577 if (state == null) { 1578 Slog.w(TAG, "Invalid IntentFilter verification token " 1579 + verificationId + " received"); 1580 break; 1581 } 1582 1583 final int userId = state.getUserId(); 1584 1585 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1586 "Processing IntentFilter verification with token:" 1587 + verificationId + " and userId:" + userId); 1588 1589 final IntentFilterVerificationResponse response = 1590 (IntentFilterVerificationResponse) msg.obj; 1591 1592 state.setVerifierResponse(response.callerUid, response.code); 1593 1594 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1595 "IntentFilter verification with token:" + verificationId 1596 + " and userId:" + userId 1597 + " is settings verifier response with response code:" 1598 + response.code); 1599 1600 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1601 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1602 + response.getFailedDomainsString()); 1603 } 1604 1605 if (state.isVerificationComplete()) { 1606 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1607 } else { 1608 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1609 "IntentFilter verification with token:" + verificationId 1610 + " was not said to be complete"); 1611 } 1612 1613 break; 1614 } 1615 } 1616 } 1617 } 1618 1619 private StorageEventListener mStorageListener = new StorageEventListener() { 1620 @Override 1621 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1622 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1623 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1624 final String volumeUuid = vol.getFsUuid(); 1625 1626 // Clean up any users or apps that were removed or recreated 1627 // while this volume was missing 1628 reconcileUsers(volumeUuid); 1629 reconcileApps(volumeUuid); 1630 1631 // Clean up any install sessions that expired or were 1632 // cancelled while this volume was missing 1633 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1634 1635 loadPrivatePackages(vol); 1636 1637 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1638 unloadPrivatePackages(vol); 1639 } 1640 } 1641 1642 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1643 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1644 updateExternalMediaStatus(true, false); 1645 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1646 updateExternalMediaStatus(false, false); 1647 } 1648 } 1649 } 1650 1651 @Override 1652 public void onVolumeForgotten(String fsUuid) { 1653 // Remove any apps installed on the forgotten volume 1654 synchronized (mPackages) { 1655 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1656 for (PackageSetting ps : packages) { 1657 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1658 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1659 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1660 } 1661 1662 mSettings.writeLPr(); 1663 } 1664 } 1665 }; 1666 1667 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1668 if (userId >= UserHandle.USER_OWNER) { 1669 grantRequestedRuntimePermissionsForUser(pkg, userId); 1670 } else if (userId == UserHandle.USER_ALL) { 1671 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1672 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1673 } 1674 } 1675 1676 // We could have touched GID membership, so flush out packages.list 1677 synchronized (mPackages) { 1678 mSettings.writePackageListLPr(); 1679 } 1680 } 1681 1682 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1683 SettingBase sb = (SettingBase) pkg.mExtras; 1684 if (sb == null) { 1685 return; 1686 } 1687 1688 PermissionsState permissionsState = sb.getPermissionsState(); 1689 1690 for (String permission : pkg.requestedPermissions) { 1691 BasePermission bp = mSettings.mPermissions.get(permission); 1692 if (bp != null && bp.isRuntime()) { 1693 permissionsState.grantRuntimePermission(bp, userId); 1694 } 1695 } 1696 } 1697 1698 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1699 Bundle extras = null; 1700 switch (res.returnCode) { 1701 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1702 extras = new Bundle(); 1703 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1704 res.origPermission); 1705 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1706 res.origPackage); 1707 break; 1708 } 1709 case PackageManager.INSTALL_SUCCEEDED: { 1710 extras = new Bundle(); 1711 extras.putBoolean(Intent.EXTRA_REPLACING, 1712 res.removedInfo != null && res.removedInfo.removedPackage != null); 1713 break; 1714 } 1715 } 1716 return extras; 1717 } 1718 1719 void scheduleWriteSettingsLocked() { 1720 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1721 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1722 } 1723 } 1724 1725 void scheduleWritePackageRestrictionsLocked(int userId) { 1726 if (!sUserManager.exists(userId)) return; 1727 mDirtyUsers.add(userId); 1728 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1729 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1730 } 1731 } 1732 1733 public static PackageManagerService main(Context context, Installer installer, 1734 boolean factoryTest, boolean onlyCore) { 1735 PackageManagerService m = new PackageManagerService(context, installer, 1736 factoryTest, onlyCore); 1737 ServiceManager.addService("package", m); 1738 return m; 1739 } 1740 1741 static String[] splitString(String str, char sep) { 1742 int count = 1; 1743 int i = 0; 1744 while ((i=str.indexOf(sep, i)) >= 0) { 1745 count++; 1746 i++; 1747 } 1748 1749 String[] res = new String[count]; 1750 i=0; 1751 count = 0; 1752 int lastI=0; 1753 while ((i=str.indexOf(sep, i)) >= 0) { 1754 res[count] = str.substring(lastI, i); 1755 count++; 1756 i++; 1757 lastI = i; 1758 } 1759 res[count] = str.substring(lastI, str.length()); 1760 return res; 1761 } 1762 1763 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1764 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1765 Context.DISPLAY_SERVICE); 1766 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1767 } 1768 1769 public PackageManagerService(Context context, Installer installer, 1770 boolean factoryTest, boolean onlyCore) { 1771 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1772 SystemClock.uptimeMillis()); 1773 1774 if (mSdkVersion <= 0) { 1775 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1776 } 1777 1778 mContext = context; 1779 mFactoryTest = factoryTest; 1780 mOnlyCore = onlyCore; 1781 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1782 mMetrics = new DisplayMetrics(); 1783 mSettings = new Settings(mPackages); 1784 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1785 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1786 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1787 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1788 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1789 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1790 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1791 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1792 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1793 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1794 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1795 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1796 1797 // TODO: add a property to control this? 1798 long dexOptLRUThresholdInMinutes; 1799 if (mLazyDexOpt) { 1800 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1801 } else { 1802 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1803 } 1804 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1805 1806 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1807 if (separateProcesses != null && separateProcesses.length() > 0) { 1808 if ("*".equals(separateProcesses)) { 1809 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1810 mSeparateProcesses = null; 1811 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1812 } else { 1813 mDefParseFlags = 0; 1814 mSeparateProcesses = separateProcesses.split(","); 1815 Slog.w(TAG, "Running with debug.separate_processes: " 1816 + separateProcesses); 1817 } 1818 } else { 1819 mDefParseFlags = 0; 1820 mSeparateProcesses = null; 1821 } 1822 1823 mInstaller = installer; 1824 mPackageDexOptimizer = new PackageDexOptimizer(this); 1825 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1826 1827 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1828 FgThread.get().getLooper()); 1829 1830 getDefaultDisplayMetrics(context, mMetrics); 1831 1832 SystemConfig systemConfig = SystemConfig.getInstance(); 1833 mGlobalGids = systemConfig.getGlobalGids(); 1834 mSystemPermissions = systemConfig.getSystemPermissions(); 1835 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1836 1837 synchronized (mInstallLock) { 1838 // writer 1839 synchronized (mPackages) { 1840 mHandlerThread = new ServiceThread(TAG, 1841 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1842 mHandlerThread.start(); 1843 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1844 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1845 1846 File dataDir = Environment.getDataDirectory(); 1847 mAppDataDir = new File(dataDir, "data"); 1848 mAppInstallDir = new File(dataDir, "app"); 1849 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1850 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1851 mUserAppDataDir = new File(dataDir, "user"); 1852 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1853 1854 sUserManager = new UserManagerService(context, this, 1855 mInstallLock, mPackages); 1856 1857 // Propagate permission configuration in to package manager. 1858 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1859 = systemConfig.getPermissions(); 1860 for (int i=0; i<permConfig.size(); i++) { 1861 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1862 BasePermission bp = mSettings.mPermissions.get(perm.name); 1863 if (bp == null) { 1864 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1865 mSettings.mPermissions.put(perm.name, bp); 1866 } 1867 if (perm.gids != null) { 1868 bp.setGids(perm.gids, perm.perUser); 1869 } 1870 } 1871 1872 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1873 for (int i=0; i<libConfig.size(); i++) { 1874 mSharedLibraries.put(libConfig.keyAt(i), 1875 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1876 } 1877 1878 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1879 1880 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1881 mSdkVersion, mOnlyCore); 1882 1883 String customResolverActivity = Resources.getSystem().getString( 1884 R.string.config_customResolverActivity); 1885 if (TextUtils.isEmpty(customResolverActivity)) { 1886 customResolverActivity = null; 1887 } else { 1888 mCustomResolverComponentName = ComponentName.unflattenFromString( 1889 customResolverActivity); 1890 } 1891 1892 long startTime = SystemClock.uptimeMillis(); 1893 1894 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1895 startTime); 1896 1897 // Set flag to monitor and not change apk file paths when 1898 // scanning install directories. 1899 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1900 1901 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1902 1903 /** 1904 * Add everything in the in the boot class path to the 1905 * list of process files because dexopt will have been run 1906 * if necessary during zygote startup. 1907 */ 1908 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1909 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1910 1911 if (bootClassPath != null) { 1912 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1913 for (String element : bootClassPathElements) { 1914 alreadyDexOpted.add(element); 1915 } 1916 } else { 1917 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1918 } 1919 1920 if (systemServerClassPath != null) { 1921 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1922 for (String element : systemServerClassPathElements) { 1923 alreadyDexOpted.add(element); 1924 } 1925 } else { 1926 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1927 } 1928 1929 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1930 final String[] dexCodeInstructionSets = 1931 getDexCodeInstructionSets( 1932 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1933 1934 /** 1935 * Ensure all external libraries have had dexopt run on them. 1936 */ 1937 if (mSharedLibraries.size() > 0) { 1938 // NOTE: For now, we're compiling these system "shared libraries" 1939 // (and framework jars) into all available architectures. It's possible 1940 // to compile them only when we come across an app that uses them (there's 1941 // already logic for that in scanPackageLI) but that adds some complexity. 1942 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1943 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1944 final String lib = libEntry.path; 1945 if (lib == null) { 1946 continue; 1947 } 1948 1949 try { 1950 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1951 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1952 alreadyDexOpted.add(lib); 1953 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1954 } 1955 } catch (FileNotFoundException e) { 1956 Slog.w(TAG, "Library not found: " + lib); 1957 } catch (IOException e) { 1958 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1959 + e.getMessage()); 1960 } 1961 } 1962 } 1963 } 1964 1965 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1966 1967 // Gross hack for now: we know this file doesn't contain any 1968 // code, so don't dexopt it to avoid the resulting log spew. 1969 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1970 1971 // Gross hack for now: we know this file is only part of 1972 // the boot class path for art, so don't dexopt it to 1973 // avoid the resulting log spew. 1974 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1975 1976 /** 1977 * There are a number of commands implemented in Java, which 1978 * we currently need to do the dexopt on so that they can be 1979 * run from a non-root shell. 1980 */ 1981 String[] frameworkFiles = frameworkDir.list(); 1982 if (frameworkFiles != null) { 1983 // TODO: We could compile these only for the most preferred ABI. We should 1984 // first double check that the dex files for these commands are not referenced 1985 // by other system apps. 1986 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1987 for (int i=0; i<frameworkFiles.length; i++) { 1988 File libPath = new File(frameworkDir, frameworkFiles[i]); 1989 String path = libPath.getPath(); 1990 // Skip the file if we already did it. 1991 if (alreadyDexOpted.contains(path)) { 1992 continue; 1993 } 1994 // Skip the file if it is not a type we want to dexopt. 1995 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1996 continue; 1997 } 1998 try { 1999 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2000 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2001 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2002 } 2003 } catch (FileNotFoundException e) { 2004 Slog.w(TAG, "Jar not found: " + path); 2005 } catch (IOException e) { 2006 Slog.w(TAG, "Exception reading jar: " + path, e); 2007 } 2008 } 2009 } 2010 } 2011 2012 // Collect vendor overlay packages. 2013 // (Do this before scanning any apps.) 2014 // For security and version matching reason, only consider 2015 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2016 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2017 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2018 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2019 2020 // Find base frameworks (resource packages without code). 2021 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2022 | PackageParser.PARSE_IS_SYSTEM_DIR 2023 | PackageParser.PARSE_IS_PRIVILEGED, 2024 scanFlags | SCAN_NO_DEX, 0); 2025 2026 // Collected privileged system packages. 2027 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2028 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2029 | PackageParser.PARSE_IS_SYSTEM_DIR 2030 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2031 2032 // Collect ordinary system packages. 2033 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2034 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2035 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2036 2037 // Collect all vendor packages. 2038 File vendorAppDir = new File("/vendor/app"); 2039 try { 2040 vendorAppDir = vendorAppDir.getCanonicalFile(); 2041 } catch (IOException e) { 2042 // failed to look up canonical path, continue with original one 2043 } 2044 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2045 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2046 2047 // Collect all OEM packages. 2048 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2049 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2050 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2051 2052 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2053 mInstaller.moveFiles(); 2054 2055 // Prune any system packages that no longer exist. 2056 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2057 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 2058 if (!mOnlyCore) { 2059 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2060 while (psit.hasNext()) { 2061 PackageSetting ps = psit.next(); 2062 2063 /* 2064 * If this is not a system app, it can't be a 2065 * disable system app. 2066 */ 2067 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2068 continue; 2069 } 2070 2071 /* 2072 * If the package is scanned, it's not erased. 2073 */ 2074 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2075 if (scannedPkg != null) { 2076 /* 2077 * If the system app is both scanned and in the 2078 * disabled packages list, then it must have been 2079 * added via OTA. Remove it from the currently 2080 * scanned package so the previously user-installed 2081 * application can be scanned. 2082 */ 2083 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2084 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2085 + ps.name + "; removing system app. Last known codePath=" 2086 + ps.codePathString + ", installStatus=" + ps.installStatus 2087 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2088 + scannedPkg.mVersionCode); 2089 removePackageLI(ps, true); 2090 expectingBetter.put(ps.name, ps.codePath); 2091 } 2092 2093 continue; 2094 } 2095 2096 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2097 psit.remove(); 2098 logCriticalInfo(Log.WARN, "System package " + ps.name 2099 + " no longer exists; wiping its data"); 2100 removeDataDirsLI(null, ps.name); 2101 } else { 2102 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2103 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2104 possiblyDeletedUpdatedSystemApps.add(ps.name); 2105 } 2106 } 2107 } 2108 } 2109 2110 //look for any incomplete package installations 2111 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2112 //clean up list 2113 for(int i = 0; i < deletePkgsList.size(); i++) { 2114 //clean up here 2115 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2116 } 2117 //delete tmp files 2118 deleteTempPackageFiles(); 2119 2120 // Remove any shared userIDs that have no associated packages 2121 mSettings.pruneSharedUsersLPw(); 2122 2123 if (!mOnlyCore) { 2124 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2125 SystemClock.uptimeMillis()); 2126 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2127 2128 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2129 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2130 2131 /** 2132 * Remove disable package settings for any updated system 2133 * apps that were removed via an OTA. If they're not a 2134 * previously-updated app, remove them completely. 2135 * Otherwise, just revoke their system-level permissions. 2136 */ 2137 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2138 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2139 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2140 2141 String msg; 2142 if (deletedPkg == null) { 2143 msg = "Updated system package " + deletedAppName 2144 + " no longer exists; wiping its data"; 2145 removeDataDirsLI(null, deletedAppName); 2146 } else { 2147 msg = "Updated system app + " + deletedAppName 2148 + " no longer present; removing system privileges for " 2149 + deletedAppName; 2150 2151 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2152 2153 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2154 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2155 } 2156 logCriticalInfo(Log.WARN, msg); 2157 } 2158 2159 /** 2160 * Make sure all system apps that we expected to appear on 2161 * the userdata partition actually showed up. If they never 2162 * appeared, crawl back and revive the system version. 2163 */ 2164 for (int i = 0; i < expectingBetter.size(); i++) { 2165 final String packageName = expectingBetter.keyAt(i); 2166 if (!mPackages.containsKey(packageName)) { 2167 final File scanFile = expectingBetter.valueAt(i); 2168 2169 logCriticalInfo(Log.WARN, "Expected better " + packageName 2170 + " but never showed up; reverting to system"); 2171 2172 final int reparseFlags; 2173 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2174 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2175 | PackageParser.PARSE_IS_SYSTEM_DIR 2176 | PackageParser.PARSE_IS_PRIVILEGED; 2177 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2178 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2179 | PackageParser.PARSE_IS_SYSTEM_DIR; 2180 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2181 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2182 | PackageParser.PARSE_IS_SYSTEM_DIR; 2183 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2184 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2185 | PackageParser.PARSE_IS_SYSTEM_DIR; 2186 } else { 2187 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2188 continue; 2189 } 2190 2191 mSettings.enableSystemPackageLPw(packageName); 2192 2193 try { 2194 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2195 } catch (PackageManagerException e) { 2196 Slog.e(TAG, "Failed to parse original system package: " 2197 + e.getMessage()); 2198 } 2199 } 2200 } 2201 } 2202 2203 // Now that we know all of the shared libraries, update all clients to have 2204 // the correct library paths. 2205 updateAllSharedLibrariesLPw(); 2206 2207 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2208 // NOTE: We ignore potential failures here during a system scan (like 2209 // the rest of the commands above) because there's precious little we 2210 // can do about it. A settings error is reported, though. 2211 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2212 false /* force dexopt */, false /* defer dexopt */); 2213 } 2214 2215 // Now that we know all the packages we are keeping, 2216 // read and update their last usage times. 2217 mPackageUsage.readLP(); 2218 2219 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2220 SystemClock.uptimeMillis()); 2221 Slog.i(TAG, "Time to scan packages: " 2222 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2223 + " seconds"); 2224 2225 // If the platform SDK has changed since the last time we booted, 2226 // we need to re-grant app permission to catch any new ones that 2227 // appear. This is really a hack, and means that apps can in some 2228 // cases get permissions that the user didn't initially explicitly 2229 // allow... it would be nice to have some better way to handle 2230 // this situation. 2231 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2232 != mSdkVersion; 2233 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2234 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2235 + "; regranting permissions for internal storage"); 2236 mSettings.mInternalSdkPlatform = mSdkVersion; 2237 2238 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2239 | (regrantPermissions 2240 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2241 : 0)); 2242 2243 // If this is the first boot, and it is a normal boot, then 2244 // we need to initialize the default preferred apps. 2245 if (!mRestoredSettings && !onlyCore) { 2246 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2247 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2248 } 2249 2250 // If this is first boot after an OTA, and a normal boot, then 2251 // we need to clear code cache directories. 2252 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2253 if (mIsUpgrade && !onlyCore) { 2254 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2255 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2256 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2257 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2258 } 2259 mSettings.mFingerprint = Build.FINGERPRINT; 2260 } 2261 2262 primeDomainVerificationsLPw(); 2263 checkDefaultBrowser(); 2264 2265 // All the changes are done during package scanning. 2266 mSettings.updateInternalDatabaseVersion(); 2267 2268 // can downgrade to reader 2269 mSettings.writeLPr(); 2270 2271 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2272 SystemClock.uptimeMillis()); 2273 2274 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2275 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2276 2277 mInstallerService = new PackageInstallerService(context, this); 2278 2279 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2280 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2281 mIntentFilterVerifierComponent); 2282 2283 } // synchronized (mPackages) 2284 } // synchronized (mInstallLock) 2285 2286 // Now after opening every single application zip, make sure they 2287 // are all flushed. Not really needed, but keeps things nice and 2288 // tidy. 2289 Runtime.getRuntime().gc(); 2290 2291 // Expose private service for system components to use. 2292 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2293 } 2294 2295 @Override 2296 public boolean isFirstBoot() { 2297 return !mRestoredSettings; 2298 } 2299 2300 @Override 2301 public boolean isOnlyCoreApps() { 2302 return mOnlyCore; 2303 } 2304 2305 @Override 2306 public boolean isUpgrade() { 2307 return mIsUpgrade; 2308 } 2309 2310 private String getRequiredVerifierLPr() { 2311 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2312 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2313 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2314 2315 String requiredVerifier = null; 2316 2317 final int N = receivers.size(); 2318 for (int i = 0; i < N; i++) { 2319 final ResolveInfo info = receivers.get(i); 2320 2321 if (info.activityInfo == null) { 2322 continue; 2323 } 2324 2325 final String packageName = info.activityInfo.packageName; 2326 2327 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2328 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2329 continue; 2330 } 2331 2332 if (requiredVerifier != null) { 2333 throw new RuntimeException("There can be only one required verifier"); 2334 } 2335 2336 requiredVerifier = packageName; 2337 } 2338 2339 return requiredVerifier; 2340 } 2341 2342 private String getRequiredInstallerLPr() { 2343 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2344 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2345 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2346 2347 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2348 PACKAGE_MIME_TYPE, 0, 0); 2349 2350 String requiredInstaller = null; 2351 2352 final int N = installers.size(); 2353 for (int i = 0; i < N; i++) { 2354 final ResolveInfo info = installers.get(i); 2355 final String packageName = info.activityInfo.packageName; 2356 2357 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2358 continue; 2359 } 2360 2361 if (requiredInstaller != null) { 2362 throw new RuntimeException("There must be one required installer"); 2363 } 2364 2365 requiredInstaller = packageName; 2366 } 2367 2368 if (requiredInstaller == null) { 2369 throw new RuntimeException("There must be one required installer"); 2370 } 2371 2372 return requiredInstaller; 2373 } 2374 2375 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2376 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2377 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2378 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2379 2380 ComponentName verifierComponentName = null; 2381 2382 int priority = -1000; 2383 final int N = receivers.size(); 2384 for (int i = 0; i < N; i++) { 2385 final ResolveInfo info = receivers.get(i); 2386 2387 if (info.activityInfo == null) { 2388 continue; 2389 } 2390 2391 final String packageName = info.activityInfo.packageName; 2392 2393 final PackageSetting ps = mSettings.mPackages.get(packageName); 2394 if (ps == null) { 2395 continue; 2396 } 2397 2398 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2399 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2400 continue; 2401 } 2402 2403 // Select the IntentFilterVerifier with the highest priority 2404 if (priority < info.priority) { 2405 priority = info.priority; 2406 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2407 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2408 + verifierComponentName + " with priority: " + info.priority); 2409 } 2410 } 2411 2412 return verifierComponentName; 2413 } 2414 2415 private void primeDomainVerificationsLPw() { 2416 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2417 boolean updated = false; 2418 ArraySet<String> allHostsSet = new ArraySet<>(); 2419 for (PackageParser.Package pkg : mPackages.values()) { 2420 final String packageName = pkg.packageName; 2421 if (!hasDomainURLs(pkg)) { 2422 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2423 "package with no domain URLs: " + packageName); 2424 continue; 2425 } 2426 if (!pkg.isSystemApp()) { 2427 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2428 "No priming domain verifications for a non system package : " + 2429 packageName); 2430 continue; 2431 } 2432 for (PackageParser.Activity a : pkg.activities) { 2433 for (ActivityIntentInfo filter : a.intents) { 2434 if (hasValidDomains(filter)) { 2435 allHostsSet.addAll(filter.getHostsList()); 2436 } 2437 } 2438 } 2439 if (allHostsSet.size() == 0) { 2440 allHostsSet.add("*"); 2441 } 2442 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2443 IntentFilterVerificationInfo ivi = 2444 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2445 if (ivi != null) { 2446 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2447 "Priming domain verifications for package: " + packageName + 2448 " with hosts:" + ivi.getDomainsString()); 2449 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2450 updated = true; 2451 } 2452 else { 2453 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2454 "No priming domain verifications for package: " + packageName); 2455 } 2456 allHostsSet.clear(); 2457 } 2458 if (updated) { 2459 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2460 "Will need to write primed domain verifications"); 2461 } 2462 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2463 } 2464 2465 private void applyFactoryDefaultBrowserLPw(int userId) { 2466 // The default browser app's package name is stored in a string resource, 2467 // with a product-specific overlay used for vendor customization. 2468 String browserPkg = mContext.getResources().getString( 2469 com.android.internal.R.string.default_browser); 2470 if (browserPkg != null) { 2471 // non-empty string => required to be a known package 2472 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2473 if (ps == null) { 2474 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2475 browserPkg = null; 2476 } else { 2477 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2478 } 2479 } 2480 2481 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2482 // default. If there's more than one, just leave everything alone. 2483 if (browserPkg == null) { 2484 calculateDefaultBrowserLPw(userId); 2485 } 2486 } 2487 2488 private void calculateDefaultBrowserLPw(int userId) { 2489 List<String> allBrowsers = resolveAllBrowserApps(userId); 2490 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2491 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2492 } 2493 2494 private List<String> resolveAllBrowserApps(int userId) { 2495 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2496 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2497 PackageManager.MATCH_ALL, userId); 2498 2499 final int count = list.size(); 2500 List<String> result = new ArrayList<String>(count); 2501 for (int i=0; i<count; i++) { 2502 ResolveInfo info = list.get(i); 2503 if (info.activityInfo == null 2504 || !info.handleAllWebDataURI 2505 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2506 || result.contains(info.activityInfo.packageName)) { 2507 continue; 2508 } 2509 result.add(info.activityInfo.packageName); 2510 } 2511 2512 return result; 2513 } 2514 2515 private boolean packageIsBrowser(String packageName, int userId) { 2516 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2517 PackageManager.MATCH_ALL, userId); 2518 final int N = list.size(); 2519 for (int i = 0; i < N; i++) { 2520 ResolveInfo info = list.get(i); 2521 if (packageName.equals(info.activityInfo.packageName)) { 2522 return true; 2523 } 2524 } 2525 return false; 2526 } 2527 2528 private void checkDefaultBrowser() { 2529 final int myUserId = UserHandle.myUserId(); 2530 final String packageName = getDefaultBrowserPackageName(myUserId); 2531 if (packageName != null) { 2532 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2533 if (info == null) { 2534 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2535 synchronized (mPackages) { 2536 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2537 } 2538 } 2539 } 2540 } 2541 2542 @Override 2543 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2544 throws RemoteException { 2545 try { 2546 return super.onTransact(code, data, reply, flags); 2547 } catch (RuntimeException e) { 2548 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2549 Slog.wtf(TAG, "Package Manager Crash", e); 2550 } 2551 throw e; 2552 } 2553 } 2554 2555 void cleanupInstallFailedPackage(PackageSetting ps) { 2556 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2557 2558 removeDataDirsLI(ps.volumeUuid, ps.name); 2559 if (ps.codePath != null) { 2560 if (ps.codePath.isDirectory()) { 2561 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2562 } else { 2563 ps.codePath.delete(); 2564 } 2565 } 2566 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2567 if (ps.resourcePath.isDirectory()) { 2568 FileUtils.deleteContents(ps.resourcePath); 2569 } 2570 ps.resourcePath.delete(); 2571 } 2572 mSettings.removePackageLPw(ps.name); 2573 } 2574 2575 static int[] appendInts(int[] cur, int[] add) { 2576 if (add == null) return cur; 2577 if (cur == null) return add; 2578 final int N = add.length; 2579 for (int i=0; i<N; i++) { 2580 cur = appendInt(cur, add[i]); 2581 } 2582 return cur; 2583 } 2584 2585 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2586 if (!sUserManager.exists(userId)) return null; 2587 final PackageSetting ps = (PackageSetting) p.mExtras; 2588 if (ps == null) { 2589 return null; 2590 } 2591 2592 final PermissionsState permissionsState = ps.getPermissionsState(); 2593 2594 final int[] gids = permissionsState.computeGids(userId); 2595 final Set<String> permissions = permissionsState.getPermissions(userId); 2596 final PackageUserState state = ps.readUserState(userId); 2597 2598 return PackageParser.generatePackageInfo(p, gids, flags, 2599 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2600 } 2601 2602 @Override 2603 public boolean isPackageFrozen(String packageName) { 2604 synchronized (mPackages) { 2605 final PackageSetting ps = mSettings.mPackages.get(packageName); 2606 if (ps != null) { 2607 return ps.frozen; 2608 } 2609 } 2610 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2611 return true; 2612 } 2613 2614 @Override 2615 public boolean isPackageAvailable(String packageName, int userId) { 2616 if (!sUserManager.exists(userId)) return false; 2617 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2618 synchronized (mPackages) { 2619 PackageParser.Package p = mPackages.get(packageName); 2620 if (p != null) { 2621 final PackageSetting ps = (PackageSetting) p.mExtras; 2622 if (ps != null) { 2623 final PackageUserState state = ps.readUserState(userId); 2624 if (state != null) { 2625 return PackageParser.isAvailable(state); 2626 } 2627 } 2628 } 2629 } 2630 return false; 2631 } 2632 2633 @Override 2634 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2635 if (!sUserManager.exists(userId)) return null; 2636 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2637 // reader 2638 synchronized (mPackages) { 2639 PackageParser.Package p = mPackages.get(packageName); 2640 if (DEBUG_PACKAGE_INFO) 2641 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2642 if (p != null) { 2643 return generatePackageInfo(p, flags, userId); 2644 } 2645 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2646 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2647 } 2648 } 2649 return null; 2650 } 2651 2652 @Override 2653 public String[] currentToCanonicalPackageNames(String[] names) { 2654 String[] out = new String[names.length]; 2655 // reader 2656 synchronized (mPackages) { 2657 for (int i=names.length-1; i>=0; i--) { 2658 PackageSetting ps = mSettings.mPackages.get(names[i]); 2659 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2660 } 2661 } 2662 return out; 2663 } 2664 2665 @Override 2666 public String[] canonicalToCurrentPackageNames(String[] names) { 2667 String[] out = new String[names.length]; 2668 // reader 2669 synchronized (mPackages) { 2670 for (int i=names.length-1; i>=0; i--) { 2671 String cur = mSettings.mRenamedPackages.get(names[i]); 2672 out[i] = cur != null ? cur : names[i]; 2673 } 2674 } 2675 return out; 2676 } 2677 2678 @Override 2679 public int getPackageUid(String packageName, int userId) { 2680 if (!sUserManager.exists(userId)) return -1; 2681 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2682 2683 // reader 2684 synchronized (mPackages) { 2685 PackageParser.Package p = mPackages.get(packageName); 2686 if(p != null) { 2687 return UserHandle.getUid(userId, p.applicationInfo.uid); 2688 } 2689 PackageSetting ps = mSettings.mPackages.get(packageName); 2690 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2691 return -1; 2692 } 2693 p = ps.pkg; 2694 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2695 } 2696 } 2697 2698 @Override 2699 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2700 if (!sUserManager.exists(userId)) { 2701 return null; 2702 } 2703 2704 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2705 "getPackageGids"); 2706 2707 // reader 2708 synchronized (mPackages) { 2709 PackageParser.Package p = mPackages.get(packageName); 2710 if (DEBUG_PACKAGE_INFO) { 2711 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2712 } 2713 if (p != null) { 2714 PackageSetting ps = (PackageSetting) p.mExtras; 2715 return ps.getPermissionsState().computeGids(userId); 2716 } 2717 } 2718 2719 return null; 2720 } 2721 2722 @Override 2723 public int getMountExternalMode(int uid) { 2724 if (Process.isIsolated(uid)) { 2725 return Zygote.MOUNT_EXTERNAL_NONE; 2726 } else { 2727 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 2728 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2729 } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2730 return Zygote.MOUNT_EXTERNAL_WRITE; 2731 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2732 return Zygote.MOUNT_EXTERNAL_READ; 2733 } else { 2734 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2735 } 2736 } 2737 } 2738 2739 static PermissionInfo generatePermissionInfo( 2740 BasePermission bp, int flags) { 2741 if (bp.perm != null) { 2742 return PackageParser.generatePermissionInfo(bp.perm, flags); 2743 } 2744 PermissionInfo pi = new PermissionInfo(); 2745 pi.name = bp.name; 2746 pi.packageName = bp.sourcePackage; 2747 pi.nonLocalizedLabel = bp.name; 2748 pi.protectionLevel = bp.protectionLevel; 2749 return pi; 2750 } 2751 2752 @Override 2753 public PermissionInfo getPermissionInfo(String name, int flags) { 2754 // reader 2755 synchronized (mPackages) { 2756 final BasePermission p = mSettings.mPermissions.get(name); 2757 if (p != null) { 2758 return generatePermissionInfo(p, flags); 2759 } 2760 return null; 2761 } 2762 } 2763 2764 @Override 2765 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2766 // reader 2767 synchronized (mPackages) { 2768 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2769 for (BasePermission p : mSettings.mPermissions.values()) { 2770 if (group == null) { 2771 if (p.perm == null || p.perm.info.group == null) { 2772 out.add(generatePermissionInfo(p, flags)); 2773 } 2774 } else { 2775 if (p.perm != null && group.equals(p.perm.info.group)) { 2776 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2777 } 2778 } 2779 } 2780 2781 if (out.size() > 0) { 2782 return out; 2783 } 2784 return mPermissionGroups.containsKey(group) ? out : null; 2785 } 2786 } 2787 2788 @Override 2789 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2790 // reader 2791 synchronized (mPackages) { 2792 return PackageParser.generatePermissionGroupInfo( 2793 mPermissionGroups.get(name), flags); 2794 } 2795 } 2796 2797 @Override 2798 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2799 // reader 2800 synchronized (mPackages) { 2801 final int N = mPermissionGroups.size(); 2802 ArrayList<PermissionGroupInfo> out 2803 = new ArrayList<PermissionGroupInfo>(N); 2804 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2805 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2806 } 2807 return out; 2808 } 2809 } 2810 2811 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2812 int userId) { 2813 if (!sUserManager.exists(userId)) return null; 2814 PackageSetting ps = mSettings.mPackages.get(packageName); 2815 if (ps != null) { 2816 if (ps.pkg == null) { 2817 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2818 flags, userId); 2819 if (pInfo != null) { 2820 return pInfo.applicationInfo; 2821 } 2822 return null; 2823 } 2824 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2825 ps.readUserState(userId), userId); 2826 } 2827 return null; 2828 } 2829 2830 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2831 int userId) { 2832 if (!sUserManager.exists(userId)) return null; 2833 PackageSetting ps = mSettings.mPackages.get(packageName); 2834 if (ps != null) { 2835 PackageParser.Package pkg = ps.pkg; 2836 if (pkg == null) { 2837 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2838 return null; 2839 } 2840 // Only data remains, so we aren't worried about code paths 2841 pkg = new PackageParser.Package(packageName); 2842 pkg.applicationInfo.packageName = packageName; 2843 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2844 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2845 pkg.applicationInfo.dataDir = Environment 2846 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2847 .getAbsolutePath(); 2848 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2849 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2850 } 2851 return generatePackageInfo(pkg, flags, userId); 2852 } 2853 return null; 2854 } 2855 2856 @Override 2857 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2858 if (!sUserManager.exists(userId)) return null; 2859 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2860 // writer 2861 synchronized (mPackages) { 2862 PackageParser.Package p = mPackages.get(packageName); 2863 if (DEBUG_PACKAGE_INFO) Log.v( 2864 TAG, "getApplicationInfo " + packageName 2865 + ": " + p); 2866 if (p != null) { 2867 PackageSetting ps = mSettings.mPackages.get(packageName); 2868 if (ps == null) return null; 2869 // Note: isEnabledLP() does not apply here - always return info 2870 return PackageParser.generateApplicationInfo( 2871 p, flags, ps.readUserState(userId), userId); 2872 } 2873 if ("android".equals(packageName)||"system".equals(packageName)) { 2874 return mAndroidApplication; 2875 } 2876 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2877 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2878 } 2879 } 2880 return null; 2881 } 2882 2883 @Override 2884 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2885 final IPackageDataObserver observer) { 2886 mContext.enforceCallingOrSelfPermission( 2887 android.Manifest.permission.CLEAR_APP_CACHE, null); 2888 // Queue up an async operation since clearing cache may take a little while. 2889 mHandler.post(new Runnable() { 2890 public void run() { 2891 mHandler.removeCallbacks(this); 2892 int retCode = -1; 2893 synchronized (mInstallLock) { 2894 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2895 if (retCode < 0) { 2896 Slog.w(TAG, "Couldn't clear application caches"); 2897 } 2898 } 2899 if (observer != null) { 2900 try { 2901 observer.onRemoveCompleted(null, (retCode >= 0)); 2902 } catch (RemoteException e) { 2903 Slog.w(TAG, "RemoveException when invoking call back"); 2904 } 2905 } 2906 } 2907 }); 2908 } 2909 2910 @Override 2911 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2912 final IntentSender pi) { 2913 mContext.enforceCallingOrSelfPermission( 2914 android.Manifest.permission.CLEAR_APP_CACHE, null); 2915 // Queue up an async operation since clearing cache may take a little while. 2916 mHandler.post(new Runnable() { 2917 public void run() { 2918 mHandler.removeCallbacks(this); 2919 int retCode = -1; 2920 synchronized (mInstallLock) { 2921 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2922 if (retCode < 0) { 2923 Slog.w(TAG, "Couldn't clear application caches"); 2924 } 2925 } 2926 if(pi != null) { 2927 try { 2928 // Callback via pending intent 2929 int code = (retCode >= 0) ? 1 : 0; 2930 pi.sendIntent(null, code, null, 2931 null, null); 2932 } catch (SendIntentException e1) { 2933 Slog.i(TAG, "Failed to send pending intent"); 2934 } 2935 } 2936 } 2937 }); 2938 } 2939 2940 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2941 synchronized (mInstallLock) { 2942 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2943 throw new IOException("Failed to free enough space"); 2944 } 2945 } 2946 } 2947 2948 @Override 2949 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2950 if (!sUserManager.exists(userId)) return null; 2951 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2952 synchronized (mPackages) { 2953 PackageParser.Activity a = mActivities.mActivities.get(component); 2954 2955 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2956 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2957 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2958 if (ps == null) return null; 2959 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2960 userId); 2961 } 2962 if (mResolveComponentName.equals(component)) { 2963 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2964 new PackageUserState(), userId); 2965 } 2966 } 2967 return null; 2968 } 2969 2970 @Override 2971 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2972 String resolvedType) { 2973 synchronized (mPackages) { 2974 PackageParser.Activity a = mActivities.mActivities.get(component); 2975 if (a == null) { 2976 return false; 2977 } 2978 for (int i=0; i<a.intents.size(); i++) { 2979 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2980 intent.getData(), intent.getCategories(), TAG) >= 0) { 2981 return true; 2982 } 2983 } 2984 return false; 2985 } 2986 } 2987 2988 @Override 2989 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2990 if (!sUserManager.exists(userId)) return null; 2991 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2992 synchronized (mPackages) { 2993 PackageParser.Activity a = mReceivers.mActivities.get(component); 2994 if (DEBUG_PACKAGE_INFO) Log.v( 2995 TAG, "getReceiverInfo " + component + ": " + a); 2996 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2997 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2998 if (ps == null) return null; 2999 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3000 userId); 3001 } 3002 } 3003 return null; 3004 } 3005 3006 @Override 3007 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3008 if (!sUserManager.exists(userId)) return null; 3009 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3010 synchronized (mPackages) { 3011 PackageParser.Service s = mServices.mServices.get(component); 3012 if (DEBUG_PACKAGE_INFO) Log.v( 3013 TAG, "getServiceInfo " + component + ": " + s); 3014 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3015 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3016 if (ps == null) return null; 3017 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3018 userId); 3019 } 3020 } 3021 return null; 3022 } 3023 3024 @Override 3025 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3026 if (!sUserManager.exists(userId)) return null; 3027 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3028 synchronized (mPackages) { 3029 PackageParser.Provider p = mProviders.mProviders.get(component); 3030 if (DEBUG_PACKAGE_INFO) Log.v( 3031 TAG, "getProviderInfo " + component + ": " + p); 3032 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3033 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3034 if (ps == null) return null; 3035 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3036 userId); 3037 } 3038 } 3039 return null; 3040 } 3041 3042 @Override 3043 public String[] getSystemSharedLibraryNames() { 3044 Set<String> libSet; 3045 synchronized (mPackages) { 3046 libSet = mSharedLibraries.keySet(); 3047 int size = libSet.size(); 3048 if (size > 0) { 3049 String[] libs = new String[size]; 3050 libSet.toArray(libs); 3051 return libs; 3052 } 3053 } 3054 return null; 3055 } 3056 3057 /** 3058 * @hide 3059 */ 3060 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3061 synchronized (mPackages) { 3062 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3063 if (lib != null && lib.apk != null) { 3064 return mPackages.get(lib.apk); 3065 } 3066 } 3067 return null; 3068 } 3069 3070 @Override 3071 public FeatureInfo[] getSystemAvailableFeatures() { 3072 Collection<FeatureInfo> featSet; 3073 synchronized (mPackages) { 3074 featSet = mAvailableFeatures.values(); 3075 int size = featSet.size(); 3076 if (size > 0) { 3077 FeatureInfo[] features = new FeatureInfo[size+1]; 3078 featSet.toArray(features); 3079 FeatureInfo fi = new FeatureInfo(); 3080 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3081 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3082 features[size] = fi; 3083 return features; 3084 } 3085 } 3086 return null; 3087 } 3088 3089 @Override 3090 public boolean hasSystemFeature(String name) { 3091 synchronized (mPackages) { 3092 return mAvailableFeatures.containsKey(name); 3093 } 3094 } 3095 3096 private void checkValidCaller(int uid, int userId) { 3097 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3098 return; 3099 3100 throw new SecurityException("Caller uid=" + uid 3101 + " is not privileged to communicate with user=" + userId); 3102 } 3103 3104 @Override 3105 public int checkPermission(String permName, String pkgName, int userId) { 3106 if (!sUserManager.exists(userId)) { 3107 return PackageManager.PERMISSION_DENIED; 3108 } 3109 3110 synchronized (mPackages) { 3111 final PackageParser.Package p = mPackages.get(pkgName); 3112 if (p != null && p.mExtras != null) { 3113 final PackageSetting ps = (PackageSetting) p.mExtras; 3114 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3115 return PackageManager.PERMISSION_GRANTED; 3116 } 3117 } 3118 } 3119 3120 return PackageManager.PERMISSION_DENIED; 3121 } 3122 3123 @Override 3124 public int checkUidPermission(String permName, int uid) { 3125 final int userId = UserHandle.getUserId(uid); 3126 3127 if (!sUserManager.exists(userId)) { 3128 return PackageManager.PERMISSION_DENIED; 3129 } 3130 3131 synchronized (mPackages) { 3132 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3133 if (obj != null) { 3134 final SettingBase ps = (SettingBase) obj; 3135 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3136 return PackageManager.PERMISSION_GRANTED; 3137 } 3138 } else { 3139 ArraySet<String> perms = mSystemPermissions.get(uid); 3140 if (perms != null && perms.contains(permName)) { 3141 return PackageManager.PERMISSION_GRANTED; 3142 } 3143 } 3144 } 3145 3146 return PackageManager.PERMISSION_DENIED; 3147 } 3148 3149 /** 3150 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3151 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3152 * @param checkShell TODO(yamasani): 3153 * @param message the message to log on security exception 3154 */ 3155 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3156 boolean checkShell, String message) { 3157 if (userId < 0) { 3158 throw new IllegalArgumentException("Invalid userId " + userId); 3159 } 3160 if (checkShell) { 3161 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3162 } 3163 if (userId == UserHandle.getUserId(callingUid)) return; 3164 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3165 if (requireFullPermission) { 3166 mContext.enforceCallingOrSelfPermission( 3167 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3168 } else { 3169 try { 3170 mContext.enforceCallingOrSelfPermission( 3171 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3172 } catch (SecurityException se) { 3173 mContext.enforceCallingOrSelfPermission( 3174 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3175 } 3176 } 3177 } 3178 } 3179 3180 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3181 if (callingUid == Process.SHELL_UID) { 3182 if (userHandle >= 0 3183 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3184 throw new SecurityException("Shell does not have permission to access user " 3185 + userHandle); 3186 } else if (userHandle < 0) { 3187 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3188 + Debug.getCallers(3)); 3189 } 3190 } 3191 } 3192 3193 private BasePermission findPermissionTreeLP(String permName) { 3194 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3195 if (permName.startsWith(bp.name) && 3196 permName.length() > bp.name.length() && 3197 permName.charAt(bp.name.length()) == '.') { 3198 return bp; 3199 } 3200 } 3201 return null; 3202 } 3203 3204 private BasePermission checkPermissionTreeLP(String permName) { 3205 if (permName != null) { 3206 BasePermission bp = findPermissionTreeLP(permName); 3207 if (bp != null) { 3208 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3209 return bp; 3210 } 3211 throw new SecurityException("Calling uid " 3212 + Binder.getCallingUid() 3213 + " is not allowed to add to permission tree " 3214 + bp.name + " owned by uid " + bp.uid); 3215 } 3216 } 3217 throw new SecurityException("No permission tree found for " + permName); 3218 } 3219 3220 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3221 if (s1 == null) { 3222 return s2 == null; 3223 } 3224 if (s2 == null) { 3225 return false; 3226 } 3227 if (s1.getClass() != s2.getClass()) { 3228 return false; 3229 } 3230 return s1.equals(s2); 3231 } 3232 3233 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3234 if (pi1.icon != pi2.icon) return false; 3235 if (pi1.logo != pi2.logo) return false; 3236 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3237 if (!compareStrings(pi1.name, pi2.name)) return false; 3238 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3239 // We'll take care of setting this one. 3240 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3241 // These are not currently stored in settings. 3242 //if (!compareStrings(pi1.group, pi2.group)) return false; 3243 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3244 //if (pi1.labelRes != pi2.labelRes) return false; 3245 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3246 return true; 3247 } 3248 3249 int permissionInfoFootprint(PermissionInfo info) { 3250 int size = info.name.length(); 3251 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3252 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3253 return size; 3254 } 3255 3256 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3257 int size = 0; 3258 for (BasePermission perm : mSettings.mPermissions.values()) { 3259 if (perm.uid == tree.uid) { 3260 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3261 } 3262 } 3263 return size; 3264 } 3265 3266 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3267 // We calculate the max size of permissions defined by this uid and throw 3268 // if that plus the size of 'info' would exceed our stated maximum. 3269 if (tree.uid != Process.SYSTEM_UID) { 3270 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3271 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3272 throw new SecurityException("Permission tree size cap exceeded"); 3273 } 3274 } 3275 } 3276 3277 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3278 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3279 throw new SecurityException("Label must be specified in permission"); 3280 } 3281 BasePermission tree = checkPermissionTreeLP(info.name); 3282 BasePermission bp = mSettings.mPermissions.get(info.name); 3283 boolean added = bp == null; 3284 boolean changed = true; 3285 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3286 if (added) { 3287 enforcePermissionCapLocked(info, tree); 3288 bp = new BasePermission(info.name, tree.sourcePackage, 3289 BasePermission.TYPE_DYNAMIC); 3290 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3291 throw new SecurityException( 3292 "Not allowed to modify non-dynamic permission " 3293 + info.name); 3294 } else { 3295 if (bp.protectionLevel == fixedLevel 3296 && bp.perm.owner.equals(tree.perm.owner) 3297 && bp.uid == tree.uid 3298 && comparePermissionInfos(bp.perm.info, info)) { 3299 changed = false; 3300 } 3301 } 3302 bp.protectionLevel = fixedLevel; 3303 info = new PermissionInfo(info); 3304 info.protectionLevel = fixedLevel; 3305 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3306 bp.perm.info.packageName = tree.perm.info.packageName; 3307 bp.uid = tree.uid; 3308 if (added) { 3309 mSettings.mPermissions.put(info.name, bp); 3310 } 3311 if (changed) { 3312 if (!async) { 3313 mSettings.writeLPr(); 3314 } else { 3315 scheduleWriteSettingsLocked(); 3316 } 3317 } 3318 return added; 3319 } 3320 3321 @Override 3322 public boolean addPermission(PermissionInfo info) { 3323 synchronized (mPackages) { 3324 return addPermissionLocked(info, false); 3325 } 3326 } 3327 3328 @Override 3329 public boolean addPermissionAsync(PermissionInfo info) { 3330 synchronized (mPackages) { 3331 return addPermissionLocked(info, true); 3332 } 3333 } 3334 3335 @Override 3336 public void removePermission(String name) { 3337 synchronized (mPackages) { 3338 checkPermissionTreeLP(name); 3339 BasePermission bp = mSettings.mPermissions.get(name); 3340 if (bp != null) { 3341 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3342 throw new SecurityException( 3343 "Not allowed to modify non-dynamic permission " 3344 + name); 3345 } 3346 mSettings.mPermissions.remove(name); 3347 mSettings.writeLPr(); 3348 } 3349 } 3350 } 3351 3352 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3353 BasePermission bp) { 3354 int index = pkg.requestedPermissions.indexOf(bp.name); 3355 if (index == -1) { 3356 throw new SecurityException("Package " + pkg.packageName 3357 + " has not requested permission " + bp.name); 3358 } 3359 if (!bp.isRuntime()) { 3360 throw new SecurityException("Permission " + bp.name 3361 + " is not a changeable permission type"); 3362 } 3363 } 3364 3365 @Override 3366 public void grantRuntimePermission(String packageName, String name, final int userId) { 3367 if (!sUserManager.exists(userId)) { 3368 Log.e(TAG, "No such user:" + userId); 3369 return; 3370 } 3371 3372 mContext.enforceCallingOrSelfPermission( 3373 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3374 "grantRuntimePermission"); 3375 3376 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3377 "grantRuntimePermission"); 3378 3379 final int uid; 3380 final SettingBase sb; 3381 3382 synchronized (mPackages) { 3383 final PackageParser.Package pkg = mPackages.get(packageName); 3384 if (pkg == null) { 3385 throw new IllegalArgumentException("Unknown package: " + packageName); 3386 } 3387 3388 final BasePermission bp = mSettings.mPermissions.get(name); 3389 if (bp == null) { 3390 throw new IllegalArgumentException("Unknown permission: " + name); 3391 } 3392 3393 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3394 3395 uid = pkg.applicationInfo.uid; 3396 sb = (SettingBase) pkg.mExtras; 3397 if (sb == null) { 3398 throw new IllegalArgumentException("Unknown package: " + packageName); 3399 } 3400 3401 final PermissionsState permissionsState = sb.getPermissionsState(); 3402 3403 final int flags = permissionsState.getPermissionFlags(name, userId); 3404 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3405 throw new SecurityException("Cannot grant system fixed permission: " 3406 + name + " for package: " + packageName); 3407 } 3408 3409 final int result = permissionsState.grantRuntimePermission(bp, userId); 3410 switch (result) { 3411 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3412 return; 3413 } 3414 3415 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3416 mHandler.post(new Runnable() { 3417 @Override 3418 public void run() { 3419 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3420 } 3421 }); 3422 } break; 3423 } 3424 3425 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3426 3427 // Not critical if that is lost - app has to request again. 3428 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3429 } 3430 3431 if (READ_EXTERNAL_STORAGE.equals(name) 3432 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3433 final long token = Binder.clearCallingIdentity(); 3434 try { 3435 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3436 storage.remountUid(uid); 3437 } finally { 3438 Binder.restoreCallingIdentity(token); 3439 } 3440 } 3441 } 3442 3443 @Override 3444 public void revokeRuntimePermission(String packageName, String name, int userId) { 3445 if (!sUserManager.exists(userId)) { 3446 Log.e(TAG, "No such user:" + userId); 3447 return; 3448 } 3449 3450 mContext.enforceCallingOrSelfPermission( 3451 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3452 "revokeRuntimePermission"); 3453 3454 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3455 "revokeRuntimePermission"); 3456 3457 final SettingBase sb; 3458 3459 synchronized (mPackages) { 3460 final PackageParser.Package pkg = mPackages.get(packageName); 3461 if (pkg == null) { 3462 throw new IllegalArgumentException("Unknown package: " + packageName); 3463 } 3464 3465 final BasePermission bp = mSettings.mPermissions.get(name); 3466 if (bp == null) { 3467 throw new IllegalArgumentException("Unknown permission: " + name); 3468 } 3469 3470 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3471 3472 sb = (SettingBase) pkg.mExtras; 3473 if (sb == null) { 3474 throw new IllegalArgumentException("Unknown package: " + packageName); 3475 } 3476 3477 final PermissionsState permissionsState = sb.getPermissionsState(); 3478 3479 final int flags = permissionsState.getPermissionFlags(name, userId); 3480 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3481 throw new SecurityException("Cannot revoke system fixed permission: " 3482 + name + " for package: " + packageName); 3483 } 3484 3485 if (permissionsState.revokeRuntimePermission(bp, userId) == 3486 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3487 return; 3488 } 3489 3490 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3491 3492 // Critical, after this call app should never have the permission. 3493 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3494 } 3495 3496 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3497 } 3498 3499 @Override 3500 public void resetRuntimePermissions() { 3501 mContext.enforceCallingOrSelfPermission( 3502 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3503 "revokeRuntimePermission"); 3504 3505 int callingUid = Binder.getCallingUid(); 3506 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3507 mContext.enforceCallingOrSelfPermission( 3508 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3509 "resetRuntimePermissions"); 3510 } 3511 3512 final int[] userIds; 3513 3514 synchronized (mPackages) { 3515 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3516 final int userCount = UserManagerService.getInstance().getUserIds().length; 3517 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3518 } 3519 3520 for (int userId : userIds) { 3521 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3522 } 3523 } 3524 3525 @Override 3526 public int getPermissionFlags(String name, String packageName, int userId) { 3527 if (!sUserManager.exists(userId)) { 3528 return 0; 3529 } 3530 3531 mContext.enforceCallingOrSelfPermission( 3532 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3533 "getPermissionFlags"); 3534 3535 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3536 "getPermissionFlags"); 3537 3538 synchronized (mPackages) { 3539 final PackageParser.Package pkg = mPackages.get(packageName); 3540 if (pkg == null) { 3541 throw new IllegalArgumentException("Unknown package: " + packageName); 3542 } 3543 3544 final BasePermission bp = mSettings.mPermissions.get(name); 3545 if (bp == null) { 3546 throw new IllegalArgumentException("Unknown permission: " + name); 3547 } 3548 3549 SettingBase sb = (SettingBase) pkg.mExtras; 3550 if (sb == null) { 3551 throw new IllegalArgumentException("Unknown package: " + packageName); 3552 } 3553 3554 PermissionsState permissionsState = sb.getPermissionsState(); 3555 return permissionsState.getPermissionFlags(name, userId); 3556 } 3557 } 3558 3559 @Override 3560 public void updatePermissionFlags(String name, String packageName, int flagMask, 3561 int flagValues, int userId) { 3562 if (!sUserManager.exists(userId)) { 3563 return; 3564 } 3565 3566 mContext.enforceCallingOrSelfPermission( 3567 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3568 "updatePermissionFlags"); 3569 3570 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3571 "updatePermissionFlags"); 3572 3573 // Only the system can change system fixed flags. 3574 if (getCallingUid() != Process.SYSTEM_UID) { 3575 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3576 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3577 } 3578 3579 synchronized (mPackages) { 3580 final PackageParser.Package pkg = mPackages.get(packageName); 3581 if (pkg == null) { 3582 throw new IllegalArgumentException("Unknown package: " + packageName); 3583 } 3584 3585 final BasePermission bp = mSettings.mPermissions.get(name); 3586 if (bp == null) { 3587 throw new IllegalArgumentException("Unknown permission: " + name); 3588 } 3589 3590 SettingBase sb = (SettingBase) pkg.mExtras; 3591 if (sb == null) { 3592 throw new IllegalArgumentException("Unknown package: " + packageName); 3593 } 3594 3595 PermissionsState permissionsState = sb.getPermissionsState(); 3596 3597 // Only the package manager can change flags for system component permissions. 3598 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3599 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3600 return; 3601 } 3602 3603 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3604 3605 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3606 // Install and runtime permissions are stored in different places, 3607 // so figure out what permission changed and persist the change. 3608 if (permissionsState.getInstallPermissionState(name) != null) { 3609 scheduleWriteSettingsLocked(); 3610 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3611 || hadState) { 3612 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3613 } 3614 } 3615 } 3616 } 3617 3618 /** 3619 * Update the permission flags for all packages and runtime permissions of a user in order 3620 * to allow device or profile owner to remove POLICY_FIXED. 3621 */ 3622 @Override 3623 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3624 if (!sUserManager.exists(userId)) { 3625 return; 3626 } 3627 3628 mContext.enforceCallingOrSelfPermission( 3629 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3630 "updatePermissionFlagsForAllApps"); 3631 3632 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3633 "updatePermissionFlagsForAllApps"); 3634 3635 // Only the system can change system fixed flags. 3636 if (getCallingUid() != Process.SYSTEM_UID) { 3637 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3638 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3639 } 3640 3641 synchronized (mPackages) { 3642 boolean changed = false; 3643 final int packageCount = mPackages.size(); 3644 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3645 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3646 SettingBase sb = (SettingBase) pkg.mExtras; 3647 if (sb == null) { 3648 continue; 3649 } 3650 PermissionsState permissionsState = sb.getPermissionsState(); 3651 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3652 userId, flagMask, flagValues); 3653 } 3654 if (changed) { 3655 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3656 } 3657 } 3658 } 3659 3660 @Override 3661 public boolean shouldShowRequestPermissionRationale(String permissionName, 3662 String packageName, int userId) { 3663 if (UserHandle.getCallingUserId() != userId) { 3664 mContext.enforceCallingPermission( 3665 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3666 "canShowRequestPermissionRationale for user " + userId); 3667 } 3668 3669 final int uid = getPackageUid(packageName, userId); 3670 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3671 return false; 3672 } 3673 3674 if (checkPermission(permissionName, packageName, userId) 3675 == PackageManager.PERMISSION_GRANTED) { 3676 return false; 3677 } 3678 3679 final int flags; 3680 3681 final long identity = Binder.clearCallingIdentity(); 3682 try { 3683 flags = getPermissionFlags(permissionName, 3684 packageName, userId); 3685 } finally { 3686 Binder.restoreCallingIdentity(identity); 3687 } 3688 3689 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3690 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3691 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3692 3693 if ((flags & fixedFlags) != 0) { 3694 return false; 3695 } 3696 3697 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3698 } 3699 3700 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3701 BasePermission bp = mSettings.mPermissions.get(permission); 3702 if (bp == null) { 3703 throw new SecurityException("Missing " + permission + " permission"); 3704 } 3705 3706 SettingBase sb = (SettingBase) pkg.mExtras; 3707 PermissionsState permissionsState = sb.getPermissionsState(); 3708 3709 if (permissionsState.grantInstallPermission(bp) != 3710 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3711 scheduleWriteSettingsLocked(); 3712 } 3713 } 3714 3715 @Override 3716 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3717 mContext.enforceCallingOrSelfPermission( 3718 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3719 "addOnPermissionsChangeListener"); 3720 3721 synchronized (mPackages) { 3722 mOnPermissionChangeListeners.addListenerLocked(listener); 3723 } 3724 } 3725 3726 @Override 3727 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3728 synchronized (mPackages) { 3729 mOnPermissionChangeListeners.removeListenerLocked(listener); 3730 } 3731 } 3732 3733 @Override 3734 public boolean isProtectedBroadcast(String actionName) { 3735 synchronized (mPackages) { 3736 return mProtectedBroadcasts.contains(actionName); 3737 } 3738 } 3739 3740 @Override 3741 public int checkSignatures(String pkg1, String pkg2) { 3742 synchronized (mPackages) { 3743 final PackageParser.Package p1 = mPackages.get(pkg1); 3744 final PackageParser.Package p2 = mPackages.get(pkg2); 3745 if (p1 == null || p1.mExtras == null 3746 || p2 == null || p2.mExtras == null) { 3747 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3748 } 3749 return compareSignatures(p1.mSignatures, p2.mSignatures); 3750 } 3751 } 3752 3753 @Override 3754 public int checkUidSignatures(int uid1, int uid2) { 3755 // Map to base uids. 3756 uid1 = UserHandle.getAppId(uid1); 3757 uid2 = UserHandle.getAppId(uid2); 3758 // reader 3759 synchronized (mPackages) { 3760 Signature[] s1; 3761 Signature[] s2; 3762 Object obj = mSettings.getUserIdLPr(uid1); 3763 if (obj != null) { 3764 if (obj instanceof SharedUserSetting) { 3765 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3766 } else if (obj instanceof PackageSetting) { 3767 s1 = ((PackageSetting)obj).signatures.mSignatures; 3768 } else { 3769 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3770 } 3771 } else { 3772 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3773 } 3774 obj = mSettings.getUserIdLPr(uid2); 3775 if (obj != null) { 3776 if (obj instanceof SharedUserSetting) { 3777 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3778 } else if (obj instanceof PackageSetting) { 3779 s2 = ((PackageSetting)obj).signatures.mSignatures; 3780 } else { 3781 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3782 } 3783 } else { 3784 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3785 } 3786 return compareSignatures(s1, s2); 3787 } 3788 } 3789 3790 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3791 final long identity = Binder.clearCallingIdentity(); 3792 try { 3793 if (sb instanceof SharedUserSetting) { 3794 SharedUserSetting sus = (SharedUserSetting) sb; 3795 final int packageCount = sus.packages.size(); 3796 for (int i = 0; i < packageCount; i++) { 3797 PackageSetting susPs = sus.packages.valueAt(i); 3798 if (userId == UserHandle.USER_ALL) { 3799 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3800 } else { 3801 final int uid = UserHandle.getUid(userId, susPs.appId); 3802 killUid(uid, reason); 3803 } 3804 } 3805 } else if (sb instanceof PackageSetting) { 3806 PackageSetting ps = (PackageSetting) sb; 3807 if (userId == UserHandle.USER_ALL) { 3808 killApplication(ps.pkg.packageName, ps.appId, reason); 3809 } else { 3810 final int uid = UserHandle.getUid(userId, ps.appId); 3811 killUid(uid, reason); 3812 } 3813 } 3814 } finally { 3815 Binder.restoreCallingIdentity(identity); 3816 } 3817 } 3818 3819 private static void killUid(int uid, String reason) { 3820 IActivityManager am = ActivityManagerNative.getDefault(); 3821 if (am != null) { 3822 try { 3823 am.killUid(uid, reason); 3824 } catch (RemoteException e) { 3825 /* ignore - same process */ 3826 } 3827 } 3828 } 3829 3830 /** 3831 * Compares two sets of signatures. Returns: 3832 * <br /> 3833 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3834 * <br /> 3835 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3836 * <br /> 3837 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3838 * <br /> 3839 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3840 * <br /> 3841 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3842 */ 3843 static int compareSignatures(Signature[] s1, Signature[] s2) { 3844 if (s1 == null) { 3845 return s2 == null 3846 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3847 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3848 } 3849 3850 if (s2 == null) { 3851 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3852 } 3853 3854 if (s1.length != s2.length) { 3855 return PackageManager.SIGNATURE_NO_MATCH; 3856 } 3857 3858 // Since both signature sets are of size 1, we can compare without HashSets. 3859 if (s1.length == 1) { 3860 return s1[0].equals(s2[0]) ? 3861 PackageManager.SIGNATURE_MATCH : 3862 PackageManager.SIGNATURE_NO_MATCH; 3863 } 3864 3865 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3866 for (Signature sig : s1) { 3867 set1.add(sig); 3868 } 3869 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3870 for (Signature sig : s2) { 3871 set2.add(sig); 3872 } 3873 // Make sure s2 contains all signatures in s1. 3874 if (set1.equals(set2)) { 3875 return PackageManager.SIGNATURE_MATCH; 3876 } 3877 return PackageManager.SIGNATURE_NO_MATCH; 3878 } 3879 3880 /** 3881 * If the database version for this type of package (internal storage or 3882 * external storage) is less than the version where package signatures 3883 * were updated, return true. 3884 */ 3885 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3886 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3887 DatabaseVersion.SIGNATURE_END_ENTITY)) 3888 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3889 DatabaseVersion.SIGNATURE_END_ENTITY)); 3890 } 3891 3892 /** 3893 * Used for backward compatibility to make sure any packages with 3894 * certificate chains get upgraded to the new style. {@code existingSigs} 3895 * will be in the old format (since they were stored on disk from before the 3896 * system upgrade) and {@code scannedSigs} will be in the newer format. 3897 */ 3898 private int compareSignaturesCompat(PackageSignatures existingSigs, 3899 PackageParser.Package scannedPkg) { 3900 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3901 return PackageManager.SIGNATURE_NO_MATCH; 3902 } 3903 3904 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3905 for (Signature sig : existingSigs.mSignatures) { 3906 existingSet.add(sig); 3907 } 3908 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3909 for (Signature sig : scannedPkg.mSignatures) { 3910 try { 3911 Signature[] chainSignatures = sig.getChainSignatures(); 3912 for (Signature chainSig : chainSignatures) { 3913 scannedCompatSet.add(chainSig); 3914 } 3915 } catch (CertificateEncodingException e) { 3916 scannedCompatSet.add(sig); 3917 } 3918 } 3919 /* 3920 * Make sure the expanded scanned set contains all signatures in the 3921 * existing one. 3922 */ 3923 if (scannedCompatSet.equals(existingSet)) { 3924 // Migrate the old signatures to the new scheme. 3925 existingSigs.assignSignatures(scannedPkg.mSignatures); 3926 // The new KeySets will be re-added later in the scanning process. 3927 synchronized (mPackages) { 3928 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3929 } 3930 return PackageManager.SIGNATURE_MATCH; 3931 } 3932 return PackageManager.SIGNATURE_NO_MATCH; 3933 } 3934 3935 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3936 if (isExternal(scannedPkg)) { 3937 return mSettings.isExternalDatabaseVersionOlderThan( 3938 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3939 } else { 3940 return mSettings.isInternalDatabaseVersionOlderThan( 3941 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3942 } 3943 } 3944 3945 private int compareSignaturesRecover(PackageSignatures existingSigs, 3946 PackageParser.Package scannedPkg) { 3947 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3948 return PackageManager.SIGNATURE_NO_MATCH; 3949 } 3950 3951 String msg = null; 3952 try { 3953 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3954 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3955 + scannedPkg.packageName); 3956 return PackageManager.SIGNATURE_MATCH; 3957 } 3958 } catch (CertificateException e) { 3959 msg = e.getMessage(); 3960 } 3961 3962 logCriticalInfo(Log.INFO, 3963 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3964 return PackageManager.SIGNATURE_NO_MATCH; 3965 } 3966 3967 @Override 3968 public String[] getPackagesForUid(int uid) { 3969 uid = UserHandle.getAppId(uid); 3970 // reader 3971 synchronized (mPackages) { 3972 Object obj = mSettings.getUserIdLPr(uid); 3973 if (obj instanceof SharedUserSetting) { 3974 final SharedUserSetting sus = (SharedUserSetting) obj; 3975 final int N = sus.packages.size(); 3976 final String[] res = new String[N]; 3977 final Iterator<PackageSetting> it = sus.packages.iterator(); 3978 int i = 0; 3979 while (it.hasNext()) { 3980 res[i++] = it.next().name; 3981 } 3982 return res; 3983 } else if (obj instanceof PackageSetting) { 3984 final PackageSetting ps = (PackageSetting) obj; 3985 return new String[] { ps.name }; 3986 } 3987 } 3988 return null; 3989 } 3990 3991 @Override 3992 public String getNameForUid(int uid) { 3993 // reader 3994 synchronized (mPackages) { 3995 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3996 if (obj instanceof SharedUserSetting) { 3997 final SharedUserSetting sus = (SharedUserSetting) obj; 3998 return sus.name + ":" + sus.userId; 3999 } else if (obj instanceof PackageSetting) { 4000 final PackageSetting ps = (PackageSetting) obj; 4001 return ps.name; 4002 } 4003 } 4004 return null; 4005 } 4006 4007 @Override 4008 public int getUidForSharedUser(String sharedUserName) { 4009 if(sharedUserName == null) { 4010 return -1; 4011 } 4012 // reader 4013 synchronized (mPackages) { 4014 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4015 if (suid == null) { 4016 return -1; 4017 } 4018 return suid.userId; 4019 } 4020 } 4021 4022 @Override 4023 public int getFlagsForUid(int uid) { 4024 synchronized (mPackages) { 4025 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4026 if (obj instanceof SharedUserSetting) { 4027 final SharedUserSetting sus = (SharedUserSetting) obj; 4028 return sus.pkgFlags; 4029 } else if (obj instanceof PackageSetting) { 4030 final PackageSetting ps = (PackageSetting) obj; 4031 return ps.pkgFlags; 4032 } 4033 } 4034 return 0; 4035 } 4036 4037 @Override 4038 public int getPrivateFlagsForUid(int uid) { 4039 synchronized (mPackages) { 4040 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4041 if (obj instanceof SharedUserSetting) { 4042 final SharedUserSetting sus = (SharedUserSetting) obj; 4043 return sus.pkgPrivateFlags; 4044 } else if (obj instanceof PackageSetting) { 4045 final PackageSetting ps = (PackageSetting) obj; 4046 return ps.pkgPrivateFlags; 4047 } 4048 } 4049 return 0; 4050 } 4051 4052 @Override 4053 public boolean isUidPrivileged(int uid) { 4054 uid = UserHandle.getAppId(uid); 4055 // reader 4056 synchronized (mPackages) { 4057 Object obj = mSettings.getUserIdLPr(uid); 4058 if (obj instanceof SharedUserSetting) { 4059 final SharedUserSetting sus = (SharedUserSetting) obj; 4060 final Iterator<PackageSetting> it = sus.packages.iterator(); 4061 while (it.hasNext()) { 4062 if (it.next().isPrivileged()) { 4063 return true; 4064 } 4065 } 4066 } else if (obj instanceof PackageSetting) { 4067 final PackageSetting ps = (PackageSetting) obj; 4068 return ps.isPrivileged(); 4069 } 4070 } 4071 return false; 4072 } 4073 4074 @Override 4075 public String[] getAppOpPermissionPackages(String permissionName) { 4076 synchronized (mPackages) { 4077 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4078 if (pkgs == null) { 4079 return null; 4080 } 4081 return pkgs.toArray(new String[pkgs.size()]); 4082 } 4083 } 4084 4085 @Override 4086 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4087 int flags, int userId) { 4088 if (!sUserManager.exists(userId)) return null; 4089 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4090 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4091 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4092 } 4093 4094 @Override 4095 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4096 IntentFilter filter, int match, ComponentName activity) { 4097 final int userId = UserHandle.getCallingUserId(); 4098 if (DEBUG_PREFERRED) { 4099 Log.v(TAG, "setLastChosenActivity intent=" + intent 4100 + " resolvedType=" + resolvedType 4101 + " flags=" + flags 4102 + " filter=" + filter 4103 + " match=" + match 4104 + " activity=" + activity); 4105 filter.dump(new PrintStreamPrinter(System.out), " "); 4106 } 4107 intent.setComponent(null); 4108 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4109 // Find any earlier preferred or last chosen entries and nuke them 4110 findPreferredActivity(intent, resolvedType, 4111 flags, query, 0, false, true, false, userId); 4112 // Add the new activity as the last chosen for this filter 4113 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4114 "Setting last chosen"); 4115 } 4116 4117 @Override 4118 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4119 final int userId = UserHandle.getCallingUserId(); 4120 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4121 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4122 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4123 false, false, false, userId); 4124 } 4125 4126 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4127 int flags, List<ResolveInfo> query, int userId) { 4128 if (query != null) { 4129 final int N = query.size(); 4130 if (N == 1) { 4131 return query.get(0); 4132 } else if (N > 1) { 4133 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4134 // If there is more than one activity with the same priority, 4135 // then let the user decide between them. 4136 ResolveInfo r0 = query.get(0); 4137 ResolveInfo r1 = query.get(1); 4138 if (DEBUG_INTENT_MATCHING || debug) { 4139 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4140 + r1.activityInfo.name + "=" + r1.priority); 4141 } 4142 // If the first activity has a higher priority, or a different 4143 // default, then it is always desireable to pick it. 4144 if (r0.priority != r1.priority 4145 || r0.preferredOrder != r1.preferredOrder 4146 || r0.isDefault != r1.isDefault) { 4147 return query.get(0); 4148 } 4149 // If we have saved a preference for a preferred activity for 4150 // this Intent, use that. 4151 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4152 flags, query, r0.priority, true, false, debug, userId); 4153 if (ri != null) { 4154 return ri; 4155 } 4156 if (userId != 0) { 4157 ri = new ResolveInfo(mResolveInfo); 4158 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4159 ri.activityInfo.applicationInfo = new ApplicationInfo( 4160 ri.activityInfo.applicationInfo); 4161 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4162 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4163 return ri; 4164 } 4165 return mResolveInfo; 4166 } 4167 } 4168 return null; 4169 } 4170 4171 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4172 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4173 final int N = query.size(); 4174 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4175 .get(userId); 4176 // Get the list of persistent preferred activities that handle the intent 4177 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4178 List<PersistentPreferredActivity> pprefs = ppir != null 4179 ? ppir.queryIntent(intent, resolvedType, 4180 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4181 : null; 4182 if (pprefs != null && pprefs.size() > 0) { 4183 final int M = pprefs.size(); 4184 for (int i=0; i<M; i++) { 4185 final PersistentPreferredActivity ppa = pprefs.get(i); 4186 if (DEBUG_PREFERRED || debug) { 4187 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4188 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4189 + "\n component=" + ppa.mComponent); 4190 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4191 } 4192 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4193 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4194 if (DEBUG_PREFERRED || debug) { 4195 Slog.v(TAG, "Found persistent preferred activity:"); 4196 if (ai != null) { 4197 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4198 } else { 4199 Slog.v(TAG, " null"); 4200 } 4201 } 4202 if (ai == null) { 4203 // This previously registered persistent preferred activity 4204 // component is no longer known. Ignore it and do NOT remove it. 4205 continue; 4206 } 4207 for (int j=0; j<N; j++) { 4208 final ResolveInfo ri = query.get(j); 4209 if (!ri.activityInfo.applicationInfo.packageName 4210 .equals(ai.applicationInfo.packageName)) { 4211 continue; 4212 } 4213 if (!ri.activityInfo.name.equals(ai.name)) { 4214 continue; 4215 } 4216 // Found a persistent preference that can handle the intent. 4217 if (DEBUG_PREFERRED || debug) { 4218 Slog.v(TAG, "Returning persistent preferred activity: " + 4219 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4220 } 4221 return ri; 4222 } 4223 } 4224 } 4225 return null; 4226 } 4227 4228 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4229 List<ResolveInfo> query, int priority, boolean always, 4230 boolean removeMatches, boolean debug, int userId) { 4231 if (!sUserManager.exists(userId)) return null; 4232 // writer 4233 synchronized (mPackages) { 4234 if (intent.getSelector() != null) { 4235 intent = intent.getSelector(); 4236 } 4237 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4238 4239 // Try to find a matching persistent preferred activity. 4240 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4241 debug, userId); 4242 4243 // If a persistent preferred activity matched, use it. 4244 if (pri != null) { 4245 return pri; 4246 } 4247 4248 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4249 // Get the list of preferred activities that handle the intent 4250 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4251 List<PreferredActivity> prefs = pir != null 4252 ? pir.queryIntent(intent, resolvedType, 4253 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4254 : null; 4255 if (prefs != null && prefs.size() > 0) { 4256 boolean changed = false; 4257 try { 4258 // First figure out how good the original match set is. 4259 // We will only allow preferred activities that came 4260 // from the same match quality. 4261 int match = 0; 4262 4263 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4264 4265 final int N = query.size(); 4266 for (int j=0; j<N; j++) { 4267 final ResolveInfo ri = query.get(j); 4268 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4269 + ": 0x" + Integer.toHexString(match)); 4270 if (ri.match > match) { 4271 match = ri.match; 4272 } 4273 } 4274 4275 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4276 + Integer.toHexString(match)); 4277 4278 match &= IntentFilter.MATCH_CATEGORY_MASK; 4279 final int M = prefs.size(); 4280 for (int i=0; i<M; i++) { 4281 final PreferredActivity pa = prefs.get(i); 4282 if (DEBUG_PREFERRED || debug) { 4283 Slog.v(TAG, "Checking PreferredActivity ds=" 4284 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4285 + "\n component=" + pa.mPref.mComponent); 4286 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4287 } 4288 if (pa.mPref.mMatch != match) { 4289 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4290 + Integer.toHexString(pa.mPref.mMatch)); 4291 continue; 4292 } 4293 // If it's not an "always" type preferred activity and that's what we're 4294 // looking for, skip it. 4295 if (always && !pa.mPref.mAlways) { 4296 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4297 continue; 4298 } 4299 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4300 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4301 if (DEBUG_PREFERRED || debug) { 4302 Slog.v(TAG, "Found preferred activity:"); 4303 if (ai != null) { 4304 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4305 } else { 4306 Slog.v(TAG, " null"); 4307 } 4308 } 4309 if (ai == null) { 4310 // This previously registered preferred activity 4311 // component is no longer known. Most likely an update 4312 // to the app was installed and in the new version this 4313 // component no longer exists. Clean it up by removing 4314 // it from the preferred activities list, and skip it. 4315 Slog.w(TAG, "Removing dangling preferred activity: " 4316 + pa.mPref.mComponent); 4317 pir.removeFilter(pa); 4318 changed = true; 4319 continue; 4320 } 4321 for (int j=0; j<N; j++) { 4322 final ResolveInfo ri = query.get(j); 4323 if (!ri.activityInfo.applicationInfo.packageName 4324 .equals(ai.applicationInfo.packageName)) { 4325 continue; 4326 } 4327 if (!ri.activityInfo.name.equals(ai.name)) { 4328 continue; 4329 } 4330 4331 if (removeMatches) { 4332 pir.removeFilter(pa); 4333 changed = true; 4334 if (DEBUG_PREFERRED) { 4335 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4336 } 4337 break; 4338 } 4339 4340 // Okay we found a previously set preferred or last chosen app. 4341 // If the result set is different from when this 4342 // was created, we need to clear it and re-ask the 4343 // user their preference, if we're looking for an "always" type entry. 4344 if (always && !pa.mPref.sameSet(query)) { 4345 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4346 + intent + " type " + resolvedType); 4347 if (DEBUG_PREFERRED) { 4348 Slog.v(TAG, "Removing preferred activity since set changed " 4349 + pa.mPref.mComponent); 4350 } 4351 pir.removeFilter(pa); 4352 // Re-add the filter as a "last chosen" entry (!always) 4353 PreferredActivity lastChosen = new PreferredActivity( 4354 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4355 pir.addFilter(lastChosen); 4356 changed = true; 4357 return null; 4358 } 4359 4360 // Yay! Either the set matched or we're looking for the last chosen 4361 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4362 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4363 return ri; 4364 } 4365 } 4366 } finally { 4367 if (changed) { 4368 if (DEBUG_PREFERRED) { 4369 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4370 } 4371 scheduleWritePackageRestrictionsLocked(userId); 4372 } 4373 } 4374 } 4375 } 4376 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4377 return null; 4378 } 4379 4380 /* 4381 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4382 */ 4383 @Override 4384 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4385 int targetUserId) { 4386 mContext.enforceCallingOrSelfPermission( 4387 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4388 List<CrossProfileIntentFilter> matches = 4389 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4390 if (matches != null) { 4391 int size = matches.size(); 4392 for (int i = 0; i < size; i++) { 4393 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4394 } 4395 } 4396 if (hasWebURI(intent)) { 4397 // cross-profile app linking works only towards the parent. 4398 final UserInfo parent = getProfileParent(sourceUserId); 4399 synchronized(mPackages) { 4400 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4401 parent.id) != null; 4402 } 4403 } 4404 return false; 4405 } 4406 4407 private UserInfo getProfileParent(int userId) { 4408 final long identity = Binder.clearCallingIdentity(); 4409 try { 4410 return sUserManager.getProfileParent(userId); 4411 } finally { 4412 Binder.restoreCallingIdentity(identity); 4413 } 4414 } 4415 4416 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4417 String resolvedType, int userId) { 4418 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4419 if (resolver != null) { 4420 return resolver.queryIntent(intent, resolvedType, false, userId); 4421 } 4422 return null; 4423 } 4424 4425 @Override 4426 public List<ResolveInfo> queryIntentActivities(Intent intent, 4427 String resolvedType, int flags, int userId) { 4428 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4429 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4430 ComponentName comp = intent.getComponent(); 4431 if (comp == null) { 4432 if (intent.getSelector() != null) { 4433 intent = intent.getSelector(); 4434 comp = intent.getComponent(); 4435 } 4436 } 4437 4438 if (comp != null) { 4439 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4440 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4441 if (ai != null) { 4442 final ResolveInfo ri = new ResolveInfo(); 4443 ri.activityInfo = ai; 4444 list.add(ri); 4445 } 4446 return list; 4447 } 4448 4449 // reader 4450 synchronized (mPackages) { 4451 final String pkgName = intent.getPackage(); 4452 if (pkgName == null) { 4453 List<CrossProfileIntentFilter> matchingFilters = 4454 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4455 // Check for results that need to skip the current profile. 4456 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4457 resolvedType, flags, userId); 4458 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4459 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4460 result.add(xpResolveInfo); 4461 return filterIfNotPrimaryUser(result, userId); 4462 } 4463 4464 // Check for results in the current profile. 4465 List<ResolveInfo> result = mActivities.queryIntent( 4466 intent, resolvedType, flags, userId); 4467 4468 // Check for cross profile results. 4469 xpResolveInfo = queryCrossProfileIntents( 4470 matchingFilters, intent, resolvedType, flags, userId); 4471 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4472 result.add(xpResolveInfo); 4473 Collections.sort(result, mResolvePrioritySorter); 4474 } 4475 result = filterIfNotPrimaryUser(result, userId); 4476 if (hasWebURI(intent)) { 4477 CrossProfileDomainInfo xpDomainInfo = null; 4478 final UserInfo parent = getProfileParent(userId); 4479 if (parent != null) { 4480 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4481 flags, userId, parent.id); 4482 } 4483 if (xpDomainInfo != null) { 4484 if (xpResolveInfo != null) { 4485 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4486 // in the result. 4487 result.remove(xpResolveInfo); 4488 } 4489 if (result.size() == 0) { 4490 result.add(xpDomainInfo.resolveInfo); 4491 return result; 4492 } 4493 } else if (result.size() <= 1) { 4494 return result; 4495 } 4496 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4497 xpDomainInfo); 4498 Collections.sort(result, mResolvePrioritySorter); 4499 } 4500 return result; 4501 } 4502 final PackageParser.Package pkg = mPackages.get(pkgName); 4503 if (pkg != null) { 4504 return filterIfNotPrimaryUser( 4505 mActivities.queryIntentForPackage( 4506 intent, resolvedType, flags, pkg.activities, userId), 4507 userId); 4508 } 4509 return new ArrayList<ResolveInfo>(); 4510 } 4511 } 4512 4513 private static class CrossProfileDomainInfo { 4514 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4515 ResolveInfo resolveInfo; 4516 /* Best domain verification status of the activities found in the other profile */ 4517 int bestDomainVerificationStatus; 4518 } 4519 4520 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4521 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4522 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4523 sourceUserId)) { 4524 return null; 4525 } 4526 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4527 resolvedType, flags, parentUserId); 4528 4529 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4530 return null; 4531 } 4532 CrossProfileDomainInfo result = null; 4533 int size = resultTargetUser.size(); 4534 for (int i = 0; i < size; i++) { 4535 ResolveInfo riTargetUser = resultTargetUser.get(i); 4536 // Intent filter verification is only for filters that specify a host. So don't return 4537 // those that handle all web uris. 4538 if (riTargetUser.handleAllWebDataURI) { 4539 continue; 4540 } 4541 String packageName = riTargetUser.activityInfo.packageName; 4542 PackageSetting ps = mSettings.mPackages.get(packageName); 4543 if (ps == null) { 4544 continue; 4545 } 4546 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4547 if (result == null) { 4548 result = new CrossProfileDomainInfo(); 4549 result.resolveInfo = 4550 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4551 result.bestDomainVerificationStatus = status; 4552 } else { 4553 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4554 result.bestDomainVerificationStatus); 4555 } 4556 } 4557 return result; 4558 } 4559 4560 /** 4561 * Verification statuses are ordered from the worse to the best, except for 4562 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4563 */ 4564 private int bestDomainVerificationStatus(int status1, int status2) { 4565 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4566 return status2; 4567 } 4568 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4569 return status1; 4570 } 4571 return (int) MathUtils.max(status1, status2); 4572 } 4573 4574 private boolean isUserEnabled(int userId) { 4575 long callingId = Binder.clearCallingIdentity(); 4576 try { 4577 UserInfo userInfo = sUserManager.getUserInfo(userId); 4578 return userInfo != null && userInfo.isEnabled(); 4579 } finally { 4580 Binder.restoreCallingIdentity(callingId); 4581 } 4582 } 4583 4584 /** 4585 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4586 * 4587 * @return filtered list 4588 */ 4589 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4590 if (userId == UserHandle.USER_OWNER) { 4591 return resolveInfos; 4592 } 4593 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4594 ResolveInfo info = resolveInfos.get(i); 4595 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4596 resolveInfos.remove(i); 4597 } 4598 } 4599 return resolveInfos; 4600 } 4601 4602 private static boolean hasWebURI(Intent intent) { 4603 if (intent.getData() == null) { 4604 return false; 4605 } 4606 final String scheme = intent.getScheme(); 4607 if (TextUtils.isEmpty(scheme)) { 4608 return false; 4609 } 4610 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4611 } 4612 4613 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4614 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4615 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4616 Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " + 4617 candidates.size()); 4618 } 4619 4620 final int userId = UserHandle.getCallingUserId(); 4621 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4622 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4623 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4624 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4625 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4626 4627 synchronized (mPackages) { 4628 final int count = candidates.size(); 4629 // First, try to use linked apps. Partition the candidates into four lists: 4630 // one for the final results, one for the "do not use ever", one for "undefined status" 4631 // and finally one for "browser app type". 4632 for (int n=0; n<count; n++) { 4633 ResolveInfo info = candidates.get(n); 4634 String packageName = info.activityInfo.packageName; 4635 PackageSetting ps = mSettings.mPackages.get(packageName); 4636 if (ps != null) { 4637 // Add to the special match all list (Browser use case) 4638 if (info.handleAllWebDataURI) { 4639 matchAllList.add(info); 4640 continue; 4641 } 4642 // Try to get the status from User settings first 4643 int status = getDomainVerificationStatusLPr(ps, userId); 4644 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4645 if (DEBUG_DOMAIN_VERIFICATION) { 4646 Slog.i(TAG, " + always: " + info.activityInfo.packageName); 4647 } 4648 alwaysList.add(info); 4649 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4650 if (DEBUG_DOMAIN_VERIFICATION) { 4651 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4652 } 4653 neverList.add(info); 4654 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4655 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4656 if (DEBUG_DOMAIN_VERIFICATION) { 4657 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4658 } 4659 undefinedList.add(info); 4660 } 4661 } 4662 } 4663 // First try to add the "always" resolution for the current user if there is any 4664 if (alwaysList.size() > 0) { 4665 result.addAll(alwaysList); 4666 // if there is an "always" for the parent user, add it. 4667 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4668 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4669 result.add(xpDomainInfo.resolveInfo); 4670 } else { 4671 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4672 result.addAll(undefinedList); 4673 if (xpDomainInfo != null && ( 4674 xpDomainInfo.bestDomainVerificationStatus 4675 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4676 || xpDomainInfo.bestDomainVerificationStatus 4677 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4678 result.add(xpDomainInfo.resolveInfo); 4679 } 4680 // Also add Browsers (all of them or only the default one) 4681 if ((flags & MATCH_ALL) != 0) { 4682 result.addAll(matchAllList); 4683 } else { 4684 // Try to add the Default Browser if we can 4685 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4686 UserHandle.myUserId()); 4687 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4688 boolean defaultBrowserFound = false; 4689 final int browserCount = matchAllList.size(); 4690 for (int n=0; n<browserCount; n++) { 4691 ResolveInfo browser = matchAllList.get(n); 4692 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4693 result.add(browser); 4694 defaultBrowserFound = true; 4695 break; 4696 } 4697 } 4698 if (!defaultBrowserFound) { 4699 result.addAll(matchAllList); 4700 } 4701 } else { 4702 result.addAll(matchAllList); 4703 } 4704 } 4705 4706 // If there is nothing selected, add all candidates and remove the ones that the user 4707 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4708 if (result.size() == 0) { 4709 result.addAll(candidates); 4710 result.removeAll(neverList); 4711 } 4712 } 4713 } 4714 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4715 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4716 result.size()); 4717 for (ResolveInfo info : result) { 4718 Slog.v(TAG, " + " + info.activityInfo); 4719 } 4720 } 4721 return result; 4722 } 4723 4724 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4725 int status = ps.getDomainVerificationStatusForUser(userId); 4726 // if none available, get the master status 4727 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4728 if (ps.getIntentFilterVerificationInfo() != null) { 4729 status = ps.getIntentFilterVerificationInfo().getStatus(); 4730 } 4731 } 4732 return status; 4733 } 4734 4735 private ResolveInfo querySkipCurrentProfileIntents( 4736 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4737 int flags, int sourceUserId) { 4738 if (matchingFilters != null) { 4739 int size = matchingFilters.size(); 4740 for (int i = 0; i < size; i ++) { 4741 CrossProfileIntentFilter filter = matchingFilters.get(i); 4742 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4743 // Checking if there are activities in the target user that can handle the 4744 // intent. 4745 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4746 flags, sourceUserId); 4747 if (resolveInfo != null) { 4748 return resolveInfo; 4749 } 4750 } 4751 } 4752 } 4753 return null; 4754 } 4755 4756 // Return matching ResolveInfo if any for skip current profile intent filters. 4757 private ResolveInfo queryCrossProfileIntents( 4758 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4759 int flags, int sourceUserId) { 4760 if (matchingFilters != null) { 4761 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4762 // match the same intent. For performance reasons, it is better not to 4763 // run queryIntent twice for the same userId 4764 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4765 int size = matchingFilters.size(); 4766 for (int i = 0; i < size; i++) { 4767 CrossProfileIntentFilter filter = matchingFilters.get(i); 4768 int targetUserId = filter.getTargetUserId(); 4769 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4770 && !alreadyTriedUserIds.get(targetUserId)) { 4771 // Checking if there are activities in the target user that can handle the 4772 // intent. 4773 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4774 flags, sourceUserId); 4775 if (resolveInfo != null) return resolveInfo; 4776 alreadyTriedUserIds.put(targetUserId, true); 4777 } 4778 } 4779 } 4780 return null; 4781 } 4782 4783 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4784 String resolvedType, int flags, int sourceUserId) { 4785 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4786 resolvedType, flags, filter.getTargetUserId()); 4787 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4788 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4789 } 4790 return null; 4791 } 4792 4793 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4794 int sourceUserId, int targetUserId) { 4795 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4796 String className; 4797 if (targetUserId == UserHandle.USER_OWNER) { 4798 className = FORWARD_INTENT_TO_USER_OWNER; 4799 } else { 4800 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4801 } 4802 ComponentName forwardingActivityComponentName = new ComponentName( 4803 mAndroidApplication.packageName, className); 4804 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4805 sourceUserId); 4806 if (targetUserId == UserHandle.USER_OWNER) { 4807 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4808 forwardingResolveInfo.noResourceId = true; 4809 } 4810 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4811 forwardingResolveInfo.priority = 0; 4812 forwardingResolveInfo.preferredOrder = 0; 4813 forwardingResolveInfo.match = 0; 4814 forwardingResolveInfo.isDefault = true; 4815 forwardingResolveInfo.filter = filter; 4816 forwardingResolveInfo.targetUserId = targetUserId; 4817 return forwardingResolveInfo; 4818 } 4819 4820 @Override 4821 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4822 Intent[] specifics, String[] specificTypes, Intent intent, 4823 String resolvedType, int flags, int userId) { 4824 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4825 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4826 false, "query intent activity options"); 4827 final String resultsAction = intent.getAction(); 4828 4829 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4830 | PackageManager.GET_RESOLVED_FILTER, userId); 4831 4832 if (DEBUG_INTENT_MATCHING) { 4833 Log.v(TAG, "Query " + intent + ": " + results); 4834 } 4835 4836 int specificsPos = 0; 4837 int N; 4838 4839 // todo: note that the algorithm used here is O(N^2). This 4840 // isn't a problem in our current environment, but if we start running 4841 // into situations where we have more than 5 or 10 matches then this 4842 // should probably be changed to something smarter... 4843 4844 // First we go through and resolve each of the specific items 4845 // that were supplied, taking care of removing any corresponding 4846 // duplicate items in the generic resolve list. 4847 if (specifics != null) { 4848 for (int i=0; i<specifics.length; i++) { 4849 final Intent sintent = specifics[i]; 4850 if (sintent == null) { 4851 continue; 4852 } 4853 4854 if (DEBUG_INTENT_MATCHING) { 4855 Log.v(TAG, "Specific #" + i + ": " + sintent); 4856 } 4857 4858 String action = sintent.getAction(); 4859 if (resultsAction != null && resultsAction.equals(action)) { 4860 // If this action was explicitly requested, then don't 4861 // remove things that have it. 4862 action = null; 4863 } 4864 4865 ResolveInfo ri = null; 4866 ActivityInfo ai = null; 4867 4868 ComponentName comp = sintent.getComponent(); 4869 if (comp == null) { 4870 ri = resolveIntent( 4871 sintent, 4872 specificTypes != null ? specificTypes[i] : null, 4873 flags, userId); 4874 if (ri == null) { 4875 continue; 4876 } 4877 if (ri == mResolveInfo) { 4878 // ACK! Must do something better with this. 4879 } 4880 ai = ri.activityInfo; 4881 comp = new ComponentName(ai.applicationInfo.packageName, 4882 ai.name); 4883 } else { 4884 ai = getActivityInfo(comp, flags, userId); 4885 if (ai == null) { 4886 continue; 4887 } 4888 } 4889 4890 // Look for any generic query activities that are duplicates 4891 // of this specific one, and remove them from the results. 4892 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4893 N = results.size(); 4894 int j; 4895 for (j=specificsPos; j<N; j++) { 4896 ResolveInfo sri = results.get(j); 4897 if ((sri.activityInfo.name.equals(comp.getClassName()) 4898 && sri.activityInfo.applicationInfo.packageName.equals( 4899 comp.getPackageName())) 4900 || (action != null && sri.filter.matchAction(action))) { 4901 results.remove(j); 4902 if (DEBUG_INTENT_MATCHING) Log.v( 4903 TAG, "Removing duplicate item from " + j 4904 + " due to specific " + specificsPos); 4905 if (ri == null) { 4906 ri = sri; 4907 } 4908 j--; 4909 N--; 4910 } 4911 } 4912 4913 // Add this specific item to its proper place. 4914 if (ri == null) { 4915 ri = new ResolveInfo(); 4916 ri.activityInfo = ai; 4917 } 4918 results.add(specificsPos, ri); 4919 ri.specificIndex = i; 4920 specificsPos++; 4921 } 4922 } 4923 4924 // Now we go through the remaining generic results and remove any 4925 // duplicate actions that are found here. 4926 N = results.size(); 4927 for (int i=specificsPos; i<N-1; i++) { 4928 final ResolveInfo rii = results.get(i); 4929 if (rii.filter == null) { 4930 continue; 4931 } 4932 4933 // Iterate over all of the actions of this result's intent 4934 // filter... typically this should be just one. 4935 final Iterator<String> it = rii.filter.actionsIterator(); 4936 if (it == null) { 4937 continue; 4938 } 4939 while (it.hasNext()) { 4940 final String action = it.next(); 4941 if (resultsAction != null && resultsAction.equals(action)) { 4942 // If this action was explicitly requested, then don't 4943 // remove things that have it. 4944 continue; 4945 } 4946 for (int j=i+1; j<N; j++) { 4947 final ResolveInfo rij = results.get(j); 4948 if (rij.filter != null && rij.filter.hasAction(action)) { 4949 results.remove(j); 4950 if (DEBUG_INTENT_MATCHING) Log.v( 4951 TAG, "Removing duplicate item from " + j 4952 + " due to action " + action + " at " + i); 4953 j--; 4954 N--; 4955 } 4956 } 4957 } 4958 4959 // If the caller didn't request filter information, drop it now 4960 // so we don't have to marshall/unmarshall it. 4961 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4962 rii.filter = null; 4963 } 4964 } 4965 4966 // Filter out the caller activity if so requested. 4967 if (caller != null) { 4968 N = results.size(); 4969 for (int i=0; i<N; i++) { 4970 ActivityInfo ainfo = results.get(i).activityInfo; 4971 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4972 && caller.getClassName().equals(ainfo.name)) { 4973 results.remove(i); 4974 break; 4975 } 4976 } 4977 } 4978 4979 // If the caller didn't request filter information, 4980 // drop them now so we don't have to 4981 // marshall/unmarshall it. 4982 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4983 N = results.size(); 4984 for (int i=0; i<N; i++) { 4985 results.get(i).filter = null; 4986 } 4987 } 4988 4989 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4990 return results; 4991 } 4992 4993 @Override 4994 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4995 int userId) { 4996 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4997 ComponentName comp = intent.getComponent(); 4998 if (comp == null) { 4999 if (intent.getSelector() != null) { 5000 intent = intent.getSelector(); 5001 comp = intent.getComponent(); 5002 } 5003 } 5004 if (comp != null) { 5005 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5006 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5007 if (ai != null) { 5008 ResolveInfo ri = new ResolveInfo(); 5009 ri.activityInfo = ai; 5010 list.add(ri); 5011 } 5012 return list; 5013 } 5014 5015 // reader 5016 synchronized (mPackages) { 5017 String pkgName = intent.getPackage(); 5018 if (pkgName == null) { 5019 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5020 } 5021 final PackageParser.Package pkg = mPackages.get(pkgName); 5022 if (pkg != null) { 5023 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5024 userId); 5025 } 5026 return null; 5027 } 5028 } 5029 5030 @Override 5031 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5032 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5033 if (!sUserManager.exists(userId)) return null; 5034 if (query != null) { 5035 if (query.size() >= 1) { 5036 // If there is more than one service with the same priority, 5037 // just arbitrarily pick the first one. 5038 return query.get(0); 5039 } 5040 } 5041 return null; 5042 } 5043 5044 @Override 5045 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5046 int userId) { 5047 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5048 ComponentName comp = intent.getComponent(); 5049 if (comp == null) { 5050 if (intent.getSelector() != null) { 5051 intent = intent.getSelector(); 5052 comp = intent.getComponent(); 5053 } 5054 } 5055 if (comp != null) { 5056 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5057 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5058 if (si != null) { 5059 final ResolveInfo ri = new ResolveInfo(); 5060 ri.serviceInfo = si; 5061 list.add(ri); 5062 } 5063 return list; 5064 } 5065 5066 // reader 5067 synchronized (mPackages) { 5068 String pkgName = intent.getPackage(); 5069 if (pkgName == null) { 5070 return mServices.queryIntent(intent, resolvedType, flags, userId); 5071 } 5072 final PackageParser.Package pkg = mPackages.get(pkgName); 5073 if (pkg != null) { 5074 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5075 userId); 5076 } 5077 return null; 5078 } 5079 } 5080 5081 @Override 5082 public List<ResolveInfo> queryIntentContentProviders( 5083 Intent intent, String resolvedType, int flags, int userId) { 5084 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5085 ComponentName comp = intent.getComponent(); 5086 if (comp == null) { 5087 if (intent.getSelector() != null) { 5088 intent = intent.getSelector(); 5089 comp = intent.getComponent(); 5090 } 5091 } 5092 if (comp != null) { 5093 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5094 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5095 if (pi != null) { 5096 final ResolveInfo ri = new ResolveInfo(); 5097 ri.providerInfo = pi; 5098 list.add(ri); 5099 } 5100 return list; 5101 } 5102 5103 // reader 5104 synchronized (mPackages) { 5105 String pkgName = intent.getPackage(); 5106 if (pkgName == null) { 5107 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5108 } 5109 final PackageParser.Package pkg = mPackages.get(pkgName); 5110 if (pkg != null) { 5111 return mProviders.queryIntentForPackage( 5112 intent, resolvedType, flags, pkg.providers, userId); 5113 } 5114 return null; 5115 } 5116 } 5117 5118 @Override 5119 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5120 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5121 5122 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5123 5124 // writer 5125 synchronized (mPackages) { 5126 ArrayList<PackageInfo> list; 5127 if (listUninstalled) { 5128 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5129 for (PackageSetting ps : mSettings.mPackages.values()) { 5130 PackageInfo pi; 5131 if (ps.pkg != null) { 5132 pi = generatePackageInfo(ps.pkg, flags, userId); 5133 } else { 5134 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5135 } 5136 if (pi != null) { 5137 list.add(pi); 5138 } 5139 } 5140 } else { 5141 list = new ArrayList<PackageInfo>(mPackages.size()); 5142 for (PackageParser.Package p : mPackages.values()) { 5143 PackageInfo pi = generatePackageInfo(p, flags, userId); 5144 if (pi != null) { 5145 list.add(pi); 5146 } 5147 } 5148 } 5149 5150 return new ParceledListSlice<PackageInfo>(list); 5151 } 5152 } 5153 5154 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5155 String[] permissions, boolean[] tmp, int flags, int userId) { 5156 int numMatch = 0; 5157 final PermissionsState permissionsState = ps.getPermissionsState(); 5158 for (int i=0; i<permissions.length; i++) { 5159 final String permission = permissions[i]; 5160 if (permissionsState.hasPermission(permission, userId)) { 5161 tmp[i] = true; 5162 numMatch++; 5163 } else { 5164 tmp[i] = false; 5165 } 5166 } 5167 if (numMatch == 0) { 5168 return; 5169 } 5170 PackageInfo pi; 5171 if (ps.pkg != null) { 5172 pi = generatePackageInfo(ps.pkg, flags, userId); 5173 } else { 5174 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5175 } 5176 // The above might return null in cases of uninstalled apps or install-state 5177 // skew across users/profiles. 5178 if (pi != null) { 5179 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5180 if (numMatch == permissions.length) { 5181 pi.requestedPermissions = permissions; 5182 } else { 5183 pi.requestedPermissions = new String[numMatch]; 5184 numMatch = 0; 5185 for (int i=0; i<permissions.length; i++) { 5186 if (tmp[i]) { 5187 pi.requestedPermissions[numMatch] = permissions[i]; 5188 numMatch++; 5189 } 5190 } 5191 } 5192 } 5193 list.add(pi); 5194 } 5195 } 5196 5197 @Override 5198 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5199 String[] permissions, int flags, int userId) { 5200 if (!sUserManager.exists(userId)) return null; 5201 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5202 5203 // writer 5204 synchronized (mPackages) { 5205 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5206 boolean[] tmpBools = new boolean[permissions.length]; 5207 if (listUninstalled) { 5208 for (PackageSetting ps : mSettings.mPackages.values()) { 5209 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5210 } 5211 } else { 5212 for (PackageParser.Package pkg : mPackages.values()) { 5213 PackageSetting ps = (PackageSetting)pkg.mExtras; 5214 if (ps != null) { 5215 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5216 userId); 5217 } 5218 } 5219 } 5220 5221 return new ParceledListSlice<PackageInfo>(list); 5222 } 5223 } 5224 5225 @Override 5226 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5227 if (!sUserManager.exists(userId)) return null; 5228 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5229 5230 // writer 5231 synchronized (mPackages) { 5232 ArrayList<ApplicationInfo> list; 5233 if (listUninstalled) { 5234 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5235 for (PackageSetting ps : mSettings.mPackages.values()) { 5236 ApplicationInfo ai; 5237 if (ps.pkg != null) { 5238 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5239 ps.readUserState(userId), userId); 5240 } else { 5241 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5242 } 5243 if (ai != null) { 5244 list.add(ai); 5245 } 5246 } 5247 } else { 5248 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5249 for (PackageParser.Package p : mPackages.values()) { 5250 if (p.mExtras != null) { 5251 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5252 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5253 if (ai != null) { 5254 list.add(ai); 5255 } 5256 } 5257 } 5258 } 5259 5260 return new ParceledListSlice<ApplicationInfo>(list); 5261 } 5262 } 5263 5264 public List<ApplicationInfo> getPersistentApplications(int flags) { 5265 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5266 5267 // reader 5268 synchronized (mPackages) { 5269 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5270 final int userId = UserHandle.getCallingUserId(); 5271 while (i.hasNext()) { 5272 final PackageParser.Package p = i.next(); 5273 if (p.applicationInfo != null 5274 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5275 && (!mSafeMode || isSystemApp(p))) { 5276 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5277 if (ps != null) { 5278 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5279 ps.readUserState(userId), userId); 5280 if (ai != null) { 5281 finalList.add(ai); 5282 } 5283 } 5284 } 5285 } 5286 } 5287 5288 return finalList; 5289 } 5290 5291 @Override 5292 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5293 if (!sUserManager.exists(userId)) return null; 5294 // reader 5295 synchronized (mPackages) { 5296 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5297 PackageSetting ps = provider != null 5298 ? mSettings.mPackages.get(provider.owner.packageName) 5299 : null; 5300 return ps != null 5301 && mSettings.isEnabledLPr(provider.info, flags, userId) 5302 && (!mSafeMode || (provider.info.applicationInfo.flags 5303 &ApplicationInfo.FLAG_SYSTEM) != 0) 5304 ? PackageParser.generateProviderInfo(provider, flags, 5305 ps.readUserState(userId), userId) 5306 : null; 5307 } 5308 } 5309 5310 /** 5311 * @deprecated 5312 */ 5313 @Deprecated 5314 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5315 // reader 5316 synchronized (mPackages) { 5317 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5318 .entrySet().iterator(); 5319 final int userId = UserHandle.getCallingUserId(); 5320 while (i.hasNext()) { 5321 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5322 PackageParser.Provider p = entry.getValue(); 5323 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5324 5325 if (ps != null && p.syncable 5326 && (!mSafeMode || (p.info.applicationInfo.flags 5327 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5328 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5329 ps.readUserState(userId), userId); 5330 if (info != null) { 5331 outNames.add(entry.getKey()); 5332 outInfo.add(info); 5333 } 5334 } 5335 } 5336 } 5337 } 5338 5339 @Override 5340 public List<ProviderInfo> queryContentProviders(String processName, 5341 int uid, int flags) { 5342 ArrayList<ProviderInfo> finalList = null; 5343 // reader 5344 synchronized (mPackages) { 5345 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5346 final int userId = processName != null ? 5347 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5348 while (i.hasNext()) { 5349 final PackageParser.Provider p = i.next(); 5350 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5351 if (ps != null && p.info.authority != null 5352 && (processName == null 5353 || (p.info.processName.equals(processName) 5354 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5355 && mSettings.isEnabledLPr(p.info, flags, userId) 5356 && (!mSafeMode 5357 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5358 if (finalList == null) { 5359 finalList = new ArrayList<ProviderInfo>(3); 5360 } 5361 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5362 ps.readUserState(userId), userId); 5363 if (info != null) { 5364 finalList.add(info); 5365 } 5366 } 5367 } 5368 } 5369 5370 if (finalList != null) { 5371 Collections.sort(finalList, mProviderInitOrderSorter); 5372 } 5373 5374 return finalList; 5375 } 5376 5377 @Override 5378 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5379 int flags) { 5380 // reader 5381 synchronized (mPackages) { 5382 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5383 return PackageParser.generateInstrumentationInfo(i, flags); 5384 } 5385 } 5386 5387 @Override 5388 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5389 int flags) { 5390 ArrayList<InstrumentationInfo> finalList = 5391 new ArrayList<InstrumentationInfo>(); 5392 5393 // reader 5394 synchronized (mPackages) { 5395 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5396 while (i.hasNext()) { 5397 final PackageParser.Instrumentation p = i.next(); 5398 if (targetPackage == null 5399 || targetPackage.equals(p.info.targetPackage)) { 5400 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5401 flags); 5402 if (ii != null) { 5403 finalList.add(ii); 5404 } 5405 } 5406 } 5407 } 5408 5409 return finalList; 5410 } 5411 5412 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5413 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5414 if (overlays == null) { 5415 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5416 return; 5417 } 5418 for (PackageParser.Package opkg : overlays.values()) { 5419 // Not much to do if idmap fails: we already logged the error 5420 // and we certainly don't want to abort installation of pkg simply 5421 // because an overlay didn't fit properly. For these reasons, 5422 // ignore the return value of createIdmapForPackagePairLI. 5423 createIdmapForPackagePairLI(pkg, opkg); 5424 } 5425 } 5426 5427 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5428 PackageParser.Package opkg) { 5429 if (!opkg.mTrustedOverlay) { 5430 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5431 opkg.baseCodePath + ": overlay not trusted"); 5432 return false; 5433 } 5434 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5435 if (overlaySet == null) { 5436 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5437 opkg.baseCodePath + " but target package has no known overlays"); 5438 return false; 5439 } 5440 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5441 // TODO: generate idmap for split APKs 5442 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5443 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5444 + opkg.baseCodePath); 5445 return false; 5446 } 5447 PackageParser.Package[] overlayArray = 5448 overlaySet.values().toArray(new PackageParser.Package[0]); 5449 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5450 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5451 return p1.mOverlayPriority - p2.mOverlayPriority; 5452 } 5453 }; 5454 Arrays.sort(overlayArray, cmp); 5455 5456 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5457 int i = 0; 5458 for (PackageParser.Package p : overlayArray) { 5459 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5460 } 5461 return true; 5462 } 5463 5464 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5465 final File[] files = dir.listFiles(); 5466 if (ArrayUtils.isEmpty(files)) { 5467 Log.d(TAG, "No files in app dir " + dir); 5468 return; 5469 } 5470 5471 if (DEBUG_PACKAGE_SCANNING) { 5472 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5473 + " flags=0x" + Integer.toHexString(parseFlags)); 5474 } 5475 5476 for (File file : files) { 5477 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5478 && !PackageInstallerService.isStageName(file.getName()); 5479 if (!isPackage) { 5480 // Ignore entries which are not packages 5481 continue; 5482 } 5483 try { 5484 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5485 scanFlags, currentTime, null); 5486 } catch (PackageManagerException e) { 5487 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5488 5489 // Delete invalid userdata apps 5490 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5491 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5492 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5493 if (file.isDirectory()) { 5494 mInstaller.rmPackageDir(file.getAbsolutePath()); 5495 } else { 5496 file.delete(); 5497 } 5498 } 5499 } 5500 } 5501 } 5502 5503 private static File getSettingsProblemFile() { 5504 File dataDir = Environment.getDataDirectory(); 5505 File systemDir = new File(dataDir, "system"); 5506 File fname = new File(systemDir, "uiderrors.txt"); 5507 return fname; 5508 } 5509 5510 static void reportSettingsProblem(int priority, String msg) { 5511 logCriticalInfo(priority, msg); 5512 } 5513 5514 static void logCriticalInfo(int priority, String msg) { 5515 Slog.println(priority, TAG, msg); 5516 EventLogTags.writePmCriticalInfo(msg); 5517 try { 5518 File fname = getSettingsProblemFile(); 5519 FileOutputStream out = new FileOutputStream(fname, true); 5520 PrintWriter pw = new FastPrintWriter(out); 5521 SimpleDateFormat formatter = new SimpleDateFormat(); 5522 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5523 pw.println(dateString + ": " + msg); 5524 pw.close(); 5525 FileUtils.setPermissions( 5526 fname.toString(), 5527 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5528 -1, -1); 5529 } catch (java.io.IOException e) { 5530 } 5531 } 5532 5533 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5534 PackageParser.Package pkg, File srcFile, int parseFlags) 5535 throws PackageManagerException { 5536 if (ps != null 5537 && ps.codePath.equals(srcFile) 5538 && ps.timeStamp == srcFile.lastModified() 5539 && !isCompatSignatureUpdateNeeded(pkg) 5540 && !isRecoverSignatureUpdateNeeded(pkg)) { 5541 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5542 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5543 ArraySet<PublicKey> signingKs; 5544 synchronized (mPackages) { 5545 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5546 } 5547 if (ps.signatures.mSignatures != null 5548 && ps.signatures.mSignatures.length != 0 5549 && signingKs != null) { 5550 // Optimization: reuse the existing cached certificates 5551 // if the package appears to be unchanged. 5552 pkg.mSignatures = ps.signatures.mSignatures; 5553 pkg.mSigningKeys = signingKs; 5554 return; 5555 } 5556 5557 Slog.w(TAG, "PackageSetting for " + ps.name 5558 + " is missing signatures. Collecting certs again to recover them."); 5559 } else { 5560 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5561 } 5562 5563 try { 5564 pp.collectCertificates(pkg, parseFlags); 5565 pp.collectManifestDigest(pkg); 5566 } catch (PackageParserException e) { 5567 throw PackageManagerException.from(e); 5568 } 5569 } 5570 5571 /* 5572 * Scan a package and return the newly parsed package. 5573 * Returns null in case of errors and the error code is stored in mLastScanError 5574 */ 5575 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5576 long currentTime, UserHandle user) throws PackageManagerException { 5577 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5578 parseFlags |= mDefParseFlags; 5579 PackageParser pp = new PackageParser(); 5580 pp.setSeparateProcesses(mSeparateProcesses); 5581 pp.setOnlyCoreApps(mOnlyCore); 5582 pp.setDisplayMetrics(mMetrics); 5583 5584 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5585 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5586 } 5587 5588 final PackageParser.Package pkg; 5589 try { 5590 pkg = pp.parsePackage(scanFile, parseFlags); 5591 } catch (PackageParserException e) { 5592 throw PackageManagerException.from(e); 5593 } 5594 5595 PackageSetting ps = null; 5596 PackageSetting updatedPkg; 5597 // reader 5598 synchronized (mPackages) { 5599 // Look to see if we already know about this package. 5600 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5601 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5602 // This package has been renamed to its original name. Let's 5603 // use that. 5604 ps = mSettings.peekPackageLPr(oldName); 5605 } 5606 // If there was no original package, see one for the real package name. 5607 if (ps == null) { 5608 ps = mSettings.peekPackageLPr(pkg.packageName); 5609 } 5610 // Check to see if this package could be hiding/updating a system 5611 // package. Must look for it either under the original or real 5612 // package name depending on our state. 5613 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5614 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5615 } 5616 boolean updatedPkgBetter = false; 5617 // First check if this is a system package that may involve an update 5618 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5619 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5620 // it needs to drop FLAG_PRIVILEGED. 5621 if (locationIsPrivileged(scanFile)) { 5622 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5623 } else { 5624 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5625 } 5626 5627 if (ps != null && !ps.codePath.equals(scanFile)) { 5628 // The path has changed from what was last scanned... check the 5629 // version of the new path against what we have stored to determine 5630 // what to do. 5631 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5632 if (pkg.mVersionCode <= ps.versionCode) { 5633 // The system package has been updated and the code path does not match 5634 // Ignore entry. Skip it. 5635 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5636 + " ignored: updated version " + ps.versionCode 5637 + " better than this " + pkg.mVersionCode); 5638 if (!updatedPkg.codePath.equals(scanFile)) { 5639 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5640 + ps.name + " changing from " + updatedPkg.codePathString 5641 + " to " + scanFile); 5642 updatedPkg.codePath = scanFile; 5643 updatedPkg.codePathString = scanFile.toString(); 5644 updatedPkg.resourcePath = scanFile; 5645 updatedPkg.resourcePathString = scanFile.toString(); 5646 } 5647 updatedPkg.pkg = pkg; 5648 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5649 } else { 5650 // The current app on the system partition is better than 5651 // what we have updated to on the data partition; switch 5652 // back to the system partition version. 5653 // At this point, its safely assumed that package installation for 5654 // apps in system partition will go through. If not there won't be a working 5655 // version of the app 5656 // writer 5657 synchronized (mPackages) { 5658 // Just remove the loaded entries from package lists. 5659 mPackages.remove(ps.name); 5660 } 5661 5662 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5663 + " reverting from " + ps.codePathString 5664 + ": new version " + pkg.mVersionCode 5665 + " better than installed " + ps.versionCode); 5666 5667 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5668 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5669 synchronized (mInstallLock) { 5670 args.cleanUpResourcesLI(); 5671 } 5672 synchronized (mPackages) { 5673 mSettings.enableSystemPackageLPw(ps.name); 5674 } 5675 updatedPkgBetter = true; 5676 } 5677 } 5678 } 5679 5680 if (updatedPkg != null) { 5681 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5682 // initially 5683 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5684 5685 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5686 // flag set initially 5687 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5688 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5689 } 5690 } 5691 5692 // Verify certificates against what was last scanned 5693 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5694 5695 /* 5696 * A new system app appeared, but we already had a non-system one of the 5697 * same name installed earlier. 5698 */ 5699 boolean shouldHideSystemApp = false; 5700 if (updatedPkg == null && ps != null 5701 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5702 /* 5703 * Check to make sure the signatures match first. If they don't, 5704 * wipe the installed application and its data. 5705 */ 5706 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5707 != PackageManager.SIGNATURE_MATCH) { 5708 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5709 + " signatures don't match existing userdata copy; removing"); 5710 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5711 ps = null; 5712 } else { 5713 /* 5714 * If the newly-added system app is an older version than the 5715 * already installed version, hide it. It will be scanned later 5716 * and re-added like an update. 5717 */ 5718 if (pkg.mVersionCode <= ps.versionCode) { 5719 shouldHideSystemApp = true; 5720 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5721 + " but new version " + pkg.mVersionCode + " better than installed " 5722 + ps.versionCode + "; hiding system"); 5723 } else { 5724 /* 5725 * The newly found system app is a newer version that the 5726 * one previously installed. Simply remove the 5727 * already-installed application and replace it with our own 5728 * while keeping the application data. 5729 */ 5730 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5731 + " reverting from " + ps.codePathString + ": new version " 5732 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5733 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5734 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5735 synchronized (mInstallLock) { 5736 args.cleanUpResourcesLI(); 5737 } 5738 } 5739 } 5740 } 5741 5742 // The apk is forward locked (not public) if its code and resources 5743 // are kept in different files. (except for app in either system or 5744 // vendor path). 5745 // TODO grab this value from PackageSettings 5746 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5747 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5748 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5749 } 5750 } 5751 5752 // TODO: extend to support forward-locked splits 5753 String resourcePath = null; 5754 String baseResourcePath = null; 5755 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5756 if (ps != null && ps.resourcePathString != null) { 5757 resourcePath = ps.resourcePathString; 5758 baseResourcePath = ps.resourcePathString; 5759 } else { 5760 // Should not happen at all. Just log an error. 5761 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5762 } 5763 } else { 5764 resourcePath = pkg.codePath; 5765 baseResourcePath = pkg.baseCodePath; 5766 } 5767 5768 // Set application objects path explicitly. 5769 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5770 pkg.applicationInfo.setCodePath(pkg.codePath); 5771 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5772 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5773 pkg.applicationInfo.setResourcePath(resourcePath); 5774 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5775 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5776 5777 // Note that we invoke the following method only if we are about to unpack an application 5778 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5779 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5780 5781 /* 5782 * If the system app should be overridden by a previously installed 5783 * data, hide the system app now and let the /data/app scan pick it up 5784 * again. 5785 */ 5786 if (shouldHideSystemApp) { 5787 synchronized (mPackages) { 5788 /* 5789 * We have to grant systems permissions before we hide, because 5790 * grantPermissions will assume the package update is trying to 5791 * expand its permissions. 5792 */ 5793 grantPermissionsLPw(pkg, true, pkg.packageName); 5794 mSettings.disableSystemPackageLPw(pkg.packageName); 5795 } 5796 } 5797 5798 return scannedPkg; 5799 } 5800 5801 private static String fixProcessName(String defProcessName, 5802 String processName, int uid) { 5803 if (processName == null) { 5804 return defProcessName; 5805 } 5806 return processName; 5807 } 5808 5809 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5810 throws PackageManagerException { 5811 if (pkgSetting.signatures.mSignatures != null) { 5812 // Already existing package. Make sure signatures match 5813 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5814 == PackageManager.SIGNATURE_MATCH; 5815 if (!match) { 5816 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5817 == PackageManager.SIGNATURE_MATCH; 5818 } 5819 if (!match) { 5820 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5821 == PackageManager.SIGNATURE_MATCH; 5822 } 5823 if (!match) { 5824 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5825 + pkg.packageName + " signatures do not match the " 5826 + "previously installed version; ignoring!"); 5827 } 5828 } 5829 5830 // Check for shared user signatures 5831 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5832 // Already existing package. Make sure signatures match 5833 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5834 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5835 if (!match) { 5836 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5837 == PackageManager.SIGNATURE_MATCH; 5838 } 5839 if (!match) { 5840 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5841 == PackageManager.SIGNATURE_MATCH; 5842 } 5843 if (!match) { 5844 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5845 "Package " + pkg.packageName 5846 + " has no signatures that match those in shared user " 5847 + pkgSetting.sharedUser.name + "; ignoring!"); 5848 } 5849 } 5850 } 5851 5852 /** 5853 * Enforces that only the system UID or root's UID can call a method exposed 5854 * via Binder. 5855 * 5856 * @param message used as message if SecurityException is thrown 5857 * @throws SecurityException if the caller is not system or root 5858 */ 5859 private static final void enforceSystemOrRoot(String message) { 5860 final int uid = Binder.getCallingUid(); 5861 if (uid != Process.SYSTEM_UID && uid != 0) { 5862 throw new SecurityException(message); 5863 } 5864 } 5865 5866 @Override 5867 public void performBootDexOpt() { 5868 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5869 5870 // Before everything else, see whether we need to fstrim. 5871 try { 5872 IMountService ms = PackageHelper.getMountService(); 5873 if (ms != null) { 5874 final boolean isUpgrade = isUpgrade(); 5875 boolean doTrim = isUpgrade; 5876 if (doTrim) { 5877 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5878 } else { 5879 final long interval = android.provider.Settings.Global.getLong( 5880 mContext.getContentResolver(), 5881 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5882 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5883 if (interval > 0) { 5884 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5885 if (timeSinceLast > interval) { 5886 doTrim = true; 5887 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5888 + "; running immediately"); 5889 } 5890 } 5891 } 5892 if (doTrim) { 5893 if (!isFirstBoot()) { 5894 try { 5895 ActivityManagerNative.getDefault().showBootMessage( 5896 mContext.getResources().getString( 5897 R.string.android_upgrading_fstrim), true); 5898 } catch (RemoteException e) { 5899 } 5900 } 5901 ms.runMaintenance(); 5902 } 5903 } else { 5904 Slog.e(TAG, "Mount service unavailable!"); 5905 } 5906 } catch (RemoteException e) { 5907 // Can't happen; MountService is local 5908 } 5909 5910 final ArraySet<PackageParser.Package> pkgs; 5911 synchronized (mPackages) { 5912 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5913 } 5914 5915 if (pkgs != null) { 5916 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5917 // in case the device runs out of space. 5918 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5919 // Give priority to core apps. 5920 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5921 PackageParser.Package pkg = it.next(); 5922 if (pkg.coreApp) { 5923 if (DEBUG_DEXOPT) { 5924 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5925 } 5926 sortedPkgs.add(pkg); 5927 it.remove(); 5928 } 5929 } 5930 // Give priority to system apps that listen for pre boot complete. 5931 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5932 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5933 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5934 PackageParser.Package pkg = it.next(); 5935 if (pkgNames.contains(pkg.packageName)) { 5936 if (DEBUG_DEXOPT) { 5937 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5938 } 5939 sortedPkgs.add(pkg); 5940 it.remove(); 5941 } 5942 } 5943 // Give priority to system apps. 5944 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5945 PackageParser.Package pkg = it.next(); 5946 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5947 if (DEBUG_DEXOPT) { 5948 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5949 } 5950 sortedPkgs.add(pkg); 5951 it.remove(); 5952 } 5953 } 5954 // Give priority to updated system apps. 5955 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5956 PackageParser.Package pkg = it.next(); 5957 if (pkg.isUpdatedSystemApp()) { 5958 if (DEBUG_DEXOPT) { 5959 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5960 } 5961 sortedPkgs.add(pkg); 5962 it.remove(); 5963 } 5964 } 5965 // Give priority to apps that listen for boot complete. 5966 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5967 pkgNames = getPackageNamesForIntent(intent); 5968 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5969 PackageParser.Package pkg = it.next(); 5970 if (pkgNames.contains(pkg.packageName)) { 5971 if (DEBUG_DEXOPT) { 5972 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5973 } 5974 sortedPkgs.add(pkg); 5975 it.remove(); 5976 } 5977 } 5978 // Filter out packages that aren't recently used. 5979 filterRecentlyUsedApps(pkgs); 5980 // Add all remaining apps. 5981 for (PackageParser.Package pkg : pkgs) { 5982 if (DEBUG_DEXOPT) { 5983 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5984 } 5985 sortedPkgs.add(pkg); 5986 } 5987 5988 // If we want to be lazy, filter everything that wasn't recently used. 5989 if (mLazyDexOpt) { 5990 filterRecentlyUsedApps(sortedPkgs); 5991 } 5992 5993 int i = 0; 5994 int total = sortedPkgs.size(); 5995 File dataDir = Environment.getDataDirectory(); 5996 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5997 if (lowThreshold == 0) { 5998 throw new IllegalStateException("Invalid low memory threshold"); 5999 } 6000 for (PackageParser.Package pkg : sortedPkgs) { 6001 long usableSpace = dataDir.getUsableSpace(); 6002 if (usableSpace < lowThreshold) { 6003 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6004 break; 6005 } 6006 performBootDexOpt(pkg, ++i, total); 6007 } 6008 } 6009 } 6010 6011 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6012 // Filter out packages that aren't recently used. 6013 // 6014 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6015 // should do a full dexopt. 6016 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6017 int total = pkgs.size(); 6018 int skipped = 0; 6019 long now = System.currentTimeMillis(); 6020 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6021 PackageParser.Package pkg = i.next(); 6022 long then = pkg.mLastPackageUsageTimeInMills; 6023 if (then + mDexOptLRUThresholdInMills < now) { 6024 if (DEBUG_DEXOPT) { 6025 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6026 ((then == 0) ? "never" : new Date(then))); 6027 } 6028 i.remove(); 6029 skipped++; 6030 } 6031 } 6032 if (DEBUG_DEXOPT) { 6033 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6034 } 6035 } 6036 } 6037 6038 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6039 List<ResolveInfo> ris = null; 6040 try { 6041 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6042 intent, null, 0, UserHandle.USER_OWNER); 6043 } catch (RemoteException e) { 6044 } 6045 ArraySet<String> pkgNames = new ArraySet<String>(); 6046 if (ris != null) { 6047 for (ResolveInfo ri : ris) { 6048 pkgNames.add(ri.activityInfo.packageName); 6049 } 6050 } 6051 return pkgNames; 6052 } 6053 6054 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6055 if (DEBUG_DEXOPT) { 6056 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6057 } 6058 if (!isFirstBoot()) { 6059 try { 6060 ActivityManagerNative.getDefault().showBootMessage( 6061 mContext.getResources().getString(R.string.android_upgrading_apk, 6062 curr, total), true); 6063 } catch (RemoteException e) { 6064 } 6065 } 6066 PackageParser.Package p = pkg; 6067 synchronized (mInstallLock) { 6068 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6069 false /* force dex */, false /* defer */, true /* include dependencies */); 6070 } 6071 } 6072 6073 @Override 6074 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6075 return performDexOpt(packageName, instructionSet, false); 6076 } 6077 6078 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6079 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6080 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6081 if (!dexopt && !updateUsage) { 6082 // We aren't going to dexopt or update usage, so bail early. 6083 return false; 6084 } 6085 PackageParser.Package p; 6086 final String targetInstructionSet; 6087 synchronized (mPackages) { 6088 p = mPackages.get(packageName); 6089 if (p == null) { 6090 return false; 6091 } 6092 if (updateUsage) { 6093 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6094 } 6095 mPackageUsage.write(false); 6096 if (!dexopt) { 6097 // We aren't going to dexopt, so bail early. 6098 return false; 6099 } 6100 6101 targetInstructionSet = instructionSet != null ? instructionSet : 6102 getPrimaryInstructionSet(p.applicationInfo); 6103 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6104 return false; 6105 } 6106 } 6107 6108 synchronized (mInstallLock) { 6109 final String[] instructionSets = new String[] { targetInstructionSet }; 6110 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6111 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6112 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6113 } 6114 } 6115 6116 public ArraySet<String> getPackagesThatNeedDexOpt() { 6117 ArraySet<String> pkgs = null; 6118 synchronized (mPackages) { 6119 for (PackageParser.Package p : mPackages.values()) { 6120 if (DEBUG_DEXOPT) { 6121 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6122 } 6123 if (!p.mDexOptPerformed.isEmpty()) { 6124 continue; 6125 } 6126 if (pkgs == null) { 6127 pkgs = new ArraySet<String>(); 6128 } 6129 pkgs.add(p.packageName); 6130 } 6131 } 6132 return pkgs; 6133 } 6134 6135 public void shutdown() { 6136 mPackageUsage.write(true); 6137 } 6138 6139 @Override 6140 public void forceDexOpt(String packageName) { 6141 enforceSystemOrRoot("forceDexOpt"); 6142 6143 PackageParser.Package pkg; 6144 synchronized (mPackages) { 6145 pkg = mPackages.get(packageName); 6146 if (pkg == null) { 6147 throw new IllegalArgumentException("Missing package: " + packageName); 6148 } 6149 } 6150 6151 synchronized (mInstallLock) { 6152 final String[] instructionSets = new String[] { 6153 getPrimaryInstructionSet(pkg.applicationInfo) }; 6154 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6155 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6156 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6157 throw new IllegalStateException("Failed to dexopt: " + res); 6158 } 6159 } 6160 } 6161 6162 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6163 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6164 Slog.w(TAG, "Unable to update from " + oldPkg.name 6165 + " to " + newPkg.packageName 6166 + ": old package not in system partition"); 6167 return false; 6168 } else if (mPackages.get(oldPkg.name) != null) { 6169 Slog.w(TAG, "Unable to update from " + oldPkg.name 6170 + " to " + newPkg.packageName 6171 + ": old package still exists"); 6172 return false; 6173 } 6174 return true; 6175 } 6176 6177 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6178 int[] users = sUserManager.getUserIds(); 6179 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6180 if (res < 0) { 6181 return res; 6182 } 6183 for (int user : users) { 6184 if (user != 0) { 6185 res = mInstaller.createUserData(volumeUuid, packageName, 6186 UserHandle.getUid(user, uid), user, seinfo); 6187 if (res < 0) { 6188 return res; 6189 } 6190 } 6191 } 6192 return res; 6193 } 6194 6195 private int removeDataDirsLI(String volumeUuid, String packageName) { 6196 int[] users = sUserManager.getUserIds(); 6197 int res = 0; 6198 for (int user : users) { 6199 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6200 if (resInner < 0) { 6201 res = resInner; 6202 } 6203 } 6204 6205 return res; 6206 } 6207 6208 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6209 int[] users = sUserManager.getUserIds(); 6210 int res = 0; 6211 for (int user : users) { 6212 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6213 if (resInner < 0) { 6214 res = resInner; 6215 } 6216 } 6217 return res; 6218 } 6219 6220 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6221 PackageParser.Package changingLib) { 6222 if (file.path != null) { 6223 usesLibraryFiles.add(file.path); 6224 return; 6225 } 6226 PackageParser.Package p = mPackages.get(file.apk); 6227 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6228 // If we are doing this while in the middle of updating a library apk, 6229 // then we need to make sure to use that new apk for determining the 6230 // dependencies here. (We haven't yet finished committing the new apk 6231 // to the package manager state.) 6232 if (p == null || p.packageName.equals(changingLib.packageName)) { 6233 p = changingLib; 6234 } 6235 } 6236 if (p != null) { 6237 usesLibraryFiles.addAll(p.getAllCodePaths()); 6238 } 6239 } 6240 6241 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6242 PackageParser.Package changingLib) throws PackageManagerException { 6243 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6244 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6245 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6246 for (int i=0; i<N; i++) { 6247 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6248 if (file == null) { 6249 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6250 "Package " + pkg.packageName + " requires unavailable shared library " 6251 + pkg.usesLibraries.get(i) + "; failing!"); 6252 } 6253 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6254 } 6255 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6256 for (int i=0; i<N; i++) { 6257 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6258 if (file == null) { 6259 Slog.w(TAG, "Package " + pkg.packageName 6260 + " desires unavailable shared library " 6261 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6262 } else { 6263 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6264 } 6265 } 6266 N = usesLibraryFiles.size(); 6267 if (N > 0) { 6268 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6269 } else { 6270 pkg.usesLibraryFiles = null; 6271 } 6272 } 6273 } 6274 6275 private static boolean hasString(List<String> list, List<String> which) { 6276 if (list == null) { 6277 return false; 6278 } 6279 for (int i=list.size()-1; i>=0; i--) { 6280 for (int j=which.size()-1; j>=0; j--) { 6281 if (which.get(j).equals(list.get(i))) { 6282 return true; 6283 } 6284 } 6285 } 6286 return false; 6287 } 6288 6289 private void updateAllSharedLibrariesLPw() { 6290 for (PackageParser.Package pkg : mPackages.values()) { 6291 try { 6292 updateSharedLibrariesLPw(pkg, null); 6293 } catch (PackageManagerException e) { 6294 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6295 } 6296 } 6297 } 6298 6299 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6300 PackageParser.Package changingPkg) { 6301 ArrayList<PackageParser.Package> res = null; 6302 for (PackageParser.Package pkg : mPackages.values()) { 6303 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6304 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6305 if (res == null) { 6306 res = new ArrayList<PackageParser.Package>(); 6307 } 6308 res.add(pkg); 6309 try { 6310 updateSharedLibrariesLPw(pkg, changingPkg); 6311 } catch (PackageManagerException e) { 6312 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6313 } 6314 } 6315 } 6316 return res; 6317 } 6318 6319 /** 6320 * Derive the value of the {@code cpuAbiOverride} based on the provided 6321 * value and an optional stored value from the package settings. 6322 */ 6323 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6324 String cpuAbiOverride = null; 6325 6326 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6327 cpuAbiOverride = null; 6328 } else if (abiOverride != null) { 6329 cpuAbiOverride = abiOverride; 6330 } else if (settings != null) { 6331 cpuAbiOverride = settings.cpuAbiOverrideString; 6332 } 6333 6334 return cpuAbiOverride; 6335 } 6336 6337 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6338 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6339 boolean success = false; 6340 try { 6341 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6342 currentTime, user); 6343 success = true; 6344 return res; 6345 } finally { 6346 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6347 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6348 } 6349 } 6350 } 6351 6352 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6353 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6354 final File scanFile = new File(pkg.codePath); 6355 if (pkg.applicationInfo.getCodePath() == null || 6356 pkg.applicationInfo.getResourcePath() == null) { 6357 // Bail out. The resource and code paths haven't been set. 6358 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6359 "Code and resource paths haven't been set correctly"); 6360 } 6361 6362 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6363 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6364 } else { 6365 // Only allow system apps to be flagged as core apps. 6366 pkg.coreApp = false; 6367 } 6368 6369 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6370 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6371 } 6372 6373 if (mCustomResolverComponentName != null && 6374 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6375 setUpCustomResolverActivity(pkg); 6376 } 6377 6378 if (pkg.packageName.equals("android")) { 6379 synchronized (mPackages) { 6380 if (mAndroidApplication != null) { 6381 Slog.w(TAG, "*************************************************"); 6382 Slog.w(TAG, "Core android package being redefined. Skipping."); 6383 Slog.w(TAG, " file=" + scanFile); 6384 Slog.w(TAG, "*************************************************"); 6385 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6386 "Core android package being redefined. Skipping."); 6387 } 6388 6389 // Set up information for our fall-back user intent resolution activity. 6390 mPlatformPackage = pkg; 6391 pkg.mVersionCode = mSdkVersion; 6392 mAndroidApplication = pkg.applicationInfo; 6393 6394 if (!mResolverReplaced) { 6395 mResolveActivity.applicationInfo = mAndroidApplication; 6396 mResolveActivity.name = ResolverActivity.class.getName(); 6397 mResolveActivity.packageName = mAndroidApplication.packageName; 6398 mResolveActivity.processName = "system:ui"; 6399 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6400 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6401 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6402 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6403 mResolveActivity.exported = true; 6404 mResolveActivity.enabled = true; 6405 mResolveInfo.activityInfo = mResolveActivity; 6406 mResolveInfo.priority = 0; 6407 mResolveInfo.preferredOrder = 0; 6408 mResolveInfo.match = 0; 6409 mResolveComponentName = new ComponentName( 6410 mAndroidApplication.packageName, mResolveActivity.name); 6411 } 6412 } 6413 } 6414 6415 if (DEBUG_PACKAGE_SCANNING) { 6416 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6417 Log.d(TAG, "Scanning package " + pkg.packageName); 6418 } 6419 6420 if (mPackages.containsKey(pkg.packageName) 6421 || mSharedLibraries.containsKey(pkg.packageName)) { 6422 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6423 "Application package " + pkg.packageName 6424 + " already installed. Skipping duplicate."); 6425 } 6426 6427 // If we're only installing presumed-existing packages, require that the 6428 // scanned APK is both already known and at the path previously established 6429 // for it. Previously unknown packages we pick up normally, but if we have an 6430 // a priori expectation about this package's install presence, enforce it. 6431 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6432 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6433 if (known != null) { 6434 if (DEBUG_PACKAGE_SCANNING) { 6435 Log.d(TAG, "Examining " + pkg.codePath 6436 + " and requiring known paths " + known.codePathString 6437 + " & " + known.resourcePathString); 6438 } 6439 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6440 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6441 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6442 "Application package " + pkg.packageName 6443 + " found at " + pkg.applicationInfo.getCodePath() 6444 + " but expected at " + known.codePathString + "; ignoring."); 6445 } 6446 } 6447 } 6448 6449 // Initialize package source and resource directories 6450 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6451 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6452 6453 SharedUserSetting suid = null; 6454 PackageSetting pkgSetting = null; 6455 6456 if (!isSystemApp(pkg)) { 6457 // Only system apps can use these features. 6458 pkg.mOriginalPackages = null; 6459 pkg.mRealPackage = null; 6460 pkg.mAdoptPermissions = null; 6461 } 6462 6463 // writer 6464 synchronized (mPackages) { 6465 if (pkg.mSharedUserId != null) { 6466 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6467 if (suid == null) { 6468 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6469 "Creating application package " + pkg.packageName 6470 + " for shared user failed"); 6471 } 6472 if (DEBUG_PACKAGE_SCANNING) { 6473 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6474 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6475 + "): packages=" + suid.packages); 6476 } 6477 } 6478 6479 // Check if we are renaming from an original package name. 6480 PackageSetting origPackage = null; 6481 String realName = null; 6482 if (pkg.mOriginalPackages != null) { 6483 // This package may need to be renamed to a previously 6484 // installed name. Let's check on that... 6485 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6486 if (pkg.mOriginalPackages.contains(renamed)) { 6487 // This package had originally been installed as the 6488 // original name, and we have already taken care of 6489 // transitioning to the new one. Just update the new 6490 // one to continue using the old name. 6491 realName = pkg.mRealPackage; 6492 if (!pkg.packageName.equals(renamed)) { 6493 // Callers into this function may have already taken 6494 // care of renaming the package; only do it here if 6495 // it is not already done. 6496 pkg.setPackageName(renamed); 6497 } 6498 6499 } else { 6500 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6501 if ((origPackage = mSettings.peekPackageLPr( 6502 pkg.mOriginalPackages.get(i))) != null) { 6503 // We do have the package already installed under its 6504 // original name... should we use it? 6505 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6506 // New package is not compatible with original. 6507 origPackage = null; 6508 continue; 6509 } else if (origPackage.sharedUser != null) { 6510 // Make sure uid is compatible between packages. 6511 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6512 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6513 + " to " + pkg.packageName + ": old uid " 6514 + origPackage.sharedUser.name 6515 + " differs from " + pkg.mSharedUserId); 6516 origPackage = null; 6517 continue; 6518 } 6519 } else { 6520 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6521 + pkg.packageName + " to old name " + origPackage.name); 6522 } 6523 break; 6524 } 6525 } 6526 } 6527 } 6528 6529 if (mTransferedPackages.contains(pkg.packageName)) { 6530 Slog.w(TAG, "Package " + pkg.packageName 6531 + " was transferred to another, but its .apk remains"); 6532 } 6533 6534 // Just create the setting, don't add it yet. For already existing packages 6535 // the PkgSetting exists already and doesn't have to be created. 6536 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6537 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6538 pkg.applicationInfo.primaryCpuAbi, 6539 pkg.applicationInfo.secondaryCpuAbi, 6540 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6541 user, false); 6542 if (pkgSetting == null) { 6543 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6544 "Creating application package " + pkg.packageName + " failed"); 6545 } 6546 6547 if (pkgSetting.origPackage != null) { 6548 // If we are first transitioning from an original package, 6549 // fix up the new package's name now. We need to do this after 6550 // looking up the package under its new name, so getPackageLP 6551 // can take care of fiddling things correctly. 6552 pkg.setPackageName(origPackage.name); 6553 6554 // File a report about this. 6555 String msg = "New package " + pkgSetting.realName 6556 + " renamed to replace old package " + pkgSetting.name; 6557 reportSettingsProblem(Log.WARN, msg); 6558 6559 // Make a note of it. 6560 mTransferedPackages.add(origPackage.name); 6561 6562 // No longer need to retain this. 6563 pkgSetting.origPackage = null; 6564 } 6565 6566 if (realName != null) { 6567 // Make a note of it. 6568 mTransferedPackages.add(pkg.packageName); 6569 } 6570 6571 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6572 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6573 } 6574 6575 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6576 // Check all shared libraries and map to their actual file path. 6577 // We only do this here for apps not on a system dir, because those 6578 // are the only ones that can fail an install due to this. We 6579 // will take care of the system apps by updating all of their 6580 // library paths after the scan is done. 6581 updateSharedLibrariesLPw(pkg, null); 6582 } 6583 6584 if (mFoundPolicyFile) { 6585 SELinuxMMAC.assignSeinfoValue(pkg); 6586 } 6587 6588 pkg.applicationInfo.uid = pkgSetting.appId; 6589 pkg.mExtras = pkgSetting; 6590 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6591 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6592 // We just determined the app is signed correctly, so bring 6593 // over the latest parsed certs. 6594 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6595 } else { 6596 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6597 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6598 "Package " + pkg.packageName + " upgrade keys do not match the " 6599 + "previously installed version"); 6600 } else { 6601 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6602 String msg = "System package " + pkg.packageName 6603 + " signature changed; retaining data."; 6604 reportSettingsProblem(Log.WARN, msg); 6605 } 6606 } 6607 } else { 6608 try { 6609 verifySignaturesLP(pkgSetting, pkg); 6610 // We just determined the app is signed correctly, so bring 6611 // over the latest parsed certs. 6612 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6613 } catch (PackageManagerException e) { 6614 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6615 throw e; 6616 } 6617 // The signature has changed, but this package is in the system 6618 // image... let's recover! 6619 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6620 // However... if this package is part of a shared user, but it 6621 // doesn't match the signature of the shared user, let's fail. 6622 // What this means is that you can't change the signatures 6623 // associated with an overall shared user, which doesn't seem all 6624 // that unreasonable. 6625 if (pkgSetting.sharedUser != null) { 6626 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6627 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6628 throw new PackageManagerException( 6629 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6630 "Signature mismatch for shared user : " 6631 + pkgSetting.sharedUser); 6632 } 6633 } 6634 // File a report about this. 6635 String msg = "System package " + pkg.packageName 6636 + " signature changed; retaining data."; 6637 reportSettingsProblem(Log.WARN, msg); 6638 } 6639 } 6640 // Verify that this new package doesn't have any content providers 6641 // that conflict with existing packages. Only do this if the 6642 // package isn't already installed, since we don't want to break 6643 // things that are installed. 6644 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6645 final int N = pkg.providers.size(); 6646 int i; 6647 for (i=0; i<N; i++) { 6648 PackageParser.Provider p = pkg.providers.get(i); 6649 if (p.info.authority != null) { 6650 String names[] = p.info.authority.split(";"); 6651 for (int j = 0; j < names.length; j++) { 6652 if (mProvidersByAuthority.containsKey(names[j])) { 6653 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6654 final String otherPackageName = 6655 ((other != null && other.getComponentName() != null) ? 6656 other.getComponentName().getPackageName() : "?"); 6657 throw new PackageManagerException( 6658 INSTALL_FAILED_CONFLICTING_PROVIDER, 6659 "Can't install because provider name " + names[j] 6660 + " (in package " + pkg.applicationInfo.packageName 6661 + ") is already used by " + otherPackageName); 6662 } 6663 } 6664 } 6665 } 6666 } 6667 6668 if (pkg.mAdoptPermissions != null) { 6669 // This package wants to adopt ownership of permissions from 6670 // another package. 6671 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6672 final String origName = pkg.mAdoptPermissions.get(i); 6673 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6674 if (orig != null) { 6675 if (verifyPackageUpdateLPr(orig, pkg)) { 6676 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6677 + pkg.packageName); 6678 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6679 } 6680 } 6681 } 6682 } 6683 } 6684 6685 final String pkgName = pkg.packageName; 6686 6687 final long scanFileTime = scanFile.lastModified(); 6688 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6689 pkg.applicationInfo.processName = fixProcessName( 6690 pkg.applicationInfo.packageName, 6691 pkg.applicationInfo.processName, 6692 pkg.applicationInfo.uid); 6693 6694 File dataPath; 6695 if (mPlatformPackage == pkg) { 6696 // The system package is special. 6697 dataPath = new File(Environment.getDataDirectory(), "system"); 6698 6699 pkg.applicationInfo.dataDir = dataPath.getPath(); 6700 6701 } else { 6702 // This is a normal package, need to make its data directory. 6703 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6704 UserHandle.USER_OWNER, pkg.packageName); 6705 6706 boolean uidError = false; 6707 if (dataPath.exists()) { 6708 int currentUid = 0; 6709 try { 6710 StructStat stat = Os.stat(dataPath.getPath()); 6711 currentUid = stat.st_uid; 6712 } catch (ErrnoException e) { 6713 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6714 } 6715 6716 // If we have mismatched owners for the data path, we have a problem. 6717 if (currentUid != pkg.applicationInfo.uid) { 6718 boolean recovered = false; 6719 if (currentUid == 0) { 6720 // The directory somehow became owned by root. Wow. 6721 // This is probably because the system was stopped while 6722 // installd was in the middle of messing with its libs 6723 // directory. Ask installd to fix that. 6724 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6725 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6726 if (ret >= 0) { 6727 recovered = true; 6728 String msg = "Package " + pkg.packageName 6729 + " unexpectedly changed to uid 0; recovered to " + 6730 + pkg.applicationInfo.uid; 6731 reportSettingsProblem(Log.WARN, msg); 6732 } 6733 } 6734 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6735 || (scanFlags&SCAN_BOOTING) != 0)) { 6736 // If this is a system app, we can at least delete its 6737 // current data so the application will still work. 6738 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6739 if (ret >= 0) { 6740 // TODO: Kill the processes first 6741 // Old data gone! 6742 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6743 ? "System package " : "Third party package "; 6744 String msg = prefix + pkg.packageName 6745 + " has changed from uid: " 6746 + currentUid + " to " 6747 + pkg.applicationInfo.uid + "; old data erased"; 6748 reportSettingsProblem(Log.WARN, msg); 6749 recovered = true; 6750 6751 // And now re-install the app. 6752 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6753 pkg.applicationInfo.seinfo); 6754 if (ret == -1) { 6755 // Ack should not happen! 6756 msg = prefix + pkg.packageName 6757 + " could not have data directory re-created after delete."; 6758 reportSettingsProblem(Log.WARN, msg); 6759 throw new PackageManagerException( 6760 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6761 } 6762 } 6763 if (!recovered) { 6764 mHasSystemUidErrors = true; 6765 } 6766 } else if (!recovered) { 6767 // If we allow this install to proceed, we will be broken. 6768 // Abort, abort! 6769 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6770 "scanPackageLI"); 6771 } 6772 if (!recovered) { 6773 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6774 + pkg.applicationInfo.uid + "/fs_" 6775 + currentUid; 6776 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6777 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6778 String msg = "Package " + pkg.packageName 6779 + " has mismatched uid: " 6780 + currentUid + " on disk, " 6781 + pkg.applicationInfo.uid + " in settings"; 6782 // writer 6783 synchronized (mPackages) { 6784 mSettings.mReadMessages.append(msg); 6785 mSettings.mReadMessages.append('\n'); 6786 uidError = true; 6787 if (!pkgSetting.uidError) { 6788 reportSettingsProblem(Log.ERROR, msg); 6789 } 6790 } 6791 } 6792 } 6793 pkg.applicationInfo.dataDir = dataPath.getPath(); 6794 if (mShouldRestoreconData) { 6795 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6796 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6797 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6798 } 6799 } else { 6800 if (DEBUG_PACKAGE_SCANNING) { 6801 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6802 Log.v(TAG, "Want this data dir: " + dataPath); 6803 } 6804 //invoke installer to do the actual installation 6805 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6806 pkg.applicationInfo.seinfo); 6807 if (ret < 0) { 6808 // Error from installer 6809 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6810 "Unable to create data dirs [errorCode=" + ret + "]"); 6811 } 6812 6813 if (dataPath.exists()) { 6814 pkg.applicationInfo.dataDir = dataPath.getPath(); 6815 } else { 6816 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6817 pkg.applicationInfo.dataDir = null; 6818 } 6819 } 6820 6821 pkgSetting.uidError = uidError; 6822 } 6823 6824 final String path = scanFile.getPath(); 6825 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6826 6827 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6828 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6829 6830 // Some system apps still use directory structure for native libraries 6831 // in which case we might end up not detecting abi solely based on apk 6832 // structure. Try to detect abi based on directory structure. 6833 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6834 pkg.applicationInfo.primaryCpuAbi == null) { 6835 setBundledAppAbisAndRoots(pkg, pkgSetting); 6836 setNativeLibraryPaths(pkg); 6837 } 6838 6839 } else { 6840 if ((scanFlags & SCAN_MOVE) != 0) { 6841 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6842 // but we already have this packages package info in the PackageSetting. We just 6843 // use that and derive the native library path based on the new codepath. 6844 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6845 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6846 } 6847 6848 // Set native library paths again. For moves, the path will be updated based on the 6849 // ABIs we've determined above. For non-moves, the path will be updated based on the 6850 // ABIs we determined during compilation, but the path will depend on the final 6851 // package path (after the rename away from the stage path). 6852 setNativeLibraryPaths(pkg); 6853 } 6854 6855 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6856 final int[] userIds = sUserManager.getUserIds(); 6857 synchronized (mInstallLock) { 6858 // Make sure all user data directories are ready to roll; we're okay 6859 // if they already exist 6860 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6861 for (int userId : userIds) { 6862 if (userId != 0) { 6863 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6864 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6865 pkg.applicationInfo.seinfo); 6866 } 6867 } 6868 } 6869 6870 // Create a native library symlink only if we have native libraries 6871 // and if the native libraries are 32 bit libraries. We do not provide 6872 // this symlink for 64 bit libraries. 6873 if (pkg.applicationInfo.primaryCpuAbi != null && 6874 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6875 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6876 for (int userId : userIds) { 6877 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6878 nativeLibPath, userId) < 0) { 6879 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6880 "Failed linking native library dir (user=" + userId + ")"); 6881 } 6882 } 6883 } 6884 } 6885 6886 // This is a special case for the "system" package, where the ABI is 6887 // dictated by the zygote configuration (and init.rc). We should keep track 6888 // of this ABI so that we can deal with "normal" applications that run under 6889 // the same UID correctly. 6890 if (mPlatformPackage == pkg) { 6891 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6892 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6893 } 6894 6895 // If there's a mismatch between the abi-override in the package setting 6896 // and the abiOverride specified for the install. Warn about this because we 6897 // would've already compiled the app without taking the package setting into 6898 // account. 6899 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6900 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6901 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6902 " for package: " + pkg.packageName); 6903 } 6904 } 6905 6906 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6907 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6908 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6909 6910 // Copy the derived override back to the parsed package, so that we can 6911 // update the package settings accordingly. 6912 pkg.cpuAbiOverride = cpuAbiOverride; 6913 6914 if (DEBUG_ABI_SELECTION) { 6915 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6916 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6917 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6918 } 6919 6920 // Push the derived path down into PackageSettings so we know what to 6921 // clean up at uninstall time. 6922 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6923 6924 if (DEBUG_ABI_SELECTION) { 6925 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6926 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6927 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6928 } 6929 6930 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6931 // We don't do this here during boot because we can do it all 6932 // at once after scanning all existing packages. 6933 // 6934 // We also do this *before* we perform dexopt on this package, so that 6935 // we can avoid redundant dexopts, and also to make sure we've got the 6936 // code and package path correct. 6937 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6938 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6939 } 6940 6941 if ((scanFlags & SCAN_NO_DEX) == 0) { 6942 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6943 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6944 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6945 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6946 } 6947 } 6948 if (mFactoryTest && pkg.requestedPermissions.contains( 6949 android.Manifest.permission.FACTORY_TEST)) { 6950 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6951 } 6952 6953 ArrayList<PackageParser.Package> clientLibPkgs = null; 6954 6955 // writer 6956 synchronized (mPackages) { 6957 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6958 // Only system apps can add new shared libraries. 6959 if (pkg.libraryNames != null) { 6960 for (int i=0; i<pkg.libraryNames.size(); i++) { 6961 String name = pkg.libraryNames.get(i); 6962 boolean allowed = false; 6963 if (pkg.isUpdatedSystemApp()) { 6964 // New library entries can only be added through the 6965 // system image. This is important to get rid of a lot 6966 // of nasty edge cases: for example if we allowed a non- 6967 // system update of the app to add a library, then uninstalling 6968 // the update would make the library go away, and assumptions 6969 // we made such as through app install filtering would now 6970 // have allowed apps on the device which aren't compatible 6971 // with it. Better to just have the restriction here, be 6972 // conservative, and create many fewer cases that can negatively 6973 // impact the user experience. 6974 final PackageSetting sysPs = mSettings 6975 .getDisabledSystemPkgLPr(pkg.packageName); 6976 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6977 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6978 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6979 allowed = true; 6980 allowed = true; 6981 break; 6982 } 6983 } 6984 } 6985 } else { 6986 allowed = true; 6987 } 6988 if (allowed) { 6989 if (!mSharedLibraries.containsKey(name)) { 6990 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6991 } else if (!name.equals(pkg.packageName)) { 6992 Slog.w(TAG, "Package " + pkg.packageName + " library " 6993 + name + " already exists; skipping"); 6994 } 6995 } else { 6996 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6997 + name + " that is not declared on system image; skipping"); 6998 } 6999 } 7000 if ((scanFlags&SCAN_BOOTING) == 0) { 7001 // If we are not booting, we need to update any applications 7002 // that are clients of our shared library. If we are booting, 7003 // this will all be done once the scan is complete. 7004 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7005 } 7006 } 7007 } 7008 } 7009 7010 // We also need to dexopt any apps that are dependent on this library. Note that 7011 // if these fail, we should abort the install since installing the library will 7012 // result in some apps being broken. 7013 if (clientLibPkgs != null) { 7014 if ((scanFlags & SCAN_NO_DEX) == 0) { 7015 for (int i = 0; i < clientLibPkgs.size(); i++) { 7016 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7017 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7018 null /* instruction sets */, forceDex, 7019 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7020 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7021 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7022 "scanPackageLI failed to dexopt clientLibPkgs"); 7023 } 7024 } 7025 } 7026 } 7027 7028 // Also need to kill any apps that are dependent on the library. 7029 if (clientLibPkgs != null) { 7030 for (int i=0; i<clientLibPkgs.size(); i++) { 7031 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7032 killApplication(clientPkg.applicationInfo.packageName, 7033 clientPkg.applicationInfo.uid, "update lib"); 7034 } 7035 } 7036 7037 // Make sure we're not adding any bogus keyset info 7038 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7039 ksms.assertScannedPackageValid(pkg); 7040 7041 // writer 7042 synchronized (mPackages) { 7043 // We don't expect installation to fail beyond this point 7044 7045 // Add the new setting to mSettings 7046 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7047 // Add the new setting to mPackages 7048 mPackages.put(pkg.applicationInfo.packageName, pkg); 7049 // Make sure we don't accidentally delete its data. 7050 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7051 while (iter.hasNext()) { 7052 PackageCleanItem item = iter.next(); 7053 if (pkgName.equals(item.packageName)) { 7054 iter.remove(); 7055 } 7056 } 7057 7058 // Take care of first install / last update times. 7059 if (currentTime != 0) { 7060 if (pkgSetting.firstInstallTime == 0) { 7061 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7062 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7063 pkgSetting.lastUpdateTime = currentTime; 7064 } 7065 } else if (pkgSetting.firstInstallTime == 0) { 7066 // We need *something*. Take time time stamp of the file. 7067 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7068 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7069 if (scanFileTime != pkgSetting.timeStamp) { 7070 // A package on the system image has changed; consider this 7071 // to be an update. 7072 pkgSetting.lastUpdateTime = scanFileTime; 7073 } 7074 } 7075 7076 // Add the package's KeySets to the global KeySetManagerService 7077 ksms.addScannedPackageLPw(pkg); 7078 7079 int N = pkg.providers.size(); 7080 StringBuilder r = null; 7081 int i; 7082 for (i=0; i<N; i++) { 7083 PackageParser.Provider p = pkg.providers.get(i); 7084 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7085 p.info.processName, pkg.applicationInfo.uid); 7086 mProviders.addProvider(p); 7087 p.syncable = p.info.isSyncable; 7088 if (p.info.authority != null) { 7089 String names[] = p.info.authority.split(";"); 7090 p.info.authority = null; 7091 for (int j = 0; j < names.length; j++) { 7092 if (j == 1 && p.syncable) { 7093 // We only want the first authority for a provider to possibly be 7094 // syncable, so if we already added this provider using a different 7095 // authority clear the syncable flag. We copy the provider before 7096 // changing it because the mProviders object contains a reference 7097 // to a provider that we don't want to change. 7098 // Only do this for the second authority since the resulting provider 7099 // object can be the same for all future authorities for this provider. 7100 p = new PackageParser.Provider(p); 7101 p.syncable = false; 7102 } 7103 if (!mProvidersByAuthority.containsKey(names[j])) { 7104 mProvidersByAuthority.put(names[j], p); 7105 if (p.info.authority == null) { 7106 p.info.authority = names[j]; 7107 } else { 7108 p.info.authority = p.info.authority + ";" + names[j]; 7109 } 7110 if (DEBUG_PACKAGE_SCANNING) { 7111 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7112 Log.d(TAG, "Registered content provider: " + names[j] 7113 + ", className = " + p.info.name + ", isSyncable = " 7114 + p.info.isSyncable); 7115 } 7116 } else { 7117 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7118 Slog.w(TAG, "Skipping provider name " + names[j] + 7119 " (in package " + pkg.applicationInfo.packageName + 7120 "): name already used by " 7121 + ((other != null && other.getComponentName() != null) 7122 ? other.getComponentName().getPackageName() : "?")); 7123 } 7124 } 7125 } 7126 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7127 if (r == null) { 7128 r = new StringBuilder(256); 7129 } else { 7130 r.append(' '); 7131 } 7132 r.append(p.info.name); 7133 } 7134 } 7135 if (r != null) { 7136 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7137 } 7138 7139 N = pkg.services.size(); 7140 r = null; 7141 for (i=0; i<N; i++) { 7142 PackageParser.Service s = pkg.services.get(i); 7143 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7144 s.info.processName, pkg.applicationInfo.uid); 7145 mServices.addService(s); 7146 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7147 if (r == null) { 7148 r = new StringBuilder(256); 7149 } else { 7150 r.append(' '); 7151 } 7152 r.append(s.info.name); 7153 } 7154 } 7155 if (r != null) { 7156 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7157 } 7158 7159 N = pkg.receivers.size(); 7160 r = null; 7161 for (i=0; i<N; i++) { 7162 PackageParser.Activity a = pkg.receivers.get(i); 7163 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7164 a.info.processName, pkg.applicationInfo.uid); 7165 mReceivers.addActivity(a, "receiver"); 7166 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7167 if (r == null) { 7168 r = new StringBuilder(256); 7169 } else { 7170 r.append(' '); 7171 } 7172 r.append(a.info.name); 7173 } 7174 } 7175 if (r != null) { 7176 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7177 } 7178 7179 N = pkg.activities.size(); 7180 r = null; 7181 for (i=0; i<N; i++) { 7182 PackageParser.Activity a = pkg.activities.get(i); 7183 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7184 a.info.processName, pkg.applicationInfo.uid); 7185 mActivities.addActivity(a, "activity"); 7186 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7187 if (r == null) { 7188 r = new StringBuilder(256); 7189 } else { 7190 r.append(' '); 7191 } 7192 r.append(a.info.name); 7193 } 7194 } 7195 if (r != null) { 7196 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7197 } 7198 7199 N = pkg.permissionGroups.size(); 7200 r = null; 7201 for (i=0; i<N; i++) { 7202 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7203 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7204 if (cur == null) { 7205 mPermissionGroups.put(pg.info.name, pg); 7206 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7207 if (r == null) { 7208 r = new StringBuilder(256); 7209 } else { 7210 r.append(' '); 7211 } 7212 r.append(pg.info.name); 7213 } 7214 } else { 7215 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7216 + pg.info.packageName + " ignored: original from " 7217 + cur.info.packageName); 7218 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7219 if (r == null) { 7220 r = new StringBuilder(256); 7221 } else { 7222 r.append(' '); 7223 } 7224 r.append("DUP:"); 7225 r.append(pg.info.name); 7226 } 7227 } 7228 } 7229 if (r != null) { 7230 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7231 } 7232 7233 N = pkg.permissions.size(); 7234 r = null; 7235 for (i=0; i<N; i++) { 7236 PackageParser.Permission p = pkg.permissions.get(i); 7237 7238 // Now that permission groups have a special meaning, we ignore permission 7239 // groups for legacy apps to prevent unexpected behavior. In particular, 7240 // permissions for one app being granted to someone just becuase they happen 7241 // to be in a group defined by another app (before this had no implications). 7242 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7243 p.group = mPermissionGroups.get(p.info.group); 7244 // Warn for a permission in an unknown group. 7245 if (p.info.group != null && p.group == null) { 7246 Slog.w(TAG, "Permission " + p.info.name + " from package " 7247 + p.info.packageName + " in an unknown group " + p.info.group); 7248 } 7249 } 7250 7251 ArrayMap<String, BasePermission> permissionMap = 7252 p.tree ? mSettings.mPermissionTrees 7253 : mSettings.mPermissions; 7254 BasePermission bp = permissionMap.get(p.info.name); 7255 7256 // Allow system apps to redefine non-system permissions 7257 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7258 final boolean currentOwnerIsSystem = (bp.perm != null 7259 && isSystemApp(bp.perm.owner)); 7260 if (isSystemApp(p.owner)) { 7261 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7262 // It's a built-in permission and no owner, take ownership now 7263 bp.packageSetting = pkgSetting; 7264 bp.perm = p; 7265 bp.uid = pkg.applicationInfo.uid; 7266 bp.sourcePackage = p.info.packageName; 7267 } else if (!currentOwnerIsSystem) { 7268 String msg = "New decl " + p.owner + " of permission " 7269 + p.info.name + " is system; overriding " + bp.sourcePackage; 7270 reportSettingsProblem(Log.WARN, msg); 7271 bp = null; 7272 } 7273 } 7274 } 7275 7276 if (bp == null) { 7277 bp = new BasePermission(p.info.name, p.info.packageName, 7278 BasePermission.TYPE_NORMAL); 7279 permissionMap.put(p.info.name, bp); 7280 } 7281 7282 if (bp.perm == null) { 7283 if (bp.sourcePackage == null 7284 || bp.sourcePackage.equals(p.info.packageName)) { 7285 BasePermission tree = findPermissionTreeLP(p.info.name); 7286 if (tree == null 7287 || tree.sourcePackage.equals(p.info.packageName)) { 7288 bp.packageSetting = pkgSetting; 7289 bp.perm = p; 7290 bp.uid = pkg.applicationInfo.uid; 7291 bp.sourcePackage = p.info.packageName; 7292 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7293 if (r == null) { 7294 r = new StringBuilder(256); 7295 } else { 7296 r.append(' '); 7297 } 7298 r.append(p.info.name); 7299 } 7300 } else { 7301 Slog.w(TAG, "Permission " + p.info.name + " from package " 7302 + p.info.packageName + " ignored: base tree " 7303 + tree.name + " is from package " 7304 + tree.sourcePackage); 7305 } 7306 } else { 7307 Slog.w(TAG, "Permission " + p.info.name + " from package " 7308 + p.info.packageName + " ignored: original from " 7309 + bp.sourcePackage); 7310 } 7311 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7312 if (r == null) { 7313 r = new StringBuilder(256); 7314 } else { 7315 r.append(' '); 7316 } 7317 r.append("DUP:"); 7318 r.append(p.info.name); 7319 } 7320 if (bp.perm == p) { 7321 bp.protectionLevel = p.info.protectionLevel; 7322 } 7323 } 7324 7325 if (r != null) { 7326 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7327 } 7328 7329 N = pkg.instrumentation.size(); 7330 r = null; 7331 for (i=0; i<N; i++) { 7332 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7333 a.info.packageName = pkg.applicationInfo.packageName; 7334 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7335 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7336 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7337 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7338 a.info.dataDir = pkg.applicationInfo.dataDir; 7339 7340 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7341 // need other information about the application, like the ABI and what not ? 7342 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7343 mInstrumentation.put(a.getComponentName(), a); 7344 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7345 if (r == null) { 7346 r = new StringBuilder(256); 7347 } else { 7348 r.append(' '); 7349 } 7350 r.append(a.info.name); 7351 } 7352 } 7353 if (r != null) { 7354 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7355 } 7356 7357 if (pkg.protectedBroadcasts != null) { 7358 N = pkg.protectedBroadcasts.size(); 7359 for (i=0; i<N; i++) { 7360 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7361 } 7362 } 7363 7364 pkgSetting.setTimeStamp(scanFileTime); 7365 7366 // Create idmap files for pairs of (packages, overlay packages). 7367 // Note: "android", ie framework-res.apk, is handled by native layers. 7368 if (pkg.mOverlayTarget != null) { 7369 // This is an overlay package. 7370 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7371 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7372 mOverlays.put(pkg.mOverlayTarget, 7373 new ArrayMap<String, PackageParser.Package>()); 7374 } 7375 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7376 map.put(pkg.packageName, pkg); 7377 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7378 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7379 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7380 "scanPackageLI failed to createIdmap"); 7381 } 7382 } 7383 } else if (mOverlays.containsKey(pkg.packageName) && 7384 !pkg.packageName.equals("android")) { 7385 // This is a regular package, with one or more known overlay packages. 7386 createIdmapsForPackageLI(pkg); 7387 } 7388 } 7389 7390 return pkg; 7391 } 7392 7393 /** 7394 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7395 * is derived purely on the basis of the contents of {@code scanFile} and 7396 * {@code cpuAbiOverride}. 7397 * 7398 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7399 */ 7400 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7401 String cpuAbiOverride, boolean extractLibs) 7402 throws PackageManagerException { 7403 // TODO: We can probably be smarter about this stuff. For installed apps, 7404 // we can calculate this information at install time once and for all. For 7405 // system apps, we can probably assume that this information doesn't change 7406 // after the first boot scan. As things stand, we do lots of unnecessary work. 7407 7408 // Give ourselves some initial paths; we'll come back for another 7409 // pass once we've determined ABI below. 7410 setNativeLibraryPaths(pkg); 7411 7412 // We would never need to extract libs for forward-locked and external packages, 7413 // since the container service will do it for us. We shouldn't attempt to 7414 // extract libs from system app when it was not updated. 7415 if (pkg.isForwardLocked() || isExternal(pkg) || 7416 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7417 extractLibs = false; 7418 } 7419 7420 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7421 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7422 7423 NativeLibraryHelper.Handle handle = null; 7424 try { 7425 handle = NativeLibraryHelper.Handle.create(scanFile); 7426 // TODO(multiArch): This can be null for apps that didn't go through the 7427 // usual installation process. We can calculate it again, like we 7428 // do during install time. 7429 // 7430 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7431 // unnecessary. 7432 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7433 7434 // Null out the abis so that they can be recalculated. 7435 pkg.applicationInfo.primaryCpuAbi = null; 7436 pkg.applicationInfo.secondaryCpuAbi = null; 7437 if (isMultiArch(pkg.applicationInfo)) { 7438 // Warn if we've set an abiOverride for multi-lib packages.. 7439 // By definition, we need to copy both 32 and 64 bit libraries for 7440 // such packages. 7441 if (pkg.cpuAbiOverride != null 7442 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7443 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7444 } 7445 7446 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7447 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7448 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7449 if (extractLibs) { 7450 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7451 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7452 useIsaSpecificSubdirs); 7453 } else { 7454 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7455 } 7456 } 7457 7458 maybeThrowExceptionForMultiArchCopy( 7459 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7460 7461 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7462 if (extractLibs) { 7463 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7464 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7465 useIsaSpecificSubdirs); 7466 } else { 7467 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7468 } 7469 } 7470 7471 maybeThrowExceptionForMultiArchCopy( 7472 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7473 7474 if (abi64 >= 0) { 7475 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7476 } 7477 7478 if (abi32 >= 0) { 7479 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7480 if (abi64 >= 0) { 7481 pkg.applicationInfo.secondaryCpuAbi = abi; 7482 } else { 7483 pkg.applicationInfo.primaryCpuAbi = abi; 7484 } 7485 } 7486 } else { 7487 String[] abiList = (cpuAbiOverride != null) ? 7488 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7489 7490 // Enable gross and lame hacks for apps that are built with old 7491 // SDK tools. We must scan their APKs for renderscript bitcode and 7492 // not launch them if it's present. Don't bother checking on devices 7493 // that don't have 64 bit support. 7494 boolean needsRenderScriptOverride = false; 7495 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7496 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7497 abiList = Build.SUPPORTED_32_BIT_ABIS; 7498 needsRenderScriptOverride = true; 7499 } 7500 7501 final int copyRet; 7502 if (extractLibs) { 7503 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7504 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7505 } else { 7506 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7507 } 7508 7509 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7510 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7511 "Error unpackaging native libs for app, errorCode=" + copyRet); 7512 } 7513 7514 if (copyRet >= 0) { 7515 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7516 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7517 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7518 } else if (needsRenderScriptOverride) { 7519 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7520 } 7521 } 7522 } catch (IOException ioe) { 7523 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7524 } finally { 7525 IoUtils.closeQuietly(handle); 7526 } 7527 7528 // Now that we've calculated the ABIs and determined if it's an internal app, 7529 // we will go ahead and populate the nativeLibraryPath. 7530 setNativeLibraryPaths(pkg); 7531 } 7532 7533 /** 7534 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7535 * i.e, so that all packages can be run inside a single process if required. 7536 * 7537 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7538 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7539 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7540 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7541 * updating a package that belongs to a shared user. 7542 * 7543 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7544 * adds unnecessary complexity. 7545 */ 7546 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7547 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7548 String requiredInstructionSet = null; 7549 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7550 requiredInstructionSet = VMRuntime.getInstructionSet( 7551 scannedPackage.applicationInfo.primaryCpuAbi); 7552 } 7553 7554 PackageSetting requirer = null; 7555 for (PackageSetting ps : packagesForUser) { 7556 // If packagesForUser contains scannedPackage, we skip it. This will happen 7557 // when scannedPackage is an update of an existing package. Without this check, 7558 // we will never be able to change the ABI of any package belonging to a shared 7559 // user, even if it's compatible with other packages. 7560 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7561 if (ps.primaryCpuAbiString == null) { 7562 continue; 7563 } 7564 7565 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7566 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7567 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7568 // this but there's not much we can do. 7569 String errorMessage = "Instruction set mismatch, " 7570 + ((requirer == null) ? "[caller]" : requirer) 7571 + " requires " + requiredInstructionSet + " whereas " + ps 7572 + " requires " + instructionSet; 7573 Slog.w(TAG, errorMessage); 7574 } 7575 7576 if (requiredInstructionSet == null) { 7577 requiredInstructionSet = instructionSet; 7578 requirer = ps; 7579 } 7580 } 7581 } 7582 7583 if (requiredInstructionSet != null) { 7584 String adjustedAbi; 7585 if (requirer != null) { 7586 // requirer != null implies that either scannedPackage was null or that scannedPackage 7587 // did not require an ABI, in which case we have to adjust scannedPackage to match 7588 // the ABI of the set (which is the same as requirer's ABI) 7589 adjustedAbi = requirer.primaryCpuAbiString; 7590 if (scannedPackage != null) { 7591 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7592 } 7593 } else { 7594 // requirer == null implies that we're updating all ABIs in the set to 7595 // match scannedPackage. 7596 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7597 } 7598 7599 for (PackageSetting ps : packagesForUser) { 7600 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7601 if (ps.primaryCpuAbiString != null) { 7602 continue; 7603 } 7604 7605 ps.primaryCpuAbiString = adjustedAbi; 7606 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7607 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7608 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7609 7610 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7611 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7612 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7613 ps.primaryCpuAbiString = null; 7614 ps.pkg.applicationInfo.primaryCpuAbi = null; 7615 return; 7616 } else { 7617 mInstaller.rmdex(ps.codePathString, 7618 getDexCodeInstructionSet(getPreferredInstructionSet())); 7619 } 7620 } 7621 } 7622 } 7623 } 7624 } 7625 7626 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7627 synchronized (mPackages) { 7628 mResolverReplaced = true; 7629 // Set up information for custom user intent resolution activity. 7630 mResolveActivity.applicationInfo = pkg.applicationInfo; 7631 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7632 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7633 mResolveActivity.processName = pkg.applicationInfo.packageName; 7634 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7635 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7636 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7637 mResolveActivity.theme = 0; 7638 mResolveActivity.exported = true; 7639 mResolveActivity.enabled = true; 7640 mResolveInfo.activityInfo = mResolveActivity; 7641 mResolveInfo.priority = 0; 7642 mResolveInfo.preferredOrder = 0; 7643 mResolveInfo.match = 0; 7644 mResolveComponentName = mCustomResolverComponentName; 7645 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7646 mResolveComponentName); 7647 } 7648 } 7649 7650 private static String calculateBundledApkRoot(final String codePathString) { 7651 final File codePath = new File(codePathString); 7652 final File codeRoot; 7653 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7654 codeRoot = Environment.getRootDirectory(); 7655 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7656 codeRoot = Environment.getOemDirectory(); 7657 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7658 codeRoot = Environment.getVendorDirectory(); 7659 } else { 7660 // Unrecognized code path; take its top real segment as the apk root: 7661 // e.g. /something/app/blah.apk => /something 7662 try { 7663 File f = codePath.getCanonicalFile(); 7664 File parent = f.getParentFile(); // non-null because codePath is a file 7665 File tmp; 7666 while ((tmp = parent.getParentFile()) != null) { 7667 f = parent; 7668 parent = tmp; 7669 } 7670 codeRoot = f; 7671 Slog.w(TAG, "Unrecognized code path " 7672 + codePath + " - using " + codeRoot); 7673 } catch (IOException e) { 7674 // Can't canonicalize the code path -- shenanigans? 7675 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7676 return Environment.getRootDirectory().getPath(); 7677 } 7678 } 7679 return codeRoot.getPath(); 7680 } 7681 7682 /** 7683 * Derive and set the location of native libraries for the given package, 7684 * which varies depending on where and how the package was installed. 7685 */ 7686 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7687 final ApplicationInfo info = pkg.applicationInfo; 7688 final String codePath = pkg.codePath; 7689 final File codeFile = new File(codePath); 7690 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7691 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7692 7693 info.nativeLibraryRootDir = null; 7694 info.nativeLibraryRootRequiresIsa = false; 7695 info.nativeLibraryDir = null; 7696 info.secondaryNativeLibraryDir = null; 7697 7698 if (isApkFile(codeFile)) { 7699 // Monolithic install 7700 if (bundledApp) { 7701 // If "/system/lib64/apkname" exists, assume that is the per-package 7702 // native library directory to use; otherwise use "/system/lib/apkname". 7703 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7704 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7705 getPrimaryInstructionSet(info)); 7706 7707 // This is a bundled system app so choose the path based on the ABI. 7708 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7709 // is just the default path. 7710 final String apkName = deriveCodePathName(codePath); 7711 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7712 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7713 apkName).getAbsolutePath(); 7714 7715 if (info.secondaryCpuAbi != null) { 7716 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7717 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7718 secondaryLibDir, apkName).getAbsolutePath(); 7719 } 7720 } else if (asecApp) { 7721 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7722 .getAbsolutePath(); 7723 } else { 7724 final String apkName = deriveCodePathName(codePath); 7725 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7726 .getAbsolutePath(); 7727 } 7728 7729 info.nativeLibraryRootRequiresIsa = false; 7730 info.nativeLibraryDir = info.nativeLibraryRootDir; 7731 } else { 7732 // Cluster install 7733 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7734 info.nativeLibraryRootRequiresIsa = true; 7735 7736 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7737 getPrimaryInstructionSet(info)).getAbsolutePath(); 7738 7739 if (info.secondaryCpuAbi != null) { 7740 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7741 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7742 } 7743 } 7744 } 7745 7746 /** 7747 * Calculate the abis and roots for a bundled app. These can uniquely 7748 * be determined from the contents of the system partition, i.e whether 7749 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7750 * of this information, and instead assume that the system was built 7751 * sensibly. 7752 */ 7753 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7754 PackageSetting pkgSetting) { 7755 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7756 7757 // If "/system/lib64/apkname" exists, assume that is the per-package 7758 // native library directory to use; otherwise use "/system/lib/apkname". 7759 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7760 setBundledAppAbi(pkg, apkRoot, apkName); 7761 // pkgSetting might be null during rescan following uninstall of updates 7762 // to a bundled app, so accommodate that possibility. The settings in 7763 // that case will be established later from the parsed package. 7764 // 7765 // If the settings aren't null, sync them up with what we've just derived. 7766 // note that apkRoot isn't stored in the package settings. 7767 if (pkgSetting != null) { 7768 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7769 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7770 } 7771 } 7772 7773 /** 7774 * Deduces the ABI of a bundled app and sets the relevant fields on the 7775 * parsed pkg object. 7776 * 7777 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7778 * under which system libraries are installed. 7779 * @param apkName the name of the installed package. 7780 */ 7781 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7782 final File codeFile = new File(pkg.codePath); 7783 7784 final boolean has64BitLibs; 7785 final boolean has32BitLibs; 7786 if (isApkFile(codeFile)) { 7787 // Monolithic install 7788 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7789 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7790 } else { 7791 // Cluster install 7792 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7793 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7794 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7795 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7796 has64BitLibs = (new File(rootDir, isa)).exists(); 7797 } else { 7798 has64BitLibs = false; 7799 } 7800 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7801 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7802 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7803 has32BitLibs = (new File(rootDir, isa)).exists(); 7804 } else { 7805 has32BitLibs = false; 7806 } 7807 } 7808 7809 if (has64BitLibs && !has32BitLibs) { 7810 // The package has 64 bit libs, but not 32 bit libs. Its primary 7811 // ABI should be 64 bit. We can safely assume here that the bundled 7812 // native libraries correspond to the most preferred ABI in the list. 7813 7814 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7815 pkg.applicationInfo.secondaryCpuAbi = null; 7816 } else if (has32BitLibs && !has64BitLibs) { 7817 // The package has 32 bit libs but not 64 bit libs. Its primary 7818 // ABI should be 32 bit. 7819 7820 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7821 pkg.applicationInfo.secondaryCpuAbi = null; 7822 } else if (has32BitLibs && has64BitLibs) { 7823 // The application has both 64 and 32 bit bundled libraries. We check 7824 // here that the app declares multiArch support, and warn if it doesn't. 7825 // 7826 // We will be lenient here and record both ABIs. The primary will be the 7827 // ABI that's higher on the list, i.e, a device that's configured to prefer 7828 // 64 bit apps will see a 64 bit primary ABI, 7829 7830 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7831 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7832 } 7833 7834 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7835 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7836 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7837 } else { 7838 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7839 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7840 } 7841 } else { 7842 pkg.applicationInfo.primaryCpuAbi = null; 7843 pkg.applicationInfo.secondaryCpuAbi = null; 7844 } 7845 } 7846 7847 private void killApplication(String pkgName, int appId, String reason) { 7848 // Request the ActivityManager to kill the process(only for existing packages) 7849 // so that we do not end up in a confused state while the user is still using the older 7850 // version of the application while the new one gets installed. 7851 IActivityManager am = ActivityManagerNative.getDefault(); 7852 if (am != null) { 7853 try { 7854 am.killApplicationWithAppId(pkgName, appId, reason); 7855 } catch (RemoteException e) { 7856 } 7857 } 7858 } 7859 7860 void removePackageLI(PackageSetting ps, boolean chatty) { 7861 if (DEBUG_INSTALL) { 7862 if (chatty) 7863 Log.d(TAG, "Removing package " + ps.name); 7864 } 7865 7866 // writer 7867 synchronized (mPackages) { 7868 mPackages.remove(ps.name); 7869 final PackageParser.Package pkg = ps.pkg; 7870 if (pkg != null) { 7871 cleanPackageDataStructuresLILPw(pkg, chatty); 7872 } 7873 } 7874 } 7875 7876 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7877 if (DEBUG_INSTALL) { 7878 if (chatty) 7879 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7880 } 7881 7882 // writer 7883 synchronized (mPackages) { 7884 mPackages.remove(pkg.applicationInfo.packageName); 7885 cleanPackageDataStructuresLILPw(pkg, chatty); 7886 } 7887 } 7888 7889 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7890 int N = pkg.providers.size(); 7891 StringBuilder r = null; 7892 int i; 7893 for (i=0; i<N; i++) { 7894 PackageParser.Provider p = pkg.providers.get(i); 7895 mProviders.removeProvider(p); 7896 if (p.info.authority == null) { 7897 7898 /* There was another ContentProvider with this authority when 7899 * this app was installed so this authority is null, 7900 * Ignore it as we don't have to unregister the provider. 7901 */ 7902 continue; 7903 } 7904 String names[] = p.info.authority.split(";"); 7905 for (int j = 0; j < names.length; j++) { 7906 if (mProvidersByAuthority.get(names[j]) == p) { 7907 mProvidersByAuthority.remove(names[j]); 7908 if (DEBUG_REMOVE) { 7909 if (chatty) 7910 Log.d(TAG, "Unregistered content provider: " + names[j] 7911 + ", className = " + p.info.name + ", isSyncable = " 7912 + p.info.isSyncable); 7913 } 7914 } 7915 } 7916 if (DEBUG_REMOVE && chatty) { 7917 if (r == null) { 7918 r = new StringBuilder(256); 7919 } else { 7920 r.append(' '); 7921 } 7922 r.append(p.info.name); 7923 } 7924 } 7925 if (r != null) { 7926 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7927 } 7928 7929 N = pkg.services.size(); 7930 r = null; 7931 for (i=0; i<N; i++) { 7932 PackageParser.Service s = pkg.services.get(i); 7933 mServices.removeService(s); 7934 if (chatty) { 7935 if (r == null) { 7936 r = new StringBuilder(256); 7937 } else { 7938 r.append(' '); 7939 } 7940 r.append(s.info.name); 7941 } 7942 } 7943 if (r != null) { 7944 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7945 } 7946 7947 N = pkg.receivers.size(); 7948 r = null; 7949 for (i=0; i<N; i++) { 7950 PackageParser.Activity a = pkg.receivers.get(i); 7951 mReceivers.removeActivity(a, "receiver"); 7952 if (DEBUG_REMOVE && chatty) { 7953 if (r == null) { 7954 r = new StringBuilder(256); 7955 } else { 7956 r.append(' '); 7957 } 7958 r.append(a.info.name); 7959 } 7960 } 7961 if (r != null) { 7962 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7963 } 7964 7965 N = pkg.activities.size(); 7966 r = null; 7967 for (i=0; i<N; i++) { 7968 PackageParser.Activity a = pkg.activities.get(i); 7969 mActivities.removeActivity(a, "activity"); 7970 if (DEBUG_REMOVE && chatty) { 7971 if (r == null) { 7972 r = new StringBuilder(256); 7973 } else { 7974 r.append(' '); 7975 } 7976 r.append(a.info.name); 7977 } 7978 } 7979 if (r != null) { 7980 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7981 } 7982 7983 N = pkg.permissions.size(); 7984 r = null; 7985 for (i=0; i<N; i++) { 7986 PackageParser.Permission p = pkg.permissions.get(i); 7987 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7988 if (bp == null) { 7989 bp = mSettings.mPermissionTrees.get(p.info.name); 7990 } 7991 if (bp != null && bp.perm == p) { 7992 bp.perm = null; 7993 if (DEBUG_REMOVE && chatty) { 7994 if (r == null) { 7995 r = new StringBuilder(256); 7996 } else { 7997 r.append(' '); 7998 } 7999 r.append(p.info.name); 8000 } 8001 } 8002 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8003 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8004 if (appOpPerms != null) { 8005 appOpPerms.remove(pkg.packageName); 8006 } 8007 } 8008 } 8009 if (r != null) { 8010 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8011 } 8012 8013 N = pkg.requestedPermissions.size(); 8014 r = null; 8015 for (i=0; i<N; i++) { 8016 String perm = pkg.requestedPermissions.get(i); 8017 BasePermission bp = mSettings.mPermissions.get(perm); 8018 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8019 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8020 if (appOpPerms != null) { 8021 appOpPerms.remove(pkg.packageName); 8022 if (appOpPerms.isEmpty()) { 8023 mAppOpPermissionPackages.remove(perm); 8024 } 8025 } 8026 } 8027 } 8028 if (r != null) { 8029 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8030 } 8031 8032 N = pkg.instrumentation.size(); 8033 r = null; 8034 for (i=0; i<N; i++) { 8035 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8036 mInstrumentation.remove(a.getComponentName()); 8037 if (DEBUG_REMOVE && chatty) { 8038 if (r == null) { 8039 r = new StringBuilder(256); 8040 } else { 8041 r.append(' '); 8042 } 8043 r.append(a.info.name); 8044 } 8045 } 8046 if (r != null) { 8047 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8048 } 8049 8050 r = null; 8051 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8052 // Only system apps can hold shared libraries. 8053 if (pkg.libraryNames != null) { 8054 for (i=0; i<pkg.libraryNames.size(); i++) { 8055 String name = pkg.libraryNames.get(i); 8056 SharedLibraryEntry cur = mSharedLibraries.get(name); 8057 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8058 mSharedLibraries.remove(name); 8059 if (DEBUG_REMOVE && chatty) { 8060 if (r == null) { 8061 r = new StringBuilder(256); 8062 } else { 8063 r.append(' '); 8064 } 8065 r.append(name); 8066 } 8067 } 8068 } 8069 } 8070 } 8071 if (r != null) { 8072 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8073 } 8074 } 8075 8076 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8077 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8078 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8079 return true; 8080 } 8081 } 8082 return false; 8083 } 8084 8085 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8086 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8087 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8088 8089 private void updatePermissionsLPw(String changingPkg, 8090 PackageParser.Package pkgInfo, int flags) { 8091 // Make sure there are no dangling permission trees. 8092 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8093 while (it.hasNext()) { 8094 final BasePermission bp = it.next(); 8095 if (bp.packageSetting == null) { 8096 // We may not yet have parsed the package, so just see if 8097 // we still know about its settings. 8098 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8099 } 8100 if (bp.packageSetting == null) { 8101 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8102 + " from package " + bp.sourcePackage); 8103 it.remove(); 8104 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8105 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8106 Slog.i(TAG, "Removing old permission tree: " + bp.name 8107 + " from package " + bp.sourcePackage); 8108 flags |= UPDATE_PERMISSIONS_ALL; 8109 it.remove(); 8110 } 8111 } 8112 } 8113 8114 // Make sure all dynamic permissions have been assigned to a package, 8115 // and make sure there are no dangling permissions. 8116 it = mSettings.mPermissions.values().iterator(); 8117 while (it.hasNext()) { 8118 final BasePermission bp = it.next(); 8119 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8120 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8121 + bp.name + " pkg=" + bp.sourcePackage 8122 + " info=" + bp.pendingInfo); 8123 if (bp.packageSetting == null && bp.pendingInfo != null) { 8124 final BasePermission tree = findPermissionTreeLP(bp.name); 8125 if (tree != null && tree.perm != null) { 8126 bp.packageSetting = tree.packageSetting; 8127 bp.perm = new PackageParser.Permission(tree.perm.owner, 8128 new PermissionInfo(bp.pendingInfo)); 8129 bp.perm.info.packageName = tree.perm.info.packageName; 8130 bp.perm.info.name = bp.name; 8131 bp.uid = tree.uid; 8132 } 8133 } 8134 } 8135 if (bp.packageSetting == null) { 8136 // We may not yet have parsed the package, so just see if 8137 // we still know about its settings. 8138 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8139 } 8140 if (bp.packageSetting == null) { 8141 Slog.w(TAG, "Removing dangling permission: " + bp.name 8142 + " from package " + bp.sourcePackage); 8143 it.remove(); 8144 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8145 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8146 Slog.i(TAG, "Removing old permission: " + bp.name 8147 + " from package " + bp.sourcePackage); 8148 flags |= UPDATE_PERMISSIONS_ALL; 8149 it.remove(); 8150 } 8151 } 8152 } 8153 8154 // Now update the permissions for all packages, in particular 8155 // replace the granted permissions of the system packages. 8156 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8157 for (PackageParser.Package pkg : mPackages.values()) { 8158 if (pkg != pkgInfo) { 8159 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8160 changingPkg); 8161 } 8162 } 8163 } 8164 8165 if (pkgInfo != null) { 8166 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8167 } 8168 } 8169 8170 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8171 String packageOfInterest) { 8172 // IMPORTANT: There are two types of permissions: install and runtime. 8173 // Install time permissions are granted when the app is installed to 8174 // all device users and users added in the future. Runtime permissions 8175 // are granted at runtime explicitly to specific users. Normal and signature 8176 // protected permissions are install time permissions. Dangerous permissions 8177 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8178 // otherwise they are runtime permissions. This function does not manage 8179 // runtime permissions except for the case an app targeting Lollipop MR1 8180 // being upgraded to target a newer SDK, in which case dangerous permissions 8181 // are transformed from install time to runtime ones. 8182 8183 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8184 if (ps == null) { 8185 return; 8186 } 8187 8188 PermissionsState permissionsState = ps.getPermissionsState(); 8189 PermissionsState origPermissions = permissionsState; 8190 8191 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8192 8193 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8194 8195 boolean changedInstallPermission = false; 8196 8197 if (replace) { 8198 ps.installPermissionsFixed = false; 8199 if (!ps.isSharedUser()) { 8200 origPermissions = new PermissionsState(permissionsState); 8201 permissionsState.reset(); 8202 } 8203 } 8204 8205 permissionsState.setGlobalGids(mGlobalGids); 8206 8207 final int N = pkg.requestedPermissions.size(); 8208 for (int i=0; i<N; i++) { 8209 final String name = pkg.requestedPermissions.get(i); 8210 final BasePermission bp = mSettings.mPermissions.get(name); 8211 8212 if (DEBUG_INSTALL) { 8213 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8214 } 8215 8216 if (bp == null || bp.packageSetting == null) { 8217 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8218 Slog.w(TAG, "Unknown permission " + name 8219 + " in package " + pkg.packageName); 8220 } 8221 continue; 8222 } 8223 8224 final String perm = bp.name; 8225 boolean allowedSig = false; 8226 int grant = GRANT_DENIED; 8227 8228 // Keep track of app op permissions. 8229 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8230 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8231 if (pkgs == null) { 8232 pkgs = new ArraySet<>(); 8233 mAppOpPermissionPackages.put(bp.name, pkgs); 8234 } 8235 pkgs.add(pkg.packageName); 8236 } 8237 8238 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8239 switch (level) { 8240 case PermissionInfo.PROTECTION_NORMAL: { 8241 // For all apps normal permissions are install time ones. 8242 grant = GRANT_INSTALL; 8243 } break; 8244 8245 case PermissionInfo.PROTECTION_DANGEROUS: { 8246 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8247 // For legacy apps dangerous permissions are install time ones. 8248 grant = GRANT_INSTALL_LEGACY; 8249 } else if (origPermissions.hasInstallPermission(bp.name)) { 8250 // For legacy apps that became modern, install becomes runtime. 8251 grant = GRANT_UPGRADE; 8252 } else { 8253 // For modern apps keep runtime permissions unchanged. 8254 grant = GRANT_RUNTIME; 8255 } 8256 } break; 8257 8258 case PermissionInfo.PROTECTION_SIGNATURE: { 8259 // For all apps signature permissions are install time ones. 8260 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8261 if (allowedSig) { 8262 grant = GRANT_INSTALL; 8263 } 8264 } break; 8265 } 8266 8267 if (DEBUG_INSTALL) { 8268 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8269 } 8270 8271 if (grant != GRANT_DENIED) { 8272 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8273 // If this is an existing, non-system package, then 8274 // we can't add any new permissions to it. 8275 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8276 // Except... if this is a permission that was added 8277 // to the platform (note: need to only do this when 8278 // updating the platform). 8279 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8280 grant = GRANT_DENIED; 8281 } 8282 } 8283 } 8284 8285 switch (grant) { 8286 case GRANT_INSTALL: { 8287 // Revoke this as runtime permission to handle the case of 8288 // a runtime permission being downgraded to an install one. 8289 for (int userId : UserManagerService.getInstance().getUserIds()) { 8290 if (origPermissions.getRuntimePermissionState( 8291 bp.name, userId) != null) { 8292 // Revoke the runtime permission and clear the flags. 8293 origPermissions.revokeRuntimePermission(bp, userId); 8294 origPermissions.updatePermissionFlags(bp, userId, 8295 PackageManager.MASK_PERMISSION_FLAGS, 0); 8296 // If we revoked a permission permission, we have to write. 8297 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8298 changedRuntimePermissionUserIds, userId); 8299 } 8300 } 8301 // Grant an install permission. 8302 if (permissionsState.grantInstallPermission(bp) != 8303 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8304 changedInstallPermission = true; 8305 } 8306 } break; 8307 8308 case GRANT_INSTALL_LEGACY: { 8309 // Grant an install permission. 8310 if (permissionsState.grantInstallPermission(bp) != 8311 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8312 changedInstallPermission = true; 8313 } 8314 } break; 8315 8316 case GRANT_RUNTIME: { 8317 // Grant previously granted runtime permissions. 8318 for (int userId : UserManagerService.getInstance().getUserIds()) { 8319 PermissionState permissionState = origPermissions 8320 .getRuntimePermissionState(bp.name, userId); 8321 final int flags = permissionState != null 8322 ? permissionState.getFlags() : 0; 8323 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8324 if (permissionsState.grantRuntimePermission(bp, userId) == 8325 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8326 // If we cannot put the permission as it was, we have to write. 8327 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8328 changedRuntimePermissionUserIds, userId); 8329 } 8330 } 8331 // Propagate the permission flags. 8332 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8333 } 8334 } break; 8335 8336 case GRANT_UPGRADE: { 8337 // Grant runtime permissions for a previously held install permission. 8338 PermissionState permissionState = origPermissions 8339 .getInstallPermissionState(bp.name); 8340 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8341 8342 if (origPermissions.revokeInstallPermission(bp) 8343 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8344 // We will be transferring the permission flags, so clear them. 8345 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8346 PackageManager.MASK_PERMISSION_FLAGS, 0); 8347 changedInstallPermission = true; 8348 } 8349 8350 // If the permission is not to be promoted to runtime we ignore it and 8351 // also its other flags as they are not applicable to install permissions. 8352 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8353 for (int userId : currentUserIds) { 8354 if (permissionsState.grantRuntimePermission(bp, userId) != 8355 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8356 // Transfer the permission flags. 8357 permissionsState.updatePermissionFlags(bp, userId, 8358 flags, flags); 8359 // If we granted the permission, we have to write. 8360 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8361 changedRuntimePermissionUserIds, userId); 8362 } 8363 } 8364 } 8365 } break; 8366 8367 default: { 8368 if (packageOfInterest == null 8369 || packageOfInterest.equals(pkg.packageName)) { 8370 Slog.w(TAG, "Not granting permission " + perm 8371 + " to package " + pkg.packageName 8372 + " because it was previously installed without"); 8373 } 8374 } break; 8375 } 8376 } else { 8377 if (permissionsState.revokeInstallPermission(bp) != 8378 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8379 // Also drop the permission flags. 8380 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8381 PackageManager.MASK_PERMISSION_FLAGS, 0); 8382 changedInstallPermission = true; 8383 Slog.i(TAG, "Un-granting permission " + perm 8384 + " from package " + pkg.packageName 8385 + " (protectionLevel=" + bp.protectionLevel 8386 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8387 + ")"); 8388 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8389 // Don't print warning for app op permissions, since it is fine for them 8390 // not to be granted, there is a UI for the user to decide. 8391 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8392 Slog.w(TAG, "Not granting permission " + perm 8393 + " to package " + pkg.packageName 8394 + " (protectionLevel=" + bp.protectionLevel 8395 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8396 + ")"); 8397 } 8398 } 8399 } 8400 } 8401 8402 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8403 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8404 // This is the first that we have heard about this package, so the 8405 // permissions we have now selected are fixed until explicitly 8406 // changed. 8407 ps.installPermissionsFixed = true; 8408 } 8409 8410 // Persist the runtime permissions state for users with changes. 8411 for (int userId : changedRuntimePermissionUserIds) { 8412 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8413 } 8414 } 8415 8416 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8417 boolean allowed = false; 8418 final int NP = PackageParser.NEW_PERMISSIONS.length; 8419 for (int ip=0; ip<NP; ip++) { 8420 final PackageParser.NewPermissionInfo npi 8421 = PackageParser.NEW_PERMISSIONS[ip]; 8422 if (npi.name.equals(perm) 8423 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8424 allowed = true; 8425 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8426 + pkg.packageName); 8427 break; 8428 } 8429 } 8430 return allowed; 8431 } 8432 8433 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8434 BasePermission bp, PermissionsState origPermissions) { 8435 boolean allowed; 8436 allowed = (compareSignatures( 8437 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8438 == PackageManager.SIGNATURE_MATCH) 8439 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8440 == PackageManager.SIGNATURE_MATCH); 8441 if (!allowed && (bp.protectionLevel 8442 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8443 if (isSystemApp(pkg)) { 8444 // For updated system applications, a system permission 8445 // is granted only if it had been defined by the original application. 8446 if (pkg.isUpdatedSystemApp()) { 8447 final PackageSetting sysPs = mSettings 8448 .getDisabledSystemPkgLPr(pkg.packageName); 8449 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8450 // If the original was granted this permission, we take 8451 // that grant decision as read and propagate it to the 8452 // update. 8453 if (sysPs.isPrivileged()) { 8454 allowed = true; 8455 } 8456 } else { 8457 // The system apk may have been updated with an older 8458 // version of the one on the data partition, but which 8459 // granted a new system permission that it didn't have 8460 // before. In this case we do want to allow the app to 8461 // now get the new permission if the ancestral apk is 8462 // privileged to get it. 8463 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8464 for (int j=0; 8465 j<sysPs.pkg.requestedPermissions.size(); j++) { 8466 if (perm.equals( 8467 sysPs.pkg.requestedPermissions.get(j))) { 8468 allowed = true; 8469 break; 8470 } 8471 } 8472 } 8473 } 8474 } else { 8475 allowed = isPrivilegedApp(pkg); 8476 } 8477 } 8478 } 8479 if (!allowed) { 8480 if (!allowed && (bp.protectionLevel 8481 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8482 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8483 // If this was a previously normal/dangerous permission that got moved 8484 // to a system permission as part of the runtime permission redesign, then 8485 // we still want to blindly grant it to old apps. 8486 allowed = true; 8487 } 8488 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8489 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8490 // If this permission is to be granted to the system installer and 8491 // this app is an installer, then it gets the permission. 8492 allowed = true; 8493 } 8494 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8495 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8496 // If this permission is to be granted to the system verifier and 8497 // this app is a verifier, then it gets the permission. 8498 allowed = true; 8499 } 8500 if (!allowed && (bp.protectionLevel 8501 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8502 && isSystemApp(pkg)) { 8503 // Any pre-installed system app is allowed to get this permission. 8504 allowed = true; 8505 } 8506 if (!allowed && (bp.protectionLevel 8507 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8508 // For development permissions, a development permission 8509 // is granted only if it was already granted. 8510 allowed = origPermissions.hasInstallPermission(perm); 8511 } 8512 } 8513 return allowed; 8514 } 8515 8516 final class ActivityIntentResolver 8517 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8518 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8519 boolean defaultOnly, int userId) { 8520 if (!sUserManager.exists(userId)) return null; 8521 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8522 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8523 } 8524 8525 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8526 int userId) { 8527 if (!sUserManager.exists(userId)) return null; 8528 mFlags = flags; 8529 return super.queryIntent(intent, resolvedType, 8530 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8531 } 8532 8533 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8534 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8535 if (!sUserManager.exists(userId)) return null; 8536 if (packageActivities == null) { 8537 return null; 8538 } 8539 mFlags = flags; 8540 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8541 final int N = packageActivities.size(); 8542 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8543 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8544 8545 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8546 for (int i = 0; i < N; ++i) { 8547 intentFilters = packageActivities.get(i).intents; 8548 if (intentFilters != null && intentFilters.size() > 0) { 8549 PackageParser.ActivityIntentInfo[] array = 8550 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8551 intentFilters.toArray(array); 8552 listCut.add(array); 8553 } 8554 } 8555 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8556 } 8557 8558 public final void addActivity(PackageParser.Activity a, String type) { 8559 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8560 mActivities.put(a.getComponentName(), a); 8561 if (DEBUG_SHOW_INFO) 8562 Log.v( 8563 TAG, " " + type + " " + 8564 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8565 if (DEBUG_SHOW_INFO) 8566 Log.v(TAG, " Class=" + a.info.name); 8567 final int NI = a.intents.size(); 8568 for (int j=0; j<NI; j++) { 8569 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8570 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8571 intent.setPriority(0); 8572 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8573 + a.className + " with priority > 0, forcing to 0"); 8574 } 8575 if (DEBUG_SHOW_INFO) { 8576 Log.v(TAG, " IntentFilter:"); 8577 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8578 } 8579 if (!intent.debugCheck()) { 8580 Log.w(TAG, "==> For Activity " + a.info.name); 8581 } 8582 addFilter(intent); 8583 } 8584 } 8585 8586 public final void removeActivity(PackageParser.Activity a, String type) { 8587 mActivities.remove(a.getComponentName()); 8588 if (DEBUG_SHOW_INFO) { 8589 Log.v(TAG, " " + type + " " 8590 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8591 : a.info.name) + ":"); 8592 Log.v(TAG, " Class=" + a.info.name); 8593 } 8594 final int NI = a.intents.size(); 8595 for (int j=0; j<NI; j++) { 8596 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8597 if (DEBUG_SHOW_INFO) { 8598 Log.v(TAG, " IntentFilter:"); 8599 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8600 } 8601 removeFilter(intent); 8602 } 8603 } 8604 8605 @Override 8606 protected boolean allowFilterResult( 8607 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8608 ActivityInfo filterAi = filter.activity.info; 8609 for (int i=dest.size()-1; i>=0; i--) { 8610 ActivityInfo destAi = dest.get(i).activityInfo; 8611 if (destAi.name == filterAi.name 8612 && destAi.packageName == filterAi.packageName) { 8613 return false; 8614 } 8615 } 8616 return true; 8617 } 8618 8619 @Override 8620 protected ActivityIntentInfo[] newArray(int size) { 8621 return new ActivityIntentInfo[size]; 8622 } 8623 8624 @Override 8625 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8626 if (!sUserManager.exists(userId)) return true; 8627 PackageParser.Package p = filter.activity.owner; 8628 if (p != null) { 8629 PackageSetting ps = (PackageSetting)p.mExtras; 8630 if (ps != null) { 8631 // System apps are never considered stopped for purposes of 8632 // filtering, because there may be no way for the user to 8633 // actually re-launch them. 8634 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8635 && ps.getStopped(userId); 8636 } 8637 } 8638 return false; 8639 } 8640 8641 @Override 8642 protected boolean isPackageForFilter(String packageName, 8643 PackageParser.ActivityIntentInfo info) { 8644 return packageName.equals(info.activity.owner.packageName); 8645 } 8646 8647 @Override 8648 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8649 int match, int userId) { 8650 if (!sUserManager.exists(userId)) return null; 8651 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8652 return null; 8653 } 8654 final PackageParser.Activity activity = info.activity; 8655 if (mSafeMode && (activity.info.applicationInfo.flags 8656 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8657 return null; 8658 } 8659 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8660 if (ps == null) { 8661 return null; 8662 } 8663 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8664 ps.readUserState(userId), userId); 8665 if (ai == null) { 8666 return null; 8667 } 8668 final ResolveInfo res = new ResolveInfo(); 8669 res.activityInfo = ai; 8670 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8671 res.filter = info; 8672 } 8673 if (info != null) { 8674 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8675 } 8676 res.priority = info.getPriority(); 8677 res.preferredOrder = activity.owner.mPreferredOrder; 8678 //System.out.println("Result: " + res.activityInfo.className + 8679 // " = " + res.priority); 8680 res.match = match; 8681 res.isDefault = info.hasDefault; 8682 res.labelRes = info.labelRes; 8683 res.nonLocalizedLabel = info.nonLocalizedLabel; 8684 if (userNeedsBadging(userId)) { 8685 res.noResourceId = true; 8686 } else { 8687 res.icon = info.icon; 8688 } 8689 res.iconResourceId = info.icon; 8690 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8691 return res; 8692 } 8693 8694 @Override 8695 protected void sortResults(List<ResolveInfo> results) { 8696 Collections.sort(results, mResolvePrioritySorter); 8697 } 8698 8699 @Override 8700 protected void dumpFilter(PrintWriter out, String prefix, 8701 PackageParser.ActivityIntentInfo filter) { 8702 out.print(prefix); out.print( 8703 Integer.toHexString(System.identityHashCode(filter.activity))); 8704 out.print(' '); 8705 filter.activity.printComponentShortName(out); 8706 out.print(" filter "); 8707 out.println(Integer.toHexString(System.identityHashCode(filter))); 8708 } 8709 8710 @Override 8711 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8712 return filter.activity; 8713 } 8714 8715 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8716 PackageParser.Activity activity = (PackageParser.Activity)label; 8717 out.print(prefix); out.print( 8718 Integer.toHexString(System.identityHashCode(activity))); 8719 out.print(' '); 8720 activity.printComponentShortName(out); 8721 if (count > 1) { 8722 out.print(" ("); out.print(count); out.print(" filters)"); 8723 } 8724 out.println(); 8725 } 8726 8727// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8728// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8729// final List<ResolveInfo> retList = Lists.newArrayList(); 8730// while (i.hasNext()) { 8731// final ResolveInfo resolveInfo = i.next(); 8732// if (isEnabledLP(resolveInfo.activityInfo)) { 8733// retList.add(resolveInfo); 8734// } 8735// } 8736// return retList; 8737// } 8738 8739 // Keys are String (activity class name), values are Activity. 8740 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8741 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8742 private int mFlags; 8743 } 8744 8745 private final class ServiceIntentResolver 8746 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8747 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8748 boolean defaultOnly, int userId) { 8749 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8750 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8751 } 8752 8753 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8754 int userId) { 8755 if (!sUserManager.exists(userId)) return null; 8756 mFlags = flags; 8757 return super.queryIntent(intent, resolvedType, 8758 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8759 } 8760 8761 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8762 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8763 if (!sUserManager.exists(userId)) return null; 8764 if (packageServices == null) { 8765 return null; 8766 } 8767 mFlags = flags; 8768 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8769 final int N = packageServices.size(); 8770 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8771 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8772 8773 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8774 for (int i = 0; i < N; ++i) { 8775 intentFilters = packageServices.get(i).intents; 8776 if (intentFilters != null && intentFilters.size() > 0) { 8777 PackageParser.ServiceIntentInfo[] array = 8778 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8779 intentFilters.toArray(array); 8780 listCut.add(array); 8781 } 8782 } 8783 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8784 } 8785 8786 public final void addService(PackageParser.Service s) { 8787 mServices.put(s.getComponentName(), s); 8788 if (DEBUG_SHOW_INFO) { 8789 Log.v(TAG, " " 8790 + (s.info.nonLocalizedLabel != null 8791 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8792 Log.v(TAG, " Class=" + s.info.name); 8793 } 8794 final int NI = s.intents.size(); 8795 int j; 8796 for (j=0; j<NI; j++) { 8797 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8798 if (DEBUG_SHOW_INFO) { 8799 Log.v(TAG, " IntentFilter:"); 8800 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8801 } 8802 if (!intent.debugCheck()) { 8803 Log.w(TAG, "==> For Service " + s.info.name); 8804 } 8805 addFilter(intent); 8806 } 8807 } 8808 8809 public final void removeService(PackageParser.Service s) { 8810 mServices.remove(s.getComponentName()); 8811 if (DEBUG_SHOW_INFO) { 8812 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8813 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8814 Log.v(TAG, " Class=" + s.info.name); 8815 } 8816 final int NI = s.intents.size(); 8817 int j; 8818 for (j=0; j<NI; j++) { 8819 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8820 if (DEBUG_SHOW_INFO) { 8821 Log.v(TAG, " IntentFilter:"); 8822 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8823 } 8824 removeFilter(intent); 8825 } 8826 } 8827 8828 @Override 8829 protected boolean allowFilterResult( 8830 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8831 ServiceInfo filterSi = filter.service.info; 8832 for (int i=dest.size()-1; i>=0; i--) { 8833 ServiceInfo destAi = dest.get(i).serviceInfo; 8834 if (destAi.name == filterSi.name 8835 && destAi.packageName == filterSi.packageName) { 8836 return false; 8837 } 8838 } 8839 return true; 8840 } 8841 8842 @Override 8843 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8844 return new PackageParser.ServiceIntentInfo[size]; 8845 } 8846 8847 @Override 8848 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8849 if (!sUserManager.exists(userId)) return true; 8850 PackageParser.Package p = filter.service.owner; 8851 if (p != null) { 8852 PackageSetting ps = (PackageSetting)p.mExtras; 8853 if (ps != null) { 8854 // System apps are never considered stopped for purposes of 8855 // filtering, because there may be no way for the user to 8856 // actually re-launch them. 8857 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8858 && ps.getStopped(userId); 8859 } 8860 } 8861 return false; 8862 } 8863 8864 @Override 8865 protected boolean isPackageForFilter(String packageName, 8866 PackageParser.ServiceIntentInfo info) { 8867 return packageName.equals(info.service.owner.packageName); 8868 } 8869 8870 @Override 8871 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8872 int match, int userId) { 8873 if (!sUserManager.exists(userId)) return null; 8874 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8875 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8876 return null; 8877 } 8878 final PackageParser.Service service = info.service; 8879 if (mSafeMode && (service.info.applicationInfo.flags 8880 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8881 return null; 8882 } 8883 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8884 if (ps == null) { 8885 return null; 8886 } 8887 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8888 ps.readUserState(userId), userId); 8889 if (si == null) { 8890 return null; 8891 } 8892 final ResolveInfo res = new ResolveInfo(); 8893 res.serviceInfo = si; 8894 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8895 res.filter = filter; 8896 } 8897 res.priority = info.getPriority(); 8898 res.preferredOrder = service.owner.mPreferredOrder; 8899 res.match = match; 8900 res.isDefault = info.hasDefault; 8901 res.labelRes = info.labelRes; 8902 res.nonLocalizedLabel = info.nonLocalizedLabel; 8903 res.icon = info.icon; 8904 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8905 return res; 8906 } 8907 8908 @Override 8909 protected void sortResults(List<ResolveInfo> results) { 8910 Collections.sort(results, mResolvePrioritySorter); 8911 } 8912 8913 @Override 8914 protected void dumpFilter(PrintWriter out, String prefix, 8915 PackageParser.ServiceIntentInfo filter) { 8916 out.print(prefix); out.print( 8917 Integer.toHexString(System.identityHashCode(filter.service))); 8918 out.print(' '); 8919 filter.service.printComponentShortName(out); 8920 out.print(" filter "); 8921 out.println(Integer.toHexString(System.identityHashCode(filter))); 8922 } 8923 8924 @Override 8925 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8926 return filter.service; 8927 } 8928 8929 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8930 PackageParser.Service service = (PackageParser.Service)label; 8931 out.print(prefix); out.print( 8932 Integer.toHexString(System.identityHashCode(service))); 8933 out.print(' '); 8934 service.printComponentShortName(out); 8935 if (count > 1) { 8936 out.print(" ("); out.print(count); out.print(" filters)"); 8937 } 8938 out.println(); 8939 } 8940 8941// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8942// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8943// final List<ResolveInfo> retList = Lists.newArrayList(); 8944// while (i.hasNext()) { 8945// final ResolveInfo resolveInfo = (ResolveInfo) i; 8946// if (isEnabledLP(resolveInfo.serviceInfo)) { 8947// retList.add(resolveInfo); 8948// } 8949// } 8950// return retList; 8951// } 8952 8953 // Keys are String (activity class name), values are Activity. 8954 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8955 = new ArrayMap<ComponentName, PackageParser.Service>(); 8956 private int mFlags; 8957 }; 8958 8959 private final class ProviderIntentResolver 8960 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8961 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8962 boolean defaultOnly, int userId) { 8963 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8964 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8965 } 8966 8967 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8968 int userId) { 8969 if (!sUserManager.exists(userId)) 8970 return null; 8971 mFlags = flags; 8972 return super.queryIntent(intent, resolvedType, 8973 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8974 } 8975 8976 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8977 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8978 if (!sUserManager.exists(userId)) 8979 return null; 8980 if (packageProviders == null) { 8981 return null; 8982 } 8983 mFlags = flags; 8984 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8985 final int N = packageProviders.size(); 8986 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8987 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8988 8989 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8990 for (int i = 0; i < N; ++i) { 8991 intentFilters = packageProviders.get(i).intents; 8992 if (intentFilters != null && intentFilters.size() > 0) { 8993 PackageParser.ProviderIntentInfo[] array = 8994 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8995 intentFilters.toArray(array); 8996 listCut.add(array); 8997 } 8998 } 8999 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9000 } 9001 9002 public final void addProvider(PackageParser.Provider p) { 9003 if (mProviders.containsKey(p.getComponentName())) { 9004 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9005 return; 9006 } 9007 9008 mProviders.put(p.getComponentName(), p); 9009 if (DEBUG_SHOW_INFO) { 9010 Log.v(TAG, " " 9011 + (p.info.nonLocalizedLabel != null 9012 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9013 Log.v(TAG, " Class=" + p.info.name); 9014 } 9015 final int NI = p.intents.size(); 9016 int j; 9017 for (j = 0; j < NI; j++) { 9018 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9019 if (DEBUG_SHOW_INFO) { 9020 Log.v(TAG, " IntentFilter:"); 9021 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9022 } 9023 if (!intent.debugCheck()) { 9024 Log.w(TAG, "==> For Provider " + p.info.name); 9025 } 9026 addFilter(intent); 9027 } 9028 } 9029 9030 public final void removeProvider(PackageParser.Provider p) { 9031 mProviders.remove(p.getComponentName()); 9032 if (DEBUG_SHOW_INFO) { 9033 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9034 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9035 Log.v(TAG, " Class=" + p.info.name); 9036 } 9037 final int NI = p.intents.size(); 9038 int j; 9039 for (j = 0; j < NI; j++) { 9040 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9041 if (DEBUG_SHOW_INFO) { 9042 Log.v(TAG, " IntentFilter:"); 9043 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9044 } 9045 removeFilter(intent); 9046 } 9047 } 9048 9049 @Override 9050 protected boolean allowFilterResult( 9051 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9052 ProviderInfo filterPi = filter.provider.info; 9053 for (int i = dest.size() - 1; i >= 0; i--) { 9054 ProviderInfo destPi = dest.get(i).providerInfo; 9055 if (destPi.name == filterPi.name 9056 && destPi.packageName == filterPi.packageName) { 9057 return false; 9058 } 9059 } 9060 return true; 9061 } 9062 9063 @Override 9064 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9065 return new PackageParser.ProviderIntentInfo[size]; 9066 } 9067 9068 @Override 9069 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9070 if (!sUserManager.exists(userId)) 9071 return true; 9072 PackageParser.Package p = filter.provider.owner; 9073 if (p != null) { 9074 PackageSetting ps = (PackageSetting) p.mExtras; 9075 if (ps != null) { 9076 // System apps are never considered stopped for purposes of 9077 // filtering, because there may be no way for the user to 9078 // actually re-launch them. 9079 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9080 && ps.getStopped(userId); 9081 } 9082 } 9083 return false; 9084 } 9085 9086 @Override 9087 protected boolean isPackageForFilter(String packageName, 9088 PackageParser.ProviderIntentInfo info) { 9089 return packageName.equals(info.provider.owner.packageName); 9090 } 9091 9092 @Override 9093 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9094 int match, int userId) { 9095 if (!sUserManager.exists(userId)) 9096 return null; 9097 final PackageParser.ProviderIntentInfo info = filter; 9098 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9099 return null; 9100 } 9101 final PackageParser.Provider provider = info.provider; 9102 if (mSafeMode && (provider.info.applicationInfo.flags 9103 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9104 return null; 9105 } 9106 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9107 if (ps == null) { 9108 return null; 9109 } 9110 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9111 ps.readUserState(userId), userId); 9112 if (pi == null) { 9113 return null; 9114 } 9115 final ResolveInfo res = new ResolveInfo(); 9116 res.providerInfo = pi; 9117 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9118 res.filter = filter; 9119 } 9120 res.priority = info.getPriority(); 9121 res.preferredOrder = provider.owner.mPreferredOrder; 9122 res.match = match; 9123 res.isDefault = info.hasDefault; 9124 res.labelRes = info.labelRes; 9125 res.nonLocalizedLabel = info.nonLocalizedLabel; 9126 res.icon = info.icon; 9127 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9128 return res; 9129 } 9130 9131 @Override 9132 protected void sortResults(List<ResolveInfo> results) { 9133 Collections.sort(results, mResolvePrioritySorter); 9134 } 9135 9136 @Override 9137 protected void dumpFilter(PrintWriter out, String prefix, 9138 PackageParser.ProviderIntentInfo filter) { 9139 out.print(prefix); 9140 out.print( 9141 Integer.toHexString(System.identityHashCode(filter.provider))); 9142 out.print(' '); 9143 filter.provider.printComponentShortName(out); 9144 out.print(" filter "); 9145 out.println(Integer.toHexString(System.identityHashCode(filter))); 9146 } 9147 9148 @Override 9149 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9150 return filter.provider; 9151 } 9152 9153 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9154 PackageParser.Provider provider = (PackageParser.Provider)label; 9155 out.print(prefix); out.print( 9156 Integer.toHexString(System.identityHashCode(provider))); 9157 out.print(' '); 9158 provider.printComponentShortName(out); 9159 if (count > 1) { 9160 out.print(" ("); out.print(count); out.print(" filters)"); 9161 } 9162 out.println(); 9163 } 9164 9165 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9166 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9167 private int mFlags; 9168 }; 9169 9170 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9171 new Comparator<ResolveInfo>() { 9172 public int compare(ResolveInfo r1, ResolveInfo r2) { 9173 int v1 = r1.priority; 9174 int v2 = r2.priority; 9175 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9176 if (v1 != v2) { 9177 return (v1 > v2) ? -1 : 1; 9178 } 9179 v1 = r1.preferredOrder; 9180 v2 = r2.preferredOrder; 9181 if (v1 != v2) { 9182 return (v1 > v2) ? -1 : 1; 9183 } 9184 if (r1.isDefault != r2.isDefault) { 9185 return r1.isDefault ? -1 : 1; 9186 } 9187 v1 = r1.match; 9188 v2 = r2.match; 9189 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9190 if (v1 != v2) { 9191 return (v1 > v2) ? -1 : 1; 9192 } 9193 if (r1.system != r2.system) { 9194 return r1.system ? -1 : 1; 9195 } 9196 return 0; 9197 } 9198 }; 9199 9200 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9201 new Comparator<ProviderInfo>() { 9202 public int compare(ProviderInfo p1, ProviderInfo p2) { 9203 final int v1 = p1.initOrder; 9204 final int v2 = p2.initOrder; 9205 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9206 } 9207 }; 9208 9209 final void sendPackageBroadcast(final String action, final String pkg, 9210 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9211 final int[] userIds) { 9212 mHandler.post(new Runnable() { 9213 @Override 9214 public void run() { 9215 try { 9216 final IActivityManager am = ActivityManagerNative.getDefault(); 9217 if (am == null) return; 9218 final int[] resolvedUserIds; 9219 if (userIds == null) { 9220 resolvedUserIds = am.getRunningUserIds(); 9221 } else { 9222 resolvedUserIds = userIds; 9223 } 9224 for (int id : resolvedUserIds) { 9225 final Intent intent = new Intent(action, 9226 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9227 if (extras != null) { 9228 intent.putExtras(extras); 9229 } 9230 if (targetPkg != null) { 9231 intent.setPackage(targetPkg); 9232 } 9233 // Modify the UID when posting to other users 9234 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9235 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9236 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9237 intent.putExtra(Intent.EXTRA_UID, uid); 9238 } 9239 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9240 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9241 if (DEBUG_BROADCASTS) { 9242 RuntimeException here = new RuntimeException("here"); 9243 here.fillInStackTrace(); 9244 Slog.d(TAG, "Sending to user " + id + ": " 9245 + intent.toShortString(false, true, false, false) 9246 + " " + intent.getExtras(), here); 9247 } 9248 am.broadcastIntent(null, intent, null, finishedReceiver, 9249 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9250 null, finishedReceiver != null, false, id); 9251 } 9252 } catch (RemoteException ex) { 9253 } 9254 } 9255 }); 9256 } 9257 9258 /** 9259 * Check if the external storage media is available. This is true if there 9260 * is a mounted external storage medium or if the external storage is 9261 * emulated. 9262 */ 9263 private boolean isExternalMediaAvailable() { 9264 return mMediaMounted || Environment.isExternalStorageEmulated(); 9265 } 9266 9267 @Override 9268 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9269 // writer 9270 synchronized (mPackages) { 9271 if (!isExternalMediaAvailable()) { 9272 // If the external storage is no longer mounted at this point, 9273 // the caller may not have been able to delete all of this 9274 // packages files and can not delete any more. Bail. 9275 return null; 9276 } 9277 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9278 if (lastPackage != null) { 9279 pkgs.remove(lastPackage); 9280 } 9281 if (pkgs.size() > 0) { 9282 return pkgs.get(0); 9283 } 9284 } 9285 return null; 9286 } 9287 9288 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9289 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9290 userId, andCode ? 1 : 0, packageName); 9291 if (mSystemReady) { 9292 msg.sendToTarget(); 9293 } else { 9294 if (mPostSystemReadyMessages == null) { 9295 mPostSystemReadyMessages = new ArrayList<>(); 9296 } 9297 mPostSystemReadyMessages.add(msg); 9298 } 9299 } 9300 9301 void startCleaningPackages() { 9302 // reader 9303 synchronized (mPackages) { 9304 if (!isExternalMediaAvailable()) { 9305 return; 9306 } 9307 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9308 return; 9309 } 9310 } 9311 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9312 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9313 IActivityManager am = ActivityManagerNative.getDefault(); 9314 if (am != null) { 9315 try { 9316 am.startService(null, intent, null, mContext.getOpPackageName(), 9317 UserHandle.USER_OWNER); 9318 } catch (RemoteException e) { 9319 } 9320 } 9321 } 9322 9323 @Override 9324 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9325 int installFlags, String installerPackageName, VerificationParams verificationParams, 9326 String packageAbiOverride) { 9327 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9328 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9329 } 9330 9331 @Override 9332 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9333 int installFlags, String installerPackageName, VerificationParams verificationParams, 9334 String packageAbiOverride, int userId) { 9335 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9336 9337 final int callingUid = Binder.getCallingUid(); 9338 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9339 9340 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9341 try { 9342 if (observer != null) { 9343 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9344 } 9345 } catch (RemoteException re) { 9346 } 9347 return; 9348 } 9349 9350 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9351 installFlags |= PackageManager.INSTALL_FROM_ADB; 9352 9353 } else { 9354 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9355 // about installerPackageName. 9356 9357 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9358 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9359 } 9360 9361 UserHandle user; 9362 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9363 user = UserHandle.ALL; 9364 } else { 9365 user = new UserHandle(userId); 9366 } 9367 9368 // Only system components can circumvent runtime permissions when installing. 9369 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9370 && mContext.checkCallingOrSelfPermission(Manifest.permission 9371 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9372 throw new SecurityException("You need the " 9373 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9374 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9375 } 9376 9377 verificationParams.setInstallerUid(callingUid); 9378 9379 final File originFile = new File(originPath); 9380 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9381 9382 final Message msg = mHandler.obtainMessage(INIT_COPY); 9383 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9384 null, verificationParams, user, packageAbiOverride); 9385 mHandler.sendMessage(msg); 9386 } 9387 9388 void installStage(String packageName, File stagedDir, String stagedCid, 9389 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9390 String installerPackageName, int installerUid, UserHandle user) { 9391 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9392 params.referrerUri, installerUid, null); 9393 verifParams.setInstallerUid(installerUid); 9394 9395 final OriginInfo origin; 9396 if (stagedDir != null) { 9397 origin = OriginInfo.fromStagedFile(stagedDir); 9398 } else { 9399 origin = OriginInfo.fromStagedContainer(stagedCid); 9400 } 9401 9402 final Message msg = mHandler.obtainMessage(INIT_COPY); 9403 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9404 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9405 mHandler.sendMessage(msg); 9406 } 9407 9408 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9409 Bundle extras = new Bundle(1); 9410 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9411 9412 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9413 packageName, extras, null, null, new int[] {userId}); 9414 try { 9415 IActivityManager am = ActivityManagerNative.getDefault(); 9416 final boolean isSystem = 9417 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9418 if (isSystem && am.isUserRunning(userId, false)) { 9419 // The just-installed/enabled app is bundled on the system, so presumed 9420 // to be able to run automatically without needing an explicit launch. 9421 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9422 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9423 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9424 .setPackage(packageName); 9425 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9426 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9427 } 9428 } catch (RemoteException e) { 9429 // shouldn't happen 9430 Slog.w(TAG, "Unable to bootstrap installed package", e); 9431 } 9432 } 9433 9434 @Override 9435 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9436 int userId) { 9437 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9438 PackageSetting pkgSetting; 9439 final int uid = Binder.getCallingUid(); 9440 enforceCrossUserPermission(uid, userId, true, true, 9441 "setApplicationHiddenSetting for user " + userId); 9442 9443 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9444 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9445 return false; 9446 } 9447 9448 long callingId = Binder.clearCallingIdentity(); 9449 try { 9450 boolean sendAdded = false; 9451 boolean sendRemoved = false; 9452 // writer 9453 synchronized (mPackages) { 9454 pkgSetting = mSettings.mPackages.get(packageName); 9455 if (pkgSetting == null) { 9456 return false; 9457 } 9458 if (pkgSetting.getHidden(userId) != hidden) { 9459 pkgSetting.setHidden(hidden, userId); 9460 mSettings.writePackageRestrictionsLPr(userId); 9461 if (hidden) { 9462 sendRemoved = true; 9463 } else { 9464 sendAdded = true; 9465 } 9466 } 9467 } 9468 if (sendAdded) { 9469 sendPackageAddedForUser(packageName, pkgSetting, userId); 9470 return true; 9471 } 9472 if (sendRemoved) { 9473 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9474 "hiding pkg"); 9475 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9476 } 9477 } finally { 9478 Binder.restoreCallingIdentity(callingId); 9479 } 9480 return false; 9481 } 9482 9483 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9484 int userId) { 9485 final PackageRemovedInfo info = new PackageRemovedInfo(); 9486 info.removedPackage = packageName; 9487 info.removedUsers = new int[] {userId}; 9488 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9489 info.sendBroadcast(false, false, false); 9490 } 9491 9492 /** 9493 * Returns true if application is not found or there was an error. Otherwise it returns 9494 * the hidden state of the package for the given user. 9495 */ 9496 @Override 9497 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9498 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9499 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9500 false, "getApplicationHidden for user " + userId); 9501 PackageSetting pkgSetting; 9502 long callingId = Binder.clearCallingIdentity(); 9503 try { 9504 // writer 9505 synchronized (mPackages) { 9506 pkgSetting = mSettings.mPackages.get(packageName); 9507 if (pkgSetting == null) { 9508 return true; 9509 } 9510 return pkgSetting.getHidden(userId); 9511 } 9512 } finally { 9513 Binder.restoreCallingIdentity(callingId); 9514 } 9515 } 9516 9517 /** 9518 * @hide 9519 */ 9520 @Override 9521 public int installExistingPackageAsUser(String packageName, int userId) { 9522 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9523 null); 9524 PackageSetting pkgSetting; 9525 final int uid = Binder.getCallingUid(); 9526 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9527 + userId); 9528 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9529 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9530 } 9531 9532 long callingId = Binder.clearCallingIdentity(); 9533 try { 9534 boolean sendAdded = false; 9535 9536 // writer 9537 synchronized (mPackages) { 9538 pkgSetting = mSettings.mPackages.get(packageName); 9539 if (pkgSetting == null) { 9540 return PackageManager.INSTALL_FAILED_INVALID_URI; 9541 } 9542 if (!pkgSetting.getInstalled(userId)) { 9543 pkgSetting.setInstalled(true, userId); 9544 pkgSetting.setHidden(false, userId); 9545 mSettings.writePackageRestrictionsLPr(userId); 9546 sendAdded = true; 9547 } 9548 } 9549 9550 if (sendAdded) { 9551 sendPackageAddedForUser(packageName, pkgSetting, userId); 9552 } 9553 } finally { 9554 Binder.restoreCallingIdentity(callingId); 9555 } 9556 9557 return PackageManager.INSTALL_SUCCEEDED; 9558 } 9559 9560 boolean isUserRestricted(int userId, String restrictionKey) { 9561 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9562 if (restrictions.getBoolean(restrictionKey, false)) { 9563 Log.w(TAG, "User is restricted: " + restrictionKey); 9564 return true; 9565 } 9566 return false; 9567 } 9568 9569 @Override 9570 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9571 mContext.enforceCallingOrSelfPermission( 9572 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9573 "Only package verification agents can verify applications"); 9574 9575 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9576 final PackageVerificationResponse response = new PackageVerificationResponse( 9577 verificationCode, Binder.getCallingUid()); 9578 msg.arg1 = id; 9579 msg.obj = response; 9580 mHandler.sendMessage(msg); 9581 } 9582 9583 @Override 9584 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9585 long millisecondsToDelay) { 9586 mContext.enforceCallingOrSelfPermission( 9587 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9588 "Only package verification agents can extend verification timeouts"); 9589 9590 final PackageVerificationState state = mPendingVerification.get(id); 9591 final PackageVerificationResponse response = new PackageVerificationResponse( 9592 verificationCodeAtTimeout, Binder.getCallingUid()); 9593 9594 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9595 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9596 } 9597 if (millisecondsToDelay < 0) { 9598 millisecondsToDelay = 0; 9599 } 9600 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9601 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9602 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9603 } 9604 9605 if ((state != null) && !state.timeoutExtended()) { 9606 state.extendTimeout(); 9607 9608 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9609 msg.arg1 = id; 9610 msg.obj = response; 9611 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9612 } 9613 } 9614 9615 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9616 int verificationCode, UserHandle user) { 9617 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9618 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9619 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9620 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9621 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9622 9623 mContext.sendBroadcastAsUser(intent, user, 9624 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9625 } 9626 9627 private ComponentName matchComponentForVerifier(String packageName, 9628 List<ResolveInfo> receivers) { 9629 ActivityInfo targetReceiver = null; 9630 9631 final int NR = receivers.size(); 9632 for (int i = 0; i < NR; i++) { 9633 final ResolveInfo info = receivers.get(i); 9634 if (info.activityInfo == null) { 9635 continue; 9636 } 9637 9638 if (packageName.equals(info.activityInfo.packageName)) { 9639 targetReceiver = info.activityInfo; 9640 break; 9641 } 9642 } 9643 9644 if (targetReceiver == null) { 9645 return null; 9646 } 9647 9648 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9649 } 9650 9651 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9652 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9653 if (pkgInfo.verifiers.length == 0) { 9654 return null; 9655 } 9656 9657 final int N = pkgInfo.verifiers.length; 9658 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9659 for (int i = 0; i < N; i++) { 9660 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9661 9662 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9663 receivers); 9664 if (comp == null) { 9665 continue; 9666 } 9667 9668 final int verifierUid = getUidForVerifier(verifierInfo); 9669 if (verifierUid == -1) { 9670 continue; 9671 } 9672 9673 if (DEBUG_VERIFY) { 9674 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9675 + " with the correct signature"); 9676 } 9677 sufficientVerifiers.add(comp); 9678 verificationState.addSufficientVerifier(verifierUid); 9679 } 9680 9681 return sufficientVerifiers; 9682 } 9683 9684 private int getUidForVerifier(VerifierInfo verifierInfo) { 9685 synchronized (mPackages) { 9686 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9687 if (pkg == null) { 9688 return -1; 9689 } else if (pkg.mSignatures.length != 1) { 9690 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9691 + " has more than one signature; ignoring"); 9692 return -1; 9693 } 9694 9695 /* 9696 * If the public key of the package's signature does not match 9697 * our expected public key, then this is a different package and 9698 * we should skip. 9699 */ 9700 9701 final byte[] expectedPublicKey; 9702 try { 9703 final Signature verifierSig = pkg.mSignatures[0]; 9704 final PublicKey publicKey = verifierSig.getPublicKey(); 9705 expectedPublicKey = publicKey.getEncoded(); 9706 } catch (CertificateException e) { 9707 return -1; 9708 } 9709 9710 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9711 9712 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9713 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9714 + " does not have the expected public key; ignoring"); 9715 return -1; 9716 } 9717 9718 return pkg.applicationInfo.uid; 9719 } 9720 } 9721 9722 @Override 9723 public void finishPackageInstall(int token) { 9724 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9725 9726 if (DEBUG_INSTALL) { 9727 Slog.v(TAG, "BM finishing package install for " + token); 9728 } 9729 9730 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9731 mHandler.sendMessage(msg); 9732 } 9733 9734 /** 9735 * Get the verification agent timeout. 9736 * 9737 * @return verification timeout in milliseconds 9738 */ 9739 private long getVerificationTimeout() { 9740 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9741 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9742 DEFAULT_VERIFICATION_TIMEOUT); 9743 } 9744 9745 /** 9746 * Get the default verification agent response code. 9747 * 9748 * @return default verification response code 9749 */ 9750 private int getDefaultVerificationResponse() { 9751 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9752 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9753 DEFAULT_VERIFICATION_RESPONSE); 9754 } 9755 9756 /** 9757 * Check whether or not package verification has been enabled. 9758 * 9759 * @return true if verification should be performed 9760 */ 9761 private boolean isVerificationEnabled(int userId, int installFlags) { 9762 if (!DEFAULT_VERIFY_ENABLE) { 9763 return false; 9764 } 9765 9766 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9767 9768 // Check if installing from ADB 9769 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9770 // Do not run verification in a test harness environment 9771 if (ActivityManager.isRunningInTestHarness()) { 9772 return false; 9773 } 9774 if (ensureVerifyAppsEnabled) { 9775 return true; 9776 } 9777 // Check if the developer does not want package verification for ADB installs 9778 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9779 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9780 return false; 9781 } 9782 } 9783 9784 if (ensureVerifyAppsEnabled) { 9785 return true; 9786 } 9787 9788 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9789 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9790 } 9791 9792 @Override 9793 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9794 throws RemoteException { 9795 mContext.enforceCallingOrSelfPermission( 9796 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9797 "Only intentfilter verification agents can verify applications"); 9798 9799 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9800 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9801 Binder.getCallingUid(), verificationCode, failedDomains); 9802 msg.arg1 = id; 9803 msg.obj = response; 9804 mHandler.sendMessage(msg); 9805 } 9806 9807 @Override 9808 public int getIntentVerificationStatus(String packageName, int userId) { 9809 synchronized (mPackages) { 9810 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9811 } 9812 } 9813 9814 @Override 9815 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9816 mContext.enforceCallingOrSelfPermission( 9817 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9818 9819 boolean result = false; 9820 synchronized (mPackages) { 9821 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9822 } 9823 if (result) { 9824 scheduleWritePackageRestrictionsLocked(userId); 9825 } 9826 return result; 9827 } 9828 9829 @Override 9830 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9831 synchronized (mPackages) { 9832 return mSettings.getIntentFilterVerificationsLPr(packageName); 9833 } 9834 } 9835 9836 @Override 9837 public List<IntentFilter> getAllIntentFilters(String packageName) { 9838 if (TextUtils.isEmpty(packageName)) { 9839 return Collections.<IntentFilter>emptyList(); 9840 } 9841 synchronized (mPackages) { 9842 PackageParser.Package pkg = mPackages.get(packageName); 9843 if (pkg == null || pkg.activities == null) { 9844 return Collections.<IntentFilter>emptyList(); 9845 } 9846 final int count = pkg.activities.size(); 9847 ArrayList<IntentFilter> result = new ArrayList<>(); 9848 for (int n=0; n<count; n++) { 9849 PackageParser.Activity activity = pkg.activities.get(n); 9850 if (activity.intents != null || activity.intents.size() > 0) { 9851 result.addAll(activity.intents); 9852 } 9853 } 9854 return result; 9855 } 9856 } 9857 9858 @Override 9859 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9860 mContext.enforceCallingOrSelfPermission( 9861 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9862 9863 synchronized (mPackages) { 9864 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9865 if (packageName != null) { 9866 result |= updateIntentVerificationStatus(packageName, 9867 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9868 UserHandle.myUserId()); 9869 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9870 packageName, userId); 9871 } 9872 return result; 9873 } 9874 } 9875 9876 @Override 9877 public String getDefaultBrowserPackageName(int userId) { 9878 synchronized (mPackages) { 9879 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9880 } 9881 } 9882 9883 /** 9884 * Get the "allow unknown sources" setting. 9885 * 9886 * @return the current "allow unknown sources" setting 9887 */ 9888 private int getUnknownSourcesSettings() { 9889 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9890 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9891 -1); 9892 } 9893 9894 @Override 9895 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9896 final int uid = Binder.getCallingUid(); 9897 // writer 9898 synchronized (mPackages) { 9899 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9900 if (targetPackageSetting == null) { 9901 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9902 } 9903 9904 PackageSetting installerPackageSetting; 9905 if (installerPackageName != null) { 9906 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9907 if (installerPackageSetting == null) { 9908 throw new IllegalArgumentException("Unknown installer package: " 9909 + installerPackageName); 9910 } 9911 } else { 9912 installerPackageSetting = null; 9913 } 9914 9915 Signature[] callerSignature; 9916 Object obj = mSettings.getUserIdLPr(uid); 9917 if (obj != null) { 9918 if (obj instanceof SharedUserSetting) { 9919 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9920 } else if (obj instanceof PackageSetting) { 9921 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9922 } else { 9923 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9924 } 9925 } else { 9926 throw new SecurityException("Unknown calling uid " + uid); 9927 } 9928 9929 // Verify: can't set installerPackageName to a package that is 9930 // not signed with the same cert as the caller. 9931 if (installerPackageSetting != null) { 9932 if (compareSignatures(callerSignature, 9933 installerPackageSetting.signatures.mSignatures) 9934 != PackageManager.SIGNATURE_MATCH) { 9935 throw new SecurityException( 9936 "Caller does not have same cert as new installer package " 9937 + installerPackageName); 9938 } 9939 } 9940 9941 // Verify: if target already has an installer package, it must 9942 // be signed with the same cert as the caller. 9943 if (targetPackageSetting.installerPackageName != null) { 9944 PackageSetting setting = mSettings.mPackages.get( 9945 targetPackageSetting.installerPackageName); 9946 // If the currently set package isn't valid, then it's always 9947 // okay to change it. 9948 if (setting != null) { 9949 if (compareSignatures(callerSignature, 9950 setting.signatures.mSignatures) 9951 != PackageManager.SIGNATURE_MATCH) { 9952 throw new SecurityException( 9953 "Caller does not have same cert as old installer package " 9954 + targetPackageSetting.installerPackageName); 9955 } 9956 } 9957 } 9958 9959 // Okay! 9960 targetPackageSetting.installerPackageName = installerPackageName; 9961 scheduleWriteSettingsLocked(); 9962 } 9963 } 9964 9965 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9966 // Queue up an async operation since the package installation may take a little while. 9967 mHandler.post(new Runnable() { 9968 public void run() { 9969 mHandler.removeCallbacks(this); 9970 // Result object to be returned 9971 PackageInstalledInfo res = new PackageInstalledInfo(); 9972 res.returnCode = currentStatus; 9973 res.uid = -1; 9974 res.pkg = null; 9975 res.removedInfo = new PackageRemovedInfo(); 9976 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9977 args.doPreInstall(res.returnCode); 9978 synchronized (mInstallLock) { 9979 installPackageLI(args, res); 9980 } 9981 args.doPostInstall(res.returnCode, res.uid); 9982 } 9983 9984 // A restore should be performed at this point if (a) the install 9985 // succeeded, (b) the operation is not an update, and (c) the new 9986 // package has not opted out of backup participation. 9987 final boolean update = res.removedInfo.removedPackage != null; 9988 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9989 boolean doRestore = !update 9990 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9991 9992 // Set up the post-install work request bookkeeping. This will be used 9993 // and cleaned up by the post-install event handling regardless of whether 9994 // there's a restore pass performed. Token values are >= 1. 9995 int token; 9996 if (mNextInstallToken < 0) mNextInstallToken = 1; 9997 token = mNextInstallToken++; 9998 9999 PostInstallData data = new PostInstallData(args, res); 10000 mRunningInstalls.put(token, data); 10001 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10002 10003 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10004 // Pass responsibility to the Backup Manager. It will perform a 10005 // restore if appropriate, then pass responsibility back to the 10006 // Package Manager to run the post-install observer callbacks 10007 // and broadcasts. 10008 IBackupManager bm = IBackupManager.Stub.asInterface( 10009 ServiceManager.getService(Context.BACKUP_SERVICE)); 10010 if (bm != null) { 10011 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10012 + " to BM for possible restore"); 10013 try { 10014 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10015 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10016 } else { 10017 doRestore = false; 10018 } 10019 } catch (RemoteException e) { 10020 // can't happen; the backup manager is local 10021 } catch (Exception e) { 10022 Slog.e(TAG, "Exception trying to enqueue restore", e); 10023 doRestore = false; 10024 } 10025 } else { 10026 Slog.e(TAG, "Backup Manager not found!"); 10027 doRestore = false; 10028 } 10029 } 10030 10031 if (!doRestore) { 10032 // No restore possible, or the Backup Manager was mysteriously not 10033 // available -- just fire the post-install work request directly. 10034 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10035 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10036 mHandler.sendMessage(msg); 10037 } 10038 } 10039 }); 10040 } 10041 10042 private abstract class HandlerParams { 10043 private static final int MAX_RETRIES = 4; 10044 10045 /** 10046 * Number of times startCopy() has been attempted and had a non-fatal 10047 * error. 10048 */ 10049 private int mRetries = 0; 10050 10051 /** User handle for the user requesting the information or installation. */ 10052 private final UserHandle mUser; 10053 10054 HandlerParams(UserHandle user) { 10055 mUser = user; 10056 } 10057 10058 UserHandle getUser() { 10059 return mUser; 10060 } 10061 10062 final boolean startCopy() { 10063 boolean res; 10064 try { 10065 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10066 10067 if (++mRetries > MAX_RETRIES) { 10068 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10069 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10070 handleServiceError(); 10071 return false; 10072 } else { 10073 handleStartCopy(); 10074 res = true; 10075 } 10076 } catch (RemoteException e) { 10077 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10078 mHandler.sendEmptyMessage(MCS_RECONNECT); 10079 res = false; 10080 } 10081 handleReturnCode(); 10082 return res; 10083 } 10084 10085 final void serviceError() { 10086 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10087 handleServiceError(); 10088 handleReturnCode(); 10089 } 10090 10091 abstract void handleStartCopy() throws RemoteException; 10092 abstract void handleServiceError(); 10093 abstract void handleReturnCode(); 10094 } 10095 10096 class MeasureParams extends HandlerParams { 10097 private final PackageStats mStats; 10098 private boolean mSuccess; 10099 10100 private final IPackageStatsObserver mObserver; 10101 10102 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10103 super(new UserHandle(stats.userHandle)); 10104 mObserver = observer; 10105 mStats = stats; 10106 } 10107 10108 @Override 10109 public String toString() { 10110 return "MeasureParams{" 10111 + Integer.toHexString(System.identityHashCode(this)) 10112 + " " + mStats.packageName + "}"; 10113 } 10114 10115 @Override 10116 void handleStartCopy() throws RemoteException { 10117 synchronized (mInstallLock) { 10118 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10119 } 10120 10121 if (mSuccess) { 10122 final boolean mounted; 10123 if (Environment.isExternalStorageEmulated()) { 10124 mounted = true; 10125 } else { 10126 final String status = Environment.getExternalStorageState(); 10127 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10128 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10129 } 10130 10131 if (mounted) { 10132 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10133 10134 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10135 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10136 10137 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10138 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10139 10140 // Always subtract cache size, since it's a subdirectory 10141 mStats.externalDataSize -= mStats.externalCacheSize; 10142 10143 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10144 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10145 10146 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10147 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10148 } 10149 } 10150 } 10151 10152 @Override 10153 void handleReturnCode() { 10154 if (mObserver != null) { 10155 try { 10156 mObserver.onGetStatsCompleted(mStats, mSuccess); 10157 } catch (RemoteException e) { 10158 Slog.i(TAG, "Observer no longer exists."); 10159 } 10160 } 10161 } 10162 10163 @Override 10164 void handleServiceError() { 10165 Slog.e(TAG, "Could not measure application " + mStats.packageName 10166 + " external storage"); 10167 } 10168 } 10169 10170 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10171 throws RemoteException { 10172 long result = 0; 10173 for (File path : paths) { 10174 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10175 } 10176 return result; 10177 } 10178 10179 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10180 for (File path : paths) { 10181 try { 10182 mcs.clearDirectory(path.getAbsolutePath()); 10183 } catch (RemoteException e) { 10184 } 10185 } 10186 } 10187 10188 static class OriginInfo { 10189 /** 10190 * Location where install is coming from, before it has been 10191 * copied/renamed into place. This could be a single monolithic APK 10192 * file, or a cluster directory. This location may be untrusted. 10193 */ 10194 final File file; 10195 final String cid; 10196 10197 /** 10198 * Flag indicating that {@link #file} or {@link #cid} has already been 10199 * staged, meaning downstream users don't need to defensively copy the 10200 * contents. 10201 */ 10202 final boolean staged; 10203 10204 /** 10205 * Flag indicating that {@link #file} or {@link #cid} is an already 10206 * installed app that is being moved. 10207 */ 10208 final boolean existing; 10209 10210 final String resolvedPath; 10211 final File resolvedFile; 10212 10213 static OriginInfo fromNothing() { 10214 return new OriginInfo(null, null, false, false); 10215 } 10216 10217 static OriginInfo fromUntrustedFile(File file) { 10218 return new OriginInfo(file, null, false, false); 10219 } 10220 10221 static OriginInfo fromExistingFile(File file) { 10222 return new OriginInfo(file, null, false, true); 10223 } 10224 10225 static OriginInfo fromStagedFile(File file) { 10226 return new OriginInfo(file, null, true, false); 10227 } 10228 10229 static OriginInfo fromStagedContainer(String cid) { 10230 return new OriginInfo(null, cid, true, false); 10231 } 10232 10233 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10234 this.file = file; 10235 this.cid = cid; 10236 this.staged = staged; 10237 this.existing = existing; 10238 10239 if (cid != null) { 10240 resolvedPath = PackageHelper.getSdDir(cid); 10241 resolvedFile = new File(resolvedPath); 10242 } else if (file != null) { 10243 resolvedPath = file.getAbsolutePath(); 10244 resolvedFile = file; 10245 } else { 10246 resolvedPath = null; 10247 resolvedFile = null; 10248 } 10249 } 10250 } 10251 10252 class MoveInfo { 10253 final int moveId; 10254 final String fromUuid; 10255 final String toUuid; 10256 final String packageName; 10257 final String dataAppName; 10258 final int appId; 10259 final String seinfo; 10260 10261 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10262 String dataAppName, int appId, String seinfo) { 10263 this.moveId = moveId; 10264 this.fromUuid = fromUuid; 10265 this.toUuid = toUuid; 10266 this.packageName = packageName; 10267 this.dataAppName = dataAppName; 10268 this.appId = appId; 10269 this.seinfo = seinfo; 10270 } 10271 } 10272 10273 class InstallParams extends HandlerParams { 10274 final OriginInfo origin; 10275 final MoveInfo move; 10276 final IPackageInstallObserver2 observer; 10277 int installFlags; 10278 final String installerPackageName; 10279 final String volumeUuid; 10280 final VerificationParams verificationParams; 10281 private InstallArgs mArgs; 10282 private int mRet; 10283 final String packageAbiOverride; 10284 10285 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10286 int installFlags, String installerPackageName, String volumeUuid, 10287 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10288 super(user); 10289 this.origin = origin; 10290 this.move = move; 10291 this.observer = observer; 10292 this.installFlags = installFlags; 10293 this.installerPackageName = installerPackageName; 10294 this.volumeUuid = volumeUuid; 10295 this.verificationParams = verificationParams; 10296 this.packageAbiOverride = packageAbiOverride; 10297 } 10298 10299 @Override 10300 public String toString() { 10301 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10302 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10303 } 10304 10305 public ManifestDigest getManifestDigest() { 10306 if (verificationParams == null) { 10307 return null; 10308 } 10309 return verificationParams.getManifestDigest(); 10310 } 10311 10312 private int installLocationPolicy(PackageInfoLite pkgLite) { 10313 String packageName = pkgLite.packageName; 10314 int installLocation = pkgLite.installLocation; 10315 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10316 // reader 10317 synchronized (mPackages) { 10318 PackageParser.Package pkg = mPackages.get(packageName); 10319 if (pkg != null) { 10320 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10321 // Check for downgrading. 10322 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10323 try { 10324 checkDowngrade(pkg, pkgLite); 10325 } catch (PackageManagerException e) { 10326 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10327 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10328 } 10329 } 10330 // Check for updated system application. 10331 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10332 if (onSd) { 10333 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10334 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10335 } 10336 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10337 } else { 10338 if (onSd) { 10339 // Install flag overrides everything. 10340 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10341 } 10342 // If current upgrade specifies particular preference 10343 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10344 // Application explicitly specified internal. 10345 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10346 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10347 // App explictly prefers external. Let policy decide 10348 } else { 10349 // Prefer previous location 10350 if (isExternal(pkg)) { 10351 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10352 } 10353 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10354 } 10355 } 10356 } else { 10357 // Invalid install. Return error code 10358 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10359 } 10360 } 10361 } 10362 // All the special cases have been taken care of. 10363 // Return result based on recommended install location. 10364 if (onSd) { 10365 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10366 } 10367 return pkgLite.recommendedInstallLocation; 10368 } 10369 10370 /* 10371 * Invoke remote method to get package information and install 10372 * location values. Override install location based on default 10373 * policy if needed and then create install arguments based 10374 * on the install location. 10375 */ 10376 public void handleStartCopy() throws RemoteException { 10377 int ret = PackageManager.INSTALL_SUCCEEDED; 10378 10379 // If we're already staged, we've firmly committed to an install location 10380 if (origin.staged) { 10381 if (origin.file != null) { 10382 installFlags |= PackageManager.INSTALL_INTERNAL; 10383 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10384 } else if (origin.cid != null) { 10385 installFlags |= PackageManager.INSTALL_EXTERNAL; 10386 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10387 } else { 10388 throw new IllegalStateException("Invalid stage location"); 10389 } 10390 } 10391 10392 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10393 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10394 10395 PackageInfoLite pkgLite = null; 10396 10397 if (onInt && onSd) { 10398 // Check if both bits are set. 10399 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10400 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10401 } else { 10402 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10403 packageAbiOverride); 10404 10405 /* 10406 * If we have too little free space, try to free cache 10407 * before giving up. 10408 */ 10409 if (!origin.staged && pkgLite.recommendedInstallLocation 10410 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10411 // TODO: focus freeing disk space on the target device 10412 final StorageManager storage = StorageManager.from(mContext); 10413 final long lowThreshold = storage.getStorageLowBytes( 10414 Environment.getDataDirectory()); 10415 10416 final long sizeBytes = mContainerService.calculateInstalledSize( 10417 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10418 10419 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10420 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10421 installFlags, packageAbiOverride); 10422 } 10423 10424 /* 10425 * The cache free must have deleted the file we 10426 * downloaded to install. 10427 * 10428 * TODO: fix the "freeCache" call to not delete 10429 * the file we care about. 10430 */ 10431 if (pkgLite.recommendedInstallLocation 10432 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10433 pkgLite.recommendedInstallLocation 10434 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10435 } 10436 } 10437 } 10438 10439 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10440 int loc = pkgLite.recommendedInstallLocation; 10441 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10442 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10443 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10444 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10445 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10446 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10447 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10448 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10449 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10450 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10451 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10452 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10453 } else { 10454 // Override with defaults if needed. 10455 loc = installLocationPolicy(pkgLite); 10456 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10457 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10458 } else if (!onSd && !onInt) { 10459 // Override install location with flags 10460 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10461 // Set the flag to install on external media. 10462 installFlags |= PackageManager.INSTALL_EXTERNAL; 10463 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10464 } else { 10465 // Make sure the flag for installing on external 10466 // media is unset 10467 installFlags |= PackageManager.INSTALL_INTERNAL; 10468 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10469 } 10470 } 10471 } 10472 } 10473 10474 final InstallArgs args = createInstallArgs(this); 10475 mArgs = args; 10476 10477 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10478 /* 10479 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10480 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10481 */ 10482 int userIdentifier = getUser().getIdentifier(); 10483 if (userIdentifier == UserHandle.USER_ALL 10484 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10485 userIdentifier = UserHandle.USER_OWNER; 10486 } 10487 10488 /* 10489 * Determine if we have any installed package verifiers. If we 10490 * do, then we'll defer to them to verify the packages. 10491 */ 10492 final int requiredUid = mRequiredVerifierPackage == null ? -1 10493 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10494 if (!origin.existing && requiredUid != -1 10495 && isVerificationEnabled(userIdentifier, installFlags)) { 10496 final Intent verification = new Intent( 10497 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10498 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10499 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10500 PACKAGE_MIME_TYPE); 10501 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10502 10503 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10504 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10505 0 /* TODO: Which userId? */); 10506 10507 if (DEBUG_VERIFY) { 10508 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10509 + verification.toString() + " with " + pkgLite.verifiers.length 10510 + " optional verifiers"); 10511 } 10512 10513 final int verificationId = mPendingVerificationToken++; 10514 10515 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10516 10517 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10518 installerPackageName); 10519 10520 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10521 installFlags); 10522 10523 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10524 pkgLite.packageName); 10525 10526 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10527 pkgLite.versionCode); 10528 10529 if (verificationParams != null) { 10530 if (verificationParams.getVerificationURI() != null) { 10531 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10532 verificationParams.getVerificationURI()); 10533 } 10534 if (verificationParams.getOriginatingURI() != null) { 10535 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10536 verificationParams.getOriginatingURI()); 10537 } 10538 if (verificationParams.getReferrer() != null) { 10539 verification.putExtra(Intent.EXTRA_REFERRER, 10540 verificationParams.getReferrer()); 10541 } 10542 if (verificationParams.getOriginatingUid() >= 0) { 10543 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10544 verificationParams.getOriginatingUid()); 10545 } 10546 if (verificationParams.getInstallerUid() >= 0) { 10547 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10548 verificationParams.getInstallerUid()); 10549 } 10550 } 10551 10552 final PackageVerificationState verificationState = new PackageVerificationState( 10553 requiredUid, args); 10554 10555 mPendingVerification.append(verificationId, verificationState); 10556 10557 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10558 receivers, verificationState); 10559 10560 /* 10561 * If any sufficient verifiers were listed in the package 10562 * manifest, attempt to ask them. 10563 */ 10564 if (sufficientVerifiers != null) { 10565 final int N = sufficientVerifiers.size(); 10566 if (N == 0) { 10567 Slog.i(TAG, "Additional verifiers required, but none installed."); 10568 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10569 } else { 10570 for (int i = 0; i < N; i++) { 10571 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10572 10573 final Intent sufficientIntent = new Intent(verification); 10574 sufficientIntent.setComponent(verifierComponent); 10575 10576 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10577 } 10578 } 10579 } 10580 10581 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10582 mRequiredVerifierPackage, receivers); 10583 if (ret == PackageManager.INSTALL_SUCCEEDED 10584 && mRequiredVerifierPackage != null) { 10585 /* 10586 * Send the intent to the required verification agent, 10587 * but only start the verification timeout after the 10588 * target BroadcastReceivers have run. 10589 */ 10590 verification.setComponent(requiredVerifierComponent); 10591 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10592 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10593 new BroadcastReceiver() { 10594 @Override 10595 public void onReceive(Context context, Intent intent) { 10596 final Message msg = mHandler 10597 .obtainMessage(CHECK_PENDING_VERIFICATION); 10598 msg.arg1 = verificationId; 10599 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10600 } 10601 }, null, 0, null, null); 10602 10603 /* 10604 * We don't want the copy to proceed until verification 10605 * succeeds, so null out this field. 10606 */ 10607 mArgs = null; 10608 } 10609 } else { 10610 /* 10611 * No package verification is enabled, so immediately start 10612 * the remote call to initiate copy using temporary file. 10613 */ 10614 ret = args.copyApk(mContainerService, true); 10615 } 10616 } 10617 10618 mRet = ret; 10619 } 10620 10621 @Override 10622 void handleReturnCode() { 10623 // If mArgs is null, then MCS couldn't be reached. When it 10624 // reconnects, it will try again to install. At that point, this 10625 // will succeed. 10626 if (mArgs != null) { 10627 processPendingInstall(mArgs, mRet); 10628 } 10629 } 10630 10631 @Override 10632 void handleServiceError() { 10633 mArgs = createInstallArgs(this); 10634 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10635 } 10636 10637 public boolean isForwardLocked() { 10638 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10639 } 10640 } 10641 10642 /** 10643 * Used during creation of InstallArgs 10644 * 10645 * @param installFlags package installation flags 10646 * @return true if should be installed on external storage 10647 */ 10648 private static boolean installOnExternalAsec(int installFlags) { 10649 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10650 return false; 10651 } 10652 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10653 return true; 10654 } 10655 return false; 10656 } 10657 10658 /** 10659 * Used during creation of InstallArgs 10660 * 10661 * @param installFlags package installation flags 10662 * @return true if should be installed as forward locked 10663 */ 10664 private static boolean installForwardLocked(int installFlags) { 10665 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10666 } 10667 10668 private InstallArgs createInstallArgs(InstallParams params) { 10669 if (params.move != null) { 10670 return new MoveInstallArgs(params); 10671 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10672 return new AsecInstallArgs(params); 10673 } else { 10674 return new FileInstallArgs(params); 10675 } 10676 } 10677 10678 /** 10679 * Create args that describe an existing installed package. Typically used 10680 * when cleaning up old installs, or used as a move source. 10681 */ 10682 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10683 String resourcePath, String[] instructionSets) { 10684 final boolean isInAsec; 10685 if (installOnExternalAsec(installFlags)) { 10686 /* Apps on SD card are always in ASEC containers. */ 10687 isInAsec = true; 10688 } else if (installForwardLocked(installFlags) 10689 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10690 /* 10691 * Forward-locked apps are only in ASEC containers if they're the 10692 * new style 10693 */ 10694 isInAsec = true; 10695 } else { 10696 isInAsec = false; 10697 } 10698 10699 if (isInAsec) { 10700 return new AsecInstallArgs(codePath, instructionSets, 10701 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10702 } else { 10703 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10704 } 10705 } 10706 10707 static abstract class InstallArgs { 10708 /** @see InstallParams#origin */ 10709 final OriginInfo origin; 10710 /** @see InstallParams#move */ 10711 final MoveInfo move; 10712 10713 final IPackageInstallObserver2 observer; 10714 // Always refers to PackageManager flags only 10715 final int installFlags; 10716 final String installerPackageName; 10717 final String volumeUuid; 10718 final ManifestDigest manifestDigest; 10719 final UserHandle user; 10720 final String abiOverride; 10721 10722 // The list of instruction sets supported by this app. This is currently 10723 // only used during the rmdex() phase to clean up resources. We can get rid of this 10724 // if we move dex files under the common app path. 10725 /* nullable */ String[] instructionSets; 10726 10727 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10728 int installFlags, String installerPackageName, String volumeUuid, 10729 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10730 String abiOverride) { 10731 this.origin = origin; 10732 this.move = move; 10733 this.installFlags = installFlags; 10734 this.observer = observer; 10735 this.installerPackageName = installerPackageName; 10736 this.volumeUuid = volumeUuid; 10737 this.manifestDigest = manifestDigest; 10738 this.user = user; 10739 this.instructionSets = instructionSets; 10740 this.abiOverride = abiOverride; 10741 } 10742 10743 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10744 abstract int doPreInstall(int status); 10745 10746 /** 10747 * Rename package into final resting place. All paths on the given 10748 * scanned package should be updated to reflect the rename. 10749 */ 10750 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10751 abstract int doPostInstall(int status, int uid); 10752 10753 /** @see PackageSettingBase#codePathString */ 10754 abstract String getCodePath(); 10755 /** @see PackageSettingBase#resourcePathString */ 10756 abstract String getResourcePath(); 10757 10758 // Need installer lock especially for dex file removal. 10759 abstract void cleanUpResourcesLI(); 10760 abstract boolean doPostDeleteLI(boolean delete); 10761 10762 /** 10763 * Called before the source arguments are copied. This is used mostly 10764 * for MoveParams when it needs to read the source file to put it in the 10765 * destination. 10766 */ 10767 int doPreCopy() { 10768 return PackageManager.INSTALL_SUCCEEDED; 10769 } 10770 10771 /** 10772 * Called after the source arguments are copied. This is used mostly for 10773 * MoveParams when it needs to read the source file to put it in the 10774 * destination. 10775 * 10776 * @return 10777 */ 10778 int doPostCopy(int uid) { 10779 return PackageManager.INSTALL_SUCCEEDED; 10780 } 10781 10782 protected boolean isFwdLocked() { 10783 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10784 } 10785 10786 protected boolean isExternalAsec() { 10787 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10788 } 10789 10790 UserHandle getUser() { 10791 return user; 10792 } 10793 } 10794 10795 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10796 if (!allCodePaths.isEmpty()) { 10797 if (instructionSets == null) { 10798 throw new IllegalStateException("instructionSet == null"); 10799 } 10800 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10801 for (String codePath : allCodePaths) { 10802 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10803 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10804 if (retCode < 0) { 10805 Slog.w(TAG, "Couldn't remove dex file for package: " 10806 + " at location " + codePath + ", retcode=" + retCode); 10807 // we don't consider this to be a failure of the core package deletion 10808 } 10809 } 10810 } 10811 } 10812 } 10813 10814 /** 10815 * Logic to handle installation of non-ASEC applications, including copying 10816 * and renaming logic. 10817 */ 10818 class FileInstallArgs extends InstallArgs { 10819 private File codeFile; 10820 private File resourceFile; 10821 10822 // Example topology: 10823 // /data/app/com.example/base.apk 10824 // /data/app/com.example/split_foo.apk 10825 // /data/app/com.example/lib/arm/libfoo.so 10826 // /data/app/com.example/lib/arm64/libfoo.so 10827 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10828 10829 /** New install */ 10830 FileInstallArgs(InstallParams params) { 10831 super(params.origin, params.move, params.observer, params.installFlags, 10832 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10833 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10834 if (isFwdLocked()) { 10835 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10836 } 10837 } 10838 10839 /** Existing install */ 10840 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10841 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10842 null); 10843 this.codeFile = (codePath != null) ? new File(codePath) : null; 10844 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10845 } 10846 10847 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10848 if (origin.staged) { 10849 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10850 codeFile = origin.file; 10851 resourceFile = origin.file; 10852 return PackageManager.INSTALL_SUCCEEDED; 10853 } 10854 10855 try { 10856 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10857 codeFile = tempDir; 10858 resourceFile = tempDir; 10859 } catch (IOException e) { 10860 Slog.w(TAG, "Failed to create copy file: " + e); 10861 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10862 } 10863 10864 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10865 @Override 10866 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10867 if (!FileUtils.isValidExtFilename(name)) { 10868 throw new IllegalArgumentException("Invalid filename: " + name); 10869 } 10870 try { 10871 final File file = new File(codeFile, name); 10872 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10873 O_RDWR | O_CREAT, 0644); 10874 Os.chmod(file.getAbsolutePath(), 0644); 10875 return new ParcelFileDescriptor(fd); 10876 } catch (ErrnoException e) { 10877 throw new RemoteException("Failed to open: " + e.getMessage()); 10878 } 10879 } 10880 }; 10881 10882 int ret = PackageManager.INSTALL_SUCCEEDED; 10883 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10884 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10885 Slog.e(TAG, "Failed to copy package"); 10886 return ret; 10887 } 10888 10889 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10890 NativeLibraryHelper.Handle handle = null; 10891 try { 10892 handle = NativeLibraryHelper.Handle.create(codeFile); 10893 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10894 abiOverride); 10895 } catch (IOException e) { 10896 Slog.e(TAG, "Copying native libraries failed", e); 10897 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10898 } finally { 10899 IoUtils.closeQuietly(handle); 10900 } 10901 10902 return ret; 10903 } 10904 10905 int doPreInstall(int status) { 10906 if (status != PackageManager.INSTALL_SUCCEEDED) { 10907 cleanUp(); 10908 } 10909 return status; 10910 } 10911 10912 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10913 if (status != PackageManager.INSTALL_SUCCEEDED) { 10914 cleanUp(); 10915 return false; 10916 } 10917 10918 final File targetDir = codeFile.getParentFile(); 10919 final File beforeCodeFile = codeFile; 10920 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10921 10922 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10923 try { 10924 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10925 } catch (ErrnoException e) { 10926 Slog.w(TAG, "Failed to rename", e); 10927 return false; 10928 } 10929 10930 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10931 Slog.w(TAG, "Failed to restorecon"); 10932 return false; 10933 } 10934 10935 // Reflect the rename internally 10936 codeFile = afterCodeFile; 10937 resourceFile = afterCodeFile; 10938 10939 // Reflect the rename in scanned details 10940 pkg.codePath = afterCodeFile.getAbsolutePath(); 10941 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10942 pkg.baseCodePath); 10943 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10944 pkg.splitCodePaths); 10945 10946 // Reflect the rename in app info 10947 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10948 pkg.applicationInfo.setCodePath(pkg.codePath); 10949 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10950 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10951 pkg.applicationInfo.setResourcePath(pkg.codePath); 10952 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10953 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10954 10955 return true; 10956 } 10957 10958 int doPostInstall(int status, int uid) { 10959 if (status != PackageManager.INSTALL_SUCCEEDED) { 10960 cleanUp(); 10961 } 10962 return status; 10963 } 10964 10965 @Override 10966 String getCodePath() { 10967 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10968 } 10969 10970 @Override 10971 String getResourcePath() { 10972 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10973 } 10974 10975 private boolean cleanUp() { 10976 if (codeFile == null || !codeFile.exists()) { 10977 return false; 10978 } 10979 10980 if (codeFile.isDirectory()) { 10981 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10982 } else { 10983 codeFile.delete(); 10984 } 10985 10986 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10987 resourceFile.delete(); 10988 } 10989 10990 return true; 10991 } 10992 10993 void cleanUpResourcesLI() { 10994 // Try enumerating all code paths before deleting 10995 List<String> allCodePaths = Collections.EMPTY_LIST; 10996 if (codeFile != null && codeFile.exists()) { 10997 try { 10998 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10999 allCodePaths = pkg.getAllCodePaths(); 11000 } catch (PackageParserException e) { 11001 // Ignored; we tried our best 11002 } 11003 } 11004 11005 cleanUp(); 11006 removeDexFiles(allCodePaths, instructionSets); 11007 } 11008 11009 boolean doPostDeleteLI(boolean delete) { 11010 // XXX err, shouldn't we respect the delete flag? 11011 cleanUpResourcesLI(); 11012 return true; 11013 } 11014 } 11015 11016 private boolean isAsecExternal(String cid) { 11017 final String asecPath = PackageHelper.getSdFilesystem(cid); 11018 return !asecPath.startsWith(mAsecInternalPath); 11019 } 11020 11021 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11022 PackageManagerException { 11023 if (copyRet < 0) { 11024 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11025 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11026 throw new PackageManagerException(copyRet, message); 11027 } 11028 } 11029 } 11030 11031 /** 11032 * Extract the MountService "container ID" from the full code path of an 11033 * .apk. 11034 */ 11035 static String cidFromCodePath(String fullCodePath) { 11036 int eidx = fullCodePath.lastIndexOf("/"); 11037 String subStr1 = fullCodePath.substring(0, eidx); 11038 int sidx = subStr1.lastIndexOf("/"); 11039 return subStr1.substring(sidx+1, eidx); 11040 } 11041 11042 /** 11043 * Logic to handle installation of ASEC applications, including copying and 11044 * renaming logic. 11045 */ 11046 class AsecInstallArgs extends InstallArgs { 11047 static final String RES_FILE_NAME = "pkg.apk"; 11048 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11049 11050 String cid; 11051 String packagePath; 11052 String resourcePath; 11053 11054 /** New install */ 11055 AsecInstallArgs(InstallParams params) { 11056 super(params.origin, params.move, params.observer, params.installFlags, 11057 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11058 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11059 } 11060 11061 /** Existing install */ 11062 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11063 boolean isExternal, boolean isForwardLocked) { 11064 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11065 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11066 instructionSets, null); 11067 // Hackily pretend we're still looking at a full code path 11068 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11069 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11070 } 11071 11072 // Extract cid from fullCodePath 11073 int eidx = fullCodePath.lastIndexOf("/"); 11074 String subStr1 = fullCodePath.substring(0, eidx); 11075 int sidx = subStr1.lastIndexOf("/"); 11076 cid = subStr1.substring(sidx+1, eidx); 11077 setMountPath(subStr1); 11078 } 11079 11080 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11081 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11082 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11083 instructionSets, null); 11084 this.cid = cid; 11085 setMountPath(PackageHelper.getSdDir(cid)); 11086 } 11087 11088 void createCopyFile() { 11089 cid = mInstallerService.allocateExternalStageCidLegacy(); 11090 } 11091 11092 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11093 if (origin.staged) { 11094 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11095 cid = origin.cid; 11096 setMountPath(PackageHelper.getSdDir(cid)); 11097 return PackageManager.INSTALL_SUCCEEDED; 11098 } 11099 11100 if (temp) { 11101 createCopyFile(); 11102 } else { 11103 /* 11104 * Pre-emptively destroy the container since it's destroyed if 11105 * copying fails due to it existing anyway. 11106 */ 11107 PackageHelper.destroySdDir(cid); 11108 } 11109 11110 final String newMountPath = imcs.copyPackageToContainer( 11111 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11112 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11113 11114 if (newMountPath != null) { 11115 setMountPath(newMountPath); 11116 return PackageManager.INSTALL_SUCCEEDED; 11117 } else { 11118 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11119 } 11120 } 11121 11122 @Override 11123 String getCodePath() { 11124 return packagePath; 11125 } 11126 11127 @Override 11128 String getResourcePath() { 11129 return resourcePath; 11130 } 11131 11132 int doPreInstall(int status) { 11133 if (status != PackageManager.INSTALL_SUCCEEDED) { 11134 // Destroy container 11135 PackageHelper.destroySdDir(cid); 11136 } else { 11137 boolean mounted = PackageHelper.isContainerMounted(cid); 11138 if (!mounted) { 11139 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11140 Process.SYSTEM_UID); 11141 if (newMountPath != null) { 11142 setMountPath(newMountPath); 11143 } else { 11144 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11145 } 11146 } 11147 } 11148 return status; 11149 } 11150 11151 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11152 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11153 String newMountPath = null; 11154 if (PackageHelper.isContainerMounted(cid)) { 11155 // Unmount the container 11156 if (!PackageHelper.unMountSdDir(cid)) { 11157 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11158 return false; 11159 } 11160 } 11161 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11162 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11163 " which might be stale. Will try to clean up."); 11164 // Clean up the stale container and proceed to recreate. 11165 if (!PackageHelper.destroySdDir(newCacheId)) { 11166 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11167 return false; 11168 } 11169 // Successfully cleaned up stale container. Try to rename again. 11170 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11171 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11172 + " inspite of cleaning it up."); 11173 return false; 11174 } 11175 } 11176 if (!PackageHelper.isContainerMounted(newCacheId)) { 11177 Slog.w(TAG, "Mounting container " + newCacheId); 11178 newMountPath = PackageHelper.mountSdDir(newCacheId, 11179 getEncryptKey(), Process.SYSTEM_UID); 11180 } else { 11181 newMountPath = PackageHelper.getSdDir(newCacheId); 11182 } 11183 if (newMountPath == null) { 11184 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11185 return false; 11186 } 11187 Log.i(TAG, "Succesfully renamed " + cid + 11188 " to " + newCacheId + 11189 " at new path: " + newMountPath); 11190 cid = newCacheId; 11191 11192 final File beforeCodeFile = new File(packagePath); 11193 setMountPath(newMountPath); 11194 final File afterCodeFile = new File(packagePath); 11195 11196 // Reflect the rename in scanned details 11197 pkg.codePath = afterCodeFile.getAbsolutePath(); 11198 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11199 pkg.baseCodePath); 11200 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11201 pkg.splitCodePaths); 11202 11203 // Reflect the rename in app info 11204 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11205 pkg.applicationInfo.setCodePath(pkg.codePath); 11206 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11207 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11208 pkg.applicationInfo.setResourcePath(pkg.codePath); 11209 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11210 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11211 11212 return true; 11213 } 11214 11215 private void setMountPath(String mountPath) { 11216 final File mountFile = new File(mountPath); 11217 11218 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11219 if (monolithicFile.exists()) { 11220 packagePath = monolithicFile.getAbsolutePath(); 11221 if (isFwdLocked()) { 11222 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11223 } else { 11224 resourcePath = packagePath; 11225 } 11226 } else { 11227 packagePath = mountFile.getAbsolutePath(); 11228 resourcePath = packagePath; 11229 } 11230 } 11231 11232 int doPostInstall(int status, int uid) { 11233 if (status != PackageManager.INSTALL_SUCCEEDED) { 11234 cleanUp(); 11235 } else { 11236 final int groupOwner; 11237 final String protectedFile; 11238 if (isFwdLocked()) { 11239 groupOwner = UserHandle.getSharedAppGid(uid); 11240 protectedFile = RES_FILE_NAME; 11241 } else { 11242 groupOwner = -1; 11243 protectedFile = null; 11244 } 11245 11246 if (uid < Process.FIRST_APPLICATION_UID 11247 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11248 Slog.e(TAG, "Failed to finalize " + cid); 11249 PackageHelper.destroySdDir(cid); 11250 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11251 } 11252 11253 boolean mounted = PackageHelper.isContainerMounted(cid); 11254 if (!mounted) { 11255 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11256 } 11257 } 11258 return status; 11259 } 11260 11261 private void cleanUp() { 11262 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11263 11264 // Destroy secure container 11265 PackageHelper.destroySdDir(cid); 11266 } 11267 11268 private List<String> getAllCodePaths() { 11269 final File codeFile = new File(getCodePath()); 11270 if (codeFile != null && codeFile.exists()) { 11271 try { 11272 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11273 return pkg.getAllCodePaths(); 11274 } catch (PackageParserException e) { 11275 // Ignored; we tried our best 11276 } 11277 } 11278 return Collections.EMPTY_LIST; 11279 } 11280 11281 void cleanUpResourcesLI() { 11282 // Enumerate all code paths before deleting 11283 cleanUpResourcesLI(getAllCodePaths()); 11284 } 11285 11286 private void cleanUpResourcesLI(List<String> allCodePaths) { 11287 cleanUp(); 11288 removeDexFiles(allCodePaths, instructionSets); 11289 } 11290 11291 String getPackageName() { 11292 return getAsecPackageName(cid); 11293 } 11294 11295 boolean doPostDeleteLI(boolean delete) { 11296 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11297 final List<String> allCodePaths = getAllCodePaths(); 11298 boolean mounted = PackageHelper.isContainerMounted(cid); 11299 if (mounted) { 11300 // Unmount first 11301 if (PackageHelper.unMountSdDir(cid)) { 11302 mounted = false; 11303 } 11304 } 11305 if (!mounted && delete) { 11306 cleanUpResourcesLI(allCodePaths); 11307 } 11308 return !mounted; 11309 } 11310 11311 @Override 11312 int doPreCopy() { 11313 if (isFwdLocked()) { 11314 if (!PackageHelper.fixSdPermissions(cid, 11315 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11316 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11317 } 11318 } 11319 11320 return PackageManager.INSTALL_SUCCEEDED; 11321 } 11322 11323 @Override 11324 int doPostCopy(int uid) { 11325 if (isFwdLocked()) { 11326 if (uid < Process.FIRST_APPLICATION_UID 11327 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11328 RES_FILE_NAME)) { 11329 Slog.e(TAG, "Failed to finalize " + cid); 11330 PackageHelper.destroySdDir(cid); 11331 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11332 } 11333 } 11334 11335 return PackageManager.INSTALL_SUCCEEDED; 11336 } 11337 } 11338 11339 /** 11340 * Logic to handle movement of existing installed applications. 11341 */ 11342 class MoveInstallArgs extends InstallArgs { 11343 private File codeFile; 11344 private File resourceFile; 11345 11346 /** New install */ 11347 MoveInstallArgs(InstallParams params) { 11348 super(params.origin, params.move, params.observer, params.installFlags, 11349 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11350 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11351 } 11352 11353 int copyApk(IMediaContainerService imcs, boolean temp) { 11354 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11355 + move.fromUuid + " to " + move.toUuid); 11356 synchronized (mInstaller) { 11357 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11358 move.dataAppName, move.appId, move.seinfo) != 0) { 11359 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11360 } 11361 } 11362 11363 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11364 resourceFile = codeFile; 11365 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11366 11367 return PackageManager.INSTALL_SUCCEEDED; 11368 } 11369 11370 int doPreInstall(int status) { 11371 if (status != PackageManager.INSTALL_SUCCEEDED) { 11372 cleanUp(move.toUuid); 11373 } 11374 return status; 11375 } 11376 11377 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11378 if (status != PackageManager.INSTALL_SUCCEEDED) { 11379 cleanUp(move.toUuid); 11380 return false; 11381 } 11382 11383 // Reflect the move in app info 11384 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11385 pkg.applicationInfo.setCodePath(pkg.codePath); 11386 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11387 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11388 pkg.applicationInfo.setResourcePath(pkg.codePath); 11389 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11390 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11391 11392 return true; 11393 } 11394 11395 int doPostInstall(int status, int uid) { 11396 if (status == PackageManager.INSTALL_SUCCEEDED) { 11397 cleanUp(move.fromUuid); 11398 } else { 11399 cleanUp(move.toUuid); 11400 } 11401 return status; 11402 } 11403 11404 @Override 11405 String getCodePath() { 11406 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11407 } 11408 11409 @Override 11410 String getResourcePath() { 11411 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11412 } 11413 11414 private boolean cleanUp(String volumeUuid) { 11415 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11416 move.dataAppName); 11417 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11418 synchronized (mInstallLock) { 11419 // Clean up both app data and code 11420 removeDataDirsLI(volumeUuid, move.packageName); 11421 if (codeFile.isDirectory()) { 11422 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11423 } else { 11424 codeFile.delete(); 11425 } 11426 } 11427 return true; 11428 } 11429 11430 void cleanUpResourcesLI() { 11431 throw new UnsupportedOperationException(); 11432 } 11433 11434 boolean doPostDeleteLI(boolean delete) { 11435 throw new UnsupportedOperationException(); 11436 } 11437 } 11438 11439 static String getAsecPackageName(String packageCid) { 11440 int idx = packageCid.lastIndexOf("-"); 11441 if (idx == -1) { 11442 return packageCid; 11443 } 11444 return packageCid.substring(0, idx); 11445 } 11446 11447 // Utility method used to create code paths based on package name and available index. 11448 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11449 String idxStr = ""; 11450 int idx = 1; 11451 // Fall back to default value of idx=1 if prefix is not 11452 // part of oldCodePath 11453 if (oldCodePath != null) { 11454 String subStr = oldCodePath; 11455 // Drop the suffix right away 11456 if (suffix != null && subStr.endsWith(suffix)) { 11457 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11458 } 11459 // If oldCodePath already contains prefix find out the 11460 // ending index to either increment or decrement. 11461 int sidx = subStr.lastIndexOf(prefix); 11462 if (sidx != -1) { 11463 subStr = subStr.substring(sidx + prefix.length()); 11464 if (subStr != null) { 11465 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11466 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11467 } 11468 try { 11469 idx = Integer.parseInt(subStr); 11470 if (idx <= 1) { 11471 idx++; 11472 } else { 11473 idx--; 11474 } 11475 } catch(NumberFormatException e) { 11476 } 11477 } 11478 } 11479 } 11480 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11481 return prefix + idxStr; 11482 } 11483 11484 private File getNextCodePath(File targetDir, String packageName) { 11485 int suffix = 1; 11486 File result; 11487 do { 11488 result = new File(targetDir, packageName + "-" + suffix); 11489 suffix++; 11490 } while (result.exists()); 11491 return result; 11492 } 11493 11494 // Utility method that returns the relative package path with respect 11495 // to the installation directory. Like say for /data/data/com.test-1.apk 11496 // string com.test-1 is returned. 11497 static String deriveCodePathName(String codePath) { 11498 if (codePath == null) { 11499 return null; 11500 } 11501 final File codeFile = new File(codePath); 11502 final String name = codeFile.getName(); 11503 if (codeFile.isDirectory()) { 11504 return name; 11505 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11506 final int lastDot = name.lastIndexOf('.'); 11507 return name.substring(0, lastDot); 11508 } else { 11509 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11510 return null; 11511 } 11512 } 11513 11514 class PackageInstalledInfo { 11515 String name; 11516 int uid; 11517 // The set of users that originally had this package installed. 11518 int[] origUsers; 11519 // The set of users that now have this package installed. 11520 int[] newUsers; 11521 PackageParser.Package pkg; 11522 int returnCode; 11523 String returnMsg; 11524 PackageRemovedInfo removedInfo; 11525 11526 public void setError(int code, String msg) { 11527 returnCode = code; 11528 returnMsg = msg; 11529 Slog.w(TAG, msg); 11530 } 11531 11532 public void setError(String msg, PackageParserException e) { 11533 returnCode = e.error; 11534 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11535 Slog.w(TAG, msg, e); 11536 } 11537 11538 public void setError(String msg, PackageManagerException e) { 11539 returnCode = e.error; 11540 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11541 Slog.w(TAG, msg, e); 11542 } 11543 11544 // In some error cases we want to convey more info back to the observer 11545 String origPackage; 11546 String origPermission; 11547 } 11548 11549 /* 11550 * Install a non-existing package. 11551 */ 11552 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11553 UserHandle user, String installerPackageName, String volumeUuid, 11554 PackageInstalledInfo res) { 11555 // Remember this for later, in case we need to rollback this install 11556 String pkgName = pkg.packageName; 11557 11558 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11559 final boolean dataDirExists = Environment 11560 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11561 synchronized(mPackages) { 11562 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11563 // A package with the same name is already installed, though 11564 // it has been renamed to an older name. The package we 11565 // are trying to install should be installed as an update to 11566 // the existing one, but that has not been requested, so bail. 11567 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11568 + " without first uninstalling package running as " 11569 + mSettings.mRenamedPackages.get(pkgName)); 11570 return; 11571 } 11572 if (mPackages.containsKey(pkgName)) { 11573 // Don't allow installation over an existing package with the same name. 11574 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11575 + " without first uninstalling."); 11576 return; 11577 } 11578 } 11579 11580 try { 11581 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11582 System.currentTimeMillis(), user); 11583 11584 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11585 // delete the partially installed application. the data directory will have to be 11586 // restored if it was already existing 11587 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11588 // remove package from internal structures. Note that we want deletePackageX to 11589 // delete the package data and cache directories that it created in 11590 // scanPackageLocked, unless those directories existed before we even tried to 11591 // install. 11592 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11593 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11594 res.removedInfo, true); 11595 } 11596 11597 } catch (PackageManagerException e) { 11598 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11599 } 11600 } 11601 11602 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11603 // Can't rotate keys during boot or if sharedUser. 11604 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11605 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11606 return false; 11607 } 11608 // app is using upgradeKeySets; make sure all are valid 11609 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11610 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11611 for (int i = 0; i < upgradeKeySets.length; i++) { 11612 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11613 Slog.wtf(TAG, "Package " 11614 + (oldPs.name != null ? oldPs.name : "<null>") 11615 + " contains upgrade-key-set reference to unknown key-set: " 11616 + upgradeKeySets[i] 11617 + " reverting to signatures check."); 11618 return false; 11619 } 11620 } 11621 return true; 11622 } 11623 11624 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11625 // Upgrade keysets are being used. Determine if new package has a superset of the 11626 // required keys. 11627 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11628 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11629 for (int i = 0; i < upgradeKeySets.length; i++) { 11630 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11631 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11632 return true; 11633 } 11634 } 11635 return false; 11636 } 11637 11638 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11639 UserHandle user, String installerPackageName, String volumeUuid, 11640 PackageInstalledInfo res) { 11641 final PackageParser.Package oldPackage; 11642 final String pkgName = pkg.packageName; 11643 final int[] allUsers; 11644 final boolean[] perUserInstalled; 11645 final boolean weFroze; 11646 11647 // First find the old package info and check signatures 11648 synchronized(mPackages) { 11649 oldPackage = mPackages.get(pkgName); 11650 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11651 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11652 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11653 if(!checkUpgradeKeySetLP(ps, pkg)) { 11654 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11655 "New package not signed by keys specified by upgrade-keysets: " 11656 + pkgName); 11657 return; 11658 } 11659 } else { 11660 // default to original signature matching 11661 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11662 != PackageManager.SIGNATURE_MATCH) { 11663 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11664 "New package has a different signature: " + pkgName); 11665 return; 11666 } 11667 } 11668 11669 // In case of rollback, remember per-user/profile install state 11670 allUsers = sUserManager.getUserIds(); 11671 perUserInstalled = new boolean[allUsers.length]; 11672 for (int i = 0; i < allUsers.length; i++) { 11673 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11674 } 11675 11676 // Mark the app as frozen to prevent launching during the upgrade 11677 // process, and then kill all running instances 11678 if (!ps.frozen) { 11679 ps.frozen = true; 11680 weFroze = true; 11681 } else { 11682 weFroze = false; 11683 } 11684 } 11685 11686 // Now that we're guarded by frozen state, kill app during upgrade 11687 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11688 11689 try { 11690 boolean sysPkg = (isSystemApp(oldPackage)); 11691 if (sysPkg) { 11692 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11693 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11694 } else { 11695 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11696 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11697 } 11698 } finally { 11699 // Regardless of success or failure of upgrade steps above, always 11700 // unfreeze the package if we froze it 11701 if (weFroze) { 11702 unfreezePackage(pkgName); 11703 } 11704 } 11705 } 11706 11707 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11708 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11709 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11710 String volumeUuid, PackageInstalledInfo res) { 11711 String pkgName = deletedPackage.packageName; 11712 boolean deletedPkg = true; 11713 boolean updatedSettings = false; 11714 11715 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11716 + deletedPackage); 11717 long origUpdateTime; 11718 if (pkg.mExtras != null) { 11719 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11720 } else { 11721 origUpdateTime = 0; 11722 } 11723 11724 // First delete the existing package while retaining the data directory 11725 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11726 res.removedInfo, true)) { 11727 // If the existing package wasn't successfully deleted 11728 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11729 deletedPkg = false; 11730 } else { 11731 // Successfully deleted the old package; proceed with replace. 11732 11733 // If deleted package lived in a container, give users a chance to 11734 // relinquish resources before killing. 11735 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11736 if (DEBUG_INSTALL) { 11737 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11738 } 11739 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11740 final ArrayList<String> pkgList = new ArrayList<String>(1); 11741 pkgList.add(deletedPackage.applicationInfo.packageName); 11742 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11743 } 11744 11745 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11746 try { 11747 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11748 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11749 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11750 perUserInstalled, res, user); 11751 updatedSettings = true; 11752 } catch (PackageManagerException e) { 11753 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11754 } 11755 } 11756 11757 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11758 // remove package from internal structures. Note that we want deletePackageX to 11759 // delete the package data and cache directories that it created in 11760 // scanPackageLocked, unless those directories existed before we even tried to 11761 // install. 11762 if(updatedSettings) { 11763 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11764 deletePackageLI( 11765 pkgName, null, true, allUsers, perUserInstalled, 11766 PackageManager.DELETE_KEEP_DATA, 11767 res.removedInfo, true); 11768 } 11769 // Since we failed to install the new package we need to restore the old 11770 // package that we deleted. 11771 if (deletedPkg) { 11772 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11773 File restoreFile = new File(deletedPackage.codePath); 11774 // Parse old package 11775 boolean oldExternal = isExternal(deletedPackage); 11776 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11777 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11778 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11779 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11780 try { 11781 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11782 } catch (PackageManagerException e) { 11783 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11784 + e.getMessage()); 11785 return; 11786 } 11787 // Restore of old package succeeded. Update permissions. 11788 // writer 11789 synchronized (mPackages) { 11790 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11791 UPDATE_PERMISSIONS_ALL); 11792 // can downgrade to reader 11793 mSettings.writeLPr(); 11794 } 11795 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11796 } 11797 } 11798 } 11799 11800 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11801 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11802 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11803 String volumeUuid, PackageInstalledInfo res) { 11804 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11805 + ", old=" + deletedPackage); 11806 boolean disabledSystem = false; 11807 boolean updatedSettings = false; 11808 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11809 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11810 != 0) { 11811 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11812 } 11813 String packageName = deletedPackage.packageName; 11814 if (packageName == null) { 11815 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11816 "Attempt to delete null packageName."); 11817 return; 11818 } 11819 PackageParser.Package oldPkg; 11820 PackageSetting oldPkgSetting; 11821 // reader 11822 synchronized (mPackages) { 11823 oldPkg = mPackages.get(packageName); 11824 oldPkgSetting = mSettings.mPackages.get(packageName); 11825 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11826 (oldPkgSetting == null)) { 11827 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11828 "Couldn't find package:" + packageName + " information"); 11829 return; 11830 } 11831 } 11832 11833 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11834 res.removedInfo.removedPackage = packageName; 11835 // Remove existing system package 11836 removePackageLI(oldPkgSetting, true); 11837 // writer 11838 synchronized (mPackages) { 11839 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11840 if (!disabledSystem && deletedPackage != null) { 11841 // We didn't need to disable the .apk as a current system package, 11842 // which means we are replacing another update that is already 11843 // installed. We need to make sure to delete the older one's .apk. 11844 res.removedInfo.args = createInstallArgsForExisting(0, 11845 deletedPackage.applicationInfo.getCodePath(), 11846 deletedPackage.applicationInfo.getResourcePath(), 11847 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11848 } else { 11849 res.removedInfo.args = null; 11850 } 11851 } 11852 11853 // Successfully disabled the old package. Now proceed with re-installation 11854 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11855 11856 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11857 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11858 11859 PackageParser.Package newPackage = null; 11860 try { 11861 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11862 if (newPackage.mExtras != null) { 11863 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11864 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11865 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11866 11867 // is the update attempting to change shared user? that isn't going to work... 11868 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11869 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11870 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11871 + " to " + newPkgSetting.sharedUser); 11872 updatedSettings = true; 11873 } 11874 } 11875 11876 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11877 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11878 perUserInstalled, res, user); 11879 updatedSettings = true; 11880 } 11881 11882 } catch (PackageManagerException e) { 11883 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11884 } 11885 11886 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11887 // Re installation failed. Restore old information 11888 // Remove new pkg information 11889 if (newPackage != null) { 11890 removeInstalledPackageLI(newPackage, true); 11891 } 11892 // Add back the old system package 11893 try { 11894 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11895 } catch (PackageManagerException e) { 11896 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11897 } 11898 // Restore the old system information in Settings 11899 synchronized (mPackages) { 11900 if (disabledSystem) { 11901 mSettings.enableSystemPackageLPw(packageName); 11902 } 11903 if (updatedSettings) { 11904 mSettings.setInstallerPackageName(packageName, 11905 oldPkgSetting.installerPackageName); 11906 } 11907 mSettings.writeLPr(); 11908 } 11909 } 11910 } 11911 11912 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11913 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11914 UserHandle user) { 11915 String pkgName = newPackage.packageName; 11916 synchronized (mPackages) { 11917 //write settings. the installStatus will be incomplete at this stage. 11918 //note that the new package setting would have already been 11919 //added to mPackages. It hasn't been persisted yet. 11920 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11921 mSettings.writeLPr(); 11922 } 11923 11924 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11925 11926 synchronized (mPackages) { 11927 updatePermissionsLPw(newPackage.packageName, newPackage, 11928 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11929 ? UPDATE_PERMISSIONS_ALL : 0)); 11930 // For system-bundled packages, we assume that installing an upgraded version 11931 // of the package implies that the user actually wants to run that new code, 11932 // so we enable the package. 11933 PackageSetting ps = mSettings.mPackages.get(pkgName); 11934 if (ps != null) { 11935 if (isSystemApp(newPackage)) { 11936 // NB: implicit assumption that system package upgrades apply to all users 11937 if (DEBUG_INSTALL) { 11938 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11939 } 11940 if (res.origUsers != null) { 11941 for (int userHandle : res.origUsers) { 11942 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11943 userHandle, installerPackageName); 11944 } 11945 } 11946 // Also convey the prior install/uninstall state 11947 if (allUsers != null && perUserInstalled != null) { 11948 for (int i = 0; i < allUsers.length; i++) { 11949 if (DEBUG_INSTALL) { 11950 Slog.d(TAG, " user " + allUsers[i] 11951 + " => " + perUserInstalled[i]); 11952 } 11953 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11954 } 11955 // these install state changes will be persisted in the 11956 // upcoming call to mSettings.writeLPr(). 11957 } 11958 } 11959 // It's implied that when a user requests installation, they want the app to be 11960 // installed and enabled. 11961 int userId = user.getIdentifier(); 11962 if (userId != UserHandle.USER_ALL) { 11963 ps.setInstalled(true, userId); 11964 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11965 } 11966 } 11967 res.name = pkgName; 11968 res.uid = newPackage.applicationInfo.uid; 11969 res.pkg = newPackage; 11970 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11971 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11972 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11973 //to update install status 11974 mSettings.writeLPr(); 11975 } 11976 } 11977 11978 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11979 final int installFlags = args.installFlags; 11980 final String installerPackageName = args.installerPackageName; 11981 final String volumeUuid = args.volumeUuid; 11982 final File tmpPackageFile = new File(args.getCodePath()); 11983 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11984 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11985 || (args.volumeUuid != null)); 11986 boolean replace = false; 11987 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11988 if (args.move != null) { 11989 // moving a complete application; perfom an initial scan on the new install location 11990 scanFlags |= SCAN_INITIAL; 11991 } 11992 // Result object to be returned 11993 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11994 11995 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11996 // Retrieve PackageSettings and parse package 11997 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11998 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11999 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12000 PackageParser pp = new PackageParser(); 12001 pp.setSeparateProcesses(mSeparateProcesses); 12002 pp.setDisplayMetrics(mMetrics); 12003 12004 final PackageParser.Package pkg; 12005 try { 12006 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12007 } catch (PackageParserException e) { 12008 res.setError("Failed parse during installPackageLI", e); 12009 return; 12010 } 12011 12012 // Mark that we have an install time CPU ABI override. 12013 pkg.cpuAbiOverride = args.abiOverride; 12014 12015 String pkgName = res.name = pkg.packageName; 12016 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12017 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12018 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12019 return; 12020 } 12021 } 12022 12023 try { 12024 pp.collectCertificates(pkg, parseFlags); 12025 pp.collectManifestDigest(pkg); 12026 } catch (PackageParserException e) { 12027 res.setError("Failed collect during installPackageLI", e); 12028 return; 12029 } 12030 12031 /* If the installer passed in a manifest digest, compare it now. */ 12032 if (args.manifestDigest != null) { 12033 if (DEBUG_INSTALL) { 12034 final String parsedManifest = pkg.manifestDigest == null ? "null" 12035 : pkg.manifestDigest.toString(); 12036 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12037 + parsedManifest); 12038 } 12039 12040 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12041 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12042 return; 12043 } 12044 } else if (DEBUG_INSTALL) { 12045 final String parsedManifest = pkg.manifestDigest == null 12046 ? "null" : pkg.manifestDigest.toString(); 12047 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12048 } 12049 12050 // Get rid of all references to package scan path via parser. 12051 pp = null; 12052 String oldCodePath = null; 12053 boolean systemApp = false; 12054 synchronized (mPackages) { 12055 // Check if installing already existing package 12056 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12057 String oldName = mSettings.mRenamedPackages.get(pkgName); 12058 if (pkg.mOriginalPackages != null 12059 && pkg.mOriginalPackages.contains(oldName) 12060 && mPackages.containsKey(oldName)) { 12061 // This package is derived from an original package, 12062 // and this device has been updating from that original 12063 // name. We must continue using the original name, so 12064 // rename the new package here. 12065 pkg.setPackageName(oldName); 12066 pkgName = pkg.packageName; 12067 replace = true; 12068 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12069 + oldName + " pkgName=" + pkgName); 12070 } else if (mPackages.containsKey(pkgName)) { 12071 // This package, under its official name, already exists 12072 // on the device; we should replace it. 12073 replace = true; 12074 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12075 } 12076 12077 // Prevent apps opting out from runtime permissions 12078 if (replace) { 12079 PackageParser.Package oldPackage = mPackages.get(pkgName); 12080 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12081 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12082 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12083 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12084 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12085 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12086 + " doesn't support runtime permissions but the old" 12087 + " target SDK " + oldTargetSdk + " does."); 12088 return; 12089 } 12090 } 12091 } 12092 12093 PackageSetting ps = mSettings.mPackages.get(pkgName); 12094 if (ps != null) { 12095 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12096 12097 // Quick sanity check that we're signed correctly if updating; 12098 // we'll check this again later when scanning, but we want to 12099 // bail early here before tripping over redefined permissions. 12100 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12101 if (!checkUpgradeKeySetLP(ps, pkg)) { 12102 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12103 + pkg.packageName + " upgrade keys do not match the " 12104 + "previously installed version"); 12105 return; 12106 } 12107 } else { 12108 try { 12109 verifySignaturesLP(ps, pkg); 12110 } catch (PackageManagerException e) { 12111 res.setError(e.error, e.getMessage()); 12112 return; 12113 } 12114 } 12115 12116 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12117 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12118 systemApp = (ps.pkg.applicationInfo.flags & 12119 ApplicationInfo.FLAG_SYSTEM) != 0; 12120 } 12121 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12122 } 12123 12124 // Check whether the newly-scanned package wants to define an already-defined perm 12125 int N = pkg.permissions.size(); 12126 for (int i = N-1; i >= 0; i--) { 12127 PackageParser.Permission perm = pkg.permissions.get(i); 12128 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12129 if (bp != null) { 12130 // If the defining package is signed with our cert, it's okay. This 12131 // also includes the "updating the same package" case, of course. 12132 // "updating same package" could also involve key-rotation. 12133 final boolean sigsOk; 12134 if (bp.sourcePackage.equals(pkg.packageName) 12135 && (bp.packageSetting instanceof PackageSetting) 12136 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12137 scanFlags))) { 12138 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12139 } else { 12140 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12141 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12142 } 12143 if (!sigsOk) { 12144 // If the owning package is the system itself, we log but allow 12145 // install to proceed; we fail the install on all other permission 12146 // redefinitions. 12147 if (!bp.sourcePackage.equals("android")) { 12148 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12149 + pkg.packageName + " attempting to redeclare permission " 12150 + perm.info.name + " already owned by " + bp.sourcePackage); 12151 res.origPermission = perm.info.name; 12152 res.origPackage = bp.sourcePackage; 12153 return; 12154 } else { 12155 Slog.w(TAG, "Package " + pkg.packageName 12156 + " attempting to redeclare system permission " 12157 + perm.info.name + "; ignoring new declaration"); 12158 pkg.permissions.remove(i); 12159 } 12160 } 12161 } 12162 } 12163 12164 } 12165 12166 if (systemApp && onExternal) { 12167 // Disable updates to system apps on sdcard 12168 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12169 "Cannot install updates to system apps on sdcard"); 12170 return; 12171 } 12172 12173 if (args.move != null) { 12174 // We did an in-place move, so dex is ready to roll 12175 scanFlags |= SCAN_NO_DEX; 12176 scanFlags |= SCAN_MOVE; 12177 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12178 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12179 scanFlags |= SCAN_NO_DEX; 12180 12181 try { 12182 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12183 true /* extract libs */); 12184 } catch (PackageManagerException pme) { 12185 Slog.e(TAG, "Error deriving application ABI", pme); 12186 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12187 return; 12188 } 12189 12190 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12191 int result = mPackageDexOptimizer 12192 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12193 false /* defer */, false /* inclDependencies */); 12194 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12195 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12196 return; 12197 } 12198 } 12199 12200 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12201 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12202 return; 12203 } 12204 12205 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12206 12207 if (replace) { 12208 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12209 installerPackageName, volumeUuid, res); 12210 } else { 12211 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12212 args.user, installerPackageName, volumeUuid, res); 12213 } 12214 synchronized (mPackages) { 12215 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12216 if (ps != null) { 12217 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12218 } 12219 } 12220 } 12221 12222 private void startIntentFilterVerifications(int userId, boolean replacing, 12223 PackageParser.Package pkg) { 12224 if (mIntentFilterVerifierComponent == null) { 12225 Slog.w(TAG, "No IntentFilter verification will not be done as " 12226 + "there is no IntentFilterVerifier available!"); 12227 return; 12228 } 12229 12230 final int verifierUid = getPackageUid( 12231 mIntentFilterVerifierComponent.getPackageName(), 12232 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12233 12234 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12235 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12236 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12237 mHandler.sendMessage(msg); 12238 } 12239 12240 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12241 PackageParser.Package pkg) { 12242 int size = pkg.activities.size(); 12243 if (size == 0) { 12244 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12245 "No activity, so no need to verify any IntentFilter!"); 12246 return; 12247 } 12248 12249 final boolean hasDomainURLs = hasDomainURLs(pkg); 12250 if (!hasDomainURLs) { 12251 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12252 "No domain URLs, so no need to verify any IntentFilter!"); 12253 return; 12254 } 12255 12256 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12257 + " if any IntentFilter from the " + size 12258 + " Activities needs verification ..."); 12259 12260 int count = 0; 12261 final String packageName = pkg.packageName; 12262 12263 synchronized (mPackages) { 12264 // If this is a new install and we see that we've already run verification for this 12265 // package, we have nothing to do: it means the state was restored from backup. 12266 if (!replacing) { 12267 IntentFilterVerificationInfo ivi = 12268 mSettings.getIntentFilterVerificationLPr(packageName); 12269 if (ivi != null) { 12270 if (DEBUG_DOMAIN_VERIFICATION) { 12271 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12272 + ivi.getStatusString()); 12273 } 12274 return; 12275 } 12276 } 12277 12278 // If any filters need to be verified, then all need to be. 12279 boolean needToVerify = false; 12280 for (PackageParser.Activity a : pkg.activities) { 12281 for (ActivityIntentInfo filter : a.intents) { 12282 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12283 if (DEBUG_DOMAIN_VERIFICATION) { 12284 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12285 } 12286 needToVerify = true; 12287 break; 12288 } 12289 } 12290 } 12291 12292 if (needToVerify) { 12293 final int verificationId = mIntentFilterVerificationToken++; 12294 for (PackageParser.Activity a : pkg.activities) { 12295 for (ActivityIntentInfo filter : a.intents) { 12296 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12297 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12298 "Verification needed for IntentFilter:" + filter.toString()); 12299 mIntentFilterVerifier.addOneIntentFilterVerification( 12300 verifierUid, userId, verificationId, filter, packageName); 12301 count++; 12302 } 12303 } 12304 } 12305 } 12306 } 12307 12308 if (count > 0) { 12309 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12310 + " IntentFilter verification" + (count > 1 ? "s" : "") 12311 + " for userId:" + userId); 12312 mIntentFilterVerifier.startVerifications(userId); 12313 } else { 12314 if (DEBUG_DOMAIN_VERIFICATION) { 12315 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12316 } 12317 } 12318 } 12319 12320 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12321 final ComponentName cn = filter.activity.getComponentName(); 12322 final String packageName = cn.getPackageName(); 12323 12324 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12325 packageName); 12326 if (ivi == null) { 12327 return true; 12328 } 12329 int status = ivi.getStatus(); 12330 switch (status) { 12331 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12332 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12333 return true; 12334 12335 default: 12336 // Nothing to do 12337 return false; 12338 } 12339 } 12340 12341 private static boolean isMultiArch(PackageSetting ps) { 12342 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12343 } 12344 12345 private static boolean isMultiArch(ApplicationInfo info) { 12346 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12347 } 12348 12349 private static boolean isExternal(PackageParser.Package pkg) { 12350 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12351 } 12352 12353 private static boolean isExternal(PackageSetting ps) { 12354 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12355 } 12356 12357 private static boolean isExternal(ApplicationInfo info) { 12358 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12359 } 12360 12361 private static boolean isSystemApp(PackageParser.Package pkg) { 12362 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12363 } 12364 12365 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12366 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12367 } 12368 12369 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12370 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12371 } 12372 12373 private static boolean isSystemApp(PackageSetting ps) { 12374 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12375 } 12376 12377 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12378 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12379 } 12380 12381 private int packageFlagsToInstallFlags(PackageSetting ps) { 12382 int installFlags = 0; 12383 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12384 // This existing package was an external ASEC install when we have 12385 // the external flag without a UUID 12386 installFlags |= PackageManager.INSTALL_EXTERNAL; 12387 } 12388 if (ps.isForwardLocked()) { 12389 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12390 } 12391 return installFlags; 12392 } 12393 12394 private void deleteTempPackageFiles() { 12395 final FilenameFilter filter = new FilenameFilter() { 12396 public boolean accept(File dir, String name) { 12397 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12398 } 12399 }; 12400 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12401 file.delete(); 12402 } 12403 } 12404 12405 @Override 12406 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12407 int flags) { 12408 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12409 flags); 12410 } 12411 12412 @Override 12413 public void deletePackage(final String packageName, 12414 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12415 mContext.enforceCallingOrSelfPermission( 12416 android.Manifest.permission.DELETE_PACKAGES, null); 12417 Preconditions.checkNotNull(packageName); 12418 Preconditions.checkNotNull(observer); 12419 final int uid = Binder.getCallingUid(); 12420 if (UserHandle.getUserId(uid) != userId) { 12421 mContext.enforceCallingPermission( 12422 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12423 "deletePackage for user " + userId); 12424 } 12425 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12426 try { 12427 observer.onPackageDeleted(packageName, 12428 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12429 } catch (RemoteException re) { 12430 } 12431 return; 12432 } 12433 12434 boolean uninstallBlocked = false; 12435 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12436 int[] users = sUserManager.getUserIds(); 12437 for (int i = 0; i < users.length; ++i) { 12438 if (getBlockUninstallForUser(packageName, users[i])) { 12439 uninstallBlocked = true; 12440 break; 12441 } 12442 } 12443 } else { 12444 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12445 } 12446 if (uninstallBlocked) { 12447 try { 12448 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12449 null); 12450 } catch (RemoteException re) { 12451 } 12452 return; 12453 } 12454 12455 if (DEBUG_REMOVE) { 12456 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12457 } 12458 // Queue up an async operation since the package deletion may take a little while. 12459 mHandler.post(new Runnable() { 12460 public void run() { 12461 mHandler.removeCallbacks(this); 12462 final int returnCode = deletePackageX(packageName, userId, flags); 12463 if (observer != null) { 12464 try { 12465 observer.onPackageDeleted(packageName, returnCode, null); 12466 } catch (RemoteException e) { 12467 Log.i(TAG, "Observer no longer exists."); 12468 } //end catch 12469 } //end if 12470 } //end run 12471 }); 12472 } 12473 12474 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12475 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12476 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12477 try { 12478 if (dpm != null) { 12479 if (dpm.isDeviceOwner(packageName)) { 12480 return true; 12481 } 12482 int[] users; 12483 if (userId == UserHandle.USER_ALL) { 12484 users = sUserManager.getUserIds(); 12485 } else { 12486 users = new int[]{userId}; 12487 } 12488 for (int i = 0; i < users.length; ++i) { 12489 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12490 return true; 12491 } 12492 } 12493 } 12494 } catch (RemoteException e) { 12495 } 12496 return false; 12497 } 12498 12499 /** 12500 * This method is an internal method that could be get invoked either 12501 * to delete an installed package or to clean up a failed installation. 12502 * After deleting an installed package, a broadcast is sent to notify any 12503 * listeners that the package has been installed. For cleaning up a failed 12504 * installation, the broadcast is not necessary since the package's 12505 * installation wouldn't have sent the initial broadcast either 12506 * The key steps in deleting a package are 12507 * deleting the package information in internal structures like mPackages, 12508 * deleting the packages base directories through installd 12509 * updating mSettings to reflect current status 12510 * persisting settings for later use 12511 * sending a broadcast if necessary 12512 */ 12513 private int deletePackageX(String packageName, int userId, int flags) { 12514 final PackageRemovedInfo info = new PackageRemovedInfo(); 12515 final boolean res; 12516 12517 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12518 ? UserHandle.ALL : new UserHandle(userId); 12519 12520 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12521 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12522 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12523 } 12524 12525 boolean removedForAllUsers = false; 12526 boolean systemUpdate = false; 12527 12528 // for the uninstall-updates case and restricted profiles, remember the per- 12529 // userhandle installed state 12530 int[] allUsers; 12531 boolean[] perUserInstalled; 12532 synchronized (mPackages) { 12533 PackageSetting ps = mSettings.mPackages.get(packageName); 12534 allUsers = sUserManager.getUserIds(); 12535 perUserInstalled = new boolean[allUsers.length]; 12536 for (int i = 0; i < allUsers.length; i++) { 12537 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12538 } 12539 } 12540 12541 synchronized (mInstallLock) { 12542 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12543 res = deletePackageLI(packageName, removeForUser, 12544 true, allUsers, perUserInstalled, 12545 flags | REMOVE_CHATTY, info, true); 12546 systemUpdate = info.isRemovedPackageSystemUpdate; 12547 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12548 removedForAllUsers = true; 12549 } 12550 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12551 + " removedForAllUsers=" + removedForAllUsers); 12552 } 12553 12554 if (res) { 12555 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12556 12557 // If the removed package was a system update, the old system package 12558 // was re-enabled; we need to broadcast this information 12559 if (systemUpdate) { 12560 Bundle extras = new Bundle(1); 12561 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12562 ? info.removedAppId : info.uid); 12563 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12564 12565 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12566 extras, null, null, null); 12567 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12568 extras, null, null, null); 12569 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12570 null, packageName, null, null); 12571 } 12572 } 12573 // Force a gc here. 12574 Runtime.getRuntime().gc(); 12575 // Delete the resources here after sending the broadcast to let 12576 // other processes clean up before deleting resources. 12577 if (info.args != null) { 12578 synchronized (mInstallLock) { 12579 info.args.doPostDeleteLI(true); 12580 } 12581 } 12582 12583 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12584 } 12585 12586 class PackageRemovedInfo { 12587 String removedPackage; 12588 int uid = -1; 12589 int removedAppId = -1; 12590 int[] removedUsers = null; 12591 boolean isRemovedPackageSystemUpdate = false; 12592 // Clean up resources deleted packages. 12593 InstallArgs args = null; 12594 12595 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12596 Bundle extras = new Bundle(1); 12597 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12598 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12599 if (replacing) { 12600 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12601 } 12602 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12603 if (removedPackage != null) { 12604 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12605 extras, null, null, removedUsers); 12606 if (fullRemove && !replacing) { 12607 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12608 extras, null, null, removedUsers); 12609 } 12610 } 12611 if (removedAppId >= 0) { 12612 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12613 removedUsers); 12614 } 12615 } 12616 } 12617 12618 /* 12619 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12620 * flag is not set, the data directory is removed as well. 12621 * make sure this flag is set for partially installed apps. If not its meaningless to 12622 * delete a partially installed application. 12623 */ 12624 private void removePackageDataLI(PackageSetting ps, 12625 int[] allUserHandles, boolean[] perUserInstalled, 12626 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12627 String packageName = ps.name; 12628 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12629 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12630 // Retrieve object to delete permissions for shared user later on 12631 final PackageSetting deletedPs; 12632 // reader 12633 synchronized (mPackages) { 12634 deletedPs = mSettings.mPackages.get(packageName); 12635 if (outInfo != null) { 12636 outInfo.removedPackage = packageName; 12637 outInfo.removedUsers = deletedPs != null 12638 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12639 : null; 12640 } 12641 } 12642 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12643 removeDataDirsLI(ps.volumeUuid, packageName); 12644 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12645 } 12646 // writer 12647 synchronized (mPackages) { 12648 if (deletedPs != null) { 12649 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12650 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12651 clearDefaultBrowserIfNeeded(packageName); 12652 if (outInfo != null) { 12653 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12654 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12655 } 12656 updatePermissionsLPw(deletedPs.name, null, 0); 12657 if (deletedPs.sharedUser != null) { 12658 // Remove permissions associated with package. Since runtime 12659 // permissions are per user we have to kill the removed package 12660 // or packages running under the shared user of the removed 12661 // package if revoking the permissions requested only by the removed 12662 // package is successful and this causes a change in gids. 12663 for (int userId : UserManagerService.getInstance().getUserIds()) { 12664 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12665 userId); 12666 if (userIdToKill == UserHandle.USER_ALL 12667 || userIdToKill >= UserHandle.USER_OWNER) { 12668 // If gids changed for this user, kill all affected packages. 12669 mHandler.post(new Runnable() { 12670 @Override 12671 public void run() { 12672 // This has to happen with no lock held. 12673 killSettingPackagesForUser(deletedPs, userIdToKill, 12674 KILL_APP_REASON_GIDS_CHANGED); 12675 } 12676 }); 12677 break; 12678 } 12679 } 12680 } 12681 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12682 } 12683 // make sure to preserve per-user disabled state if this removal was just 12684 // a downgrade of a system app to the factory package 12685 if (allUserHandles != null && perUserInstalled != null) { 12686 if (DEBUG_REMOVE) { 12687 Slog.d(TAG, "Propagating install state across downgrade"); 12688 } 12689 for (int i = 0; i < allUserHandles.length; i++) { 12690 if (DEBUG_REMOVE) { 12691 Slog.d(TAG, " user " + allUserHandles[i] 12692 + " => " + perUserInstalled[i]); 12693 } 12694 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12695 } 12696 } 12697 } 12698 // can downgrade to reader 12699 if (writeSettings) { 12700 // Save settings now 12701 mSettings.writeLPr(); 12702 } 12703 } 12704 if (outInfo != null) { 12705 // A user ID was deleted here. Go through all users and remove it 12706 // from KeyStore. 12707 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12708 } 12709 } 12710 12711 static boolean locationIsPrivileged(File path) { 12712 try { 12713 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12714 .getCanonicalPath(); 12715 return path.getCanonicalPath().startsWith(privilegedAppDir); 12716 } catch (IOException e) { 12717 Slog.e(TAG, "Unable to access code path " + path); 12718 } 12719 return false; 12720 } 12721 12722 /* 12723 * Tries to delete system package. 12724 */ 12725 private boolean deleteSystemPackageLI(PackageSetting newPs, 12726 int[] allUserHandles, boolean[] perUserInstalled, 12727 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12728 final boolean applyUserRestrictions 12729 = (allUserHandles != null) && (perUserInstalled != null); 12730 PackageSetting disabledPs = null; 12731 // Confirm if the system package has been updated 12732 // An updated system app can be deleted. This will also have to restore 12733 // the system pkg from system partition 12734 // reader 12735 synchronized (mPackages) { 12736 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12737 } 12738 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12739 + " disabledPs=" + disabledPs); 12740 if (disabledPs == null) { 12741 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12742 return false; 12743 } else if (DEBUG_REMOVE) { 12744 Slog.d(TAG, "Deleting system pkg from data partition"); 12745 } 12746 if (DEBUG_REMOVE) { 12747 if (applyUserRestrictions) { 12748 Slog.d(TAG, "Remembering install states:"); 12749 for (int i = 0; i < allUserHandles.length; i++) { 12750 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12751 } 12752 } 12753 } 12754 // Delete the updated package 12755 outInfo.isRemovedPackageSystemUpdate = true; 12756 if (disabledPs.versionCode < newPs.versionCode) { 12757 // Delete data for downgrades 12758 flags &= ~PackageManager.DELETE_KEEP_DATA; 12759 } else { 12760 // Preserve data by setting flag 12761 flags |= PackageManager.DELETE_KEEP_DATA; 12762 } 12763 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12764 allUserHandles, perUserInstalled, outInfo, writeSettings); 12765 if (!ret) { 12766 return false; 12767 } 12768 // writer 12769 synchronized (mPackages) { 12770 // Reinstate the old system package 12771 mSettings.enableSystemPackageLPw(newPs.name); 12772 // Remove any native libraries from the upgraded package. 12773 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12774 } 12775 // Install the system package 12776 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12777 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12778 if (locationIsPrivileged(disabledPs.codePath)) { 12779 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12780 } 12781 12782 final PackageParser.Package newPkg; 12783 try { 12784 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12785 } catch (PackageManagerException e) { 12786 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12787 return false; 12788 } 12789 12790 // writer 12791 synchronized (mPackages) { 12792 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12793 12794 // Propagate the permissions state as we do want to drop on the floor 12795 // runtime permissions. The update permissions method below will take 12796 // care of removing obsolete permissions and grant install permissions. 12797 ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState()); 12798 updatePermissionsLPw(newPkg.packageName, newPkg, 12799 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12800 12801 if (applyUserRestrictions) { 12802 if (DEBUG_REMOVE) { 12803 Slog.d(TAG, "Propagating install state across reinstall"); 12804 } 12805 for (int i = 0; i < allUserHandles.length; i++) { 12806 if (DEBUG_REMOVE) { 12807 Slog.d(TAG, " user " + allUserHandles[i] 12808 + " => " + perUserInstalled[i]); 12809 } 12810 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12811 } 12812 // Regardless of writeSettings we need to ensure that this restriction 12813 // state propagation is persisted 12814 mSettings.writeAllUsersPackageRestrictionsLPr(); 12815 } 12816 // can downgrade to reader here 12817 if (writeSettings) { 12818 mSettings.writeLPr(); 12819 } 12820 } 12821 return true; 12822 } 12823 12824 private boolean deleteInstalledPackageLI(PackageSetting ps, 12825 boolean deleteCodeAndResources, int flags, 12826 int[] allUserHandles, boolean[] perUserInstalled, 12827 PackageRemovedInfo outInfo, boolean writeSettings) { 12828 if (outInfo != null) { 12829 outInfo.uid = ps.appId; 12830 } 12831 12832 // Delete package data from internal structures and also remove data if flag is set 12833 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12834 12835 // Delete application code and resources 12836 if (deleteCodeAndResources && (outInfo != null)) { 12837 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12838 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12839 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12840 } 12841 return true; 12842 } 12843 12844 @Override 12845 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12846 int userId) { 12847 mContext.enforceCallingOrSelfPermission( 12848 android.Manifest.permission.DELETE_PACKAGES, null); 12849 synchronized (mPackages) { 12850 PackageSetting ps = mSettings.mPackages.get(packageName); 12851 if (ps == null) { 12852 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12853 return false; 12854 } 12855 if (!ps.getInstalled(userId)) { 12856 // Can't block uninstall for an app that is not installed or enabled. 12857 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12858 return false; 12859 } 12860 ps.setBlockUninstall(blockUninstall, userId); 12861 mSettings.writePackageRestrictionsLPr(userId); 12862 } 12863 return true; 12864 } 12865 12866 @Override 12867 public boolean getBlockUninstallForUser(String packageName, int userId) { 12868 synchronized (mPackages) { 12869 PackageSetting ps = mSettings.mPackages.get(packageName); 12870 if (ps == null) { 12871 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12872 return false; 12873 } 12874 return ps.getBlockUninstall(userId); 12875 } 12876 } 12877 12878 /* 12879 * This method handles package deletion in general 12880 */ 12881 private boolean deletePackageLI(String packageName, UserHandle user, 12882 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12883 int flags, PackageRemovedInfo outInfo, 12884 boolean writeSettings) { 12885 if (packageName == null) { 12886 Slog.w(TAG, "Attempt to delete null packageName."); 12887 return false; 12888 } 12889 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12890 PackageSetting ps; 12891 boolean dataOnly = false; 12892 int removeUser = -1; 12893 int appId = -1; 12894 synchronized (mPackages) { 12895 ps = mSettings.mPackages.get(packageName); 12896 if (ps == null) { 12897 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12898 return false; 12899 } 12900 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12901 && user.getIdentifier() != UserHandle.USER_ALL) { 12902 // The caller is asking that the package only be deleted for a single 12903 // user. To do this, we just mark its uninstalled state and delete 12904 // its data. If this is a system app, we only allow this to happen if 12905 // they have set the special DELETE_SYSTEM_APP which requests different 12906 // semantics than normal for uninstalling system apps. 12907 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12908 ps.setUserState(user.getIdentifier(), 12909 COMPONENT_ENABLED_STATE_DEFAULT, 12910 false, //installed 12911 true, //stopped 12912 true, //notLaunched 12913 false, //hidden 12914 null, null, null, 12915 false, // blockUninstall 12916 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12917 if (!isSystemApp(ps)) { 12918 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12919 // Other user still have this package installed, so all 12920 // we need to do is clear this user's data and save that 12921 // it is uninstalled. 12922 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12923 removeUser = user.getIdentifier(); 12924 appId = ps.appId; 12925 scheduleWritePackageRestrictionsLocked(removeUser); 12926 } else { 12927 // We need to set it back to 'installed' so the uninstall 12928 // broadcasts will be sent correctly. 12929 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12930 ps.setInstalled(true, user.getIdentifier()); 12931 } 12932 } else { 12933 // This is a system app, so we assume that the 12934 // other users still have this package installed, so all 12935 // we need to do is clear this user's data and save that 12936 // it is uninstalled. 12937 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12938 removeUser = user.getIdentifier(); 12939 appId = ps.appId; 12940 scheduleWritePackageRestrictionsLocked(removeUser); 12941 } 12942 } 12943 } 12944 12945 if (removeUser >= 0) { 12946 // From above, we determined that we are deleting this only 12947 // for a single user. Continue the work here. 12948 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12949 if (outInfo != null) { 12950 outInfo.removedPackage = packageName; 12951 outInfo.removedAppId = appId; 12952 outInfo.removedUsers = new int[] {removeUser}; 12953 } 12954 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12955 removeKeystoreDataIfNeeded(removeUser, appId); 12956 schedulePackageCleaning(packageName, removeUser, false); 12957 synchronized (mPackages) { 12958 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12959 scheduleWritePackageRestrictionsLocked(removeUser); 12960 } 12961 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser); 12962 } 12963 return true; 12964 } 12965 12966 if (dataOnly) { 12967 // Delete application data first 12968 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12969 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12970 return true; 12971 } 12972 12973 boolean ret = false; 12974 if (isSystemApp(ps)) { 12975 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12976 // When an updated system application is deleted we delete the existing resources as well and 12977 // fall back to existing code in system partition 12978 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12979 flags, outInfo, writeSettings); 12980 } else { 12981 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12982 // Kill application pre-emptively especially for apps on sd. 12983 killApplication(packageName, ps.appId, "uninstall pkg"); 12984 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12985 allUserHandles, perUserInstalled, 12986 outInfo, writeSettings); 12987 } 12988 12989 return ret; 12990 } 12991 12992 private final class ClearStorageConnection implements ServiceConnection { 12993 IMediaContainerService mContainerService; 12994 12995 @Override 12996 public void onServiceConnected(ComponentName name, IBinder service) { 12997 synchronized (this) { 12998 mContainerService = IMediaContainerService.Stub.asInterface(service); 12999 notifyAll(); 13000 } 13001 } 13002 13003 @Override 13004 public void onServiceDisconnected(ComponentName name) { 13005 } 13006 } 13007 13008 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13009 final boolean mounted; 13010 if (Environment.isExternalStorageEmulated()) { 13011 mounted = true; 13012 } else { 13013 final String status = Environment.getExternalStorageState(); 13014 13015 mounted = status.equals(Environment.MEDIA_MOUNTED) 13016 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13017 } 13018 13019 if (!mounted) { 13020 return; 13021 } 13022 13023 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13024 int[] users; 13025 if (userId == UserHandle.USER_ALL) { 13026 users = sUserManager.getUserIds(); 13027 } else { 13028 users = new int[] { userId }; 13029 } 13030 final ClearStorageConnection conn = new ClearStorageConnection(); 13031 if (mContext.bindServiceAsUser( 13032 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13033 try { 13034 for (int curUser : users) { 13035 long timeout = SystemClock.uptimeMillis() + 5000; 13036 synchronized (conn) { 13037 long now = SystemClock.uptimeMillis(); 13038 while (conn.mContainerService == null && now < timeout) { 13039 try { 13040 conn.wait(timeout - now); 13041 } catch (InterruptedException e) { 13042 } 13043 } 13044 } 13045 if (conn.mContainerService == null) { 13046 return; 13047 } 13048 13049 final UserEnvironment userEnv = new UserEnvironment(curUser); 13050 clearDirectory(conn.mContainerService, 13051 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13052 if (allData) { 13053 clearDirectory(conn.mContainerService, 13054 userEnv.buildExternalStorageAppDataDirs(packageName)); 13055 clearDirectory(conn.mContainerService, 13056 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13057 } 13058 } 13059 } finally { 13060 mContext.unbindService(conn); 13061 } 13062 } 13063 } 13064 13065 @Override 13066 public void clearApplicationUserData(final String packageName, 13067 final IPackageDataObserver observer, final int userId) { 13068 mContext.enforceCallingOrSelfPermission( 13069 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13070 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13071 // Queue up an async operation since the package deletion may take a little while. 13072 mHandler.post(new Runnable() { 13073 public void run() { 13074 mHandler.removeCallbacks(this); 13075 final boolean succeeded; 13076 synchronized (mInstallLock) { 13077 succeeded = clearApplicationUserDataLI(packageName, userId); 13078 } 13079 clearExternalStorageDataSync(packageName, userId, true); 13080 if (succeeded) { 13081 // invoke DeviceStorageMonitor's update method to clear any notifications 13082 DeviceStorageMonitorInternal 13083 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13084 if (dsm != null) { 13085 dsm.checkMemory(); 13086 } 13087 } 13088 if(observer != null) { 13089 try { 13090 observer.onRemoveCompleted(packageName, succeeded); 13091 } catch (RemoteException e) { 13092 Log.i(TAG, "Observer no longer exists."); 13093 } 13094 } //end if observer 13095 } //end run 13096 }); 13097 } 13098 13099 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13100 if (packageName == null) { 13101 Slog.w(TAG, "Attempt to delete null packageName."); 13102 return false; 13103 } 13104 13105 // Try finding details about the requested package 13106 PackageParser.Package pkg; 13107 synchronized (mPackages) { 13108 pkg = mPackages.get(packageName); 13109 if (pkg == null) { 13110 final PackageSetting ps = mSettings.mPackages.get(packageName); 13111 if (ps != null) { 13112 pkg = ps.pkg; 13113 } 13114 } 13115 13116 if (pkg == null) { 13117 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13118 return false; 13119 } 13120 13121 PackageSetting ps = (PackageSetting) pkg.mExtras; 13122 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 13123 } 13124 13125 // Always delete data directories for package, even if we found no other 13126 // record of app. This helps users recover from UID mismatches without 13127 // resorting to a full data wipe. 13128 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13129 if (retCode < 0) { 13130 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13131 return false; 13132 } 13133 13134 final int appId = pkg.applicationInfo.uid; 13135 removeKeystoreDataIfNeeded(userId, appId); 13136 13137 // Create a native library symlink only if we have native libraries 13138 // and if the native libraries are 32 bit libraries. We do not provide 13139 // this symlink for 64 bit libraries. 13140 if (pkg.applicationInfo.primaryCpuAbi != null && 13141 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13142 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13143 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13144 nativeLibPath, userId) < 0) { 13145 Slog.w(TAG, "Failed linking native library dir"); 13146 return false; 13147 } 13148 } 13149 13150 return true; 13151 } 13152 13153 /** 13154 * Reverts user permission state changes (permissions and flags). 13155 * 13156 * @param ps The package for which to reset. 13157 * @param userId The device user for which to do a reset. 13158 */ 13159 private void resetUserChangesToRuntimePermissionsAndFlagsLocked( 13160 final PackageSetting ps, final int userId) { 13161 if (ps.pkg == null) { 13162 return; 13163 } 13164 13165 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13166 | FLAG_PERMISSION_USER_FIXED 13167 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13168 13169 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13170 | FLAG_PERMISSION_POLICY_FIXED; 13171 13172 boolean writeInstallPermissions = false; 13173 boolean writeRuntimePermissions = false; 13174 13175 final int permissionCount = ps.pkg.requestedPermissions.size(); 13176 for (int i = 0; i < permissionCount; i++) { 13177 String permission = ps.pkg.requestedPermissions.get(i); 13178 13179 BasePermission bp = mSettings.mPermissions.get(permission); 13180 if (bp == null) { 13181 continue; 13182 } 13183 13184 // If shared user we just reset the state to which only this app contributed. 13185 if (ps.sharedUser != null) { 13186 boolean used = false; 13187 final int packageCount = ps.sharedUser.packages.size(); 13188 for (int j = 0; j < packageCount; j++) { 13189 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13190 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13191 && pkg.pkg.requestedPermissions.contains(permission)) { 13192 used = true; 13193 break; 13194 } 13195 } 13196 if (used) { 13197 continue; 13198 } 13199 } 13200 13201 PermissionsState permissionsState = ps.getPermissionsState(); 13202 13203 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13204 13205 // Always clear the user settable flags. 13206 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13207 bp.name) != null; 13208 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13209 if (hasInstallState) { 13210 writeInstallPermissions = true; 13211 } else { 13212 writeRuntimePermissions = true; 13213 } 13214 } 13215 13216 // Below is only runtime permission handling. 13217 if (!bp.isRuntime()) { 13218 continue; 13219 } 13220 13221 // Never clobber system or policy. 13222 if ((oldFlags & policyOrSystemFlags) != 0) { 13223 continue; 13224 } 13225 13226 // If this permission was granted by default, make sure it is. 13227 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13228 if (permissionsState.grantRuntimePermission(bp, userId) 13229 != PERMISSION_OPERATION_FAILURE) { 13230 writeRuntimePermissions = true; 13231 } 13232 } else { 13233 // Otherwise, reset the permission. 13234 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13235 switch (revokeResult) { 13236 case PERMISSION_OPERATION_SUCCESS: { 13237 writeRuntimePermissions = true; 13238 } break; 13239 13240 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13241 writeRuntimePermissions = true; 13242 // If gids changed for this user, kill all affected packages. 13243 mHandler.post(new Runnable() { 13244 @Override 13245 public void run() { 13246 // This has to happen with no lock held. 13247 killSettingPackagesForUser(ps, userId, 13248 KILL_APP_REASON_GIDS_CHANGED); 13249 } 13250 }); 13251 } break; 13252 } 13253 } 13254 } 13255 13256 // Synchronously write as we are taking permissions away. 13257 if (writeRuntimePermissions) { 13258 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13259 } 13260 13261 // Synchronously write as we are taking permissions away. 13262 if (writeInstallPermissions) { 13263 mSettings.writeLPr(); 13264 } 13265 } 13266 13267 /** 13268 * Remove entries from the keystore daemon. Will only remove it if the 13269 * {@code appId} is valid. 13270 */ 13271 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13272 if (appId < 0) { 13273 return; 13274 } 13275 13276 final KeyStore keyStore = KeyStore.getInstance(); 13277 if (keyStore != null) { 13278 if (userId == UserHandle.USER_ALL) { 13279 for (final int individual : sUserManager.getUserIds()) { 13280 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13281 } 13282 } else { 13283 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13284 } 13285 } else { 13286 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13287 } 13288 } 13289 13290 @Override 13291 public void deleteApplicationCacheFiles(final String packageName, 13292 final IPackageDataObserver observer) { 13293 mContext.enforceCallingOrSelfPermission( 13294 android.Manifest.permission.DELETE_CACHE_FILES, null); 13295 // Queue up an async operation since the package deletion may take a little while. 13296 final int userId = UserHandle.getCallingUserId(); 13297 mHandler.post(new Runnable() { 13298 public void run() { 13299 mHandler.removeCallbacks(this); 13300 final boolean succeded; 13301 synchronized (mInstallLock) { 13302 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13303 } 13304 clearExternalStorageDataSync(packageName, userId, false); 13305 if (observer != null) { 13306 try { 13307 observer.onRemoveCompleted(packageName, succeded); 13308 } catch (RemoteException e) { 13309 Log.i(TAG, "Observer no longer exists."); 13310 } 13311 } //end if observer 13312 } //end run 13313 }); 13314 } 13315 13316 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13317 if (packageName == null) { 13318 Slog.w(TAG, "Attempt to delete null packageName."); 13319 return false; 13320 } 13321 PackageParser.Package p; 13322 synchronized (mPackages) { 13323 p = mPackages.get(packageName); 13324 } 13325 if (p == null) { 13326 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13327 return false; 13328 } 13329 final ApplicationInfo applicationInfo = p.applicationInfo; 13330 if (applicationInfo == null) { 13331 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13332 return false; 13333 } 13334 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13335 if (retCode < 0) { 13336 Slog.w(TAG, "Couldn't remove cache files for package: " 13337 + packageName + " u" + userId); 13338 return false; 13339 } 13340 return true; 13341 } 13342 13343 @Override 13344 public void getPackageSizeInfo(final String packageName, int userHandle, 13345 final IPackageStatsObserver observer) { 13346 mContext.enforceCallingOrSelfPermission( 13347 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13348 if (packageName == null) { 13349 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13350 } 13351 13352 PackageStats stats = new PackageStats(packageName, userHandle); 13353 13354 /* 13355 * Queue up an async operation since the package measurement may take a 13356 * little while. 13357 */ 13358 Message msg = mHandler.obtainMessage(INIT_COPY); 13359 msg.obj = new MeasureParams(stats, observer); 13360 mHandler.sendMessage(msg); 13361 } 13362 13363 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13364 PackageStats pStats) { 13365 if (packageName == null) { 13366 Slog.w(TAG, "Attempt to get size of null packageName."); 13367 return false; 13368 } 13369 PackageParser.Package p; 13370 boolean dataOnly = false; 13371 String libDirRoot = null; 13372 String asecPath = null; 13373 PackageSetting ps = null; 13374 synchronized (mPackages) { 13375 p = mPackages.get(packageName); 13376 ps = mSettings.mPackages.get(packageName); 13377 if(p == null) { 13378 dataOnly = true; 13379 if((ps == null) || (ps.pkg == null)) { 13380 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13381 return false; 13382 } 13383 p = ps.pkg; 13384 } 13385 if (ps != null) { 13386 libDirRoot = ps.legacyNativeLibraryPathString; 13387 } 13388 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13389 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13390 if (secureContainerId != null) { 13391 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13392 } 13393 } 13394 } 13395 String publicSrcDir = null; 13396 if(!dataOnly) { 13397 final ApplicationInfo applicationInfo = p.applicationInfo; 13398 if (applicationInfo == null) { 13399 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13400 return false; 13401 } 13402 if (p.isForwardLocked()) { 13403 publicSrcDir = applicationInfo.getBaseResourcePath(); 13404 } 13405 } 13406 // TODO: extend to measure size of split APKs 13407 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13408 // not just the first level. 13409 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13410 // just the primary. 13411 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13412 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13413 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13414 if (res < 0) { 13415 return false; 13416 } 13417 13418 // Fix-up for forward-locked applications in ASEC containers. 13419 if (!isExternal(p)) { 13420 pStats.codeSize += pStats.externalCodeSize; 13421 pStats.externalCodeSize = 0L; 13422 } 13423 13424 return true; 13425 } 13426 13427 13428 @Override 13429 public void addPackageToPreferred(String packageName) { 13430 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13431 } 13432 13433 @Override 13434 public void removePackageFromPreferred(String packageName) { 13435 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13436 } 13437 13438 @Override 13439 public List<PackageInfo> getPreferredPackages(int flags) { 13440 return new ArrayList<PackageInfo>(); 13441 } 13442 13443 private int getUidTargetSdkVersionLockedLPr(int uid) { 13444 Object obj = mSettings.getUserIdLPr(uid); 13445 if (obj instanceof SharedUserSetting) { 13446 final SharedUserSetting sus = (SharedUserSetting) obj; 13447 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13448 final Iterator<PackageSetting> it = sus.packages.iterator(); 13449 while (it.hasNext()) { 13450 final PackageSetting ps = it.next(); 13451 if (ps.pkg != null) { 13452 int v = ps.pkg.applicationInfo.targetSdkVersion; 13453 if (v < vers) vers = v; 13454 } 13455 } 13456 return vers; 13457 } else if (obj instanceof PackageSetting) { 13458 final PackageSetting ps = (PackageSetting) obj; 13459 if (ps.pkg != null) { 13460 return ps.pkg.applicationInfo.targetSdkVersion; 13461 } 13462 } 13463 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13464 } 13465 13466 @Override 13467 public void addPreferredActivity(IntentFilter filter, int match, 13468 ComponentName[] set, ComponentName activity, int userId) { 13469 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13470 "Adding preferred"); 13471 } 13472 13473 private void addPreferredActivityInternal(IntentFilter filter, int match, 13474 ComponentName[] set, ComponentName activity, boolean always, int userId, 13475 String opname) { 13476 // writer 13477 int callingUid = Binder.getCallingUid(); 13478 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13479 if (filter.countActions() == 0) { 13480 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13481 return; 13482 } 13483 synchronized (mPackages) { 13484 if (mContext.checkCallingOrSelfPermission( 13485 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13486 != PackageManager.PERMISSION_GRANTED) { 13487 if (getUidTargetSdkVersionLockedLPr(callingUid) 13488 < Build.VERSION_CODES.FROYO) { 13489 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13490 + callingUid); 13491 return; 13492 } 13493 mContext.enforceCallingOrSelfPermission( 13494 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13495 } 13496 13497 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13498 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13499 + userId + ":"); 13500 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13501 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13502 scheduleWritePackageRestrictionsLocked(userId); 13503 } 13504 } 13505 13506 @Override 13507 public void replacePreferredActivity(IntentFilter filter, int match, 13508 ComponentName[] set, ComponentName activity, int userId) { 13509 if (filter.countActions() != 1) { 13510 throw new IllegalArgumentException( 13511 "replacePreferredActivity expects filter to have only 1 action."); 13512 } 13513 if (filter.countDataAuthorities() != 0 13514 || filter.countDataPaths() != 0 13515 || filter.countDataSchemes() > 1 13516 || filter.countDataTypes() != 0) { 13517 throw new IllegalArgumentException( 13518 "replacePreferredActivity expects filter to have no data authorities, " + 13519 "paths, or types; and at most one scheme."); 13520 } 13521 13522 final int callingUid = Binder.getCallingUid(); 13523 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13524 synchronized (mPackages) { 13525 if (mContext.checkCallingOrSelfPermission( 13526 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13527 != PackageManager.PERMISSION_GRANTED) { 13528 if (getUidTargetSdkVersionLockedLPr(callingUid) 13529 < Build.VERSION_CODES.FROYO) { 13530 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13531 + Binder.getCallingUid()); 13532 return; 13533 } 13534 mContext.enforceCallingOrSelfPermission( 13535 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13536 } 13537 13538 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13539 if (pir != null) { 13540 // Get all of the existing entries that exactly match this filter. 13541 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13542 if (existing != null && existing.size() == 1) { 13543 PreferredActivity cur = existing.get(0); 13544 if (DEBUG_PREFERRED) { 13545 Slog.i(TAG, "Checking replace of preferred:"); 13546 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13547 if (!cur.mPref.mAlways) { 13548 Slog.i(TAG, " -- CUR; not mAlways!"); 13549 } else { 13550 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13551 Slog.i(TAG, " -- CUR: mSet=" 13552 + Arrays.toString(cur.mPref.mSetComponents)); 13553 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13554 Slog.i(TAG, " -- NEW: mMatch=" 13555 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13556 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13557 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13558 } 13559 } 13560 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13561 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13562 && cur.mPref.sameSet(set)) { 13563 // Setting the preferred activity to what it happens to be already 13564 if (DEBUG_PREFERRED) { 13565 Slog.i(TAG, "Replacing with same preferred activity " 13566 + cur.mPref.mShortComponent + " for user " 13567 + userId + ":"); 13568 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13569 } 13570 return; 13571 } 13572 } 13573 13574 if (existing != null) { 13575 if (DEBUG_PREFERRED) { 13576 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13577 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13578 } 13579 for (int i = 0; i < existing.size(); i++) { 13580 PreferredActivity pa = existing.get(i); 13581 if (DEBUG_PREFERRED) { 13582 Slog.i(TAG, "Removing existing preferred activity " 13583 + pa.mPref.mComponent + ":"); 13584 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13585 } 13586 pir.removeFilter(pa); 13587 } 13588 } 13589 } 13590 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13591 "Replacing preferred"); 13592 } 13593 } 13594 13595 @Override 13596 public void clearPackagePreferredActivities(String packageName) { 13597 final int uid = Binder.getCallingUid(); 13598 // writer 13599 synchronized (mPackages) { 13600 PackageParser.Package pkg = mPackages.get(packageName); 13601 if (pkg == null || pkg.applicationInfo.uid != uid) { 13602 if (mContext.checkCallingOrSelfPermission( 13603 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13604 != PackageManager.PERMISSION_GRANTED) { 13605 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13606 < Build.VERSION_CODES.FROYO) { 13607 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13608 + Binder.getCallingUid()); 13609 return; 13610 } 13611 mContext.enforceCallingOrSelfPermission( 13612 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13613 } 13614 } 13615 13616 int user = UserHandle.getCallingUserId(); 13617 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13618 scheduleWritePackageRestrictionsLocked(user); 13619 } 13620 } 13621 } 13622 13623 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13624 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13625 ArrayList<PreferredActivity> removed = null; 13626 boolean changed = false; 13627 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13628 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13629 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13630 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13631 continue; 13632 } 13633 Iterator<PreferredActivity> it = pir.filterIterator(); 13634 while (it.hasNext()) { 13635 PreferredActivity pa = it.next(); 13636 // Mark entry for removal only if it matches the package name 13637 // and the entry is of type "always". 13638 if (packageName == null || 13639 (pa.mPref.mComponent.getPackageName().equals(packageName) 13640 && pa.mPref.mAlways)) { 13641 if (removed == null) { 13642 removed = new ArrayList<PreferredActivity>(); 13643 } 13644 removed.add(pa); 13645 } 13646 } 13647 if (removed != null) { 13648 for (int j=0; j<removed.size(); j++) { 13649 PreferredActivity pa = removed.get(j); 13650 pir.removeFilter(pa); 13651 } 13652 changed = true; 13653 } 13654 } 13655 return changed; 13656 } 13657 13658 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13659 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13660 if (userId == UserHandle.USER_ALL) { 13661 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13662 sUserManager.getUserIds())) { 13663 for (int oneUserId : sUserManager.getUserIds()) { 13664 scheduleWritePackageRestrictionsLocked(oneUserId); 13665 } 13666 } 13667 } else { 13668 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13669 scheduleWritePackageRestrictionsLocked(userId); 13670 } 13671 } 13672 } 13673 13674 13675 void clearDefaultBrowserIfNeeded(String packageName) { 13676 for (int oneUserId : sUserManager.getUserIds()) { 13677 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13678 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13679 if (packageName.equals(defaultBrowserPackageName)) { 13680 setDefaultBrowserPackageName(null, oneUserId); 13681 } 13682 } 13683 } 13684 13685 @Override 13686 public void resetPreferredActivities(int userId) { 13687 mContext.enforceCallingOrSelfPermission( 13688 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13689 // writer 13690 synchronized (mPackages) { 13691 clearPackagePreferredActivitiesLPw(null, userId); 13692 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13693 applyFactoryDefaultBrowserLPw(userId); 13694 13695 scheduleWritePackageRestrictionsLocked(userId); 13696 } 13697 } 13698 13699 @Override 13700 public int getPreferredActivities(List<IntentFilter> outFilters, 13701 List<ComponentName> outActivities, String packageName) { 13702 13703 int num = 0; 13704 final int userId = UserHandle.getCallingUserId(); 13705 // reader 13706 synchronized (mPackages) { 13707 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13708 if (pir != null) { 13709 final Iterator<PreferredActivity> it = pir.filterIterator(); 13710 while (it.hasNext()) { 13711 final PreferredActivity pa = it.next(); 13712 if (packageName == null 13713 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13714 && pa.mPref.mAlways)) { 13715 if (outFilters != null) { 13716 outFilters.add(new IntentFilter(pa)); 13717 } 13718 if (outActivities != null) { 13719 outActivities.add(pa.mPref.mComponent); 13720 } 13721 } 13722 } 13723 } 13724 } 13725 13726 return num; 13727 } 13728 13729 @Override 13730 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13731 int userId) { 13732 int callingUid = Binder.getCallingUid(); 13733 if (callingUid != Process.SYSTEM_UID) { 13734 throw new SecurityException( 13735 "addPersistentPreferredActivity can only be run by the system"); 13736 } 13737 if (filter.countActions() == 0) { 13738 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13739 return; 13740 } 13741 synchronized (mPackages) { 13742 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13743 " :"); 13744 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13745 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13746 new PersistentPreferredActivity(filter, activity)); 13747 scheduleWritePackageRestrictionsLocked(userId); 13748 } 13749 } 13750 13751 @Override 13752 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13753 int callingUid = Binder.getCallingUid(); 13754 if (callingUid != Process.SYSTEM_UID) { 13755 throw new SecurityException( 13756 "clearPackagePersistentPreferredActivities can only be run by the system"); 13757 } 13758 ArrayList<PersistentPreferredActivity> removed = null; 13759 boolean changed = false; 13760 synchronized (mPackages) { 13761 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13762 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13763 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13764 .valueAt(i); 13765 if (userId != thisUserId) { 13766 continue; 13767 } 13768 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13769 while (it.hasNext()) { 13770 PersistentPreferredActivity ppa = it.next(); 13771 // Mark entry for removal only if it matches the package name. 13772 if (ppa.mComponent.getPackageName().equals(packageName)) { 13773 if (removed == null) { 13774 removed = new ArrayList<PersistentPreferredActivity>(); 13775 } 13776 removed.add(ppa); 13777 } 13778 } 13779 if (removed != null) { 13780 for (int j=0; j<removed.size(); j++) { 13781 PersistentPreferredActivity ppa = removed.get(j); 13782 ppir.removeFilter(ppa); 13783 } 13784 changed = true; 13785 } 13786 } 13787 13788 if (changed) { 13789 scheduleWritePackageRestrictionsLocked(userId); 13790 } 13791 } 13792 } 13793 13794 /** 13795 * Common machinery for picking apart a restored XML blob and passing 13796 * it to a caller-supplied functor to be applied to the running system. 13797 */ 13798 private void restoreFromXml(XmlPullParser parser, int userId, 13799 String expectedStartTag, BlobXmlRestorer functor) 13800 throws IOException, XmlPullParserException { 13801 int type; 13802 while ((type = parser.next()) != XmlPullParser.START_TAG 13803 && type != XmlPullParser.END_DOCUMENT) { 13804 } 13805 if (type != XmlPullParser.START_TAG) { 13806 // oops didn't find a start tag?! 13807 if (DEBUG_BACKUP) { 13808 Slog.e(TAG, "Didn't find start tag during restore"); 13809 } 13810 return; 13811 } 13812 13813 // this is supposed to be TAG_PREFERRED_BACKUP 13814 if (!expectedStartTag.equals(parser.getName())) { 13815 if (DEBUG_BACKUP) { 13816 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13817 } 13818 return; 13819 } 13820 13821 // skip interfering stuff, then we're aligned with the backing implementation 13822 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13823 functor.apply(parser, userId); 13824 } 13825 13826 private interface BlobXmlRestorer { 13827 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13828 } 13829 13830 /** 13831 * Non-Binder method, support for the backup/restore mechanism: write the 13832 * full set of preferred activities in its canonical XML format. Returns the 13833 * XML output as a byte array, or null if there is none. 13834 */ 13835 @Override 13836 public byte[] getPreferredActivityBackup(int userId) { 13837 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13838 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13839 } 13840 13841 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13842 try { 13843 final XmlSerializer serializer = new FastXmlSerializer(); 13844 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13845 serializer.startDocument(null, true); 13846 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13847 13848 synchronized (mPackages) { 13849 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13850 } 13851 13852 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13853 serializer.endDocument(); 13854 serializer.flush(); 13855 } catch (Exception e) { 13856 if (DEBUG_BACKUP) { 13857 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13858 } 13859 return null; 13860 } 13861 13862 return dataStream.toByteArray(); 13863 } 13864 13865 @Override 13866 public void restorePreferredActivities(byte[] backup, int userId) { 13867 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13868 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13869 } 13870 13871 try { 13872 final XmlPullParser parser = Xml.newPullParser(); 13873 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13874 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13875 new BlobXmlRestorer() { 13876 @Override 13877 public void apply(XmlPullParser parser, int userId) 13878 throws XmlPullParserException, IOException { 13879 synchronized (mPackages) { 13880 mSettings.readPreferredActivitiesLPw(parser, userId); 13881 } 13882 } 13883 } ); 13884 } catch (Exception e) { 13885 if (DEBUG_BACKUP) { 13886 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13887 } 13888 } 13889 } 13890 13891 /** 13892 * Non-Binder method, support for the backup/restore mechanism: write the 13893 * default browser (etc) settings in its canonical XML format. Returns the default 13894 * browser XML representation as a byte array, or null if there is none. 13895 */ 13896 @Override 13897 public byte[] getDefaultAppsBackup(int userId) { 13898 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13899 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13900 } 13901 13902 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13903 try { 13904 final XmlSerializer serializer = new FastXmlSerializer(); 13905 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13906 serializer.startDocument(null, true); 13907 serializer.startTag(null, TAG_DEFAULT_APPS); 13908 13909 synchronized (mPackages) { 13910 mSettings.writeDefaultAppsLPr(serializer, userId); 13911 } 13912 13913 serializer.endTag(null, TAG_DEFAULT_APPS); 13914 serializer.endDocument(); 13915 serializer.flush(); 13916 } catch (Exception e) { 13917 if (DEBUG_BACKUP) { 13918 Slog.e(TAG, "Unable to write default apps for backup", e); 13919 } 13920 return null; 13921 } 13922 13923 return dataStream.toByteArray(); 13924 } 13925 13926 @Override 13927 public void restoreDefaultApps(byte[] backup, int userId) { 13928 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13929 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13930 } 13931 13932 try { 13933 final XmlPullParser parser = Xml.newPullParser(); 13934 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13935 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13936 new BlobXmlRestorer() { 13937 @Override 13938 public void apply(XmlPullParser parser, int userId) 13939 throws XmlPullParserException, IOException { 13940 synchronized (mPackages) { 13941 mSettings.readDefaultAppsLPw(parser, userId); 13942 } 13943 } 13944 } ); 13945 } catch (Exception e) { 13946 if (DEBUG_BACKUP) { 13947 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13948 } 13949 } 13950 } 13951 13952 @Override 13953 public byte[] getIntentFilterVerificationBackup(int userId) { 13954 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13955 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13956 } 13957 13958 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13959 try { 13960 final XmlSerializer serializer = new FastXmlSerializer(); 13961 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13962 serializer.startDocument(null, true); 13963 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13964 13965 synchronized (mPackages) { 13966 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13967 } 13968 13969 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13970 serializer.endDocument(); 13971 serializer.flush(); 13972 } catch (Exception e) { 13973 if (DEBUG_BACKUP) { 13974 Slog.e(TAG, "Unable to write default apps for backup", e); 13975 } 13976 return null; 13977 } 13978 13979 return dataStream.toByteArray(); 13980 } 13981 13982 @Override 13983 public void restoreIntentFilterVerification(byte[] backup, int userId) { 13984 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13985 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13986 } 13987 13988 try { 13989 final XmlPullParser parser = Xml.newPullParser(); 13990 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13991 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 13992 new BlobXmlRestorer() { 13993 @Override 13994 public void apply(XmlPullParser parser, int userId) 13995 throws XmlPullParserException, IOException { 13996 synchronized (mPackages) { 13997 mSettings.readAllDomainVerificationsLPr(parser, userId); 13998 mSettings.writeLPr(); 13999 } 14000 } 14001 } ); 14002 } catch (Exception e) { 14003 if (DEBUG_BACKUP) { 14004 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14005 } 14006 } 14007 } 14008 14009 @Override 14010 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14011 int sourceUserId, int targetUserId, int flags) { 14012 mContext.enforceCallingOrSelfPermission( 14013 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14014 int callingUid = Binder.getCallingUid(); 14015 enforceOwnerRights(ownerPackage, callingUid); 14016 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14017 if (intentFilter.countActions() == 0) { 14018 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14019 return; 14020 } 14021 synchronized (mPackages) { 14022 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14023 ownerPackage, targetUserId, flags); 14024 CrossProfileIntentResolver resolver = 14025 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14026 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14027 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14028 if (existing != null) { 14029 int size = existing.size(); 14030 for (int i = 0; i < size; i++) { 14031 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14032 return; 14033 } 14034 } 14035 } 14036 resolver.addFilter(newFilter); 14037 scheduleWritePackageRestrictionsLocked(sourceUserId); 14038 } 14039 } 14040 14041 @Override 14042 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14043 mContext.enforceCallingOrSelfPermission( 14044 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14045 int callingUid = Binder.getCallingUid(); 14046 enforceOwnerRights(ownerPackage, callingUid); 14047 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14048 synchronized (mPackages) { 14049 CrossProfileIntentResolver resolver = 14050 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14051 ArraySet<CrossProfileIntentFilter> set = 14052 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14053 for (CrossProfileIntentFilter filter : set) { 14054 if (filter.getOwnerPackage().equals(ownerPackage)) { 14055 resolver.removeFilter(filter); 14056 } 14057 } 14058 scheduleWritePackageRestrictionsLocked(sourceUserId); 14059 } 14060 } 14061 14062 // Enforcing that callingUid is owning pkg on userId 14063 private void enforceOwnerRights(String pkg, int callingUid) { 14064 // The system owns everything. 14065 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14066 return; 14067 } 14068 int callingUserId = UserHandle.getUserId(callingUid); 14069 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14070 if (pi == null) { 14071 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14072 + callingUserId); 14073 } 14074 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14075 throw new SecurityException("Calling uid " + callingUid 14076 + " does not own package " + pkg); 14077 } 14078 } 14079 14080 @Override 14081 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14082 Intent intent = new Intent(Intent.ACTION_MAIN); 14083 intent.addCategory(Intent.CATEGORY_HOME); 14084 14085 final int callingUserId = UserHandle.getCallingUserId(); 14086 List<ResolveInfo> list = queryIntentActivities(intent, null, 14087 PackageManager.GET_META_DATA, callingUserId); 14088 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14089 true, false, false, callingUserId); 14090 14091 allHomeCandidates.clear(); 14092 if (list != null) { 14093 for (ResolveInfo ri : list) { 14094 allHomeCandidates.add(ri); 14095 } 14096 } 14097 return (preferred == null || preferred.activityInfo == null) 14098 ? null 14099 : new ComponentName(preferred.activityInfo.packageName, 14100 preferred.activityInfo.name); 14101 } 14102 14103 @Override 14104 public void setApplicationEnabledSetting(String appPackageName, 14105 int newState, int flags, int userId, String callingPackage) { 14106 if (!sUserManager.exists(userId)) return; 14107 if (callingPackage == null) { 14108 callingPackage = Integer.toString(Binder.getCallingUid()); 14109 } 14110 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14111 } 14112 14113 @Override 14114 public void setComponentEnabledSetting(ComponentName componentName, 14115 int newState, int flags, int userId) { 14116 if (!sUserManager.exists(userId)) return; 14117 setEnabledSetting(componentName.getPackageName(), 14118 componentName.getClassName(), newState, flags, userId, null); 14119 } 14120 14121 private void setEnabledSetting(final String packageName, String className, int newState, 14122 final int flags, int userId, String callingPackage) { 14123 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14124 || newState == COMPONENT_ENABLED_STATE_ENABLED 14125 || newState == COMPONENT_ENABLED_STATE_DISABLED 14126 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14127 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14128 throw new IllegalArgumentException("Invalid new component state: " 14129 + newState); 14130 } 14131 PackageSetting pkgSetting; 14132 final int uid = Binder.getCallingUid(); 14133 final int permission = mContext.checkCallingOrSelfPermission( 14134 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14135 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14136 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14137 boolean sendNow = false; 14138 boolean isApp = (className == null); 14139 String componentName = isApp ? packageName : className; 14140 int packageUid = -1; 14141 ArrayList<String> components; 14142 14143 // writer 14144 synchronized (mPackages) { 14145 pkgSetting = mSettings.mPackages.get(packageName); 14146 if (pkgSetting == null) { 14147 if (className == null) { 14148 throw new IllegalArgumentException( 14149 "Unknown package: " + packageName); 14150 } 14151 throw new IllegalArgumentException( 14152 "Unknown component: " + packageName 14153 + "/" + className); 14154 } 14155 // Allow root and verify that userId is not being specified by a different user 14156 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14157 throw new SecurityException( 14158 "Permission Denial: attempt to change component state from pid=" 14159 + Binder.getCallingPid() 14160 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14161 } 14162 if (className == null) { 14163 // We're dealing with an application/package level state change 14164 if (pkgSetting.getEnabled(userId) == newState) { 14165 // Nothing to do 14166 return; 14167 } 14168 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14169 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14170 // Don't care about who enables an app. 14171 callingPackage = null; 14172 } 14173 pkgSetting.setEnabled(newState, userId, callingPackage); 14174 // pkgSetting.pkg.mSetEnabled = newState; 14175 } else { 14176 // We're dealing with a component level state change 14177 // First, verify that this is a valid class name. 14178 PackageParser.Package pkg = pkgSetting.pkg; 14179 if (pkg == null || !pkg.hasComponentClassName(className)) { 14180 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14181 throw new IllegalArgumentException("Component class " + className 14182 + " does not exist in " + packageName); 14183 } else { 14184 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14185 + className + " does not exist in " + packageName); 14186 } 14187 } 14188 switch (newState) { 14189 case COMPONENT_ENABLED_STATE_ENABLED: 14190 if (!pkgSetting.enableComponentLPw(className, userId)) { 14191 return; 14192 } 14193 break; 14194 case COMPONENT_ENABLED_STATE_DISABLED: 14195 if (!pkgSetting.disableComponentLPw(className, userId)) { 14196 return; 14197 } 14198 break; 14199 case COMPONENT_ENABLED_STATE_DEFAULT: 14200 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14201 return; 14202 } 14203 break; 14204 default: 14205 Slog.e(TAG, "Invalid new component state: " + newState); 14206 return; 14207 } 14208 } 14209 scheduleWritePackageRestrictionsLocked(userId); 14210 components = mPendingBroadcasts.get(userId, packageName); 14211 final boolean newPackage = components == null; 14212 if (newPackage) { 14213 components = new ArrayList<String>(); 14214 } 14215 if (!components.contains(componentName)) { 14216 components.add(componentName); 14217 } 14218 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14219 sendNow = true; 14220 // Purge entry from pending broadcast list if another one exists already 14221 // since we are sending one right away. 14222 mPendingBroadcasts.remove(userId, packageName); 14223 } else { 14224 if (newPackage) { 14225 mPendingBroadcasts.put(userId, packageName, components); 14226 } 14227 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14228 // Schedule a message 14229 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14230 } 14231 } 14232 } 14233 14234 long callingId = Binder.clearCallingIdentity(); 14235 try { 14236 if (sendNow) { 14237 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14238 sendPackageChangedBroadcast(packageName, 14239 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14240 } 14241 } finally { 14242 Binder.restoreCallingIdentity(callingId); 14243 } 14244 } 14245 14246 private void sendPackageChangedBroadcast(String packageName, 14247 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14248 if (DEBUG_INSTALL) 14249 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14250 + componentNames); 14251 Bundle extras = new Bundle(4); 14252 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14253 String nameList[] = new String[componentNames.size()]; 14254 componentNames.toArray(nameList); 14255 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14256 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14257 extras.putInt(Intent.EXTRA_UID, packageUid); 14258 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14259 new int[] {UserHandle.getUserId(packageUid)}); 14260 } 14261 14262 @Override 14263 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14264 if (!sUserManager.exists(userId)) return; 14265 final int uid = Binder.getCallingUid(); 14266 final int permission = mContext.checkCallingOrSelfPermission( 14267 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14268 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14269 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14270 // writer 14271 synchronized (mPackages) { 14272 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14273 allowedByPermission, uid, userId)) { 14274 scheduleWritePackageRestrictionsLocked(userId); 14275 } 14276 } 14277 } 14278 14279 @Override 14280 public String getInstallerPackageName(String packageName) { 14281 // reader 14282 synchronized (mPackages) { 14283 return mSettings.getInstallerPackageNameLPr(packageName); 14284 } 14285 } 14286 14287 @Override 14288 public int getApplicationEnabledSetting(String packageName, int userId) { 14289 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14290 int uid = Binder.getCallingUid(); 14291 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14292 // reader 14293 synchronized (mPackages) { 14294 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14295 } 14296 } 14297 14298 @Override 14299 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14300 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14301 int uid = Binder.getCallingUid(); 14302 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14303 // reader 14304 synchronized (mPackages) { 14305 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14306 } 14307 } 14308 14309 @Override 14310 public void enterSafeMode() { 14311 enforceSystemOrRoot("Only the system can request entering safe mode"); 14312 14313 if (!mSystemReady) { 14314 mSafeMode = true; 14315 } 14316 } 14317 14318 @Override 14319 public void systemReady() { 14320 mSystemReady = true; 14321 14322 // Read the compatibilty setting when the system is ready. 14323 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14324 mContext.getContentResolver(), 14325 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14326 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14327 if (DEBUG_SETTINGS) { 14328 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14329 } 14330 14331 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14332 14333 synchronized (mPackages) { 14334 // Verify that all of the preferred activity components actually 14335 // exist. It is possible for applications to be updated and at 14336 // that point remove a previously declared activity component that 14337 // had been set as a preferred activity. We try to clean this up 14338 // the next time we encounter that preferred activity, but it is 14339 // possible for the user flow to never be able to return to that 14340 // situation so here we do a sanity check to make sure we haven't 14341 // left any junk around. 14342 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14343 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14344 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14345 removed.clear(); 14346 for (PreferredActivity pa : pir.filterSet()) { 14347 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14348 removed.add(pa); 14349 } 14350 } 14351 if (removed.size() > 0) { 14352 for (int r=0; r<removed.size(); r++) { 14353 PreferredActivity pa = removed.get(r); 14354 Slog.w(TAG, "Removing dangling preferred activity: " 14355 + pa.mPref.mComponent); 14356 pir.removeFilter(pa); 14357 } 14358 mSettings.writePackageRestrictionsLPr( 14359 mSettings.mPreferredActivities.keyAt(i)); 14360 } 14361 } 14362 14363 for (int userId : UserManagerService.getInstance().getUserIds()) { 14364 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14365 grantPermissionsUserIds = ArrayUtils.appendInt( 14366 grantPermissionsUserIds, userId); 14367 } 14368 } 14369 } 14370 sUserManager.systemReady(); 14371 14372 // If we upgraded grant all default permissions before kicking off. 14373 for (int userId : grantPermissionsUserIds) { 14374 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14375 } 14376 14377 // Kick off any messages waiting for system ready 14378 if (mPostSystemReadyMessages != null) { 14379 for (Message msg : mPostSystemReadyMessages) { 14380 msg.sendToTarget(); 14381 } 14382 mPostSystemReadyMessages = null; 14383 } 14384 14385 // Watch for external volumes that come and go over time 14386 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14387 storage.registerListener(mStorageListener); 14388 14389 mInstallerService.systemReady(); 14390 mPackageDexOptimizer.systemReady(); 14391 } 14392 14393 @Override 14394 public boolean isSafeMode() { 14395 return mSafeMode; 14396 } 14397 14398 @Override 14399 public boolean hasSystemUidErrors() { 14400 return mHasSystemUidErrors; 14401 } 14402 14403 static String arrayToString(int[] array) { 14404 StringBuffer buf = new StringBuffer(128); 14405 buf.append('['); 14406 if (array != null) { 14407 for (int i=0; i<array.length; i++) { 14408 if (i > 0) buf.append(", "); 14409 buf.append(array[i]); 14410 } 14411 } 14412 buf.append(']'); 14413 return buf.toString(); 14414 } 14415 14416 static class DumpState { 14417 public static final int DUMP_LIBS = 1 << 0; 14418 public static final int DUMP_FEATURES = 1 << 1; 14419 public static final int DUMP_RESOLVERS = 1 << 2; 14420 public static final int DUMP_PERMISSIONS = 1 << 3; 14421 public static final int DUMP_PACKAGES = 1 << 4; 14422 public static final int DUMP_SHARED_USERS = 1 << 5; 14423 public static final int DUMP_MESSAGES = 1 << 6; 14424 public static final int DUMP_PROVIDERS = 1 << 7; 14425 public static final int DUMP_VERIFIERS = 1 << 8; 14426 public static final int DUMP_PREFERRED = 1 << 9; 14427 public static final int DUMP_PREFERRED_XML = 1 << 10; 14428 public static final int DUMP_KEYSETS = 1 << 11; 14429 public static final int DUMP_VERSION = 1 << 12; 14430 public static final int DUMP_INSTALLS = 1 << 13; 14431 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14432 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14433 14434 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14435 14436 private int mTypes; 14437 14438 private int mOptions; 14439 14440 private boolean mTitlePrinted; 14441 14442 private SharedUserSetting mSharedUser; 14443 14444 public boolean isDumping(int type) { 14445 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14446 return true; 14447 } 14448 14449 return (mTypes & type) != 0; 14450 } 14451 14452 public void setDump(int type) { 14453 mTypes |= type; 14454 } 14455 14456 public boolean isOptionEnabled(int option) { 14457 return (mOptions & option) != 0; 14458 } 14459 14460 public void setOptionEnabled(int option) { 14461 mOptions |= option; 14462 } 14463 14464 public boolean onTitlePrinted() { 14465 final boolean printed = mTitlePrinted; 14466 mTitlePrinted = true; 14467 return printed; 14468 } 14469 14470 public boolean getTitlePrinted() { 14471 return mTitlePrinted; 14472 } 14473 14474 public void setTitlePrinted(boolean enabled) { 14475 mTitlePrinted = enabled; 14476 } 14477 14478 public SharedUserSetting getSharedUser() { 14479 return mSharedUser; 14480 } 14481 14482 public void setSharedUser(SharedUserSetting user) { 14483 mSharedUser = user; 14484 } 14485 } 14486 14487 @Override 14488 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14489 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14490 != PackageManager.PERMISSION_GRANTED) { 14491 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14492 + Binder.getCallingPid() 14493 + ", uid=" + Binder.getCallingUid() 14494 + " without permission " 14495 + android.Manifest.permission.DUMP); 14496 return; 14497 } 14498 14499 DumpState dumpState = new DumpState(); 14500 boolean fullPreferred = false; 14501 boolean checkin = false; 14502 14503 String packageName = null; 14504 ArraySet<String> permissionNames = null; 14505 14506 int opti = 0; 14507 while (opti < args.length) { 14508 String opt = args[opti]; 14509 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14510 break; 14511 } 14512 opti++; 14513 14514 if ("-a".equals(opt)) { 14515 // Right now we only know how to print all. 14516 } else if ("-h".equals(opt)) { 14517 pw.println("Package manager dump options:"); 14518 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14519 pw.println(" --checkin: dump for a checkin"); 14520 pw.println(" -f: print details of intent filters"); 14521 pw.println(" -h: print this help"); 14522 pw.println(" cmd may be one of:"); 14523 pw.println(" l[ibraries]: list known shared libraries"); 14524 pw.println(" f[ibraries]: list device features"); 14525 pw.println(" k[eysets]: print known keysets"); 14526 pw.println(" r[esolvers]: dump intent resolvers"); 14527 pw.println(" perm[issions]: dump permissions"); 14528 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14529 pw.println(" pref[erred]: print preferred package settings"); 14530 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14531 pw.println(" prov[iders]: dump content providers"); 14532 pw.println(" p[ackages]: dump installed packages"); 14533 pw.println(" s[hared-users]: dump shared user IDs"); 14534 pw.println(" m[essages]: print collected runtime messages"); 14535 pw.println(" v[erifiers]: print package verifier info"); 14536 pw.println(" version: print database version info"); 14537 pw.println(" write: write current settings now"); 14538 pw.println(" <package.name>: info about given package"); 14539 pw.println(" installs: details about install sessions"); 14540 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14541 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14542 return; 14543 } else if ("--checkin".equals(opt)) { 14544 checkin = true; 14545 } else if ("-f".equals(opt)) { 14546 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14547 } else { 14548 pw.println("Unknown argument: " + opt + "; use -h for help"); 14549 } 14550 } 14551 14552 // Is the caller requesting to dump a particular piece of data? 14553 if (opti < args.length) { 14554 String cmd = args[opti]; 14555 opti++; 14556 // Is this a package name? 14557 if ("android".equals(cmd) || cmd.contains(".")) { 14558 packageName = cmd; 14559 // When dumping a single package, we always dump all of its 14560 // filter information since the amount of data will be reasonable. 14561 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14562 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14563 dumpState.setDump(DumpState.DUMP_LIBS); 14564 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14565 dumpState.setDump(DumpState.DUMP_FEATURES); 14566 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14567 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14568 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14569 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14570 } else if ("permission".equals(cmd)) { 14571 if (opti >= args.length) { 14572 pw.println("Error: permission requires permission name"); 14573 return; 14574 } 14575 permissionNames = new ArraySet<>(); 14576 while (opti < args.length) { 14577 permissionNames.add(args[opti]); 14578 opti++; 14579 } 14580 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14581 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14582 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14583 dumpState.setDump(DumpState.DUMP_PREFERRED); 14584 } else if ("preferred-xml".equals(cmd)) { 14585 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14586 if (opti < args.length && "--full".equals(args[opti])) { 14587 fullPreferred = true; 14588 opti++; 14589 } 14590 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14591 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14592 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14593 dumpState.setDump(DumpState.DUMP_PACKAGES); 14594 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14595 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14596 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14597 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14598 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14599 dumpState.setDump(DumpState.DUMP_MESSAGES); 14600 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14601 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14602 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14603 || "intent-filter-verifiers".equals(cmd)) { 14604 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14605 } else if ("version".equals(cmd)) { 14606 dumpState.setDump(DumpState.DUMP_VERSION); 14607 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14608 dumpState.setDump(DumpState.DUMP_KEYSETS); 14609 } else if ("installs".equals(cmd)) { 14610 dumpState.setDump(DumpState.DUMP_INSTALLS); 14611 } else if ("write".equals(cmd)) { 14612 synchronized (mPackages) { 14613 mSettings.writeLPr(); 14614 pw.println("Settings written."); 14615 return; 14616 } 14617 } 14618 } 14619 14620 if (checkin) { 14621 pw.println("vers,1"); 14622 } 14623 14624 // reader 14625 synchronized (mPackages) { 14626 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14627 if (!checkin) { 14628 if (dumpState.onTitlePrinted()) 14629 pw.println(); 14630 pw.println("Database versions:"); 14631 pw.print(" SDK Version:"); 14632 pw.print(" internal="); 14633 pw.print(mSettings.mInternalSdkPlatform); 14634 pw.print(" external="); 14635 pw.println(mSettings.mExternalSdkPlatform); 14636 pw.print(" DB Version:"); 14637 pw.print(" internal="); 14638 pw.print(mSettings.mInternalDatabaseVersion); 14639 pw.print(" external="); 14640 pw.println(mSettings.mExternalDatabaseVersion); 14641 } 14642 } 14643 14644 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14645 if (!checkin) { 14646 if (dumpState.onTitlePrinted()) 14647 pw.println(); 14648 pw.println("Verifiers:"); 14649 pw.print(" Required: "); 14650 pw.print(mRequiredVerifierPackage); 14651 pw.print(" (uid="); 14652 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14653 pw.println(")"); 14654 } else if (mRequiredVerifierPackage != null) { 14655 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14656 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14657 } 14658 } 14659 14660 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14661 packageName == null) { 14662 if (mIntentFilterVerifierComponent != null) { 14663 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14664 if (!checkin) { 14665 if (dumpState.onTitlePrinted()) 14666 pw.println(); 14667 pw.println("Intent Filter Verifier:"); 14668 pw.print(" Using: "); 14669 pw.print(verifierPackageName); 14670 pw.print(" (uid="); 14671 pw.print(getPackageUid(verifierPackageName, 0)); 14672 pw.println(")"); 14673 } else if (verifierPackageName != null) { 14674 pw.print("ifv,"); pw.print(verifierPackageName); 14675 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14676 } 14677 } else { 14678 pw.println(); 14679 pw.println("No Intent Filter Verifier available!"); 14680 } 14681 } 14682 14683 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14684 boolean printedHeader = false; 14685 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14686 while (it.hasNext()) { 14687 String name = it.next(); 14688 SharedLibraryEntry ent = mSharedLibraries.get(name); 14689 if (!checkin) { 14690 if (!printedHeader) { 14691 if (dumpState.onTitlePrinted()) 14692 pw.println(); 14693 pw.println("Libraries:"); 14694 printedHeader = true; 14695 } 14696 pw.print(" "); 14697 } else { 14698 pw.print("lib,"); 14699 } 14700 pw.print(name); 14701 if (!checkin) { 14702 pw.print(" -> "); 14703 } 14704 if (ent.path != null) { 14705 if (!checkin) { 14706 pw.print("(jar) "); 14707 pw.print(ent.path); 14708 } else { 14709 pw.print(",jar,"); 14710 pw.print(ent.path); 14711 } 14712 } else { 14713 if (!checkin) { 14714 pw.print("(apk) "); 14715 pw.print(ent.apk); 14716 } else { 14717 pw.print(",apk,"); 14718 pw.print(ent.apk); 14719 } 14720 } 14721 pw.println(); 14722 } 14723 } 14724 14725 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14726 if (dumpState.onTitlePrinted()) 14727 pw.println(); 14728 if (!checkin) { 14729 pw.println("Features:"); 14730 } 14731 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14732 while (it.hasNext()) { 14733 String name = it.next(); 14734 if (!checkin) { 14735 pw.print(" "); 14736 } else { 14737 pw.print("feat,"); 14738 } 14739 pw.println(name); 14740 } 14741 } 14742 14743 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14744 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14745 : "Activity Resolver Table:", " ", packageName, 14746 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14747 dumpState.setTitlePrinted(true); 14748 } 14749 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14750 : "Receiver Resolver Table:", " ", packageName, 14751 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14752 dumpState.setTitlePrinted(true); 14753 } 14754 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14755 : "Service Resolver Table:", " ", packageName, 14756 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14757 dumpState.setTitlePrinted(true); 14758 } 14759 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14760 : "Provider Resolver Table:", " ", packageName, 14761 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14762 dumpState.setTitlePrinted(true); 14763 } 14764 } 14765 14766 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14767 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14768 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14769 int user = mSettings.mPreferredActivities.keyAt(i); 14770 if (pir.dump(pw, 14771 dumpState.getTitlePrinted() 14772 ? "\nPreferred Activities User " + user + ":" 14773 : "Preferred Activities User " + user + ":", " ", 14774 packageName, true, false)) { 14775 dumpState.setTitlePrinted(true); 14776 } 14777 } 14778 } 14779 14780 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14781 pw.flush(); 14782 FileOutputStream fout = new FileOutputStream(fd); 14783 BufferedOutputStream str = new BufferedOutputStream(fout); 14784 XmlSerializer serializer = new FastXmlSerializer(); 14785 try { 14786 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14787 serializer.startDocument(null, true); 14788 serializer.setFeature( 14789 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14790 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14791 serializer.endDocument(); 14792 serializer.flush(); 14793 } catch (IllegalArgumentException e) { 14794 pw.println("Failed writing: " + e); 14795 } catch (IllegalStateException e) { 14796 pw.println("Failed writing: " + e); 14797 } catch (IOException e) { 14798 pw.println("Failed writing: " + e); 14799 } 14800 } 14801 14802 if (!checkin 14803 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14804 && packageName == null) { 14805 pw.println(); 14806 int count = mSettings.mPackages.size(); 14807 if (count == 0) { 14808 pw.println("No domain preferred apps!"); 14809 pw.println(); 14810 } else { 14811 final String prefix = " "; 14812 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14813 if (allPackageSettings.size() == 0) { 14814 pw.println("No domain preferred apps!"); 14815 pw.println(); 14816 } else { 14817 pw.println("Domain preferred apps status:"); 14818 pw.println(); 14819 count = 0; 14820 for (PackageSetting ps : allPackageSettings) { 14821 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14822 if (ivi == null || ivi.getPackageName() == null) continue; 14823 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14824 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14825 pw.println(prefix + "Status: " + ivi.getStatusString()); 14826 pw.println(); 14827 count++; 14828 } 14829 if (count == 0) { 14830 pw.println(prefix + "No domain preferred app status!"); 14831 pw.println(); 14832 } 14833 for (int userId : sUserManager.getUserIds()) { 14834 pw.println("Domain preferred apps for User " + userId + ":"); 14835 pw.println(); 14836 count = 0; 14837 for (PackageSetting ps : allPackageSettings) { 14838 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14839 if (ivi == null || ivi.getPackageName() == null) { 14840 continue; 14841 } 14842 final int status = ps.getDomainVerificationStatusForUser(userId); 14843 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14844 continue; 14845 } 14846 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14847 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14848 String statusStr = IntentFilterVerificationInfo. 14849 getStatusStringFromValue(status); 14850 pw.println(prefix + "Status: " + statusStr); 14851 pw.println(); 14852 count++; 14853 } 14854 if (count == 0) { 14855 pw.println(prefix + "No domain preferred apps!"); 14856 pw.println(); 14857 } 14858 } 14859 } 14860 } 14861 } 14862 14863 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14864 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14865 if (packageName == null && permissionNames == null) { 14866 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14867 if (iperm == 0) { 14868 if (dumpState.onTitlePrinted()) 14869 pw.println(); 14870 pw.println("AppOp Permissions:"); 14871 } 14872 pw.print(" AppOp Permission "); 14873 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14874 pw.println(":"); 14875 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14876 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14877 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14878 } 14879 } 14880 } 14881 } 14882 14883 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14884 boolean printedSomething = false; 14885 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14886 if (packageName != null && !packageName.equals(p.info.packageName)) { 14887 continue; 14888 } 14889 if (!printedSomething) { 14890 if (dumpState.onTitlePrinted()) 14891 pw.println(); 14892 pw.println("Registered ContentProviders:"); 14893 printedSomething = true; 14894 } 14895 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14896 pw.print(" "); pw.println(p.toString()); 14897 } 14898 printedSomething = false; 14899 for (Map.Entry<String, PackageParser.Provider> entry : 14900 mProvidersByAuthority.entrySet()) { 14901 PackageParser.Provider p = entry.getValue(); 14902 if (packageName != null && !packageName.equals(p.info.packageName)) { 14903 continue; 14904 } 14905 if (!printedSomething) { 14906 if (dumpState.onTitlePrinted()) 14907 pw.println(); 14908 pw.println("ContentProvider Authorities:"); 14909 printedSomething = true; 14910 } 14911 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14912 pw.print(" "); pw.println(p.toString()); 14913 if (p.info != null && p.info.applicationInfo != null) { 14914 final String appInfo = p.info.applicationInfo.toString(); 14915 pw.print(" applicationInfo="); pw.println(appInfo); 14916 } 14917 } 14918 } 14919 14920 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14921 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14922 } 14923 14924 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14925 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14926 } 14927 14928 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14929 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14930 } 14931 14932 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14933 // XXX should handle packageName != null by dumping only install data that 14934 // the given package is involved with. 14935 if (dumpState.onTitlePrinted()) pw.println(); 14936 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14937 } 14938 14939 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14940 if (dumpState.onTitlePrinted()) pw.println(); 14941 mSettings.dumpReadMessagesLPr(pw, dumpState); 14942 14943 pw.println(); 14944 pw.println("Package warning messages:"); 14945 BufferedReader in = null; 14946 String line = null; 14947 try { 14948 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14949 while ((line = in.readLine()) != null) { 14950 if (line.contains("ignored: updated version")) continue; 14951 pw.println(line); 14952 } 14953 } catch (IOException ignored) { 14954 } finally { 14955 IoUtils.closeQuietly(in); 14956 } 14957 } 14958 14959 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14960 BufferedReader in = null; 14961 String line = null; 14962 try { 14963 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14964 while ((line = in.readLine()) != null) { 14965 if (line.contains("ignored: updated version")) continue; 14966 pw.print("msg,"); 14967 pw.println(line); 14968 } 14969 } catch (IOException ignored) { 14970 } finally { 14971 IoUtils.closeQuietly(in); 14972 } 14973 } 14974 } 14975 } 14976 14977 // ------- apps on sdcard specific code ------- 14978 static final boolean DEBUG_SD_INSTALL = false; 14979 14980 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14981 14982 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14983 14984 private boolean mMediaMounted = false; 14985 14986 static String getEncryptKey() { 14987 try { 14988 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14989 SD_ENCRYPTION_KEYSTORE_NAME); 14990 if (sdEncKey == null) { 14991 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14992 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14993 if (sdEncKey == null) { 14994 Slog.e(TAG, "Failed to create encryption keys"); 14995 return null; 14996 } 14997 } 14998 return sdEncKey; 14999 } catch (NoSuchAlgorithmException nsae) { 15000 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15001 return null; 15002 } catch (IOException ioe) { 15003 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15004 return null; 15005 } 15006 } 15007 15008 /* 15009 * Update media status on PackageManager. 15010 */ 15011 @Override 15012 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15013 int callingUid = Binder.getCallingUid(); 15014 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15015 throw new SecurityException("Media status can only be updated by the system"); 15016 } 15017 // reader; this apparently protects mMediaMounted, but should probably 15018 // be a different lock in that case. 15019 synchronized (mPackages) { 15020 Log.i(TAG, "Updating external media status from " 15021 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15022 + (mediaStatus ? "mounted" : "unmounted")); 15023 if (DEBUG_SD_INSTALL) 15024 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15025 + ", mMediaMounted=" + mMediaMounted); 15026 if (mediaStatus == mMediaMounted) { 15027 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15028 : 0, -1); 15029 mHandler.sendMessage(msg); 15030 return; 15031 } 15032 mMediaMounted = mediaStatus; 15033 } 15034 // Queue up an async operation since the package installation may take a 15035 // little while. 15036 mHandler.post(new Runnable() { 15037 public void run() { 15038 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15039 } 15040 }); 15041 } 15042 15043 /** 15044 * Called by MountService when the initial ASECs to scan are available. 15045 * Should block until all the ASEC containers are finished being scanned. 15046 */ 15047 public void scanAvailableAsecs() { 15048 updateExternalMediaStatusInner(true, false, false); 15049 if (mShouldRestoreconData) { 15050 SELinuxMMAC.setRestoreconDone(); 15051 mShouldRestoreconData = false; 15052 } 15053 } 15054 15055 /* 15056 * Collect information of applications on external media, map them against 15057 * existing containers and update information based on current mount status. 15058 * Please note that we always have to report status if reportStatus has been 15059 * set to true especially when unloading packages. 15060 */ 15061 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15062 boolean externalStorage) { 15063 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15064 int[] uidArr = EmptyArray.INT; 15065 15066 final String[] list = PackageHelper.getSecureContainerList(); 15067 if (ArrayUtils.isEmpty(list)) { 15068 Log.i(TAG, "No secure containers found"); 15069 } else { 15070 // Process list of secure containers and categorize them 15071 // as active or stale based on their package internal state. 15072 15073 // reader 15074 synchronized (mPackages) { 15075 for (String cid : list) { 15076 // Leave stages untouched for now; installer service owns them 15077 if (PackageInstallerService.isStageName(cid)) continue; 15078 15079 if (DEBUG_SD_INSTALL) 15080 Log.i(TAG, "Processing container " + cid); 15081 String pkgName = getAsecPackageName(cid); 15082 if (pkgName == null) { 15083 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15084 continue; 15085 } 15086 if (DEBUG_SD_INSTALL) 15087 Log.i(TAG, "Looking for pkg : " + pkgName); 15088 15089 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15090 if (ps == null) { 15091 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15092 continue; 15093 } 15094 15095 /* 15096 * Skip packages that are not external if we're unmounting 15097 * external storage. 15098 */ 15099 if (externalStorage && !isMounted && !isExternal(ps)) { 15100 continue; 15101 } 15102 15103 final AsecInstallArgs args = new AsecInstallArgs(cid, 15104 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15105 // The package status is changed only if the code path 15106 // matches between settings and the container id. 15107 if (ps.codePathString != null 15108 && ps.codePathString.startsWith(args.getCodePath())) { 15109 if (DEBUG_SD_INSTALL) { 15110 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15111 + " at code path: " + ps.codePathString); 15112 } 15113 15114 // We do have a valid package installed on sdcard 15115 processCids.put(args, ps.codePathString); 15116 final int uid = ps.appId; 15117 if (uid != -1) { 15118 uidArr = ArrayUtils.appendInt(uidArr, uid); 15119 } 15120 } else { 15121 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15122 + ps.codePathString); 15123 } 15124 } 15125 } 15126 15127 Arrays.sort(uidArr); 15128 } 15129 15130 // Process packages with valid entries. 15131 if (isMounted) { 15132 if (DEBUG_SD_INSTALL) 15133 Log.i(TAG, "Loading packages"); 15134 loadMediaPackages(processCids, uidArr); 15135 startCleaningPackages(); 15136 mInstallerService.onSecureContainersAvailable(); 15137 } else { 15138 if (DEBUG_SD_INSTALL) 15139 Log.i(TAG, "Unloading packages"); 15140 unloadMediaPackages(processCids, uidArr, reportStatus); 15141 } 15142 } 15143 15144 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15145 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15146 final int size = infos.size(); 15147 final String[] packageNames = new String[size]; 15148 final int[] packageUids = new int[size]; 15149 for (int i = 0; i < size; i++) { 15150 final ApplicationInfo info = infos.get(i); 15151 packageNames[i] = info.packageName; 15152 packageUids[i] = info.uid; 15153 } 15154 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15155 finishedReceiver); 15156 } 15157 15158 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15159 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15160 sendResourcesChangedBroadcast(mediaStatus, replacing, 15161 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15162 } 15163 15164 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15165 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15166 int size = pkgList.length; 15167 if (size > 0) { 15168 // Send broadcasts here 15169 Bundle extras = new Bundle(); 15170 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15171 if (uidArr != null) { 15172 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15173 } 15174 if (replacing) { 15175 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15176 } 15177 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15178 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15179 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15180 } 15181 } 15182 15183 /* 15184 * Look at potentially valid container ids from processCids If package 15185 * information doesn't match the one on record or package scanning fails, 15186 * the cid is added to list of removeCids. We currently don't delete stale 15187 * containers. 15188 */ 15189 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15190 ArrayList<String> pkgList = new ArrayList<String>(); 15191 Set<AsecInstallArgs> keys = processCids.keySet(); 15192 15193 for (AsecInstallArgs args : keys) { 15194 String codePath = processCids.get(args); 15195 if (DEBUG_SD_INSTALL) 15196 Log.i(TAG, "Loading container : " + args.cid); 15197 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15198 try { 15199 // Make sure there are no container errors first. 15200 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15201 Slog.e(TAG, "Failed to mount cid : " + args.cid 15202 + " when installing from sdcard"); 15203 continue; 15204 } 15205 // Check code path here. 15206 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15207 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15208 + " does not match one in settings " + codePath); 15209 continue; 15210 } 15211 // Parse package 15212 int parseFlags = mDefParseFlags; 15213 if (args.isExternalAsec()) { 15214 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15215 } 15216 if (args.isFwdLocked()) { 15217 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15218 } 15219 15220 synchronized (mInstallLock) { 15221 PackageParser.Package pkg = null; 15222 try { 15223 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15224 } catch (PackageManagerException e) { 15225 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15226 } 15227 // Scan the package 15228 if (pkg != null) { 15229 /* 15230 * TODO why is the lock being held? doPostInstall is 15231 * called in other places without the lock. This needs 15232 * to be straightened out. 15233 */ 15234 // writer 15235 synchronized (mPackages) { 15236 retCode = PackageManager.INSTALL_SUCCEEDED; 15237 pkgList.add(pkg.packageName); 15238 // Post process args 15239 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15240 pkg.applicationInfo.uid); 15241 } 15242 } else { 15243 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15244 } 15245 } 15246 15247 } finally { 15248 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15249 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15250 } 15251 } 15252 } 15253 // writer 15254 synchronized (mPackages) { 15255 // If the platform SDK has changed since the last time we booted, 15256 // we need to re-grant app permission to catch any new ones that 15257 // appear. This is really a hack, and means that apps can in some 15258 // cases get permissions that the user didn't initially explicitly 15259 // allow... it would be nice to have some better way to handle 15260 // this situation. 15261 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15262 if (regrantPermissions) 15263 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15264 + mSdkVersion + "; regranting permissions for external storage"); 15265 mSettings.mExternalSdkPlatform = mSdkVersion; 15266 15267 // Make sure group IDs have been assigned, and any permission 15268 // changes in other apps are accounted for 15269 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15270 | (regrantPermissions 15271 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15272 : 0)); 15273 15274 mSettings.updateExternalDatabaseVersion(); 15275 15276 // can downgrade to reader 15277 // Persist settings 15278 mSettings.writeLPr(); 15279 } 15280 // Send a broadcast to let everyone know we are done processing 15281 if (pkgList.size() > 0) { 15282 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15283 } 15284 } 15285 15286 /* 15287 * Utility method to unload a list of specified containers 15288 */ 15289 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15290 // Just unmount all valid containers. 15291 for (AsecInstallArgs arg : cidArgs) { 15292 synchronized (mInstallLock) { 15293 arg.doPostDeleteLI(false); 15294 } 15295 } 15296 } 15297 15298 /* 15299 * Unload packages mounted on external media. This involves deleting package 15300 * data from internal structures, sending broadcasts about diabled packages, 15301 * gc'ing to free up references, unmounting all secure containers 15302 * corresponding to packages on external media, and posting a 15303 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15304 * that we always have to post this message if status has been requested no 15305 * matter what. 15306 */ 15307 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15308 final boolean reportStatus) { 15309 if (DEBUG_SD_INSTALL) 15310 Log.i(TAG, "unloading media packages"); 15311 ArrayList<String> pkgList = new ArrayList<String>(); 15312 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15313 final Set<AsecInstallArgs> keys = processCids.keySet(); 15314 for (AsecInstallArgs args : keys) { 15315 String pkgName = args.getPackageName(); 15316 if (DEBUG_SD_INSTALL) 15317 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15318 // Delete package internally 15319 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15320 synchronized (mInstallLock) { 15321 boolean res = deletePackageLI(pkgName, null, false, null, null, 15322 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15323 if (res) { 15324 pkgList.add(pkgName); 15325 } else { 15326 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15327 failedList.add(args); 15328 } 15329 } 15330 } 15331 15332 // reader 15333 synchronized (mPackages) { 15334 // We didn't update the settings after removing each package; 15335 // write them now for all packages. 15336 mSettings.writeLPr(); 15337 } 15338 15339 // We have to absolutely send UPDATED_MEDIA_STATUS only 15340 // after confirming that all the receivers processed the ordered 15341 // broadcast when packages get disabled, force a gc to clean things up. 15342 // and unload all the containers. 15343 if (pkgList.size() > 0) { 15344 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15345 new IIntentReceiver.Stub() { 15346 public void performReceive(Intent intent, int resultCode, String data, 15347 Bundle extras, boolean ordered, boolean sticky, 15348 int sendingUser) throws RemoteException { 15349 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15350 reportStatus ? 1 : 0, 1, keys); 15351 mHandler.sendMessage(msg); 15352 } 15353 }); 15354 } else { 15355 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15356 keys); 15357 mHandler.sendMessage(msg); 15358 } 15359 } 15360 15361 private void loadPrivatePackages(VolumeInfo vol) { 15362 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15363 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15364 synchronized (mInstallLock) { 15365 synchronized (mPackages) { 15366 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15367 for (PackageSetting ps : packages) { 15368 final PackageParser.Package pkg; 15369 try { 15370 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15371 loaded.add(pkg.applicationInfo); 15372 } catch (PackageManagerException e) { 15373 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15374 } 15375 } 15376 15377 // TODO: regrant any permissions that changed based since original install 15378 15379 mSettings.writeLPr(); 15380 } 15381 } 15382 15383 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15384 sendResourcesChangedBroadcast(true, false, loaded, null); 15385 } 15386 15387 private void unloadPrivatePackages(VolumeInfo vol) { 15388 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15389 synchronized (mInstallLock) { 15390 synchronized (mPackages) { 15391 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15392 for (PackageSetting ps : packages) { 15393 if (ps.pkg == null) continue; 15394 15395 final ApplicationInfo info = ps.pkg.applicationInfo; 15396 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15397 if (deletePackageLI(ps.name, null, false, null, null, 15398 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15399 unloaded.add(info); 15400 } else { 15401 Slog.w(TAG, "Failed to unload " + ps.codePath); 15402 } 15403 } 15404 15405 mSettings.writeLPr(); 15406 } 15407 } 15408 15409 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15410 sendResourcesChangedBroadcast(false, false, unloaded, null); 15411 } 15412 15413 /** 15414 * Examine all users present on given mounted volume, and destroy data 15415 * belonging to users that are no longer valid, or whose user ID has been 15416 * recycled. 15417 */ 15418 private void reconcileUsers(String volumeUuid) { 15419 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15420 if (ArrayUtils.isEmpty(files)) { 15421 Slog.d(TAG, "No users found on " + volumeUuid); 15422 return; 15423 } 15424 15425 for (File file : files) { 15426 if (!file.isDirectory()) continue; 15427 15428 final int userId; 15429 final UserInfo info; 15430 try { 15431 userId = Integer.parseInt(file.getName()); 15432 info = sUserManager.getUserInfo(userId); 15433 } catch (NumberFormatException e) { 15434 Slog.w(TAG, "Invalid user directory " + file); 15435 continue; 15436 } 15437 15438 boolean destroyUser = false; 15439 if (info == null) { 15440 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15441 + " because no matching user was found"); 15442 destroyUser = true; 15443 } else { 15444 try { 15445 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15446 } catch (IOException e) { 15447 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15448 + " because we failed to enforce serial number: " + e); 15449 destroyUser = true; 15450 } 15451 } 15452 15453 if (destroyUser) { 15454 synchronized (mInstallLock) { 15455 mInstaller.removeUserDataDirs(volumeUuid, userId); 15456 } 15457 } 15458 } 15459 15460 final UserManager um = mContext.getSystemService(UserManager.class); 15461 for (UserInfo user : um.getUsers()) { 15462 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15463 if (userDir.exists()) continue; 15464 15465 try { 15466 UserManagerService.prepareUserDirectory(userDir); 15467 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15468 } catch (IOException e) { 15469 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15470 } 15471 } 15472 } 15473 15474 /** 15475 * Examine all apps present on given mounted volume, and destroy apps that 15476 * aren't expected, either due to uninstallation or reinstallation on 15477 * another volume. 15478 */ 15479 private void reconcileApps(String volumeUuid) { 15480 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15481 if (ArrayUtils.isEmpty(files)) { 15482 Slog.d(TAG, "No apps found on " + volumeUuid); 15483 return; 15484 } 15485 15486 for (File file : files) { 15487 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15488 && !PackageInstallerService.isStageName(file.getName()); 15489 if (!isPackage) { 15490 // Ignore entries which are not packages 15491 continue; 15492 } 15493 15494 boolean destroyApp = false; 15495 String packageName = null; 15496 try { 15497 final PackageLite pkg = PackageParser.parsePackageLite(file, 15498 PackageParser.PARSE_MUST_BE_APK); 15499 packageName = pkg.packageName; 15500 15501 synchronized (mPackages) { 15502 final PackageSetting ps = mSettings.mPackages.get(packageName); 15503 if (ps == null) { 15504 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15505 + volumeUuid + " because we found no install record"); 15506 destroyApp = true; 15507 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15508 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15509 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15510 destroyApp = true; 15511 } 15512 } 15513 15514 } catch (PackageParserException e) { 15515 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15516 destroyApp = true; 15517 } 15518 15519 if (destroyApp) { 15520 synchronized (mInstallLock) { 15521 if (packageName != null) { 15522 removeDataDirsLI(volumeUuid, packageName); 15523 } 15524 if (file.isDirectory()) { 15525 mInstaller.rmPackageDir(file.getAbsolutePath()); 15526 } else { 15527 file.delete(); 15528 } 15529 } 15530 } 15531 } 15532 } 15533 15534 private void unfreezePackage(String packageName) { 15535 synchronized (mPackages) { 15536 final PackageSetting ps = mSettings.mPackages.get(packageName); 15537 if (ps != null) { 15538 ps.frozen = false; 15539 } 15540 } 15541 } 15542 15543 @Override 15544 public int movePackage(final String packageName, final String volumeUuid) { 15545 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15546 15547 final int moveId = mNextMoveId.getAndIncrement(); 15548 try { 15549 movePackageInternal(packageName, volumeUuid, moveId); 15550 } catch (PackageManagerException e) { 15551 Slog.w(TAG, "Failed to move " + packageName, e); 15552 mMoveCallbacks.notifyStatusChanged(moveId, 15553 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15554 } 15555 return moveId; 15556 } 15557 15558 private void movePackageInternal(final String packageName, final String volumeUuid, 15559 final int moveId) throws PackageManagerException { 15560 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15561 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15562 final PackageManager pm = mContext.getPackageManager(); 15563 15564 final boolean currentAsec; 15565 final String currentVolumeUuid; 15566 final File codeFile; 15567 final String installerPackageName; 15568 final String packageAbiOverride; 15569 final int appId; 15570 final String seinfo; 15571 final String label; 15572 15573 // reader 15574 synchronized (mPackages) { 15575 final PackageParser.Package pkg = mPackages.get(packageName); 15576 final PackageSetting ps = mSettings.mPackages.get(packageName); 15577 if (pkg == null || ps == null) { 15578 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15579 } 15580 15581 if (pkg.applicationInfo.isSystemApp()) { 15582 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15583 "Cannot move system application"); 15584 } 15585 15586 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15587 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15588 "Package already moved to " + volumeUuid); 15589 } 15590 15591 final File probe = new File(pkg.codePath); 15592 final File probeOat = new File(probe, "oat"); 15593 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15594 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15595 "Move only supported for modern cluster style installs"); 15596 } 15597 15598 if (ps.frozen) { 15599 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15600 "Failed to move already frozen package"); 15601 } 15602 ps.frozen = true; 15603 15604 currentAsec = pkg.applicationInfo.isForwardLocked() 15605 || pkg.applicationInfo.isExternalAsec(); 15606 currentVolumeUuid = ps.volumeUuid; 15607 codeFile = new File(pkg.codePath); 15608 installerPackageName = ps.installerPackageName; 15609 packageAbiOverride = ps.cpuAbiOverrideString; 15610 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15611 seinfo = pkg.applicationInfo.seinfo; 15612 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15613 } 15614 15615 // Now that we're guarded by frozen state, kill app during move 15616 killApplication(packageName, appId, "move pkg"); 15617 15618 final Bundle extras = new Bundle(); 15619 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15620 extras.putString(Intent.EXTRA_TITLE, label); 15621 mMoveCallbacks.notifyCreated(moveId, extras); 15622 15623 int installFlags; 15624 final boolean moveCompleteApp; 15625 final File measurePath; 15626 15627 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15628 installFlags = INSTALL_INTERNAL; 15629 moveCompleteApp = !currentAsec; 15630 measurePath = Environment.getDataAppDirectory(volumeUuid); 15631 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15632 installFlags = INSTALL_EXTERNAL; 15633 moveCompleteApp = false; 15634 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15635 } else { 15636 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15637 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15638 || !volume.isMountedWritable()) { 15639 unfreezePackage(packageName); 15640 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15641 "Move location not mounted private volume"); 15642 } 15643 15644 Preconditions.checkState(!currentAsec); 15645 15646 installFlags = INSTALL_INTERNAL; 15647 moveCompleteApp = true; 15648 measurePath = Environment.getDataAppDirectory(volumeUuid); 15649 } 15650 15651 final PackageStats stats = new PackageStats(null, -1); 15652 synchronized (mInstaller) { 15653 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15654 unfreezePackage(packageName); 15655 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15656 "Failed to measure package size"); 15657 } 15658 } 15659 15660 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15661 + stats.dataSize); 15662 15663 final long startFreeBytes = measurePath.getFreeSpace(); 15664 final long sizeBytes; 15665 if (moveCompleteApp) { 15666 sizeBytes = stats.codeSize + stats.dataSize; 15667 } else { 15668 sizeBytes = stats.codeSize; 15669 } 15670 15671 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15672 unfreezePackage(packageName); 15673 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15674 "Not enough free space to move"); 15675 } 15676 15677 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15678 15679 final CountDownLatch installedLatch = new CountDownLatch(1); 15680 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15681 @Override 15682 public void onUserActionRequired(Intent intent) throws RemoteException { 15683 throw new IllegalStateException(); 15684 } 15685 15686 @Override 15687 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15688 Bundle extras) throws RemoteException { 15689 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15690 + PackageManager.installStatusToString(returnCode, msg)); 15691 15692 installedLatch.countDown(); 15693 15694 // Regardless of success or failure of the move operation, 15695 // always unfreeze the package 15696 unfreezePackage(packageName); 15697 15698 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15699 switch (status) { 15700 case PackageInstaller.STATUS_SUCCESS: 15701 mMoveCallbacks.notifyStatusChanged(moveId, 15702 PackageManager.MOVE_SUCCEEDED); 15703 break; 15704 case PackageInstaller.STATUS_FAILURE_STORAGE: 15705 mMoveCallbacks.notifyStatusChanged(moveId, 15706 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15707 break; 15708 default: 15709 mMoveCallbacks.notifyStatusChanged(moveId, 15710 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15711 break; 15712 } 15713 } 15714 }; 15715 15716 final MoveInfo move; 15717 if (moveCompleteApp) { 15718 // Kick off a thread to report progress estimates 15719 new Thread() { 15720 @Override 15721 public void run() { 15722 while (true) { 15723 try { 15724 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15725 break; 15726 } 15727 } catch (InterruptedException ignored) { 15728 } 15729 15730 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15731 final int progress = 10 + (int) MathUtils.constrain( 15732 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15733 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15734 } 15735 } 15736 }.start(); 15737 15738 final String dataAppName = codeFile.getName(); 15739 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15740 dataAppName, appId, seinfo); 15741 } else { 15742 move = null; 15743 } 15744 15745 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15746 15747 final Message msg = mHandler.obtainMessage(INIT_COPY); 15748 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15749 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15750 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15751 mHandler.sendMessage(msg); 15752 } 15753 15754 @Override 15755 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15756 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15757 15758 final int realMoveId = mNextMoveId.getAndIncrement(); 15759 final Bundle extras = new Bundle(); 15760 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15761 mMoveCallbacks.notifyCreated(realMoveId, extras); 15762 15763 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15764 @Override 15765 public void onCreated(int moveId, Bundle extras) { 15766 // Ignored 15767 } 15768 15769 @Override 15770 public void onStatusChanged(int moveId, int status, long estMillis) { 15771 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15772 } 15773 }; 15774 15775 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15776 storage.setPrimaryStorageUuid(volumeUuid, callback); 15777 return realMoveId; 15778 } 15779 15780 @Override 15781 public int getMoveStatus(int moveId) { 15782 mContext.enforceCallingOrSelfPermission( 15783 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15784 return mMoveCallbacks.mLastStatus.get(moveId); 15785 } 15786 15787 @Override 15788 public void registerMoveCallback(IPackageMoveObserver callback) { 15789 mContext.enforceCallingOrSelfPermission( 15790 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15791 mMoveCallbacks.register(callback); 15792 } 15793 15794 @Override 15795 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15796 mContext.enforceCallingOrSelfPermission( 15797 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15798 mMoveCallbacks.unregister(callback); 15799 } 15800 15801 @Override 15802 public boolean setInstallLocation(int loc) { 15803 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15804 null); 15805 if (getInstallLocation() == loc) { 15806 return true; 15807 } 15808 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15809 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15810 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15811 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15812 return true; 15813 } 15814 return false; 15815 } 15816 15817 @Override 15818 public int getInstallLocation() { 15819 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15820 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15821 PackageHelper.APP_INSTALL_AUTO); 15822 } 15823 15824 /** Called by UserManagerService */ 15825 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15826 mDirtyUsers.remove(userHandle); 15827 mSettings.removeUserLPw(userHandle); 15828 mPendingBroadcasts.remove(userHandle); 15829 if (mInstaller != null) { 15830 // Technically, we shouldn't be doing this with the package lock 15831 // held. However, this is very rare, and there is already so much 15832 // other disk I/O going on, that we'll let it slide for now. 15833 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15834 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15835 final String volumeUuid = vol.getFsUuid(); 15836 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15837 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15838 } 15839 } 15840 mUserNeedsBadging.delete(userHandle); 15841 removeUnusedPackagesLILPw(userManager, userHandle); 15842 } 15843 15844 /** 15845 * We're removing userHandle and would like to remove any downloaded packages 15846 * that are no longer in use by any other user. 15847 * @param userHandle the user being removed 15848 */ 15849 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15850 final boolean DEBUG_CLEAN_APKS = false; 15851 int [] users = userManager.getUserIdsLPr(); 15852 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15853 while (psit.hasNext()) { 15854 PackageSetting ps = psit.next(); 15855 if (ps.pkg == null) { 15856 continue; 15857 } 15858 final String packageName = ps.pkg.packageName; 15859 // Skip over if system app 15860 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15861 continue; 15862 } 15863 if (DEBUG_CLEAN_APKS) { 15864 Slog.i(TAG, "Checking package " + packageName); 15865 } 15866 boolean keep = false; 15867 for (int i = 0; i < users.length; i++) { 15868 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15869 keep = true; 15870 if (DEBUG_CLEAN_APKS) { 15871 Slog.i(TAG, " Keeping package " + packageName + " for user " 15872 + users[i]); 15873 } 15874 break; 15875 } 15876 } 15877 if (!keep) { 15878 if (DEBUG_CLEAN_APKS) { 15879 Slog.i(TAG, " Removing package " + packageName); 15880 } 15881 mHandler.post(new Runnable() { 15882 public void run() { 15883 deletePackageX(packageName, userHandle, 0); 15884 } //end run 15885 }); 15886 } 15887 } 15888 } 15889 15890 /** Called by UserManagerService */ 15891 void createNewUserLILPw(int userHandle) { 15892 if (mInstaller != null) { 15893 mInstaller.createUserConfig(userHandle); 15894 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 15895 applyFactoryDefaultBrowserLPw(userHandle); 15896 } 15897 } 15898 15899 void newUserCreatedLILPw(final int userHandle) { 15900 // We cannot grant the default permissions with a lock held as 15901 // we query providers from other components for default handlers 15902 // such as enabled IMEs, etc. 15903 mHandler.post(new Runnable() { 15904 @Override 15905 public void run() { 15906 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15907 } 15908 }); 15909 } 15910 15911 @Override 15912 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15913 mContext.enforceCallingOrSelfPermission( 15914 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15915 "Only package verification agents can read the verifier device identity"); 15916 15917 synchronized (mPackages) { 15918 return mSettings.getVerifierDeviceIdentityLPw(); 15919 } 15920 } 15921 15922 @Override 15923 public void setPermissionEnforced(String permission, boolean enforced) { 15924 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15925 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15926 synchronized (mPackages) { 15927 if (mSettings.mReadExternalStorageEnforced == null 15928 || mSettings.mReadExternalStorageEnforced != enforced) { 15929 mSettings.mReadExternalStorageEnforced = enforced; 15930 mSettings.writeLPr(); 15931 } 15932 } 15933 // kill any non-foreground processes so we restart them and 15934 // grant/revoke the GID. 15935 final IActivityManager am = ActivityManagerNative.getDefault(); 15936 if (am != null) { 15937 final long token = Binder.clearCallingIdentity(); 15938 try { 15939 am.killProcessesBelowForeground("setPermissionEnforcement"); 15940 } catch (RemoteException e) { 15941 } finally { 15942 Binder.restoreCallingIdentity(token); 15943 } 15944 } 15945 } else { 15946 throw new IllegalArgumentException("No selective enforcement for " + permission); 15947 } 15948 } 15949 15950 @Override 15951 @Deprecated 15952 public boolean isPermissionEnforced(String permission) { 15953 return true; 15954 } 15955 15956 @Override 15957 public boolean isStorageLow() { 15958 final long token = Binder.clearCallingIdentity(); 15959 try { 15960 final DeviceStorageMonitorInternal 15961 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15962 if (dsm != null) { 15963 return dsm.isMemoryLow(); 15964 } else { 15965 return false; 15966 } 15967 } finally { 15968 Binder.restoreCallingIdentity(token); 15969 } 15970 } 15971 15972 @Override 15973 public IPackageInstaller getPackageInstaller() { 15974 return mInstallerService; 15975 } 15976 15977 private boolean userNeedsBadging(int userId) { 15978 int index = mUserNeedsBadging.indexOfKey(userId); 15979 if (index < 0) { 15980 final UserInfo userInfo; 15981 final long token = Binder.clearCallingIdentity(); 15982 try { 15983 userInfo = sUserManager.getUserInfo(userId); 15984 } finally { 15985 Binder.restoreCallingIdentity(token); 15986 } 15987 final boolean b; 15988 if (userInfo != null && userInfo.isManagedProfile()) { 15989 b = true; 15990 } else { 15991 b = false; 15992 } 15993 mUserNeedsBadging.put(userId, b); 15994 return b; 15995 } 15996 return mUserNeedsBadging.valueAt(index); 15997 } 15998 15999 @Override 16000 public KeySet getKeySetByAlias(String packageName, String alias) { 16001 if (packageName == null || alias == null) { 16002 return null; 16003 } 16004 synchronized(mPackages) { 16005 final PackageParser.Package pkg = mPackages.get(packageName); 16006 if (pkg == null) { 16007 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16008 throw new IllegalArgumentException("Unknown package: " + packageName); 16009 } 16010 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16011 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16012 } 16013 } 16014 16015 @Override 16016 public KeySet getSigningKeySet(String packageName) { 16017 if (packageName == null) { 16018 return null; 16019 } 16020 synchronized(mPackages) { 16021 final PackageParser.Package pkg = mPackages.get(packageName); 16022 if (pkg == null) { 16023 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16024 throw new IllegalArgumentException("Unknown package: " + packageName); 16025 } 16026 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16027 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16028 throw new SecurityException("May not access signing KeySet of other apps."); 16029 } 16030 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16031 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16032 } 16033 } 16034 16035 @Override 16036 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16037 if (packageName == null || ks == null) { 16038 return false; 16039 } 16040 synchronized(mPackages) { 16041 final PackageParser.Package pkg = mPackages.get(packageName); 16042 if (pkg == null) { 16043 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16044 throw new IllegalArgumentException("Unknown package: " + packageName); 16045 } 16046 IBinder ksh = ks.getToken(); 16047 if (ksh instanceof KeySetHandle) { 16048 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16049 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16050 } 16051 return false; 16052 } 16053 } 16054 16055 @Override 16056 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16057 if (packageName == null || ks == null) { 16058 return false; 16059 } 16060 synchronized(mPackages) { 16061 final PackageParser.Package pkg = mPackages.get(packageName); 16062 if (pkg == null) { 16063 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16064 throw new IllegalArgumentException("Unknown package: " + packageName); 16065 } 16066 IBinder ksh = ks.getToken(); 16067 if (ksh instanceof KeySetHandle) { 16068 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16069 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16070 } 16071 return false; 16072 } 16073 } 16074 16075 public void getUsageStatsIfNoPackageUsageInfo() { 16076 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16077 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16078 if (usm == null) { 16079 throw new IllegalStateException("UsageStatsManager must be initialized"); 16080 } 16081 long now = System.currentTimeMillis(); 16082 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16083 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16084 String packageName = entry.getKey(); 16085 PackageParser.Package pkg = mPackages.get(packageName); 16086 if (pkg == null) { 16087 continue; 16088 } 16089 UsageStats usage = entry.getValue(); 16090 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16091 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16092 } 16093 } 16094 } 16095 16096 /** 16097 * Check and throw if the given before/after packages would be considered a 16098 * downgrade. 16099 */ 16100 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16101 throws PackageManagerException { 16102 if (after.versionCode < before.mVersionCode) { 16103 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16104 "Update version code " + after.versionCode + " is older than current " 16105 + before.mVersionCode); 16106 } else if (after.versionCode == before.mVersionCode) { 16107 if (after.baseRevisionCode < before.baseRevisionCode) { 16108 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16109 "Update base revision code " + after.baseRevisionCode 16110 + " is older than current " + before.baseRevisionCode); 16111 } 16112 16113 if (!ArrayUtils.isEmpty(after.splitNames)) { 16114 for (int i = 0; i < after.splitNames.length; i++) { 16115 final String splitName = after.splitNames[i]; 16116 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16117 if (j != -1) { 16118 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16119 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16120 "Update split " + splitName + " revision code " 16121 + after.splitRevisionCodes[i] + " is older than current " 16122 + before.splitRevisionCodes[j]); 16123 } 16124 } 16125 } 16126 } 16127 } 16128 } 16129 16130 private static class MoveCallbacks extends Handler { 16131 private static final int MSG_CREATED = 1; 16132 private static final int MSG_STATUS_CHANGED = 2; 16133 16134 private final RemoteCallbackList<IPackageMoveObserver> 16135 mCallbacks = new RemoteCallbackList<>(); 16136 16137 private final SparseIntArray mLastStatus = new SparseIntArray(); 16138 16139 public MoveCallbacks(Looper looper) { 16140 super(looper); 16141 } 16142 16143 public void register(IPackageMoveObserver callback) { 16144 mCallbacks.register(callback); 16145 } 16146 16147 public void unregister(IPackageMoveObserver callback) { 16148 mCallbacks.unregister(callback); 16149 } 16150 16151 @Override 16152 public void handleMessage(Message msg) { 16153 final SomeArgs args = (SomeArgs) msg.obj; 16154 final int n = mCallbacks.beginBroadcast(); 16155 for (int i = 0; i < n; i++) { 16156 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16157 try { 16158 invokeCallback(callback, msg.what, args); 16159 } catch (RemoteException ignored) { 16160 } 16161 } 16162 mCallbacks.finishBroadcast(); 16163 args.recycle(); 16164 } 16165 16166 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16167 throws RemoteException { 16168 switch (what) { 16169 case MSG_CREATED: { 16170 callback.onCreated(args.argi1, (Bundle) args.arg2); 16171 break; 16172 } 16173 case MSG_STATUS_CHANGED: { 16174 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16175 break; 16176 } 16177 } 16178 } 16179 16180 private void notifyCreated(int moveId, Bundle extras) { 16181 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16182 16183 final SomeArgs args = SomeArgs.obtain(); 16184 args.argi1 = moveId; 16185 args.arg2 = extras; 16186 obtainMessage(MSG_CREATED, args).sendToTarget(); 16187 } 16188 16189 private void notifyStatusChanged(int moveId, int status) { 16190 notifyStatusChanged(moveId, status, -1); 16191 } 16192 16193 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16194 Slog.v(TAG, "Move " + moveId + " status " + status); 16195 16196 final SomeArgs args = SomeArgs.obtain(); 16197 args.argi1 = moveId; 16198 args.argi2 = status; 16199 args.arg3 = estMillis; 16200 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16201 16202 synchronized (mLastStatus) { 16203 mLastStatus.put(moveId, status); 16204 } 16205 } 16206 } 16207 16208 private final class OnPermissionChangeListeners extends Handler { 16209 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16210 16211 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16212 new RemoteCallbackList<>(); 16213 16214 public OnPermissionChangeListeners(Looper looper) { 16215 super(looper); 16216 } 16217 16218 @Override 16219 public void handleMessage(Message msg) { 16220 switch (msg.what) { 16221 case MSG_ON_PERMISSIONS_CHANGED: { 16222 final int uid = msg.arg1; 16223 handleOnPermissionsChanged(uid); 16224 } break; 16225 } 16226 } 16227 16228 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16229 mPermissionListeners.register(listener); 16230 16231 } 16232 16233 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16234 mPermissionListeners.unregister(listener); 16235 } 16236 16237 public void onPermissionsChanged(int uid) { 16238 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16239 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16240 } 16241 } 16242 16243 private void handleOnPermissionsChanged(int uid) { 16244 final int count = mPermissionListeners.beginBroadcast(); 16245 try { 16246 for (int i = 0; i < count; i++) { 16247 IOnPermissionsChangeListener callback = mPermissionListeners 16248 .getBroadcastItem(i); 16249 try { 16250 callback.onPermissionsChanged(uid); 16251 } catch (RemoteException e) { 16252 Log.e(TAG, "Permission listener is dead", e); 16253 } 16254 } 16255 } finally { 16256 mPermissionListeners.finishBroadcast(); 16257 } 16258 } 16259 } 16260 16261 private class PackageManagerInternalImpl extends PackageManagerInternal { 16262 @Override 16263 public void setLocationPackagesProvider(PackagesProvider provider) { 16264 synchronized (mPackages) { 16265 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16266 } 16267 } 16268 16269 @Override 16270 public void setImePackagesProvider(PackagesProvider provider) { 16271 synchronized (mPackages) { 16272 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16273 } 16274 } 16275 16276 @Override 16277 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16278 synchronized (mPackages) { 16279 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16280 } 16281 } 16282 16283 @Override 16284 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16285 synchronized (mPackages) { 16286 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16287 } 16288 } 16289 16290 @Override 16291 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16292 synchronized (mPackages) { 16293 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16294 } 16295 } 16296 16297 @Override 16298 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16299 synchronized (mPackages) { 16300 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 16301 } 16302 } 16303 16304 @Override 16305 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16306 synchronized (mPackages) { 16307 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16308 packageName, userId); 16309 } 16310 } 16311 16312 @Override 16313 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16314 synchronized (mPackages) { 16315 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16316 packageName, userId); 16317 } 16318 } 16319 } 16320 16321 @Override 16322 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16323 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16324 synchronized (mPackages) { 16325 final long identity = Binder.clearCallingIdentity(); 16326 try { 16327 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16328 packageNames, userId); 16329 } finally { 16330 Binder.restoreCallingIdentity(identity); 16331 } 16332 } 16333 } 16334 16335 private static void enforceSystemOrPhoneCaller(String tag) { 16336 int callingUid = Binder.getCallingUid(); 16337 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16338 throw new SecurityException( 16339 "Cannot call " + tag + " from UID " + callingUid); 16340 } 16341 } 16342} 16343