PackageManagerService.java revision 01e186437f7c41b5cf8a97becb22d2f369c374da
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 package " + packageName 713 +" verificationId:" + verificationId); 714 715 synchronized (mPackages) { 716 if (verified) { 717 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 718 } else { 719 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 720 } 721 scheduleWriteSettingsLocked(); 722 723 final int userId = ivs.getUserId(); 724 if (userId != UserHandle.USER_ALL) { 725 final int userStatus = 726 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 727 728 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 729 boolean needUpdate = false; 730 731 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 732 // already been set by the User thru the Disambiguation dialog 733 switch (userStatus) { 734 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 735 if (verified) { 736 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 737 } else { 738 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 739 } 740 needUpdate = true; 741 break; 742 743 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 744 if (verified) { 745 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 746 needUpdate = true; 747 } 748 break; 749 750 default: 751 // Nothing to do 752 } 753 754 if (needUpdate) { 755 mSettings.updateIntentFilterVerificationStatusLPw( 756 packageName, updatedStatus, userId); 757 scheduleWritePackageRestrictionsLocked(userId); 758 } 759 } 760 } 761 } 762 763 @Override 764 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 765 ActivityIntentInfo filter, String packageName) { 766 if (!hasValidDomains(filter)) { 767 return false; 768 } 769 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 770 if (ivs == null) { 771 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 772 packageName); 773 } 774 if (DEBUG_DOMAIN_VERIFICATION) { 775 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 776 } 777 ivs.addFilter(filter); 778 return true; 779 } 780 781 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 782 int userId, int verificationId, String packageName) { 783 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 784 verifierUid, userId, packageName); 785 ivs.setPendingState(); 786 synchronized (mPackages) { 787 mIntentFilterVerificationStates.append(verificationId, ivs); 788 mCurrentIntentFilterVerifications.add(verificationId); 789 } 790 return ivs; 791 } 792 } 793 794 private static boolean hasValidDomains(ActivityIntentInfo filter) { 795 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 796 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 797 if (!hasHTTPorHTTPS) { 798 return false; 799 } 800 return true; 801 } 802 803 private IntentFilterVerifier mIntentFilterVerifier; 804 805 // Set of pending broadcasts for aggregating enable/disable of components. 806 static class PendingPackageBroadcasts { 807 // for each user id, a map of <package name -> components within that package> 808 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 809 810 public PendingPackageBroadcasts() { 811 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 812 } 813 814 public ArrayList<String> get(int userId, String packageName) { 815 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 816 return packages.get(packageName); 817 } 818 819 public void put(int userId, String packageName, ArrayList<String> components) { 820 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 821 packages.put(packageName, components); 822 } 823 824 public void remove(int userId, String packageName) { 825 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 826 if (packages != null) { 827 packages.remove(packageName); 828 } 829 } 830 831 public void remove(int userId) { 832 mUidMap.remove(userId); 833 } 834 835 public int userIdCount() { 836 return mUidMap.size(); 837 } 838 839 public int userIdAt(int n) { 840 return mUidMap.keyAt(n); 841 } 842 843 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 844 return mUidMap.get(userId); 845 } 846 847 public int size() { 848 // total number of pending broadcast entries across all userIds 849 int num = 0; 850 for (int i = 0; i< mUidMap.size(); i++) { 851 num += mUidMap.valueAt(i).size(); 852 } 853 return num; 854 } 855 856 public void clear() { 857 mUidMap.clear(); 858 } 859 860 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 861 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 862 if (map == null) { 863 map = new ArrayMap<String, ArrayList<String>>(); 864 mUidMap.put(userId, map); 865 } 866 return map; 867 } 868 } 869 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 870 871 // Service Connection to remote media container service to copy 872 // package uri's from external media onto secure containers 873 // or internal storage. 874 private IMediaContainerService mContainerService = null; 875 876 static final int SEND_PENDING_BROADCAST = 1; 877 static final int MCS_BOUND = 3; 878 static final int END_COPY = 4; 879 static final int INIT_COPY = 5; 880 static final int MCS_UNBIND = 6; 881 static final int START_CLEANING_PACKAGE = 7; 882 static final int FIND_INSTALL_LOC = 8; 883 static final int POST_INSTALL = 9; 884 static final int MCS_RECONNECT = 10; 885 static final int MCS_GIVE_UP = 11; 886 static final int UPDATED_MEDIA_STATUS = 12; 887 static final int WRITE_SETTINGS = 13; 888 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 889 static final int PACKAGE_VERIFIED = 15; 890 static final int CHECK_PENDING_VERIFICATION = 16; 891 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 892 static final int INTENT_FILTER_VERIFIED = 18; 893 894 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 895 896 // Delay time in millisecs 897 static final int BROADCAST_DELAY = 10 * 1000; 898 899 static UserManagerService sUserManager; 900 901 // Stores a list of users whose package restrictions file needs to be updated 902 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 903 904 final private DefaultContainerConnection mDefContainerConn = 905 new DefaultContainerConnection(); 906 class DefaultContainerConnection implements ServiceConnection { 907 public void onServiceConnected(ComponentName name, IBinder service) { 908 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 909 IMediaContainerService imcs = 910 IMediaContainerService.Stub.asInterface(service); 911 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 912 } 913 914 public void onServiceDisconnected(ComponentName name) { 915 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 916 } 917 } 918 919 // Recordkeeping of restore-after-install operations that are currently in flight 920 // between the Package Manager and the Backup Manager 921 class PostInstallData { 922 public InstallArgs args; 923 public PackageInstalledInfo res; 924 925 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 926 args = _a; 927 res = _r; 928 } 929 } 930 931 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 932 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 933 934 // XML tags for backup/restore of various bits of state 935 private static final String TAG_PREFERRED_BACKUP = "pa"; 936 private static final String TAG_DEFAULT_APPS = "da"; 937 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 938 939 final String mRequiredVerifierPackage; 940 final String mRequiredInstallerPackage; 941 942 private final PackageUsage mPackageUsage = new PackageUsage(); 943 944 private class PackageUsage { 945 private static final int WRITE_INTERVAL 946 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 947 948 private final Object mFileLock = new Object(); 949 private final AtomicLong mLastWritten = new AtomicLong(0); 950 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 951 952 private boolean mIsHistoricalPackageUsageAvailable = true; 953 954 boolean isHistoricalPackageUsageAvailable() { 955 return mIsHistoricalPackageUsageAvailable; 956 } 957 958 void write(boolean force) { 959 if (force) { 960 writeInternal(); 961 return; 962 } 963 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 964 && !DEBUG_DEXOPT) { 965 return; 966 } 967 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 968 new Thread("PackageUsage_DiskWriter") { 969 @Override 970 public void run() { 971 try { 972 writeInternal(); 973 } finally { 974 mBackgroundWriteRunning.set(false); 975 } 976 } 977 }.start(); 978 } 979 } 980 981 private void writeInternal() { 982 synchronized (mPackages) { 983 synchronized (mFileLock) { 984 AtomicFile file = getFile(); 985 FileOutputStream f = null; 986 try { 987 f = file.startWrite(); 988 BufferedOutputStream out = new BufferedOutputStream(f); 989 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 990 StringBuilder sb = new StringBuilder(); 991 for (PackageParser.Package pkg : mPackages.values()) { 992 if (pkg.mLastPackageUsageTimeInMills == 0) { 993 continue; 994 } 995 sb.setLength(0); 996 sb.append(pkg.packageName); 997 sb.append(' '); 998 sb.append((long)pkg.mLastPackageUsageTimeInMills); 999 sb.append('\n'); 1000 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1001 } 1002 out.flush(); 1003 file.finishWrite(f); 1004 } catch (IOException e) { 1005 if (f != null) { 1006 file.failWrite(f); 1007 } 1008 Log.e(TAG, "Failed to write package usage times", e); 1009 } 1010 } 1011 } 1012 mLastWritten.set(SystemClock.elapsedRealtime()); 1013 } 1014 1015 void readLP() { 1016 synchronized (mFileLock) { 1017 AtomicFile file = getFile(); 1018 BufferedInputStream in = null; 1019 try { 1020 in = new BufferedInputStream(file.openRead()); 1021 StringBuffer sb = new StringBuffer(); 1022 while (true) { 1023 String packageName = readToken(in, sb, ' '); 1024 if (packageName == null) { 1025 break; 1026 } 1027 String timeInMillisString = readToken(in, sb, '\n'); 1028 if (timeInMillisString == null) { 1029 throw new IOException("Failed to find last usage time for package " 1030 + packageName); 1031 } 1032 PackageParser.Package pkg = mPackages.get(packageName); 1033 if (pkg == null) { 1034 continue; 1035 } 1036 long timeInMillis; 1037 try { 1038 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1039 } catch (NumberFormatException e) { 1040 throw new IOException("Failed to parse " + timeInMillisString 1041 + " as a long.", e); 1042 } 1043 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1044 } 1045 } catch (FileNotFoundException expected) { 1046 mIsHistoricalPackageUsageAvailable = false; 1047 } catch (IOException e) { 1048 Log.w(TAG, "Failed to read package usage times", e); 1049 } finally { 1050 IoUtils.closeQuietly(in); 1051 } 1052 } 1053 mLastWritten.set(SystemClock.elapsedRealtime()); 1054 } 1055 1056 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1057 throws IOException { 1058 sb.setLength(0); 1059 while (true) { 1060 int ch = in.read(); 1061 if (ch == -1) { 1062 if (sb.length() == 0) { 1063 return null; 1064 } 1065 throw new IOException("Unexpected EOF"); 1066 } 1067 if (ch == endOfToken) { 1068 return sb.toString(); 1069 } 1070 sb.append((char)ch); 1071 } 1072 } 1073 1074 private AtomicFile getFile() { 1075 File dataDir = Environment.getDataDirectory(); 1076 File systemDir = new File(dataDir, "system"); 1077 File fname = new File(systemDir, "package-usage.list"); 1078 return new AtomicFile(fname); 1079 } 1080 } 1081 1082 class PackageHandler extends Handler { 1083 private boolean mBound = false; 1084 final ArrayList<HandlerParams> mPendingInstalls = 1085 new ArrayList<HandlerParams>(); 1086 1087 private boolean connectToService() { 1088 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1089 " DefaultContainerService"); 1090 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1091 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1092 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1093 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1094 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1095 mBound = true; 1096 return true; 1097 } 1098 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1099 return false; 1100 } 1101 1102 private void disconnectService() { 1103 mContainerService = null; 1104 mBound = false; 1105 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1106 mContext.unbindService(mDefContainerConn); 1107 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1108 } 1109 1110 PackageHandler(Looper looper) { 1111 super(looper); 1112 } 1113 1114 public void handleMessage(Message msg) { 1115 try { 1116 doHandleMessage(msg); 1117 } finally { 1118 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1119 } 1120 } 1121 1122 void doHandleMessage(Message msg) { 1123 switch (msg.what) { 1124 case INIT_COPY: { 1125 HandlerParams params = (HandlerParams) msg.obj; 1126 int idx = mPendingInstalls.size(); 1127 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1128 // If a bind was already initiated we dont really 1129 // need to do anything. The pending install 1130 // will be processed later on. 1131 if (!mBound) { 1132 // If this is the only one pending we might 1133 // have to bind to the service again. 1134 if (!connectToService()) { 1135 Slog.e(TAG, "Failed to bind to media container service"); 1136 params.serviceError(); 1137 return; 1138 } else { 1139 // Once we bind to the service, the first 1140 // pending request will be processed. 1141 mPendingInstalls.add(idx, params); 1142 } 1143 } else { 1144 mPendingInstalls.add(idx, params); 1145 // Already bound to the service. Just make 1146 // sure we trigger off processing the first request. 1147 if (idx == 0) { 1148 mHandler.sendEmptyMessage(MCS_BOUND); 1149 } 1150 } 1151 break; 1152 } 1153 case MCS_BOUND: { 1154 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1155 if (msg.obj != null) { 1156 mContainerService = (IMediaContainerService) msg.obj; 1157 } 1158 if (mContainerService == null) { 1159 if (!mBound) { 1160 // Something seriously wrong since we are not bound and we are not 1161 // waiting for connection. Bail out. 1162 Slog.e(TAG, "Cannot bind to media container service"); 1163 for (HandlerParams params : mPendingInstalls) { 1164 // Indicate service bind error 1165 params.serviceError(); 1166 } 1167 mPendingInstalls.clear(); 1168 } else { 1169 Slog.w(TAG, "Waiting to connect to media container service"); 1170 } 1171 } else if (mPendingInstalls.size() > 0) { 1172 HandlerParams params = mPendingInstalls.get(0); 1173 if (params != null) { 1174 if (params.startCopy()) { 1175 // We are done... look for more work or to 1176 // go idle. 1177 if (DEBUG_SD_INSTALL) Log.i(TAG, 1178 "Checking for more work or unbind..."); 1179 // Delete pending install 1180 if (mPendingInstalls.size() > 0) { 1181 mPendingInstalls.remove(0); 1182 } 1183 if (mPendingInstalls.size() == 0) { 1184 if (mBound) { 1185 if (DEBUG_SD_INSTALL) Log.i(TAG, 1186 "Posting delayed MCS_UNBIND"); 1187 removeMessages(MCS_UNBIND); 1188 Message ubmsg = obtainMessage(MCS_UNBIND); 1189 // Unbind after a little delay, to avoid 1190 // continual thrashing. 1191 sendMessageDelayed(ubmsg, 10000); 1192 } 1193 } else { 1194 // There are more pending requests in queue. 1195 // Just post MCS_BOUND message to trigger processing 1196 // of next pending install. 1197 if (DEBUG_SD_INSTALL) Log.i(TAG, 1198 "Posting MCS_BOUND for next work"); 1199 mHandler.sendEmptyMessage(MCS_BOUND); 1200 } 1201 } 1202 } 1203 } else { 1204 // Should never happen ideally. 1205 Slog.w(TAG, "Empty queue"); 1206 } 1207 break; 1208 } 1209 case MCS_RECONNECT: { 1210 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1211 if (mPendingInstalls.size() > 0) { 1212 if (mBound) { 1213 disconnectService(); 1214 } 1215 if (!connectToService()) { 1216 Slog.e(TAG, "Failed to bind to media container service"); 1217 for (HandlerParams params : mPendingInstalls) { 1218 // Indicate service bind error 1219 params.serviceError(); 1220 } 1221 mPendingInstalls.clear(); 1222 } 1223 } 1224 break; 1225 } 1226 case MCS_UNBIND: { 1227 // If there is no actual work left, then time to unbind. 1228 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1229 1230 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1231 if (mBound) { 1232 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1233 1234 disconnectService(); 1235 } 1236 } else if (mPendingInstalls.size() > 0) { 1237 // There are more pending requests in queue. 1238 // Just post MCS_BOUND message to trigger processing 1239 // of next pending install. 1240 mHandler.sendEmptyMessage(MCS_BOUND); 1241 } 1242 1243 break; 1244 } 1245 case MCS_GIVE_UP: { 1246 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1247 mPendingInstalls.remove(0); 1248 break; 1249 } 1250 case SEND_PENDING_BROADCAST: { 1251 String packages[]; 1252 ArrayList<String> components[]; 1253 int size = 0; 1254 int uids[]; 1255 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1256 synchronized (mPackages) { 1257 if (mPendingBroadcasts == null) { 1258 return; 1259 } 1260 size = mPendingBroadcasts.size(); 1261 if (size <= 0) { 1262 // Nothing to be done. Just return 1263 return; 1264 } 1265 packages = new String[size]; 1266 components = new ArrayList[size]; 1267 uids = new int[size]; 1268 int i = 0; // filling out the above arrays 1269 1270 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1271 int packageUserId = mPendingBroadcasts.userIdAt(n); 1272 Iterator<Map.Entry<String, ArrayList<String>>> it 1273 = mPendingBroadcasts.packagesForUserId(packageUserId) 1274 .entrySet().iterator(); 1275 while (it.hasNext() && i < size) { 1276 Map.Entry<String, ArrayList<String>> ent = it.next(); 1277 packages[i] = ent.getKey(); 1278 components[i] = ent.getValue(); 1279 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1280 uids[i] = (ps != null) 1281 ? UserHandle.getUid(packageUserId, ps.appId) 1282 : -1; 1283 i++; 1284 } 1285 } 1286 size = i; 1287 mPendingBroadcasts.clear(); 1288 } 1289 // Send broadcasts 1290 for (int i = 0; i < size; i++) { 1291 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1292 } 1293 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1294 break; 1295 } 1296 case START_CLEANING_PACKAGE: { 1297 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1298 final String packageName = (String)msg.obj; 1299 final int userId = msg.arg1; 1300 final boolean andCode = msg.arg2 != 0; 1301 synchronized (mPackages) { 1302 if (userId == UserHandle.USER_ALL) { 1303 int[] users = sUserManager.getUserIds(); 1304 for (int user : users) { 1305 mSettings.addPackageToCleanLPw( 1306 new PackageCleanItem(user, packageName, andCode)); 1307 } 1308 } else { 1309 mSettings.addPackageToCleanLPw( 1310 new PackageCleanItem(userId, packageName, andCode)); 1311 } 1312 } 1313 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1314 startCleaningPackages(); 1315 } break; 1316 case POST_INSTALL: { 1317 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1318 PostInstallData data = mRunningInstalls.get(msg.arg1); 1319 mRunningInstalls.delete(msg.arg1); 1320 boolean deleteOld = false; 1321 1322 if (data != null) { 1323 InstallArgs args = data.args; 1324 PackageInstalledInfo res = data.res; 1325 1326 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1327 final String packageName = res.pkg.applicationInfo.packageName; 1328 res.removedInfo.sendBroadcast(false, true, false); 1329 Bundle extras = new Bundle(1); 1330 extras.putInt(Intent.EXTRA_UID, res.uid); 1331 1332 // Now that we successfully installed the package, grant runtime 1333 // permissions if requested before broadcasting the install. 1334 if ((args.installFlags 1335 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1336 grantRequestedRuntimePermissions(res.pkg, 1337 args.user.getIdentifier()); 1338 } 1339 1340 // Determine the set of users who are adding this 1341 // package for the first time vs. those who are seeing 1342 // an update. 1343 int[] firstUsers; 1344 int[] updateUsers = new int[0]; 1345 if (res.origUsers == null || res.origUsers.length == 0) { 1346 firstUsers = res.newUsers; 1347 } else { 1348 firstUsers = new int[0]; 1349 for (int i=0; i<res.newUsers.length; i++) { 1350 int user = res.newUsers[i]; 1351 boolean isNew = true; 1352 for (int j=0; j<res.origUsers.length; j++) { 1353 if (res.origUsers[j] == user) { 1354 isNew = false; 1355 break; 1356 } 1357 } 1358 if (isNew) { 1359 int[] newFirst = new int[firstUsers.length+1]; 1360 System.arraycopy(firstUsers, 0, newFirst, 0, 1361 firstUsers.length); 1362 newFirst[firstUsers.length] = user; 1363 firstUsers = newFirst; 1364 } else { 1365 int[] newUpdate = new int[updateUsers.length+1]; 1366 System.arraycopy(updateUsers, 0, newUpdate, 0, 1367 updateUsers.length); 1368 newUpdate[updateUsers.length] = user; 1369 updateUsers = newUpdate; 1370 } 1371 } 1372 } 1373 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1374 packageName, extras, null, null, firstUsers); 1375 final boolean update = res.removedInfo.removedPackage != null; 1376 if (update) { 1377 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1378 } 1379 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1380 packageName, extras, null, null, updateUsers); 1381 if (update) { 1382 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1383 packageName, extras, null, null, updateUsers); 1384 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1385 null, null, packageName, null, updateUsers); 1386 1387 // treat asec-hosted packages like removable media on upgrade 1388 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1389 if (DEBUG_INSTALL) { 1390 Slog.i(TAG, "upgrading pkg " + res.pkg 1391 + " is ASEC-hosted -> AVAILABLE"); 1392 } 1393 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1394 ArrayList<String> pkgList = new ArrayList<String>(1); 1395 pkgList.add(packageName); 1396 sendResourcesChangedBroadcast(true, true, 1397 pkgList,uidArray, null); 1398 } 1399 } 1400 if (res.removedInfo.args != null) { 1401 // Remove the replaced package's older resources safely now 1402 deleteOld = true; 1403 } 1404 1405 // If this app is a browser and it's newly-installed for some 1406 // users, clear any default-browser state in those users 1407 if (firstUsers.length > 0) { 1408 // the app's nature doesn't depend on the user, so we can just 1409 // check its browser nature in any user and generalize. 1410 if (packageIsBrowser(packageName, firstUsers[0])) { 1411 synchronized (mPackages) { 1412 for (int userId : firstUsers) { 1413 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1414 } 1415 } 1416 } 1417 } 1418 // Log current value of "unknown sources" setting 1419 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1420 getUnknownSourcesSettings()); 1421 } 1422 // Force a gc to clear up things 1423 Runtime.getRuntime().gc(); 1424 // We delete after a gc for applications on sdcard. 1425 if (deleteOld) { 1426 synchronized (mInstallLock) { 1427 res.removedInfo.args.doPostDeleteLI(true); 1428 } 1429 } 1430 if (args.observer != null) { 1431 try { 1432 Bundle extras = extrasForInstallResult(res); 1433 args.observer.onPackageInstalled(res.name, res.returnCode, 1434 res.returnMsg, extras); 1435 } catch (RemoteException e) { 1436 Slog.i(TAG, "Observer no longer exists."); 1437 } 1438 } 1439 } else { 1440 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1441 } 1442 } break; 1443 case UPDATED_MEDIA_STATUS: { 1444 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1445 boolean reportStatus = msg.arg1 == 1; 1446 boolean doGc = msg.arg2 == 1; 1447 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1448 if (doGc) { 1449 // Force a gc to clear up stale containers. 1450 Runtime.getRuntime().gc(); 1451 } 1452 if (msg.obj != null) { 1453 @SuppressWarnings("unchecked") 1454 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1455 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1456 // Unload containers 1457 unloadAllContainers(args); 1458 } 1459 if (reportStatus) { 1460 try { 1461 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1462 PackageHelper.getMountService().finishMediaUpdate(); 1463 } catch (RemoteException e) { 1464 Log.e(TAG, "MountService not running?"); 1465 } 1466 } 1467 } break; 1468 case WRITE_SETTINGS: { 1469 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1470 synchronized (mPackages) { 1471 removeMessages(WRITE_SETTINGS); 1472 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1473 mSettings.writeLPr(); 1474 mDirtyUsers.clear(); 1475 } 1476 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1477 } break; 1478 case WRITE_PACKAGE_RESTRICTIONS: { 1479 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1480 synchronized (mPackages) { 1481 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1482 for (int userId : mDirtyUsers) { 1483 mSettings.writePackageRestrictionsLPr(userId); 1484 } 1485 mDirtyUsers.clear(); 1486 } 1487 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1488 } break; 1489 case CHECK_PENDING_VERIFICATION: { 1490 final int verificationId = msg.arg1; 1491 final PackageVerificationState state = mPendingVerification.get(verificationId); 1492 1493 if ((state != null) && !state.timeoutExtended()) { 1494 final InstallArgs args = state.getInstallArgs(); 1495 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1496 1497 Slog.i(TAG, "Verification timed out for " + originUri); 1498 mPendingVerification.remove(verificationId); 1499 1500 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1501 1502 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1503 Slog.i(TAG, "Continuing with installation of " + originUri); 1504 state.setVerifierResponse(Binder.getCallingUid(), 1505 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1506 broadcastPackageVerified(verificationId, originUri, 1507 PackageManager.VERIFICATION_ALLOW, 1508 state.getInstallArgs().getUser()); 1509 try { 1510 ret = args.copyApk(mContainerService, true); 1511 } catch (RemoteException e) { 1512 Slog.e(TAG, "Could not contact the ContainerService"); 1513 } 1514 } else { 1515 broadcastPackageVerified(verificationId, originUri, 1516 PackageManager.VERIFICATION_REJECT, 1517 state.getInstallArgs().getUser()); 1518 } 1519 1520 processPendingInstall(args, ret); 1521 mHandler.sendEmptyMessage(MCS_UNBIND); 1522 } 1523 break; 1524 } 1525 case PACKAGE_VERIFIED: { 1526 final int verificationId = msg.arg1; 1527 1528 final PackageVerificationState state = mPendingVerification.get(verificationId); 1529 if (state == null) { 1530 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1531 break; 1532 } 1533 1534 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1535 1536 state.setVerifierResponse(response.callerUid, response.code); 1537 1538 if (state.isVerificationComplete()) { 1539 mPendingVerification.remove(verificationId); 1540 1541 final InstallArgs args = state.getInstallArgs(); 1542 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1543 1544 int ret; 1545 if (state.isInstallAllowed()) { 1546 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1547 broadcastPackageVerified(verificationId, originUri, 1548 response.code, state.getInstallArgs().getUser()); 1549 try { 1550 ret = args.copyApk(mContainerService, true); 1551 } catch (RemoteException e) { 1552 Slog.e(TAG, "Could not contact the ContainerService"); 1553 } 1554 } else { 1555 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1556 } 1557 1558 processPendingInstall(args, ret); 1559 1560 mHandler.sendEmptyMessage(MCS_UNBIND); 1561 } 1562 1563 break; 1564 } 1565 case START_INTENT_FILTER_VERIFICATIONS: { 1566 IFVerificationParams params = (IFVerificationParams) msg.obj; 1567 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1568 params.replacing, params.pkg); 1569 break; 1570 } 1571 case INTENT_FILTER_VERIFIED: { 1572 final int verificationId = msg.arg1; 1573 1574 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1575 verificationId); 1576 if (state == null) { 1577 Slog.w(TAG, "Invalid IntentFilter verification token " 1578 + verificationId + " received"); 1579 break; 1580 } 1581 1582 final int userId = state.getUserId(); 1583 1584 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1585 "Processing IntentFilter verification with token:" 1586 + verificationId + " and userId:" + userId); 1587 1588 final IntentFilterVerificationResponse response = 1589 (IntentFilterVerificationResponse) msg.obj; 1590 1591 state.setVerifierResponse(response.callerUid, response.code); 1592 1593 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1594 "IntentFilter verification with token:" + verificationId 1595 + " and userId:" + userId 1596 + " is settings verifier response with response code:" 1597 + response.code); 1598 1599 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1600 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1601 + response.getFailedDomainsString()); 1602 } 1603 1604 if (state.isVerificationComplete()) { 1605 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1606 } else { 1607 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1608 "IntentFilter verification with token:" + verificationId 1609 + " was not said to be complete"); 1610 } 1611 1612 break; 1613 } 1614 } 1615 } 1616 } 1617 1618 private StorageEventListener mStorageListener = new StorageEventListener() { 1619 @Override 1620 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1621 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1622 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1623 final String volumeUuid = vol.getFsUuid(); 1624 1625 // Clean up any users or apps that were removed or recreated 1626 // while this volume was missing 1627 reconcileUsers(volumeUuid); 1628 reconcileApps(volumeUuid); 1629 1630 // Clean up any install sessions that expired or were 1631 // cancelled while this volume was missing 1632 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1633 1634 loadPrivatePackages(vol); 1635 1636 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1637 unloadPrivatePackages(vol); 1638 } 1639 } 1640 1641 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1642 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1643 updateExternalMediaStatus(true, false); 1644 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1645 updateExternalMediaStatus(false, false); 1646 } 1647 } 1648 } 1649 1650 @Override 1651 public void onVolumeForgotten(String fsUuid) { 1652 // Remove any apps installed on the forgotten volume 1653 synchronized (mPackages) { 1654 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1655 for (PackageSetting ps : packages) { 1656 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1657 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1658 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1659 } 1660 1661 mSettings.writeLPr(); 1662 } 1663 } 1664 }; 1665 1666 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1667 if (userId >= UserHandle.USER_OWNER) { 1668 grantRequestedRuntimePermissionsForUser(pkg, userId); 1669 } else if (userId == UserHandle.USER_ALL) { 1670 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1671 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1672 } 1673 } 1674 1675 // We could have touched GID membership, so flush out packages.list 1676 synchronized (mPackages) { 1677 mSettings.writePackageListLPr(); 1678 } 1679 } 1680 1681 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1682 SettingBase sb = (SettingBase) pkg.mExtras; 1683 if (sb == null) { 1684 return; 1685 } 1686 1687 PermissionsState permissionsState = sb.getPermissionsState(); 1688 1689 for (String permission : pkg.requestedPermissions) { 1690 BasePermission bp = mSettings.mPermissions.get(permission); 1691 if (bp != null && bp.isRuntime()) { 1692 permissionsState.grantRuntimePermission(bp, userId); 1693 } 1694 } 1695 } 1696 1697 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1698 Bundle extras = null; 1699 switch (res.returnCode) { 1700 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1701 extras = new Bundle(); 1702 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1703 res.origPermission); 1704 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1705 res.origPackage); 1706 break; 1707 } 1708 case PackageManager.INSTALL_SUCCEEDED: { 1709 extras = new Bundle(); 1710 extras.putBoolean(Intent.EXTRA_REPLACING, 1711 res.removedInfo != null && res.removedInfo.removedPackage != null); 1712 break; 1713 } 1714 } 1715 return extras; 1716 } 1717 1718 void scheduleWriteSettingsLocked() { 1719 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1720 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1721 } 1722 } 1723 1724 void scheduleWritePackageRestrictionsLocked(int userId) { 1725 if (!sUserManager.exists(userId)) return; 1726 mDirtyUsers.add(userId); 1727 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1728 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1729 } 1730 } 1731 1732 public static PackageManagerService main(Context context, Installer installer, 1733 boolean factoryTest, boolean onlyCore) { 1734 PackageManagerService m = new PackageManagerService(context, installer, 1735 factoryTest, onlyCore); 1736 ServiceManager.addService("package", m); 1737 return m; 1738 } 1739 1740 static String[] splitString(String str, char sep) { 1741 int count = 1; 1742 int i = 0; 1743 while ((i=str.indexOf(sep, i)) >= 0) { 1744 count++; 1745 i++; 1746 } 1747 1748 String[] res = new String[count]; 1749 i=0; 1750 count = 0; 1751 int lastI=0; 1752 while ((i=str.indexOf(sep, i)) >= 0) { 1753 res[count] = str.substring(lastI, i); 1754 count++; 1755 i++; 1756 lastI = i; 1757 } 1758 res[count] = str.substring(lastI, str.length()); 1759 return res; 1760 } 1761 1762 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1763 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1764 Context.DISPLAY_SERVICE); 1765 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1766 } 1767 1768 public PackageManagerService(Context context, Installer installer, 1769 boolean factoryTest, boolean onlyCore) { 1770 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1771 SystemClock.uptimeMillis()); 1772 1773 if (mSdkVersion <= 0) { 1774 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1775 } 1776 1777 mContext = context; 1778 mFactoryTest = factoryTest; 1779 mOnlyCore = onlyCore; 1780 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1781 mMetrics = new DisplayMetrics(); 1782 mSettings = new Settings(mPackages); 1783 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1784 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1785 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1786 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1787 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1788 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1789 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1790 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1791 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1792 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1793 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1794 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1795 1796 // TODO: add a property to control this? 1797 long dexOptLRUThresholdInMinutes; 1798 if (mLazyDexOpt) { 1799 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1800 } else { 1801 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1802 } 1803 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1804 1805 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1806 if (separateProcesses != null && separateProcesses.length() > 0) { 1807 if ("*".equals(separateProcesses)) { 1808 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1809 mSeparateProcesses = null; 1810 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1811 } else { 1812 mDefParseFlags = 0; 1813 mSeparateProcesses = separateProcesses.split(","); 1814 Slog.w(TAG, "Running with debug.separate_processes: " 1815 + separateProcesses); 1816 } 1817 } else { 1818 mDefParseFlags = 0; 1819 mSeparateProcesses = null; 1820 } 1821 1822 mInstaller = installer; 1823 mPackageDexOptimizer = new PackageDexOptimizer(this); 1824 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1825 1826 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1827 FgThread.get().getLooper()); 1828 1829 getDefaultDisplayMetrics(context, mMetrics); 1830 1831 SystemConfig systemConfig = SystemConfig.getInstance(); 1832 mGlobalGids = systemConfig.getGlobalGids(); 1833 mSystemPermissions = systemConfig.getSystemPermissions(); 1834 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1835 1836 synchronized (mInstallLock) { 1837 // writer 1838 synchronized (mPackages) { 1839 mHandlerThread = new ServiceThread(TAG, 1840 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1841 mHandlerThread.start(); 1842 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1843 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1844 1845 File dataDir = Environment.getDataDirectory(); 1846 mAppDataDir = new File(dataDir, "data"); 1847 mAppInstallDir = new File(dataDir, "app"); 1848 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1849 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1850 mUserAppDataDir = new File(dataDir, "user"); 1851 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1852 1853 sUserManager = new UserManagerService(context, this, 1854 mInstallLock, mPackages); 1855 1856 // Propagate permission configuration in to package manager. 1857 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1858 = systemConfig.getPermissions(); 1859 for (int i=0; i<permConfig.size(); i++) { 1860 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1861 BasePermission bp = mSettings.mPermissions.get(perm.name); 1862 if (bp == null) { 1863 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1864 mSettings.mPermissions.put(perm.name, bp); 1865 } 1866 if (perm.gids != null) { 1867 bp.setGids(perm.gids, perm.perUser); 1868 } 1869 } 1870 1871 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1872 for (int i=0; i<libConfig.size(); i++) { 1873 mSharedLibraries.put(libConfig.keyAt(i), 1874 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1875 } 1876 1877 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1878 1879 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1880 mSdkVersion, mOnlyCore); 1881 1882 String customResolverActivity = Resources.getSystem().getString( 1883 R.string.config_customResolverActivity); 1884 if (TextUtils.isEmpty(customResolverActivity)) { 1885 customResolverActivity = null; 1886 } else { 1887 mCustomResolverComponentName = ComponentName.unflattenFromString( 1888 customResolverActivity); 1889 } 1890 1891 long startTime = SystemClock.uptimeMillis(); 1892 1893 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1894 startTime); 1895 1896 // Set flag to monitor and not change apk file paths when 1897 // scanning install directories. 1898 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1899 1900 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1901 1902 /** 1903 * Add everything in the in the boot class path to the 1904 * list of process files because dexopt will have been run 1905 * if necessary during zygote startup. 1906 */ 1907 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1908 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1909 1910 if (bootClassPath != null) { 1911 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1912 for (String element : bootClassPathElements) { 1913 alreadyDexOpted.add(element); 1914 } 1915 } else { 1916 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1917 } 1918 1919 if (systemServerClassPath != null) { 1920 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1921 for (String element : systemServerClassPathElements) { 1922 alreadyDexOpted.add(element); 1923 } 1924 } else { 1925 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1926 } 1927 1928 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1929 final String[] dexCodeInstructionSets = 1930 getDexCodeInstructionSets( 1931 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1932 1933 /** 1934 * Ensure all external libraries have had dexopt run on them. 1935 */ 1936 if (mSharedLibraries.size() > 0) { 1937 // NOTE: For now, we're compiling these system "shared libraries" 1938 // (and framework jars) into all available architectures. It's possible 1939 // to compile them only when we come across an app that uses them (there's 1940 // already logic for that in scanPackageLI) but that adds some complexity. 1941 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1942 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1943 final String lib = libEntry.path; 1944 if (lib == null) { 1945 continue; 1946 } 1947 1948 try { 1949 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1950 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1951 alreadyDexOpted.add(lib); 1952 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1953 } 1954 } catch (FileNotFoundException e) { 1955 Slog.w(TAG, "Library not found: " + lib); 1956 } catch (IOException e) { 1957 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1958 + e.getMessage()); 1959 } 1960 } 1961 } 1962 } 1963 1964 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1965 1966 // Gross hack for now: we know this file doesn't contain any 1967 // code, so don't dexopt it to avoid the resulting log spew. 1968 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1969 1970 // Gross hack for now: we know this file is only part of 1971 // the boot class path for art, so don't dexopt it to 1972 // avoid the resulting log spew. 1973 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1974 1975 /** 1976 * There are a number of commands implemented in Java, which 1977 * we currently need to do the dexopt on so that they can be 1978 * run from a non-root shell. 1979 */ 1980 String[] frameworkFiles = frameworkDir.list(); 1981 if (frameworkFiles != null) { 1982 // TODO: We could compile these only for the most preferred ABI. We should 1983 // first double check that the dex files for these commands are not referenced 1984 // by other system apps. 1985 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1986 for (int i=0; i<frameworkFiles.length; i++) { 1987 File libPath = new File(frameworkDir, frameworkFiles[i]); 1988 String path = libPath.getPath(); 1989 // Skip the file if we already did it. 1990 if (alreadyDexOpted.contains(path)) { 1991 continue; 1992 } 1993 // Skip the file if it is not a type we want to dexopt. 1994 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1995 continue; 1996 } 1997 try { 1998 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1999 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2000 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2001 } 2002 } catch (FileNotFoundException e) { 2003 Slog.w(TAG, "Jar not found: " + path); 2004 } catch (IOException e) { 2005 Slog.w(TAG, "Exception reading jar: " + path, e); 2006 } 2007 } 2008 } 2009 } 2010 2011 // Collect vendor overlay packages. 2012 // (Do this before scanning any apps.) 2013 // For security and version matching reason, only consider 2014 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2015 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2016 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2017 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2018 2019 // Find base frameworks (resource packages without code). 2020 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2021 | PackageParser.PARSE_IS_SYSTEM_DIR 2022 | PackageParser.PARSE_IS_PRIVILEGED, 2023 scanFlags | SCAN_NO_DEX, 0); 2024 2025 // Collected privileged system packages. 2026 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2027 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2028 | PackageParser.PARSE_IS_SYSTEM_DIR 2029 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2030 2031 // Collect ordinary system packages. 2032 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2033 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2034 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2035 2036 // Collect all vendor packages. 2037 File vendorAppDir = new File("/vendor/app"); 2038 try { 2039 vendorAppDir = vendorAppDir.getCanonicalFile(); 2040 } catch (IOException e) { 2041 // failed to look up canonical path, continue with original one 2042 } 2043 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2044 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2045 2046 // Collect all OEM packages. 2047 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2048 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2049 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2050 2051 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2052 mInstaller.moveFiles(); 2053 2054 // Prune any system packages that no longer exist. 2055 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2056 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 2057 if (!mOnlyCore) { 2058 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2059 while (psit.hasNext()) { 2060 PackageSetting ps = psit.next(); 2061 2062 /* 2063 * If this is not a system app, it can't be a 2064 * disable system app. 2065 */ 2066 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2067 continue; 2068 } 2069 2070 /* 2071 * If the package is scanned, it's not erased. 2072 */ 2073 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2074 if (scannedPkg != null) { 2075 /* 2076 * If the system app is both scanned and in the 2077 * disabled packages list, then it must have been 2078 * added via OTA. Remove it from the currently 2079 * scanned package so the previously user-installed 2080 * application can be scanned. 2081 */ 2082 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2083 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2084 + ps.name + "; removing system app. Last known codePath=" 2085 + ps.codePathString + ", installStatus=" + ps.installStatus 2086 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2087 + scannedPkg.mVersionCode); 2088 removePackageLI(ps, true); 2089 expectingBetter.put(ps.name, ps.codePath); 2090 } 2091 2092 continue; 2093 } 2094 2095 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2096 psit.remove(); 2097 logCriticalInfo(Log.WARN, "System package " + ps.name 2098 + " no longer exists; wiping its data"); 2099 removeDataDirsLI(null, ps.name); 2100 } else { 2101 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2102 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2103 possiblyDeletedUpdatedSystemApps.add(ps.name); 2104 } 2105 } 2106 } 2107 } 2108 2109 //look for any incomplete package installations 2110 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2111 //clean up list 2112 for(int i = 0; i < deletePkgsList.size(); i++) { 2113 //clean up here 2114 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2115 } 2116 //delete tmp files 2117 deleteTempPackageFiles(); 2118 2119 // Remove any shared userIDs that have no associated packages 2120 mSettings.pruneSharedUsersLPw(); 2121 2122 if (!mOnlyCore) { 2123 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2124 SystemClock.uptimeMillis()); 2125 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2126 2127 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2128 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2129 2130 /** 2131 * Remove disable package settings for any updated system 2132 * apps that were removed via an OTA. If they're not a 2133 * previously-updated app, remove them completely. 2134 * Otherwise, just revoke their system-level permissions. 2135 */ 2136 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2137 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2138 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2139 2140 String msg; 2141 if (deletedPkg == null) { 2142 msg = "Updated system package " + deletedAppName 2143 + " no longer exists; wiping its data"; 2144 removeDataDirsLI(null, deletedAppName); 2145 } else { 2146 msg = "Updated system app + " + deletedAppName 2147 + " no longer present; removing system privileges for " 2148 + deletedAppName; 2149 2150 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2151 2152 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2153 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2154 } 2155 logCriticalInfo(Log.WARN, msg); 2156 } 2157 2158 /** 2159 * Make sure all system apps that we expected to appear on 2160 * the userdata partition actually showed up. If they never 2161 * appeared, crawl back and revive the system version. 2162 */ 2163 for (int i = 0; i < expectingBetter.size(); i++) { 2164 final String packageName = expectingBetter.keyAt(i); 2165 if (!mPackages.containsKey(packageName)) { 2166 final File scanFile = expectingBetter.valueAt(i); 2167 2168 logCriticalInfo(Log.WARN, "Expected better " + packageName 2169 + " but never showed up; reverting to system"); 2170 2171 final int reparseFlags; 2172 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2173 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2174 | PackageParser.PARSE_IS_SYSTEM_DIR 2175 | PackageParser.PARSE_IS_PRIVILEGED; 2176 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2177 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2178 | PackageParser.PARSE_IS_SYSTEM_DIR; 2179 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2180 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2181 | PackageParser.PARSE_IS_SYSTEM_DIR; 2182 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2183 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2184 | PackageParser.PARSE_IS_SYSTEM_DIR; 2185 } else { 2186 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2187 continue; 2188 } 2189 2190 mSettings.enableSystemPackageLPw(packageName); 2191 2192 try { 2193 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2194 } catch (PackageManagerException e) { 2195 Slog.e(TAG, "Failed to parse original system package: " 2196 + e.getMessage()); 2197 } 2198 } 2199 } 2200 } 2201 2202 // Now that we know all of the shared libraries, update all clients to have 2203 // the correct library paths. 2204 updateAllSharedLibrariesLPw(); 2205 2206 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2207 // NOTE: We ignore potential failures here during a system scan (like 2208 // the rest of the commands above) because there's precious little we 2209 // can do about it. A settings error is reported, though. 2210 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2211 false /* force dexopt */, false /* defer dexopt */); 2212 } 2213 2214 // Now that we know all the packages we are keeping, 2215 // read and update their last usage times. 2216 mPackageUsage.readLP(); 2217 2218 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2219 SystemClock.uptimeMillis()); 2220 Slog.i(TAG, "Time to scan packages: " 2221 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2222 + " seconds"); 2223 2224 // If the platform SDK has changed since the last time we booted, 2225 // we need to re-grant app permission to catch any new ones that 2226 // appear. This is really a hack, and means that apps can in some 2227 // cases get permissions that the user didn't initially explicitly 2228 // allow... it would be nice to have some better way to handle 2229 // this situation. 2230 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2231 != mSdkVersion; 2232 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2233 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2234 + "; regranting permissions for internal storage"); 2235 mSettings.mInternalSdkPlatform = mSdkVersion; 2236 2237 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2238 | (regrantPermissions 2239 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2240 : 0)); 2241 2242 // If this is the first boot, and it is a normal boot, then 2243 // we need to initialize the default preferred apps. 2244 if (!mRestoredSettings && !onlyCore) { 2245 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2246 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2247 primeDomainVerificationsLPw(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 checkDefaultBrowser(); 2263 2264 // All the changes are done during package scanning. 2265 mSettings.updateInternalDatabaseVersion(); 2266 2267 // can downgrade to reader 2268 mSettings.writeLPr(); 2269 2270 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2271 SystemClock.uptimeMillis()); 2272 2273 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2274 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2275 2276 mInstallerService = new PackageInstallerService(context, this); 2277 2278 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2279 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2280 mIntentFilterVerifierComponent); 2281 2282 } // synchronized (mPackages) 2283 } // synchronized (mInstallLock) 2284 2285 // Now after opening every single application zip, make sure they 2286 // are all flushed. Not really needed, but keeps things nice and 2287 // tidy. 2288 Runtime.getRuntime().gc(); 2289 2290 // Expose private service for system components to use. 2291 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2292 } 2293 2294 @Override 2295 public boolean isFirstBoot() { 2296 return !mRestoredSettings; 2297 } 2298 2299 @Override 2300 public boolean isOnlyCoreApps() { 2301 return mOnlyCore; 2302 } 2303 2304 @Override 2305 public boolean isUpgrade() { 2306 return mIsUpgrade; 2307 } 2308 2309 private String getRequiredVerifierLPr() { 2310 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2311 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2312 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2313 2314 String requiredVerifier = null; 2315 2316 final int N = receivers.size(); 2317 for (int i = 0; i < N; i++) { 2318 final ResolveInfo info = receivers.get(i); 2319 2320 if (info.activityInfo == null) { 2321 continue; 2322 } 2323 2324 final String packageName = info.activityInfo.packageName; 2325 2326 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2327 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2328 continue; 2329 } 2330 2331 if (requiredVerifier != null) { 2332 throw new RuntimeException("There can be only one required verifier"); 2333 } 2334 2335 requiredVerifier = packageName; 2336 } 2337 2338 return requiredVerifier; 2339 } 2340 2341 private String getRequiredInstallerLPr() { 2342 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2343 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2344 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2345 2346 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2347 PACKAGE_MIME_TYPE, 0, 0); 2348 2349 String requiredInstaller = null; 2350 2351 final int N = installers.size(); 2352 for (int i = 0; i < N; i++) { 2353 final ResolveInfo info = installers.get(i); 2354 final String packageName = info.activityInfo.packageName; 2355 2356 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2357 continue; 2358 } 2359 2360 if (requiredInstaller != null) { 2361 throw new RuntimeException("There must be one required installer"); 2362 } 2363 2364 requiredInstaller = packageName; 2365 } 2366 2367 if (requiredInstaller == null) { 2368 throw new RuntimeException("There must be one required installer"); 2369 } 2370 2371 return requiredInstaller; 2372 } 2373 2374 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2375 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2376 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2377 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2378 2379 ComponentName verifierComponentName = null; 2380 2381 int priority = -1000; 2382 final int N = receivers.size(); 2383 for (int i = 0; i < N; i++) { 2384 final ResolveInfo info = receivers.get(i); 2385 2386 if (info.activityInfo == null) { 2387 continue; 2388 } 2389 2390 final String packageName = info.activityInfo.packageName; 2391 2392 final PackageSetting ps = mSettings.mPackages.get(packageName); 2393 if (ps == null) { 2394 continue; 2395 } 2396 2397 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2398 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2399 continue; 2400 } 2401 2402 // Select the IntentFilterVerifier with the highest priority 2403 if (priority < info.priority) { 2404 priority = info.priority; 2405 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2406 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2407 + verifierComponentName + " with priority: " + info.priority); 2408 } 2409 } 2410 2411 return verifierComponentName; 2412 } 2413 2414 private void primeDomainVerificationsLPw(int userId) { 2415 if (DEBUG_DOMAIN_VERIFICATION) { 2416 Slog.d(TAG, "Priming domain verifications in user " + userId); 2417 } 2418 2419 SystemConfig systemConfig = SystemConfig.getInstance(); 2420 ArraySet<String> packages = systemConfig.getLinkedApps(); 2421 ArraySet<String> domains = new ArraySet<String>(); 2422 2423 for (String packageName : packages) { 2424 PackageParser.Package pkg = mPackages.get(packageName); 2425 if (pkg != null) { 2426 if (!pkg.isSystemApp()) { 2427 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2428 continue; 2429 } 2430 2431 domains.clear(); 2432 for (PackageParser.Activity a : pkg.activities) { 2433 for (ActivityIntentInfo filter : a.intents) { 2434 if (hasValidDomains(filter)) { 2435 domains.addAll(filter.getHostsList()); 2436 } 2437 } 2438 } 2439 2440 if (domains.size() > 0) { 2441 if (DEBUG_DOMAIN_VERIFICATION) { 2442 Slog.v(TAG, " + " + packageName); 2443 } 2444 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2445 // state w.r.t. the formal app-linkage "no verification attempted" state; 2446 // and then 'always' in the per-user state actually used for intent resolution. 2447 final IntentFilterVerificationInfo ivi; 2448 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2449 new ArrayList<String>(domains)); 2450 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2451 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2452 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2453 } else { 2454 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2455 + "' does not handle web links"); 2456 } 2457 } else { 2458 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2459 } 2460 } 2461 2462 scheduleWritePackageRestrictionsLocked(userId); 2463 scheduleWriteSettingsLocked(); 2464 } 2465 2466 private void applyFactoryDefaultBrowserLPw(int userId) { 2467 // The default browser app's package name is stored in a string resource, 2468 // with a product-specific overlay used for vendor customization. 2469 String browserPkg = mContext.getResources().getString( 2470 com.android.internal.R.string.default_browser); 2471 if (!TextUtils.isEmpty(browserPkg)) { 2472 // non-empty string => required to be a known package 2473 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2474 if (ps == null) { 2475 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2476 browserPkg = null; 2477 } else { 2478 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2479 } 2480 } 2481 2482 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2483 // default. If there's more than one, just leave everything alone. 2484 if (browserPkg == null) { 2485 calculateDefaultBrowserLPw(userId); 2486 } 2487 } 2488 2489 private void calculateDefaultBrowserLPw(int userId) { 2490 List<String> allBrowsers = resolveAllBrowserApps(userId); 2491 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2492 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2493 } 2494 2495 private List<String> resolveAllBrowserApps(int userId) { 2496 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2497 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2498 PackageManager.MATCH_ALL, userId); 2499 2500 final int count = list.size(); 2501 List<String> result = new ArrayList<String>(count); 2502 for (int i=0; i<count; i++) { 2503 ResolveInfo info = list.get(i); 2504 if (info.activityInfo == null 2505 || !info.handleAllWebDataURI 2506 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2507 || result.contains(info.activityInfo.packageName)) { 2508 continue; 2509 } 2510 result.add(info.activityInfo.packageName); 2511 } 2512 2513 return result; 2514 } 2515 2516 private boolean packageIsBrowser(String packageName, int userId) { 2517 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2518 PackageManager.MATCH_ALL, userId); 2519 final int N = list.size(); 2520 for (int i = 0; i < N; i++) { 2521 ResolveInfo info = list.get(i); 2522 if (packageName.equals(info.activityInfo.packageName)) { 2523 return true; 2524 } 2525 } 2526 return false; 2527 } 2528 2529 private void checkDefaultBrowser() { 2530 final int myUserId = UserHandle.myUserId(); 2531 final String packageName = getDefaultBrowserPackageName(myUserId); 2532 if (packageName != null) { 2533 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2534 if (info == null) { 2535 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2536 synchronized (mPackages) { 2537 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2538 } 2539 } 2540 } 2541 } 2542 2543 @Override 2544 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2545 throws RemoteException { 2546 try { 2547 return super.onTransact(code, data, reply, flags); 2548 } catch (RuntimeException e) { 2549 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2550 Slog.wtf(TAG, "Package Manager Crash", e); 2551 } 2552 throw e; 2553 } 2554 } 2555 2556 void cleanupInstallFailedPackage(PackageSetting ps) { 2557 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2558 2559 removeDataDirsLI(ps.volumeUuid, ps.name); 2560 if (ps.codePath != null) { 2561 if (ps.codePath.isDirectory()) { 2562 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2563 } else { 2564 ps.codePath.delete(); 2565 } 2566 } 2567 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2568 if (ps.resourcePath.isDirectory()) { 2569 FileUtils.deleteContents(ps.resourcePath); 2570 } 2571 ps.resourcePath.delete(); 2572 } 2573 mSettings.removePackageLPw(ps.name); 2574 } 2575 2576 static int[] appendInts(int[] cur, int[] add) { 2577 if (add == null) return cur; 2578 if (cur == null) return add; 2579 final int N = add.length; 2580 for (int i=0; i<N; i++) { 2581 cur = appendInt(cur, add[i]); 2582 } 2583 return cur; 2584 } 2585 2586 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2587 if (!sUserManager.exists(userId)) return null; 2588 final PackageSetting ps = (PackageSetting) p.mExtras; 2589 if (ps == null) { 2590 return null; 2591 } 2592 2593 final PermissionsState permissionsState = ps.getPermissionsState(); 2594 2595 final int[] gids = permissionsState.computeGids(userId); 2596 final Set<String> permissions = permissionsState.getPermissions(userId); 2597 final PackageUserState state = ps.readUserState(userId); 2598 2599 return PackageParser.generatePackageInfo(p, gids, flags, 2600 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2601 } 2602 2603 @Override 2604 public boolean isPackageFrozen(String packageName) { 2605 synchronized (mPackages) { 2606 final PackageSetting ps = mSettings.mPackages.get(packageName); 2607 if (ps != null) { 2608 return ps.frozen; 2609 } 2610 } 2611 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2612 return true; 2613 } 2614 2615 @Override 2616 public boolean isPackageAvailable(String packageName, int userId) { 2617 if (!sUserManager.exists(userId)) return false; 2618 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2619 synchronized (mPackages) { 2620 PackageParser.Package p = mPackages.get(packageName); 2621 if (p != null) { 2622 final PackageSetting ps = (PackageSetting) p.mExtras; 2623 if (ps != null) { 2624 final PackageUserState state = ps.readUserState(userId); 2625 if (state != null) { 2626 return PackageParser.isAvailable(state); 2627 } 2628 } 2629 } 2630 } 2631 return false; 2632 } 2633 2634 @Override 2635 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2636 if (!sUserManager.exists(userId)) return null; 2637 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2638 // reader 2639 synchronized (mPackages) { 2640 PackageParser.Package p = mPackages.get(packageName); 2641 if (DEBUG_PACKAGE_INFO) 2642 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2643 if (p != null) { 2644 return generatePackageInfo(p, flags, userId); 2645 } 2646 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2647 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2648 } 2649 } 2650 return null; 2651 } 2652 2653 @Override 2654 public String[] currentToCanonicalPackageNames(String[] names) { 2655 String[] out = new String[names.length]; 2656 // reader 2657 synchronized (mPackages) { 2658 for (int i=names.length-1; i>=0; i--) { 2659 PackageSetting ps = mSettings.mPackages.get(names[i]); 2660 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2661 } 2662 } 2663 return out; 2664 } 2665 2666 @Override 2667 public String[] canonicalToCurrentPackageNames(String[] names) { 2668 String[] out = new String[names.length]; 2669 // reader 2670 synchronized (mPackages) { 2671 for (int i=names.length-1; i>=0; i--) { 2672 String cur = mSettings.mRenamedPackages.get(names[i]); 2673 out[i] = cur != null ? cur : names[i]; 2674 } 2675 } 2676 return out; 2677 } 2678 2679 @Override 2680 public int getPackageUid(String packageName, int userId) { 2681 if (!sUserManager.exists(userId)) return -1; 2682 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2683 2684 // reader 2685 synchronized (mPackages) { 2686 PackageParser.Package p = mPackages.get(packageName); 2687 if(p != null) { 2688 return UserHandle.getUid(userId, p.applicationInfo.uid); 2689 } 2690 PackageSetting ps = mSettings.mPackages.get(packageName); 2691 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2692 return -1; 2693 } 2694 p = ps.pkg; 2695 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2696 } 2697 } 2698 2699 @Override 2700 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2701 if (!sUserManager.exists(userId)) { 2702 return null; 2703 } 2704 2705 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2706 "getPackageGids"); 2707 2708 // reader 2709 synchronized (mPackages) { 2710 PackageParser.Package p = mPackages.get(packageName); 2711 if (DEBUG_PACKAGE_INFO) { 2712 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2713 } 2714 if (p != null) { 2715 PackageSetting ps = (PackageSetting) p.mExtras; 2716 return ps.getPermissionsState().computeGids(userId); 2717 } 2718 } 2719 2720 return null; 2721 } 2722 2723 @Override 2724 public int getMountExternalMode(int uid) { 2725 if (Process.isIsolated(uid)) { 2726 return Zygote.MOUNT_EXTERNAL_NONE; 2727 } else { 2728 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 2729 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2730 } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2731 return Zygote.MOUNT_EXTERNAL_WRITE; 2732 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2733 return Zygote.MOUNT_EXTERNAL_READ; 2734 } else { 2735 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2736 } 2737 } 2738 } 2739 2740 static PermissionInfo generatePermissionInfo( 2741 BasePermission bp, int flags) { 2742 if (bp.perm != null) { 2743 return PackageParser.generatePermissionInfo(bp.perm, flags); 2744 } 2745 PermissionInfo pi = new PermissionInfo(); 2746 pi.name = bp.name; 2747 pi.packageName = bp.sourcePackage; 2748 pi.nonLocalizedLabel = bp.name; 2749 pi.protectionLevel = bp.protectionLevel; 2750 return pi; 2751 } 2752 2753 @Override 2754 public PermissionInfo getPermissionInfo(String name, int flags) { 2755 // reader 2756 synchronized (mPackages) { 2757 final BasePermission p = mSettings.mPermissions.get(name); 2758 if (p != null) { 2759 return generatePermissionInfo(p, flags); 2760 } 2761 return null; 2762 } 2763 } 2764 2765 @Override 2766 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2767 // reader 2768 synchronized (mPackages) { 2769 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2770 for (BasePermission p : mSettings.mPermissions.values()) { 2771 if (group == null) { 2772 if (p.perm == null || p.perm.info.group == null) { 2773 out.add(generatePermissionInfo(p, flags)); 2774 } 2775 } else { 2776 if (p.perm != null && group.equals(p.perm.info.group)) { 2777 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2778 } 2779 } 2780 } 2781 2782 if (out.size() > 0) { 2783 return out; 2784 } 2785 return mPermissionGroups.containsKey(group) ? out : null; 2786 } 2787 } 2788 2789 @Override 2790 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2791 // reader 2792 synchronized (mPackages) { 2793 return PackageParser.generatePermissionGroupInfo( 2794 mPermissionGroups.get(name), flags); 2795 } 2796 } 2797 2798 @Override 2799 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2800 // reader 2801 synchronized (mPackages) { 2802 final int N = mPermissionGroups.size(); 2803 ArrayList<PermissionGroupInfo> out 2804 = new ArrayList<PermissionGroupInfo>(N); 2805 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2806 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2807 } 2808 return out; 2809 } 2810 } 2811 2812 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2813 int userId) { 2814 if (!sUserManager.exists(userId)) return null; 2815 PackageSetting ps = mSettings.mPackages.get(packageName); 2816 if (ps != null) { 2817 if (ps.pkg == null) { 2818 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2819 flags, userId); 2820 if (pInfo != null) { 2821 return pInfo.applicationInfo; 2822 } 2823 return null; 2824 } 2825 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2826 ps.readUserState(userId), userId); 2827 } 2828 return null; 2829 } 2830 2831 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2832 int userId) { 2833 if (!sUserManager.exists(userId)) return null; 2834 PackageSetting ps = mSettings.mPackages.get(packageName); 2835 if (ps != null) { 2836 PackageParser.Package pkg = ps.pkg; 2837 if (pkg == null) { 2838 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2839 return null; 2840 } 2841 // Only data remains, so we aren't worried about code paths 2842 pkg = new PackageParser.Package(packageName); 2843 pkg.applicationInfo.packageName = packageName; 2844 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2845 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2846 pkg.applicationInfo.dataDir = Environment 2847 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2848 .getAbsolutePath(); 2849 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2850 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2851 } 2852 return generatePackageInfo(pkg, flags, userId); 2853 } 2854 return null; 2855 } 2856 2857 @Override 2858 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2859 if (!sUserManager.exists(userId)) return null; 2860 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2861 // writer 2862 synchronized (mPackages) { 2863 PackageParser.Package p = mPackages.get(packageName); 2864 if (DEBUG_PACKAGE_INFO) Log.v( 2865 TAG, "getApplicationInfo " + packageName 2866 + ": " + p); 2867 if (p != null) { 2868 PackageSetting ps = mSettings.mPackages.get(packageName); 2869 if (ps == null) return null; 2870 // Note: isEnabledLP() does not apply here - always return info 2871 return PackageParser.generateApplicationInfo( 2872 p, flags, ps.readUserState(userId), userId); 2873 } 2874 if ("android".equals(packageName)||"system".equals(packageName)) { 2875 return mAndroidApplication; 2876 } 2877 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2878 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2879 } 2880 } 2881 return null; 2882 } 2883 2884 @Override 2885 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2886 final IPackageDataObserver observer) { 2887 mContext.enforceCallingOrSelfPermission( 2888 android.Manifest.permission.CLEAR_APP_CACHE, null); 2889 // Queue up an async operation since clearing cache may take a little while. 2890 mHandler.post(new Runnable() { 2891 public void run() { 2892 mHandler.removeCallbacks(this); 2893 int retCode = -1; 2894 synchronized (mInstallLock) { 2895 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2896 if (retCode < 0) { 2897 Slog.w(TAG, "Couldn't clear application caches"); 2898 } 2899 } 2900 if (observer != null) { 2901 try { 2902 observer.onRemoveCompleted(null, (retCode >= 0)); 2903 } catch (RemoteException e) { 2904 Slog.w(TAG, "RemoveException when invoking call back"); 2905 } 2906 } 2907 } 2908 }); 2909 } 2910 2911 @Override 2912 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2913 final IntentSender pi) { 2914 mContext.enforceCallingOrSelfPermission( 2915 android.Manifest.permission.CLEAR_APP_CACHE, null); 2916 // Queue up an async operation since clearing cache may take a little while. 2917 mHandler.post(new Runnable() { 2918 public void run() { 2919 mHandler.removeCallbacks(this); 2920 int retCode = -1; 2921 synchronized (mInstallLock) { 2922 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2923 if (retCode < 0) { 2924 Slog.w(TAG, "Couldn't clear application caches"); 2925 } 2926 } 2927 if(pi != null) { 2928 try { 2929 // Callback via pending intent 2930 int code = (retCode >= 0) ? 1 : 0; 2931 pi.sendIntent(null, code, null, 2932 null, null); 2933 } catch (SendIntentException e1) { 2934 Slog.i(TAG, "Failed to send pending intent"); 2935 } 2936 } 2937 } 2938 }); 2939 } 2940 2941 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2942 synchronized (mInstallLock) { 2943 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2944 throw new IOException("Failed to free enough space"); 2945 } 2946 } 2947 } 2948 2949 @Override 2950 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2951 if (!sUserManager.exists(userId)) return null; 2952 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2953 synchronized (mPackages) { 2954 PackageParser.Activity a = mActivities.mActivities.get(component); 2955 2956 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2957 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2958 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2959 if (ps == null) return null; 2960 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2961 userId); 2962 } 2963 if (mResolveComponentName.equals(component)) { 2964 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2965 new PackageUserState(), userId); 2966 } 2967 } 2968 return null; 2969 } 2970 2971 @Override 2972 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2973 String resolvedType) { 2974 synchronized (mPackages) { 2975 PackageParser.Activity a = mActivities.mActivities.get(component); 2976 if (a == null) { 2977 return false; 2978 } 2979 for (int i=0; i<a.intents.size(); i++) { 2980 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2981 intent.getData(), intent.getCategories(), TAG) >= 0) { 2982 return true; 2983 } 2984 } 2985 return false; 2986 } 2987 } 2988 2989 @Override 2990 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2991 if (!sUserManager.exists(userId)) return null; 2992 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2993 synchronized (mPackages) { 2994 PackageParser.Activity a = mReceivers.mActivities.get(component); 2995 if (DEBUG_PACKAGE_INFO) Log.v( 2996 TAG, "getReceiverInfo " + component + ": " + a); 2997 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2998 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2999 if (ps == null) return null; 3000 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3001 userId); 3002 } 3003 } 3004 return null; 3005 } 3006 3007 @Override 3008 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3009 if (!sUserManager.exists(userId)) return null; 3010 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3011 synchronized (mPackages) { 3012 PackageParser.Service s = mServices.mServices.get(component); 3013 if (DEBUG_PACKAGE_INFO) Log.v( 3014 TAG, "getServiceInfo " + component + ": " + s); 3015 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3016 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3017 if (ps == null) return null; 3018 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3019 userId); 3020 } 3021 } 3022 return null; 3023 } 3024 3025 @Override 3026 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3027 if (!sUserManager.exists(userId)) return null; 3028 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3029 synchronized (mPackages) { 3030 PackageParser.Provider p = mProviders.mProviders.get(component); 3031 if (DEBUG_PACKAGE_INFO) Log.v( 3032 TAG, "getProviderInfo " + component + ": " + p); 3033 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3034 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3035 if (ps == null) return null; 3036 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3037 userId); 3038 } 3039 } 3040 return null; 3041 } 3042 3043 @Override 3044 public String[] getSystemSharedLibraryNames() { 3045 Set<String> libSet; 3046 synchronized (mPackages) { 3047 libSet = mSharedLibraries.keySet(); 3048 int size = libSet.size(); 3049 if (size > 0) { 3050 String[] libs = new String[size]; 3051 libSet.toArray(libs); 3052 return libs; 3053 } 3054 } 3055 return null; 3056 } 3057 3058 /** 3059 * @hide 3060 */ 3061 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3062 synchronized (mPackages) { 3063 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3064 if (lib != null && lib.apk != null) { 3065 return mPackages.get(lib.apk); 3066 } 3067 } 3068 return null; 3069 } 3070 3071 @Override 3072 public FeatureInfo[] getSystemAvailableFeatures() { 3073 Collection<FeatureInfo> featSet; 3074 synchronized (mPackages) { 3075 featSet = mAvailableFeatures.values(); 3076 int size = featSet.size(); 3077 if (size > 0) { 3078 FeatureInfo[] features = new FeatureInfo[size+1]; 3079 featSet.toArray(features); 3080 FeatureInfo fi = new FeatureInfo(); 3081 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3082 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3083 features[size] = fi; 3084 return features; 3085 } 3086 } 3087 return null; 3088 } 3089 3090 @Override 3091 public boolean hasSystemFeature(String name) { 3092 synchronized (mPackages) { 3093 return mAvailableFeatures.containsKey(name); 3094 } 3095 } 3096 3097 private void checkValidCaller(int uid, int userId) { 3098 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3099 return; 3100 3101 throw new SecurityException("Caller uid=" + uid 3102 + " is not privileged to communicate with user=" + userId); 3103 } 3104 3105 @Override 3106 public int checkPermission(String permName, String pkgName, int userId) { 3107 if (!sUserManager.exists(userId)) { 3108 return PackageManager.PERMISSION_DENIED; 3109 } 3110 3111 synchronized (mPackages) { 3112 final PackageParser.Package p = mPackages.get(pkgName); 3113 if (p != null && p.mExtras != null) { 3114 final PackageSetting ps = (PackageSetting) p.mExtras; 3115 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3116 return PackageManager.PERMISSION_GRANTED; 3117 } 3118 } 3119 } 3120 3121 return PackageManager.PERMISSION_DENIED; 3122 } 3123 3124 @Override 3125 public int checkUidPermission(String permName, int uid) { 3126 final int userId = UserHandle.getUserId(uid); 3127 3128 if (!sUserManager.exists(userId)) { 3129 return PackageManager.PERMISSION_DENIED; 3130 } 3131 3132 synchronized (mPackages) { 3133 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3134 if (obj != null) { 3135 final SettingBase ps = (SettingBase) obj; 3136 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3137 return PackageManager.PERMISSION_GRANTED; 3138 } 3139 } else { 3140 ArraySet<String> perms = mSystemPermissions.get(uid); 3141 if (perms != null && perms.contains(permName)) { 3142 return PackageManager.PERMISSION_GRANTED; 3143 } 3144 } 3145 } 3146 3147 return PackageManager.PERMISSION_DENIED; 3148 } 3149 3150 /** 3151 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3152 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3153 * @param checkShell TODO(yamasani): 3154 * @param message the message to log on security exception 3155 */ 3156 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3157 boolean checkShell, String message) { 3158 if (userId < 0) { 3159 throw new IllegalArgumentException("Invalid userId " + userId); 3160 } 3161 if (checkShell) { 3162 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3163 } 3164 if (userId == UserHandle.getUserId(callingUid)) return; 3165 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3166 if (requireFullPermission) { 3167 mContext.enforceCallingOrSelfPermission( 3168 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3169 } else { 3170 try { 3171 mContext.enforceCallingOrSelfPermission( 3172 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3173 } catch (SecurityException se) { 3174 mContext.enforceCallingOrSelfPermission( 3175 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3176 } 3177 } 3178 } 3179 } 3180 3181 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3182 if (callingUid == Process.SHELL_UID) { 3183 if (userHandle >= 0 3184 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3185 throw new SecurityException("Shell does not have permission to access user " 3186 + userHandle); 3187 } else if (userHandle < 0) { 3188 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3189 + Debug.getCallers(3)); 3190 } 3191 } 3192 } 3193 3194 private BasePermission findPermissionTreeLP(String permName) { 3195 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3196 if (permName.startsWith(bp.name) && 3197 permName.length() > bp.name.length() && 3198 permName.charAt(bp.name.length()) == '.') { 3199 return bp; 3200 } 3201 } 3202 return null; 3203 } 3204 3205 private BasePermission checkPermissionTreeLP(String permName) { 3206 if (permName != null) { 3207 BasePermission bp = findPermissionTreeLP(permName); 3208 if (bp != null) { 3209 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3210 return bp; 3211 } 3212 throw new SecurityException("Calling uid " 3213 + Binder.getCallingUid() 3214 + " is not allowed to add to permission tree " 3215 + bp.name + " owned by uid " + bp.uid); 3216 } 3217 } 3218 throw new SecurityException("No permission tree found for " + permName); 3219 } 3220 3221 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3222 if (s1 == null) { 3223 return s2 == null; 3224 } 3225 if (s2 == null) { 3226 return false; 3227 } 3228 if (s1.getClass() != s2.getClass()) { 3229 return false; 3230 } 3231 return s1.equals(s2); 3232 } 3233 3234 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3235 if (pi1.icon != pi2.icon) return false; 3236 if (pi1.logo != pi2.logo) return false; 3237 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3238 if (!compareStrings(pi1.name, pi2.name)) return false; 3239 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3240 // We'll take care of setting this one. 3241 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3242 // These are not currently stored in settings. 3243 //if (!compareStrings(pi1.group, pi2.group)) return false; 3244 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3245 //if (pi1.labelRes != pi2.labelRes) return false; 3246 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3247 return true; 3248 } 3249 3250 int permissionInfoFootprint(PermissionInfo info) { 3251 int size = info.name.length(); 3252 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3253 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3254 return size; 3255 } 3256 3257 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3258 int size = 0; 3259 for (BasePermission perm : mSettings.mPermissions.values()) { 3260 if (perm.uid == tree.uid) { 3261 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3262 } 3263 } 3264 return size; 3265 } 3266 3267 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3268 // We calculate the max size of permissions defined by this uid and throw 3269 // if that plus the size of 'info' would exceed our stated maximum. 3270 if (tree.uid != Process.SYSTEM_UID) { 3271 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3272 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3273 throw new SecurityException("Permission tree size cap exceeded"); 3274 } 3275 } 3276 } 3277 3278 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3279 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3280 throw new SecurityException("Label must be specified in permission"); 3281 } 3282 BasePermission tree = checkPermissionTreeLP(info.name); 3283 BasePermission bp = mSettings.mPermissions.get(info.name); 3284 boolean added = bp == null; 3285 boolean changed = true; 3286 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3287 if (added) { 3288 enforcePermissionCapLocked(info, tree); 3289 bp = new BasePermission(info.name, tree.sourcePackage, 3290 BasePermission.TYPE_DYNAMIC); 3291 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3292 throw new SecurityException( 3293 "Not allowed to modify non-dynamic permission " 3294 + info.name); 3295 } else { 3296 if (bp.protectionLevel == fixedLevel 3297 && bp.perm.owner.equals(tree.perm.owner) 3298 && bp.uid == tree.uid 3299 && comparePermissionInfos(bp.perm.info, info)) { 3300 changed = false; 3301 } 3302 } 3303 bp.protectionLevel = fixedLevel; 3304 info = new PermissionInfo(info); 3305 info.protectionLevel = fixedLevel; 3306 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3307 bp.perm.info.packageName = tree.perm.info.packageName; 3308 bp.uid = tree.uid; 3309 if (added) { 3310 mSettings.mPermissions.put(info.name, bp); 3311 } 3312 if (changed) { 3313 if (!async) { 3314 mSettings.writeLPr(); 3315 } else { 3316 scheduleWriteSettingsLocked(); 3317 } 3318 } 3319 return added; 3320 } 3321 3322 @Override 3323 public boolean addPermission(PermissionInfo info) { 3324 synchronized (mPackages) { 3325 return addPermissionLocked(info, false); 3326 } 3327 } 3328 3329 @Override 3330 public boolean addPermissionAsync(PermissionInfo info) { 3331 synchronized (mPackages) { 3332 return addPermissionLocked(info, true); 3333 } 3334 } 3335 3336 @Override 3337 public void removePermission(String name) { 3338 synchronized (mPackages) { 3339 checkPermissionTreeLP(name); 3340 BasePermission bp = mSettings.mPermissions.get(name); 3341 if (bp != null) { 3342 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3343 throw new SecurityException( 3344 "Not allowed to modify non-dynamic permission " 3345 + name); 3346 } 3347 mSettings.mPermissions.remove(name); 3348 mSettings.writeLPr(); 3349 } 3350 } 3351 } 3352 3353 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3354 BasePermission bp) { 3355 int index = pkg.requestedPermissions.indexOf(bp.name); 3356 if (index == -1) { 3357 throw new SecurityException("Package " + pkg.packageName 3358 + " has not requested permission " + bp.name); 3359 } 3360 if (!bp.isRuntime()) { 3361 throw new SecurityException("Permission " + bp.name 3362 + " is not a changeable permission type"); 3363 } 3364 } 3365 3366 @Override 3367 public void grantRuntimePermission(String packageName, String name, final int userId) { 3368 if (!sUserManager.exists(userId)) { 3369 Log.e(TAG, "No such user:" + userId); 3370 return; 3371 } 3372 3373 mContext.enforceCallingOrSelfPermission( 3374 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3375 "grantRuntimePermission"); 3376 3377 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3378 "grantRuntimePermission"); 3379 3380 final int uid; 3381 final SettingBase sb; 3382 3383 synchronized (mPackages) { 3384 final PackageParser.Package pkg = mPackages.get(packageName); 3385 if (pkg == null) { 3386 throw new IllegalArgumentException("Unknown package: " + packageName); 3387 } 3388 3389 final BasePermission bp = mSettings.mPermissions.get(name); 3390 if (bp == null) { 3391 throw new IllegalArgumentException("Unknown permission: " + name); 3392 } 3393 3394 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3395 3396 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3397 sb = (SettingBase) pkg.mExtras; 3398 if (sb == null) { 3399 throw new IllegalArgumentException("Unknown package: " + packageName); 3400 } 3401 3402 final PermissionsState permissionsState = sb.getPermissionsState(); 3403 3404 final int flags = permissionsState.getPermissionFlags(name, userId); 3405 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3406 throw new SecurityException("Cannot grant system fixed permission: " 3407 + name + " for package: " + packageName); 3408 } 3409 3410 final int result = permissionsState.grantRuntimePermission(bp, userId); 3411 switch (result) { 3412 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3413 return; 3414 } 3415 3416 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3417 mHandler.post(new Runnable() { 3418 @Override 3419 public void run() { 3420 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3421 } 3422 }); 3423 } break; 3424 } 3425 3426 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3427 3428 // Not critical if that is lost - app has to request again. 3429 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3430 } 3431 3432 if (READ_EXTERNAL_STORAGE.equals(name) 3433 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3434 final long token = Binder.clearCallingIdentity(); 3435 try { 3436 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3437 storage.remountUid(uid); 3438 } finally { 3439 Binder.restoreCallingIdentity(token); 3440 } 3441 } 3442 } 3443 3444 @Override 3445 public void revokeRuntimePermission(String packageName, String name, int userId) { 3446 if (!sUserManager.exists(userId)) { 3447 Log.e(TAG, "No such user:" + userId); 3448 return; 3449 } 3450 3451 mContext.enforceCallingOrSelfPermission( 3452 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3453 "revokeRuntimePermission"); 3454 3455 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3456 "revokeRuntimePermission"); 3457 3458 final SettingBase sb; 3459 3460 synchronized (mPackages) { 3461 final PackageParser.Package pkg = mPackages.get(packageName); 3462 if (pkg == null) { 3463 throw new IllegalArgumentException("Unknown package: " + packageName); 3464 } 3465 3466 final BasePermission bp = mSettings.mPermissions.get(name); 3467 if (bp == null) { 3468 throw new IllegalArgumentException("Unknown permission: " + name); 3469 } 3470 3471 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3472 3473 sb = (SettingBase) pkg.mExtras; 3474 if (sb == null) { 3475 throw new IllegalArgumentException("Unknown package: " + packageName); 3476 } 3477 3478 final PermissionsState permissionsState = sb.getPermissionsState(); 3479 3480 final int flags = permissionsState.getPermissionFlags(name, userId); 3481 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3482 throw new SecurityException("Cannot revoke system fixed permission: " 3483 + name + " for package: " + packageName); 3484 } 3485 3486 if (permissionsState.revokeRuntimePermission(bp, userId) == 3487 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3488 return; 3489 } 3490 3491 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3492 3493 // Critical, after this call app should never have the permission. 3494 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3495 } 3496 3497 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3498 } 3499 3500 @Override 3501 public void resetRuntimePermissions() { 3502 mContext.enforceCallingOrSelfPermission( 3503 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3504 "revokeRuntimePermission"); 3505 3506 int callingUid = Binder.getCallingUid(); 3507 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3508 mContext.enforceCallingOrSelfPermission( 3509 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3510 "resetRuntimePermissions"); 3511 } 3512 3513 final int[] userIds; 3514 3515 synchronized (mPackages) { 3516 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3517 final int userCount = UserManagerService.getInstance().getUserIds().length; 3518 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3519 } 3520 3521 for (int userId : userIds) { 3522 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3523 } 3524 } 3525 3526 @Override 3527 public int getPermissionFlags(String name, String packageName, int userId) { 3528 if (!sUserManager.exists(userId)) { 3529 return 0; 3530 } 3531 3532 mContext.enforceCallingOrSelfPermission( 3533 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3534 "getPermissionFlags"); 3535 3536 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3537 "getPermissionFlags"); 3538 3539 synchronized (mPackages) { 3540 final PackageParser.Package pkg = mPackages.get(packageName); 3541 if (pkg == null) { 3542 throw new IllegalArgumentException("Unknown package: " + packageName); 3543 } 3544 3545 final BasePermission bp = mSettings.mPermissions.get(name); 3546 if (bp == null) { 3547 throw new IllegalArgumentException("Unknown permission: " + name); 3548 } 3549 3550 SettingBase sb = (SettingBase) pkg.mExtras; 3551 if (sb == null) { 3552 throw new IllegalArgumentException("Unknown package: " + packageName); 3553 } 3554 3555 PermissionsState permissionsState = sb.getPermissionsState(); 3556 return permissionsState.getPermissionFlags(name, userId); 3557 } 3558 } 3559 3560 @Override 3561 public void updatePermissionFlags(String name, String packageName, int flagMask, 3562 int flagValues, int userId) { 3563 if (!sUserManager.exists(userId)) { 3564 return; 3565 } 3566 3567 mContext.enforceCallingOrSelfPermission( 3568 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3569 "updatePermissionFlags"); 3570 3571 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3572 "updatePermissionFlags"); 3573 3574 // Only the system can change system fixed flags. 3575 if (getCallingUid() != Process.SYSTEM_UID) { 3576 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3577 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3578 } 3579 3580 synchronized (mPackages) { 3581 final PackageParser.Package pkg = mPackages.get(packageName); 3582 if (pkg == null) { 3583 throw new IllegalArgumentException("Unknown package: " + packageName); 3584 } 3585 3586 final BasePermission bp = mSettings.mPermissions.get(name); 3587 if (bp == null) { 3588 throw new IllegalArgumentException("Unknown permission: " + name); 3589 } 3590 3591 SettingBase sb = (SettingBase) pkg.mExtras; 3592 if (sb == null) { 3593 throw new IllegalArgumentException("Unknown package: " + packageName); 3594 } 3595 3596 PermissionsState permissionsState = sb.getPermissionsState(); 3597 3598 // Only the package manager can change flags for system component permissions. 3599 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3600 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3601 return; 3602 } 3603 3604 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3605 3606 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3607 // Install and runtime permissions are stored in different places, 3608 // so figure out what permission changed and persist the change. 3609 if (permissionsState.getInstallPermissionState(name) != null) { 3610 scheduleWriteSettingsLocked(); 3611 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3612 || hadState) { 3613 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3614 } 3615 } 3616 } 3617 } 3618 3619 /** 3620 * Update the permission flags for all packages and runtime permissions of a user in order 3621 * to allow device or profile owner to remove POLICY_FIXED. 3622 */ 3623 @Override 3624 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3625 if (!sUserManager.exists(userId)) { 3626 return; 3627 } 3628 3629 mContext.enforceCallingOrSelfPermission( 3630 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3631 "updatePermissionFlagsForAllApps"); 3632 3633 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3634 "updatePermissionFlagsForAllApps"); 3635 3636 // Only the system can change system fixed flags. 3637 if (getCallingUid() != Process.SYSTEM_UID) { 3638 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3639 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3640 } 3641 3642 synchronized (mPackages) { 3643 boolean changed = false; 3644 final int packageCount = mPackages.size(); 3645 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3646 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3647 SettingBase sb = (SettingBase) pkg.mExtras; 3648 if (sb == null) { 3649 continue; 3650 } 3651 PermissionsState permissionsState = sb.getPermissionsState(); 3652 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3653 userId, flagMask, flagValues); 3654 } 3655 if (changed) { 3656 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3657 } 3658 } 3659 } 3660 3661 @Override 3662 public boolean shouldShowRequestPermissionRationale(String permissionName, 3663 String packageName, int userId) { 3664 if (UserHandle.getCallingUserId() != userId) { 3665 mContext.enforceCallingPermission( 3666 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3667 "canShowRequestPermissionRationale for user " + userId); 3668 } 3669 3670 final int uid = getPackageUid(packageName, userId); 3671 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3672 return false; 3673 } 3674 3675 if (checkPermission(permissionName, packageName, userId) 3676 == PackageManager.PERMISSION_GRANTED) { 3677 return false; 3678 } 3679 3680 final int flags; 3681 3682 final long identity = Binder.clearCallingIdentity(); 3683 try { 3684 flags = getPermissionFlags(permissionName, 3685 packageName, userId); 3686 } finally { 3687 Binder.restoreCallingIdentity(identity); 3688 } 3689 3690 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3691 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3692 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3693 3694 if ((flags & fixedFlags) != 0) { 3695 return false; 3696 } 3697 3698 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3699 } 3700 3701 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3702 BasePermission bp = mSettings.mPermissions.get(permission); 3703 if (bp == null) { 3704 throw new SecurityException("Missing " + permission + " permission"); 3705 } 3706 3707 SettingBase sb = (SettingBase) pkg.mExtras; 3708 PermissionsState permissionsState = sb.getPermissionsState(); 3709 3710 if (permissionsState.grantInstallPermission(bp) != 3711 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3712 scheduleWriteSettingsLocked(); 3713 } 3714 } 3715 3716 @Override 3717 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3718 mContext.enforceCallingOrSelfPermission( 3719 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3720 "addOnPermissionsChangeListener"); 3721 3722 synchronized (mPackages) { 3723 mOnPermissionChangeListeners.addListenerLocked(listener); 3724 } 3725 } 3726 3727 @Override 3728 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3729 synchronized (mPackages) { 3730 mOnPermissionChangeListeners.removeListenerLocked(listener); 3731 } 3732 } 3733 3734 @Override 3735 public boolean isProtectedBroadcast(String actionName) { 3736 synchronized (mPackages) { 3737 return mProtectedBroadcasts.contains(actionName); 3738 } 3739 } 3740 3741 @Override 3742 public int checkSignatures(String pkg1, String pkg2) { 3743 synchronized (mPackages) { 3744 final PackageParser.Package p1 = mPackages.get(pkg1); 3745 final PackageParser.Package p2 = mPackages.get(pkg2); 3746 if (p1 == null || p1.mExtras == null 3747 || p2 == null || p2.mExtras == null) { 3748 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3749 } 3750 return compareSignatures(p1.mSignatures, p2.mSignatures); 3751 } 3752 } 3753 3754 @Override 3755 public int checkUidSignatures(int uid1, int uid2) { 3756 // Map to base uids. 3757 uid1 = UserHandle.getAppId(uid1); 3758 uid2 = UserHandle.getAppId(uid2); 3759 // reader 3760 synchronized (mPackages) { 3761 Signature[] s1; 3762 Signature[] s2; 3763 Object obj = mSettings.getUserIdLPr(uid1); 3764 if (obj != null) { 3765 if (obj instanceof SharedUserSetting) { 3766 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3767 } else if (obj instanceof PackageSetting) { 3768 s1 = ((PackageSetting)obj).signatures.mSignatures; 3769 } else { 3770 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3771 } 3772 } else { 3773 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3774 } 3775 obj = mSettings.getUserIdLPr(uid2); 3776 if (obj != null) { 3777 if (obj instanceof SharedUserSetting) { 3778 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3779 } else if (obj instanceof PackageSetting) { 3780 s2 = ((PackageSetting)obj).signatures.mSignatures; 3781 } else { 3782 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3783 } 3784 } else { 3785 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3786 } 3787 return compareSignatures(s1, s2); 3788 } 3789 } 3790 3791 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3792 final long identity = Binder.clearCallingIdentity(); 3793 try { 3794 if (sb instanceof SharedUserSetting) { 3795 SharedUserSetting sus = (SharedUserSetting) sb; 3796 final int packageCount = sus.packages.size(); 3797 for (int i = 0; i < packageCount; i++) { 3798 PackageSetting susPs = sus.packages.valueAt(i); 3799 if (userId == UserHandle.USER_ALL) { 3800 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3801 } else { 3802 final int uid = UserHandle.getUid(userId, susPs.appId); 3803 killUid(uid, reason); 3804 } 3805 } 3806 } else if (sb instanceof PackageSetting) { 3807 PackageSetting ps = (PackageSetting) sb; 3808 if (userId == UserHandle.USER_ALL) { 3809 killApplication(ps.pkg.packageName, ps.appId, reason); 3810 } else { 3811 final int uid = UserHandle.getUid(userId, ps.appId); 3812 killUid(uid, reason); 3813 } 3814 } 3815 } finally { 3816 Binder.restoreCallingIdentity(identity); 3817 } 3818 } 3819 3820 private static void killUid(int uid, String reason) { 3821 IActivityManager am = ActivityManagerNative.getDefault(); 3822 if (am != null) { 3823 try { 3824 am.killUid(uid, reason); 3825 } catch (RemoteException e) { 3826 /* ignore - same process */ 3827 } 3828 } 3829 } 3830 3831 /** 3832 * Compares two sets of signatures. Returns: 3833 * <br /> 3834 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3835 * <br /> 3836 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3837 * <br /> 3838 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3839 * <br /> 3840 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3841 * <br /> 3842 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3843 */ 3844 static int compareSignatures(Signature[] s1, Signature[] s2) { 3845 if (s1 == null) { 3846 return s2 == null 3847 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3848 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3849 } 3850 3851 if (s2 == null) { 3852 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3853 } 3854 3855 if (s1.length != s2.length) { 3856 return PackageManager.SIGNATURE_NO_MATCH; 3857 } 3858 3859 // Since both signature sets are of size 1, we can compare without HashSets. 3860 if (s1.length == 1) { 3861 return s1[0].equals(s2[0]) ? 3862 PackageManager.SIGNATURE_MATCH : 3863 PackageManager.SIGNATURE_NO_MATCH; 3864 } 3865 3866 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3867 for (Signature sig : s1) { 3868 set1.add(sig); 3869 } 3870 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3871 for (Signature sig : s2) { 3872 set2.add(sig); 3873 } 3874 // Make sure s2 contains all signatures in s1. 3875 if (set1.equals(set2)) { 3876 return PackageManager.SIGNATURE_MATCH; 3877 } 3878 return PackageManager.SIGNATURE_NO_MATCH; 3879 } 3880 3881 /** 3882 * If the database version for this type of package (internal storage or 3883 * external storage) is less than the version where package signatures 3884 * were updated, return true. 3885 */ 3886 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3887 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3888 DatabaseVersion.SIGNATURE_END_ENTITY)) 3889 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3890 DatabaseVersion.SIGNATURE_END_ENTITY)); 3891 } 3892 3893 /** 3894 * Used for backward compatibility to make sure any packages with 3895 * certificate chains get upgraded to the new style. {@code existingSigs} 3896 * will be in the old format (since they were stored on disk from before the 3897 * system upgrade) and {@code scannedSigs} will be in the newer format. 3898 */ 3899 private int compareSignaturesCompat(PackageSignatures existingSigs, 3900 PackageParser.Package scannedPkg) { 3901 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3902 return PackageManager.SIGNATURE_NO_MATCH; 3903 } 3904 3905 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3906 for (Signature sig : existingSigs.mSignatures) { 3907 existingSet.add(sig); 3908 } 3909 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3910 for (Signature sig : scannedPkg.mSignatures) { 3911 try { 3912 Signature[] chainSignatures = sig.getChainSignatures(); 3913 for (Signature chainSig : chainSignatures) { 3914 scannedCompatSet.add(chainSig); 3915 } 3916 } catch (CertificateEncodingException e) { 3917 scannedCompatSet.add(sig); 3918 } 3919 } 3920 /* 3921 * Make sure the expanded scanned set contains all signatures in the 3922 * existing one. 3923 */ 3924 if (scannedCompatSet.equals(existingSet)) { 3925 // Migrate the old signatures to the new scheme. 3926 existingSigs.assignSignatures(scannedPkg.mSignatures); 3927 // The new KeySets will be re-added later in the scanning process. 3928 synchronized (mPackages) { 3929 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3930 } 3931 return PackageManager.SIGNATURE_MATCH; 3932 } 3933 return PackageManager.SIGNATURE_NO_MATCH; 3934 } 3935 3936 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3937 if (isExternal(scannedPkg)) { 3938 return mSettings.isExternalDatabaseVersionOlderThan( 3939 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3940 } else { 3941 return mSettings.isInternalDatabaseVersionOlderThan( 3942 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3943 } 3944 } 3945 3946 private int compareSignaturesRecover(PackageSignatures existingSigs, 3947 PackageParser.Package scannedPkg) { 3948 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3949 return PackageManager.SIGNATURE_NO_MATCH; 3950 } 3951 3952 String msg = null; 3953 try { 3954 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3955 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3956 + scannedPkg.packageName); 3957 return PackageManager.SIGNATURE_MATCH; 3958 } 3959 } catch (CertificateException e) { 3960 msg = e.getMessage(); 3961 } 3962 3963 logCriticalInfo(Log.INFO, 3964 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3965 return PackageManager.SIGNATURE_NO_MATCH; 3966 } 3967 3968 @Override 3969 public String[] getPackagesForUid(int uid) { 3970 uid = UserHandle.getAppId(uid); 3971 // reader 3972 synchronized (mPackages) { 3973 Object obj = mSettings.getUserIdLPr(uid); 3974 if (obj instanceof SharedUserSetting) { 3975 final SharedUserSetting sus = (SharedUserSetting) obj; 3976 final int N = sus.packages.size(); 3977 final String[] res = new String[N]; 3978 final Iterator<PackageSetting> it = sus.packages.iterator(); 3979 int i = 0; 3980 while (it.hasNext()) { 3981 res[i++] = it.next().name; 3982 } 3983 return res; 3984 } else if (obj instanceof PackageSetting) { 3985 final PackageSetting ps = (PackageSetting) obj; 3986 return new String[] { ps.name }; 3987 } 3988 } 3989 return null; 3990 } 3991 3992 @Override 3993 public String getNameForUid(int uid) { 3994 // reader 3995 synchronized (mPackages) { 3996 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3997 if (obj instanceof SharedUserSetting) { 3998 final SharedUserSetting sus = (SharedUserSetting) obj; 3999 return sus.name + ":" + sus.userId; 4000 } else if (obj instanceof PackageSetting) { 4001 final PackageSetting ps = (PackageSetting) obj; 4002 return ps.name; 4003 } 4004 } 4005 return null; 4006 } 4007 4008 @Override 4009 public int getUidForSharedUser(String sharedUserName) { 4010 if(sharedUserName == null) { 4011 return -1; 4012 } 4013 // reader 4014 synchronized (mPackages) { 4015 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4016 if (suid == null) { 4017 return -1; 4018 } 4019 return suid.userId; 4020 } 4021 } 4022 4023 @Override 4024 public int getFlagsForUid(int uid) { 4025 synchronized (mPackages) { 4026 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4027 if (obj instanceof SharedUserSetting) { 4028 final SharedUserSetting sus = (SharedUserSetting) obj; 4029 return sus.pkgFlags; 4030 } else if (obj instanceof PackageSetting) { 4031 final PackageSetting ps = (PackageSetting) obj; 4032 return ps.pkgFlags; 4033 } 4034 } 4035 return 0; 4036 } 4037 4038 @Override 4039 public int getPrivateFlagsForUid(int uid) { 4040 synchronized (mPackages) { 4041 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4042 if (obj instanceof SharedUserSetting) { 4043 final SharedUserSetting sus = (SharedUserSetting) obj; 4044 return sus.pkgPrivateFlags; 4045 } else if (obj instanceof PackageSetting) { 4046 final PackageSetting ps = (PackageSetting) obj; 4047 return ps.pkgPrivateFlags; 4048 } 4049 } 4050 return 0; 4051 } 4052 4053 @Override 4054 public boolean isUidPrivileged(int uid) { 4055 uid = UserHandle.getAppId(uid); 4056 // reader 4057 synchronized (mPackages) { 4058 Object obj = mSettings.getUserIdLPr(uid); 4059 if (obj instanceof SharedUserSetting) { 4060 final SharedUserSetting sus = (SharedUserSetting) obj; 4061 final Iterator<PackageSetting> it = sus.packages.iterator(); 4062 while (it.hasNext()) { 4063 if (it.next().isPrivileged()) { 4064 return true; 4065 } 4066 } 4067 } else if (obj instanceof PackageSetting) { 4068 final PackageSetting ps = (PackageSetting) obj; 4069 return ps.isPrivileged(); 4070 } 4071 } 4072 return false; 4073 } 4074 4075 @Override 4076 public String[] getAppOpPermissionPackages(String permissionName) { 4077 synchronized (mPackages) { 4078 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4079 if (pkgs == null) { 4080 return null; 4081 } 4082 return pkgs.toArray(new String[pkgs.size()]); 4083 } 4084 } 4085 4086 @Override 4087 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4088 int flags, int userId) { 4089 if (!sUserManager.exists(userId)) return null; 4090 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4091 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4092 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4093 } 4094 4095 @Override 4096 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4097 IntentFilter filter, int match, ComponentName activity) { 4098 final int userId = UserHandle.getCallingUserId(); 4099 if (DEBUG_PREFERRED) { 4100 Log.v(TAG, "setLastChosenActivity intent=" + intent 4101 + " resolvedType=" + resolvedType 4102 + " flags=" + flags 4103 + " filter=" + filter 4104 + " match=" + match 4105 + " activity=" + activity); 4106 filter.dump(new PrintStreamPrinter(System.out), " "); 4107 } 4108 intent.setComponent(null); 4109 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4110 // Find any earlier preferred or last chosen entries and nuke them 4111 findPreferredActivity(intent, resolvedType, 4112 flags, query, 0, false, true, false, userId); 4113 // Add the new activity as the last chosen for this filter 4114 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4115 "Setting last chosen"); 4116 } 4117 4118 @Override 4119 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4120 final int userId = UserHandle.getCallingUserId(); 4121 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4122 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4123 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4124 false, false, false, userId); 4125 } 4126 4127 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4128 int flags, List<ResolveInfo> query, int userId) { 4129 if (query != null) { 4130 final int N = query.size(); 4131 if (N == 1) { 4132 return query.get(0); 4133 } else if (N > 1) { 4134 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4135 // If there is more than one activity with the same priority, 4136 // then let the user decide between them. 4137 ResolveInfo r0 = query.get(0); 4138 ResolveInfo r1 = query.get(1); 4139 if (DEBUG_INTENT_MATCHING || debug) { 4140 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4141 + r1.activityInfo.name + "=" + r1.priority); 4142 } 4143 // If the first activity has a higher priority, or a different 4144 // default, then it is always desireable to pick it. 4145 if (r0.priority != r1.priority 4146 || r0.preferredOrder != r1.preferredOrder 4147 || r0.isDefault != r1.isDefault) { 4148 return query.get(0); 4149 } 4150 // If we have saved a preference for a preferred activity for 4151 // this Intent, use that. 4152 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4153 flags, query, r0.priority, true, false, debug, userId); 4154 if (ri != null) { 4155 return ri; 4156 } 4157 if (userId != 0) { 4158 ri = new ResolveInfo(mResolveInfo); 4159 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4160 ri.activityInfo.applicationInfo = new ApplicationInfo( 4161 ri.activityInfo.applicationInfo); 4162 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4163 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4164 return ri; 4165 } 4166 return mResolveInfo; 4167 } 4168 } 4169 return null; 4170 } 4171 4172 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4173 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4174 final int N = query.size(); 4175 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4176 .get(userId); 4177 // Get the list of persistent preferred activities that handle the intent 4178 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4179 List<PersistentPreferredActivity> pprefs = ppir != null 4180 ? ppir.queryIntent(intent, resolvedType, 4181 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4182 : null; 4183 if (pprefs != null && pprefs.size() > 0) { 4184 final int M = pprefs.size(); 4185 for (int i=0; i<M; i++) { 4186 final PersistentPreferredActivity ppa = pprefs.get(i); 4187 if (DEBUG_PREFERRED || debug) { 4188 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4189 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4190 + "\n component=" + ppa.mComponent); 4191 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4192 } 4193 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4194 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4195 if (DEBUG_PREFERRED || debug) { 4196 Slog.v(TAG, "Found persistent preferred activity:"); 4197 if (ai != null) { 4198 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4199 } else { 4200 Slog.v(TAG, " null"); 4201 } 4202 } 4203 if (ai == null) { 4204 // This previously registered persistent preferred activity 4205 // component is no longer known. Ignore it and do NOT remove it. 4206 continue; 4207 } 4208 for (int j=0; j<N; j++) { 4209 final ResolveInfo ri = query.get(j); 4210 if (!ri.activityInfo.applicationInfo.packageName 4211 .equals(ai.applicationInfo.packageName)) { 4212 continue; 4213 } 4214 if (!ri.activityInfo.name.equals(ai.name)) { 4215 continue; 4216 } 4217 // Found a persistent preference that can handle the intent. 4218 if (DEBUG_PREFERRED || debug) { 4219 Slog.v(TAG, "Returning persistent preferred activity: " + 4220 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4221 } 4222 return ri; 4223 } 4224 } 4225 } 4226 return null; 4227 } 4228 4229 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4230 List<ResolveInfo> query, int priority, boolean always, 4231 boolean removeMatches, boolean debug, int userId) { 4232 if (!sUserManager.exists(userId)) return null; 4233 // writer 4234 synchronized (mPackages) { 4235 if (intent.getSelector() != null) { 4236 intent = intent.getSelector(); 4237 } 4238 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4239 4240 // Try to find a matching persistent preferred activity. 4241 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4242 debug, userId); 4243 4244 // If a persistent preferred activity matched, use it. 4245 if (pri != null) { 4246 return pri; 4247 } 4248 4249 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4250 // Get the list of preferred activities that handle the intent 4251 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4252 List<PreferredActivity> prefs = pir != null 4253 ? pir.queryIntent(intent, resolvedType, 4254 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4255 : null; 4256 if (prefs != null && prefs.size() > 0) { 4257 boolean changed = false; 4258 try { 4259 // First figure out how good the original match set is. 4260 // We will only allow preferred activities that came 4261 // from the same match quality. 4262 int match = 0; 4263 4264 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4265 4266 final int N = query.size(); 4267 for (int j=0; j<N; j++) { 4268 final ResolveInfo ri = query.get(j); 4269 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4270 + ": 0x" + Integer.toHexString(match)); 4271 if (ri.match > match) { 4272 match = ri.match; 4273 } 4274 } 4275 4276 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4277 + Integer.toHexString(match)); 4278 4279 match &= IntentFilter.MATCH_CATEGORY_MASK; 4280 final int M = prefs.size(); 4281 for (int i=0; i<M; i++) { 4282 final PreferredActivity pa = prefs.get(i); 4283 if (DEBUG_PREFERRED || debug) { 4284 Slog.v(TAG, "Checking PreferredActivity ds=" 4285 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4286 + "\n component=" + pa.mPref.mComponent); 4287 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4288 } 4289 if (pa.mPref.mMatch != match) { 4290 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4291 + Integer.toHexString(pa.mPref.mMatch)); 4292 continue; 4293 } 4294 // If it's not an "always" type preferred activity and that's what we're 4295 // looking for, skip it. 4296 if (always && !pa.mPref.mAlways) { 4297 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4298 continue; 4299 } 4300 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4301 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4302 if (DEBUG_PREFERRED || debug) { 4303 Slog.v(TAG, "Found preferred activity:"); 4304 if (ai != null) { 4305 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4306 } else { 4307 Slog.v(TAG, " null"); 4308 } 4309 } 4310 if (ai == null) { 4311 // This previously registered preferred activity 4312 // component is no longer known. Most likely an update 4313 // to the app was installed and in the new version this 4314 // component no longer exists. Clean it up by removing 4315 // it from the preferred activities list, and skip it. 4316 Slog.w(TAG, "Removing dangling preferred activity: " 4317 + pa.mPref.mComponent); 4318 pir.removeFilter(pa); 4319 changed = true; 4320 continue; 4321 } 4322 for (int j=0; j<N; j++) { 4323 final ResolveInfo ri = query.get(j); 4324 if (!ri.activityInfo.applicationInfo.packageName 4325 .equals(ai.applicationInfo.packageName)) { 4326 continue; 4327 } 4328 if (!ri.activityInfo.name.equals(ai.name)) { 4329 continue; 4330 } 4331 4332 if (removeMatches) { 4333 pir.removeFilter(pa); 4334 changed = true; 4335 if (DEBUG_PREFERRED) { 4336 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4337 } 4338 break; 4339 } 4340 4341 // Okay we found a previously set preferred or last chosen app. 4342 // If the result set is different from when this 4343 // was created, we need to clear it and re-ask the 4344 // user their preference, if we're looking for an "always" type entry. 4345 if (always && !pa.mPref.sameSet(query)) { 4346 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4347 + intent + " type " + resolvedType); 4348 if (DEBUG_PREFERRED) { 4349 Slog.v(TAG, "Removing preferred activity since set changed " 4350 + pa.mPref.mComponent); 4351 } 4352 pir.removeFilter(pa); 4353 // Re-add the filter as a "last chosen" entry (!always) 4354 PreferredActivity lastChosen = new PreferredActivity( 4355 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4356 pir.addFilter(lastChosen); 4357 changed = true; 4358 return null; 4359 } 4360 4361 // Yay! Either the set matched or we're looking for the last chosen 4362 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4363 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4364 return ri; 4365 } 4366 } 4367 } finally { 4368 if (changed) { 4369 if (DEBUG_PREFERRED) { 4370 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4371 } 4372 scheduleWritePackageRestrictionsLocked(userId); 4373 } 4374 } 4375 } 4376 } 4377 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4378 return null; 4379 } 4380 4381 /* 4382 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4383 */ 4384 @Override 4385 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4386 int targetUserId) { 4387 mContext.enforceCallingOrSelfPermission( 4388 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4389 List<CrossProfileIntentFilter> matches = 4390 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4391 if (matches != null) { 4392 int size = matches.size(); 4393 for (int i = 0; i < size; i++) { 4394 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4395 } 4396 } 4397 if (hasWebURI(intent)) { 4398 // cross-profile app linking works only towards the parent. 4399 final UserInfo parent = getProfileParent(sourceUserId); 4400 synchronized(mPackages) { 4401 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4402 parent.id) != null; 4403 } 4404 } 4405 return false; 4406 } 4407 4408 private UserInfo getProfileParent(int userId) { 4409 final long identity = Binder.clearCallingIdentity(); 4410 try { 4411 return sUserManager.getProfileParent(userId); 4412 } finally { 4413 Binder.restoreCallingIdentity(identity); 4414 } 4415 } 4416 4417 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4418 String resolvedType, int userId) { 4419 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4420 if (resolver != null) { 4421 return resolver.queryIntent(intent, resolvedType, false, userId); 4422 } 4423 return null; 4424 } 4425 4426 @Override 4427 public List<ResolveInfo> queryIntentActivities(Intent intent, 4428 String resolvedType, int flags, int userId) { 4429 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4430 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4431 ComponentName comp = intent.getComponent(); 4432 if (comp == null) { 4433 if (intent.getSelector() != null) { 4434 intent = intent.getSelector(); 4435 comp = intent.getComponent(); 4436 } 4437 } 4438 4439 if (comp != null) { 4440 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4441 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4442 if (ai != null) { 4443 final ResolveInfo ri = new ResolveInfo(); 4444 ri.activityInfo = ai; 4445 list.add(ri); 4446 } 4447 return list; 4448 } 4449 4450 // reader 4451 synchronized (mPackages) { 4452 final String pkgName = intent.getPackage(); 4453 if (pkgName == null) { 4454 List<CrossProfileIntentFilter> matchingFilters = 4455 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4456 // Check for results that need to skip the current profile. 4457 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4458 resolvedType, flags, userId); 4459 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4460 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4461 result.add(xpResolveInfo); 4462 return filterIfNotPrimaryUser(result, userId); 4463 } 4464 4465 // Check for results in the current profile. 4466 List<ResolveInfo> result = mActivities.queryIntent( 4467 intent, resolvedType, flags, userId); 4468 4469 // Check for cross profile results. 4470 xpResolveInfo = queryCrossProfileIntents( 4471 matchingFilters, intent, resolvedType, flags, userId); 4472 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4473 result.add(xpResolveInfo); 4474 Collections.sort(result, mResolvePrioritySorter); 4475 } 4476 result = filterIfNotPrimaryUser(result, userId); 4477 if (hasWebURI(intent)) { 4478 CrossProfileDomainInfo xpDomainInfo = null; 4479 final UserInfo parent = getProfileParent(userId); 4480 if (parent != null) { 4481 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4482 flags, userId, parent.id); 4483 } 4484 if (xpDomainInfo != null) { 4485 if (xpResolveInfo != null) { 4486 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4487 // in the result. 4488 result.remove(xpResolveInfo); 4489 } 4490 if (result.size() == 0) { 4491 result.add(xpDomainInfo.resolveInfo); 4492 return result; 4493 } 4494 } else if (result.size() <= 1) { 4495 return result; 4496 } 4497 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4498 xpDomainInfo); 4499 Collections.sort(result, mResolvePrioritySorter); 4500 } 4501 return result; 4502 } 4503 final PackageParser.Package pkg = mPackages.get(pkgName); 4504 if (pkg != null) { 4505 return filterIfNotPrimaryUser( 4506 mActivities.queryIntentForPackage( 4507 intent, resolvedType, flags, pkg.activities, userId), 4508 userId); 4509 } 4510 return new ArrayList<ResolveInfo>(); 4511 } 4512 } 4513 4514 private static class CrossProfileDomainInfo { 4515 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4516 ResolveInfo resolveInfo; 4517 /* Best domain verification status of the activities found in the other profile */ 4518 int bestDomainVerificationStatus; 4519 } 4520 4521 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4522 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4523 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4524 sourceUserId)) { 4525 return null; 4526 } 4527 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4528 resolvedType, flags, parentUserId); 4529 4530 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4531 return null; 4532 } 4533 CrossProfileDomainInfo result = null; 4534 int size = resultTargetUser.size(); 4535 for (int i = 0; i < size; i++) { 4536 ResolveInfo riTargetUser = resultTargetUser.get(i); 4537 // Intent filter verification is only for filters that specify a host. So don't return 4538 // those that handle all web uris. 4539 if (riTargetUser.handleAllWebDataURI) { 4540 continue; 4541 } 4542 String packageName = riTargetUser.activityInfo.packageName; 4543 PackageSetting ps = mSettings.mPackages.get(packageName); 4544 if (ps == null) { 4545 continue; 4546 } 4547 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4548 if (result == null) { 4549 result = new CrossProfileDomainInfo(); 4550 result.resolveInfo = 4551 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4552 result.bestDomainVerificationStatus = status; 4553 } else { 4554 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4555 result.bestDomainVerificationStatus); 4556 } 4557 } 4558 return result; 4559 } 4560 4561 /** 4562 * Verification statuses are ordered from the worse to the best, except for 4563 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4564 */ 4565 private int bestDomainVerificationStatus(int status1, int status2) { 4566 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4567 return status2; 4568 } 4569 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4570 return status1; 4571 } 4572 return (int) MathUtils.max(status1, status2); 4573 } 4574 4575 private boolean isUserEnabled(int userId) { 4576 long callingId = Binder.clearCallingIdentity(); 4577 try { 4578 UserInfo userInfo = sUserManager.getUserInfo(userId); 4579 return userInfo != null && userInfo.isEnabled(); 4580 } finally { 4581 Binder.restoreCallingIdentity(callingId); 4582 } 4583 } 4584 4585 /** 4586 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4587 * 4588 * @return filtered list 4589 */ 4590 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4591 if (userId == UserHandle.USER_OWNER) { 4592 return resolveInfos; 4593 } 4594 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4595 ResolveInfo info = resolveInfos.get(i); 4596 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4597 resolveInfos.remove(i); 4598 } 4599 } 4600 return resolveInfos; 4601 } 4602 4603 private static boolean hasWebURI(Intent intent) { 4604 if (intent.getData() == null) { 4605 return false; 4606 } 4607 final String scheme = intent.getScheme(); 4608 if (TextUtils.isEmpty(scheme)) { 4609 return false; 4610 } 4611 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4612 } 4613 4614 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4615 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4616 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4617 Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " + 4618 candidates.size()); 4619 } 4620 4621 final int userId = UserHandle.getCallingUserId(); 4622 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4623 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4624 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4625 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4626 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4627 4628 synchronized (mPackages) { 4629 final int count = candidates.size(); 4630 // First, try to use linked apps. Partition the candidates into four lists: 4631 // one for the final results, one for the "do not use ever", one for "undefined status" 4632 // and finally one for "browser app type". 4633 for (int n=0; n<count; n++) { 4634 ResolveInfo info = candidates.get(n); 4635 String packageName = info.activityInfo.packageName; 4636 PackageSetting ps = mSettings.mPackages.get(packageName); 4637 if (ps != null) { 4638 // Add to the special match all list (Browser use case) 4639 if (info.handleAllWebDataURI) { 4640 matchAllList.add(info); 4641 continue; 4642 } 4643 // Try to get the status from User settings first 4644 int status = getDomainVerificationStatusLPr(ps, userId); 4645 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4646 if (DEBUG_DOMAIN_VERIFICATION) { 4647 Slog.i(TAG, " + always: " + info.activityInfo.packageName); 4648 } 4649 alwaysList.add(info); 4650 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4651 if (DEBUG_DOMAIN_VERIFICATION) { 4652 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4653 } 4654 neverList.add(info); 4655 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4656 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4657 if (DEBUG_DOMAIN_VERIFICATION) { 4658 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4659 } 4660 undefinedList.add(info); 4661 } 4662 } 4663 } 4664 // First try to add the "always" resolution for the current user if there is any 4665 if (alwaysList.size() > 0) { 4666 result.addAll(alwaysList); 4667 // if there is an "always" for the parent user, add it. 4668 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4669 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4670 result.add(xpDomainInfo.resolveInfo); 4671 } else { 4672 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4673 result.addAll(undefinedList); 4674 if (xpDomainInfo != null && ( 4675 xpDomainInfo.bestDomainVerificationStatus 4676 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4677 || xpDomainInfo.bestDomainVerificationStatus 4678 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4679 result.add(xpDomainInfo.resolveInfo); 4680 } 4681 // Also add Browsers (all of them or only the default one) 4682 if ((flags & MATCH_ALL) != 0) { 4683 result.addAll(matchAllList); 4684 } else { 4685 // Try to add the Default Browser if we can 4686 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4687 UserHandle.myUserId()); 4688 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4689 boolean defaultBrowserFound = false; 4690 final int browserCount = matchAllList.size(); 4691 for (int n=0; n<browserCount; n++) { 4692 ResolveInfo browser = matchAllList.get(n); 4693 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4694 result.add(browser); 4695 defaultBrowserFound = true; 4696 break; 4697 } 4698 } 4699 if (!defaultBrowserFound) { 4700 result.addAll(matchAllList); 4701 } 4702 } else { 4703 result.addAll(matchAllList); 4704 } 4705 } 4706 4707 // If there is nothing selected, add all candidates and remove the ones that the user 4708 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4709 if (result.size() == 0) { 4710 result.addAll(candidates); 4711 result.removeAll(neverList); 4712 } 4713 } 4714 } 4715 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4716 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4717 result.size()); 4718 for (ResolveInfo info : result) { 4719 Slog.v(TAG, " + " + info.activityInfo); 4720 } 4721 } 4722 return result; 4723 } 4724 4725 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4726 int status = ps.getDomainVerificationStatusForUser(userId); 4727 // if none available, get the master status 4728 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4729 if (ps.getIntentFilterVerificationInfo() != null) { 4730 status = ps.getIntentFilterVerificationInfo().getStatus(); 4731 } 4732 } 4733 return status; 4734 } 4735 4736 private ResolveInfo querySkipCurrentProfileIntents( 4737 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4738 int flags, int sourceUserId) { 4739 if (matchingFilters != null) { 4740 int size = matchingFilters.size(); 4741 for (int i = 0; i < size; i ++) { 4742 CrossProfileIntentFilter filter = matchingFilters.get(i); 4743 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4744 // Checking if there are activities in the target user that can handle the 4745 // intent. 4746 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4747 flags, sourceUserId); 4748 if (resolveInfo != null) { 4749 return resolveInfo; 4750 } 4751 } 4752 } 4753 } 4754 return null; 4755 } 4756 4757 // Return matching ResolveInfo if any for skip current profile intent filters. 4758 private ResolveInfo queryCrossProfileIntents( 4759 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4760 int flags, int sourceUserId) { 4761 if (matchingFilters != null) { 4762 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4763 // match the same intent. For performance reasons, it is better not to 4764 // run queryIntent twice for the same userId 4765 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4766 int size = matchingFilters.size(); 4767 for (int i = 0; i < size; i++) { 4768 CrossProfileIntentFilter filter = matchingFilters.get(i); 4769 int targetUserId = filter.getTargetUserId(); 4770 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4771 && !alreadyTriedUserIds.get(targetUserId)) { 4772 // Checking if there are activities in the target user that can handle the 4773 // intent. 4774 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4775 flags, sourceUserId); 4776 if (resolveInfo != null) return resolveInfo; 4777 alreadyTriedUserIds.put(targetUserId, true); 4778 } 4779 } 4780 } 4781 return null; 4782 } 4783 4784 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4785 String resolvedType, int flags, int sourceUserId) { 4786 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4787 resolvedType, flags, filter.getTargetUserId()); 4788 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4789 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4790 } 4791 return null; 4792 } 4793 4794 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4795 int sourceUserId, int targetUserId) { 4796 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4797 String className; 4798 if (targetUserId == UserHandle.USER_OWNER) { 4799 className = FORWARD_INTENT_TO_USER_OWNER; 4800 } else { 4801 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4802 } 4803 ComponentName forwardingActivityComponentName = new ComponentName( 4804 mAndroidApplication.packageName, className); 4805 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4806 sourceUserId); 4807 if (targetUserId == UserHandle.USER_OWNER) { 4808 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4809 forwardingResolveInfo.noResourceId = true; 4810 } 4811 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4812 forwardingResolveInfo.priority = 0; 4813 forwardingResolveInfo.preferredOrder = 0; 4814 forwardingResolveInfo.match = 0; 4815 forwardingResolveInfo.isDefault = true; 4816 forwardingResolveInfo.filter = filter; 4817 forwardingResolveInfo.targetUserId = targetUserId; 4818 return forwardingResolveInfo; 4819 } 4820 4821 @Override 4822 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4823 Intent[] specifics, String[] specificTypes, Intent intent, 4824 String resolvedType, int flags, int userId) { 4825 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4826 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4827 false, "query intent activity options"); 4828 final String resultsAction = intent.getAction(); 4829 4830 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4831 | PackageManager.GET_RESOLVED_FILTER, userId); 4832 4833 if (DEBUG_INTENT_MATCHING) { 4834 Log.v(TAG, "Query " + intent + ": " + results); 4835 } 4836 4837 int specificsPos = 0; 4838 int N; 4839 4840 // todo: note that the algorithm used here is O(N^2). This 4841 // isn't a problem in our current environment, but if we start running 4842 // into situations where we have more than 5 or 10 matches then this 4843 // should probably be changed to something smarter... 4844 4845 // First we go through and resolve each of the specific items 4846 // that were supplied, taking care of removing any corresponding 4847 // duplicate items in the generic resolve list. 4848 if (specifics != null) { 4849 for (int i=0; i<specifics.length; i++) { 4850 final Intent sintent = specifics[i]; 4851 if (sintent == null) { 4852 continue; 4853 } 4854 4855 if (DEBUG_INTENT_MATCHING) { 4856 Log.v(TAG, "Specific #" + i + ": " + sintent); 4857 } 4858 4859 String action = sintent.getAction(); 4860 if (resultsAction != null && resultsAction.equals(action)) { 4861 // If this action was explicitly requested, then don't 4862 // remove things that have it. 4863 action = null; 4864 } 4865 4866 ResolveInfo ri = null; 4867 ActivityInfo ai = null; 4868 4869 ComponentName comp = sintent.getComponent(); 4870 if (comp == null) { 4871 ri = resolveIntent( 4872 sintent, 4873 specificTypes != null ? specificTypes[i] : null, 4874 flags, userId); 4875 if (ri == null) { 4876 continue; 4877 } 4878 if (ri == mResolveInfo) { 4879 // ACK! Must do something better with this. 4880 } 4881 ai = ri.activityInfo; 4882 comp = new ComponentName(ai.applicationInfo.packageName, 4883 ai.name); 4884 } else { 4885 ai = getActivityInfo(comp, flags, userId); 4886 if (ai == null) { 4887 continue; 4888 } 4889 } 4890 4891 // Look for any generic query activities that are duplicates 4892 // of this specific one, and remove them from the results. 4893 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4894 N = results.size(); 4895 int j; 4896 for (j=specificsPos; j<N; j++) { 4897 ResolveInfo sri = results.get(j); 4898 if ((sri.activityInfo.name.equals(comp.getClassName()) 4899 && sri.activityInfo.applicationInfo.packageName.equals( 4900 comp.getPackageName())) 4901 || (action != null && sri.filter.matchAction(action))) { 4902 results.remove(j); 4903 if (DEBUG_INTENT_MATCHING) Log.v( 4904 TAG, "Removing duplicate item from " + j 4905 + " due to specific " + specificsPos); 4906 if (ri == null) { 4907 ri = sri; 4908 } 4909 j--; 4910 N--; 4911 } 4912 } 4913 4914 // Add this specific item to its proper place. 4915 if (ri == null) { 4916 ri = new ResolveInfo(); 4917 ri.activityInfo = ai; 4918 } 4919 results.add(specificsPos, ri); 4920 ri.specificIndex = i; 4921 specificsPos++; 4922 } 4923 } 4924 4925 // Now we go through the remaining generic results and remove any 4926 // duplicate actions that are found here. 4927 N = results.size(); 4928 for (int i=specificsPos; i<N-1; i++) { 4929 final ResolveInfo rii = results.get(i); 4930 if (rii.filter == null) { 4931 continue; 4932 } 4933 4934 // Iterate over all of the actions of this result's intent 4935 // filter... typically this should be just one. 4936 final Iterator<String> it = rii.filter.actionsIterator(); 4937 if (it == null) { 4938 continue; 4939 } 4940 while (it.hasNext()) { 4941 final String action = it.next(); 4942 if (resultsAction != null && resultsAction.equals(action)) { 4943 // If this action was explicitly requested, then don't 4944 // remove things that have it. 4945 continue; 4946 } 4947 for (int j=i+1; j<N; j++) { 4948 final ResolveInfo rij = results.get(j); 4949 if (rij.filter != null && rij.filter.hasAction(action)) { 4950 results.remove(j); 4951 if (DEBUG_INTENT_MATCHING) Log.v( 4952 TAG, "Removing duplicate item from " + j 4953 + " due to action " + action + " at " + i); 4954 j--; 4955 N--; 4956 } 4957 } 4958 } 4959 4960 // If the caller didn't request filter information, drop it now 4961 // so we don't have to marshall/unmarshall it. 4962 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4963 rii.filter = null; 4964 } 4965 } 4966 4967 // Filter out the caller activity if so requested. 4968 if (caller != null) { 4969 N = results.size(); 4970 for (int i=0; i<N; i++) { 4971 ActivityInfo ainfo = results.get(i).activityInfo; 4972 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4973 && caller.getClassName().equals(ainfo.name)) { 4974 results.remove(i); 4975 break; 4976 } 4977 } 4978 } 4979 4980 // If the caller didn't request filter information, 4981 // drop them now so we don't have to 4982 // marshall/unmarshall it. 4983 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4984 N = results.size(); 4985 for (int i=0; i<N; i++) { 4986 results.get(i).filter = null; 4987 } 4988 } 4989 4990 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4991 return results; 4992 } 4993 4994 @Override 4995 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4996 int userId) { 4997 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4998 ComponentName comp = intent.getComponent(); 4999 if (comp == null) { 5000 if (intent.getSelector() != null) { 5001 intent = intent.getSelector(); 5002 comp = intent.getComponent(); 5003 } 5004 } 5005 if (comp != null) { 5006 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5007 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5008 if (ai != null) { 5009 ResolveInfo ri = new ResolveInfo(); 5010 ri.activityInfo = ai; 5011 list.add(ri); 5012 } 5013 return list; 5014 } 5015 5016 // reader 5017 synchronized (mPackages) { 5018 String pkgName = intent.getPackage(); 5019 if (pkgName == null) { 5020 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5021 } 5022 final PackageParser.Package pkg = mPackages.get(pkgName); 5023 if (pkg != null) { 5024 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5025 userId); 5026 } 5027 return null; 5028 } 5029 } 5030 5031 @Override 5032 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5033 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5034 if (!sUserManager.exists(userId)) return null; 5035 if (query != null) { 5036 if (query.size() >= 1) { 5037 // If there is more than one service with the same priority, 5038 // just arbitrarily pick the first one. 5039 return query.get(0); 5040 } 5041 } 5042 return null; 5043 } 5044 5045 @Override 5046 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5047 int userId) { 5048 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5049 ComponentName comp = intent.getComponent(); 5050 if (comp == null) { 5051 if (intent.getSelector() != null) { 5052 intent = intent.getSelector(); 5053 comp = intent.getComponent(); 5054 } 5055 } 5056 if (comp != null) { 5057 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5058 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5059 if (si != null) { 5060 final ResolveInfo ri = new ResolveInfo(); 5061 ri.serviceInfo = si; 5062 list.add(ri); 5063 } 5064 return list; 5065 } 5066 5067 // reader 5068 synchronized (mPackages) { 5069 String pkgName = intent.getPackage(); 5070 if (pkgName == null) { 5071 return mServices.queryIntent(intent, resolvedType, flags, userId); 5072 } 5073 final PackageParser.Package pkg = mPackages.get(pkgName); 5074 if (pkg != null) { 5075 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5076 userId); 5077 } 5078 return null; 5079 } 5080 } 5081 5082 @Override 5083 public List<ResolveInfo> queryIntentContentProviders( 5084 Intent intent, String resolvedType, int flags, int userId) { 5085 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5086 ComponentName comp = intent.getComponent(); 5087 if (comp == null) { 5088 if (intent.getSelector() != null) { 5089 intent = intent.getSelector(); 5090 comp = intent.getComponent(); 5091 } 5092 } 5093 if (comp != null) { 5094 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5095 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5096 if (pi != null) { 5097 final ResolveInfo ri = new ResolveInfo(); 5098 ri.providerInfo = pi; 5099 list.add(ri); 5100 } 5101 return list; 5102 } 5103 5104 // reader 5105 synchronized (mPackages) { 5106 String pkgName = intent.getPackage(); 5107 if (pkgName == null) { 5108 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5109 } 5110 final PackageParser.Package pkg = mPackages.get(pkgName); 5111 if (pkg != null) { 5112 return mProviders.queryIntentForPackage( 5113 intent, resolvedType, flags, pkg.providers, userId); 5114 } 5115 return null; 5116 } 5117 } 5118 5119 @Override 5120 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5121 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5122 5123 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5124 5125 // writer 5126 synchronized (mPackages) { 5127 ArrayList<PackageInfo> list; 5128 if (listUninstalled) { 5129 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5130 for (PackageSetting ps : mSettings.mPackages.values()) { 5131 PackageInfo pi; 5132 if (ps.pkg != null) { 5133 pi = generatePackageInfo(ps.pkg, flags, userId); 5134 } else { 5135 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5136 } 5137 if (pi != null) { 5138 list.add(pi); 5139 } 5140 } 5141 } else { 5142 list = new ArrayList<PackageInfo>(mPackages.size()); 5143 for (PackageParser.Package p : mPackages.values()) { 5144 PackageInfo pi = generatePackageInfo(p, flags, userId); 5145 if (pi != null) { 5146 list.add(pi); 5147 } 5148 } 5149 } 5150 5151 return new ParceledListSlice<PackageInfo>(list); 5152 } 5153 } 5154 5155 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5156 String[] permissions, boolean[] tmp, int flags, int userId) { 5157 int numMatch = 0; 5158 final PermissionsState permissionsState = ps.getPermissionsState(); 5159 for (int i=0; i<permissions.length; i++) { 5160 final String permission = permissions[i]; 5161 if (permissionsState.hasPermission(permission, userId)) { 5162 tmp[i] = true; 5163 numMatch++; 5164 } else { 5165 tmp[i] = false; 5166 } 5167 } 5168 if (numMatch == 0) { 5169 return; 5170 } 5171 PackageInfo pi; 5172 if (ps.pkg != null) { 5173 pi = generatePackageInfo(ps.pkg, flags, userId); 5174 } else { 5175 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5176 } 5177 // The above might return null in cases of uninstalled apps or install-state 5178 // skew across users/profiles. 5179 if (pi != null) { 5180 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5181 if (numMatch == permissions.length) { 5182 pi.requestedPermissions = permissions; 5183 } else { 5184 pi.requestedPermissions = new String[numMatch]; 5185 numMatch = 0; 5186 for (int i=0; i<permissions.length; i++) { 5187 if (tmp[i]) { 5188 pi.requestedPermissions[numMatch] = permissions[i]; 5189 numMatch++; 5190 } 5191 } 5192 } 5193 } 5194 list.add(pi); 5195 } 5196 } 5197 5198 @Override 5199 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5200 String[] permissions, int flags, int userId) { 5201 if (!sUserManager.exists(userId)) return null; 5202 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5203 5204 // writer 5205 synchronized (mPackages) { 5206 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5207 boolean[] tmpBools = new boolean[permissions.length]; 5208 if (listUninstalled) { 5209 for (PackageSetting ps : mSettings.mPackages.values()) { 5210 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5211 } 5212 } else { 5213 for (PackageParser.Package pkg : mPackages.values()) { 5214 PackageSetting ps = (PackageSetting)pkg.mExtras; 5215 if (ps != null) { 5216 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5217 userId); 5218 } 5219 } 5220 } 5221 5222 return new ParceledListSlice<PackageInfo>(list); 5223 } 5224 } 5225 5226 @Override 5227 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5228 if (!sUserManager.exists(userId)) return null; 5229 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5230 5231 // writer 5232 synchronized (mPackages) { 5233 ArrayList<ApplicationInfo> list; 5234 if (listUninstalled) { 5235 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5236 for (PackageSetting ps : mSettings.mPackages.values()) { 5237 ApplicationInfo ai; 5238 if (ps.pkg != null) { 5239 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5240 ps.readUserState(userId), userId); 5241 } else { 5242 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5243 } 5244 if (ai != null) { 5245 list.add(ai); 5246 } 5247 } 5248 } else { 5249 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5250 for (PackageParser.Package p : mPackages.values()) { 5251 if (p.mExtras != null) { 5252 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5253 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5254 if (ai != null) { 5255 list.add(ai); 5256 } 5257 } 5258 } 5259 } 5260 5261 return new ParceledListSlice<ApplicationInfo>(list); 5262 } 5263 } 5264 5265 public List<ApplicationInfo> getPersistentApplications(int flags) { 5266 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5267 5268 // reader 5269 synchronized (mPackages) { 5270 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5271 final int userId = UserHandle.getCallingUserId(); 5272 while (i.hasNext()) { 5273 final PackageParser.Package p = i.next(); 5274 if (p.applicationInfo != null 5275 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5276 && (!mSafeMode || isSystemApp(p))) { 5277 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5278 if (ps != null) { 5279 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5280 ps.readUserState(userId), userId); 5281 if (ai != null) { 5282 finalList.add(ai); 5283 } 5284 } 5285 } 5286 } 5287 } 5288 5289 return finalList; 5290 } 5291 5292 @Override 5293 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5294 if (!sUserManager.exists(userId)) return null; 5295 // reader 5296 synchronized (mPackages) { 5297 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5298 PackageSetting ps = provider != null 5299 ? mSettings.mPackages.get(provider.owner.packageName) 5300 : null; 5301 return ps != null 5302 && mSettings.isEnabledLPr(provider.info, flags, userId) 5303 && (!mSafeMode || (provider.info.applicationInfo.flags 5304 &ApplicationInfo.FLAG_SYSTEM) != 0) 5305 ? PackageParser.generateProviderInfo(provider, flags, 5306 ps.readUserState(userId), userId) 5307 : null; 5308 } 5309 } 5310 5311 /** 5312 * @deprecated 5313 */ 5314 @Deprecated 5315 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5316 // reader 5317 synchronized (mPackages) { 5318 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5319 .entrySet().iterator(); 5320 final int userId = UserHandle.getCallingUserId(); 5321 while (i.hasNext()) { 5322 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5323 PackageParser.Provider p = entry.getValue(); 5324 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5325 5326 if (ps != null && p.syncable 5327 && (!mSafeMode || (p.info.applicationInfo.flags 5328 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5329 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5330 ps.readUserState(userId), userId); 5331 if (info != null) { 5332 outNames.add(entry.getKey()); 5333 outInfo.add(info); 5334 } 5335 } 5336 } 5337 } 5338 } 5339 5340 @Override 5341 public List<ProviderInfo> queryContentProviders(String processName, 5342 int uid, int flags) { 5343 ArrayList<ProviderInfo> finalList = null; 5344 // reader 5345 synchronized (mPackages) { 5346 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5347 final int userId = processName != null ? 5348 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5349 while (i.hasNext()) { 5350 final PackageParser.Provider p = i.next(); 5351 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5352 if (ps != null && p.info.authority != null 5353 && (processName == null 5354 || (p.info.processName.equals(processName) 5355 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5356 && mSettings.isEnabledLPr(p.info, flags, userId) 5357 && (!mSafeMode 5358 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5359 if (finalList == null) { 5360 finalList = new ArrayList<ProviderInfo>(3); 5361 } 5362 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5363 ps.readUserState(userId), userId); 5364 if (info != null) { 5365 finalList.add(info); 5366 } 5367 } 5368 } 5369 } 5370 5371 if (finalList != null) { 5372 Collections.sort(finalList, mProviderInitOrderSorter); 5373 } 5374 5375 return finalList; 5376 } 5377 5378 @Override 5379 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5380 int flags) { 5381 // reader 5382 synchronized (mPackages) { 5383 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5384 return PackageParser.generateInstrumentationInfo(i, flags); 5385 } 5386 } 5387 5388 @Override 5389 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5390 int flags) { 5391 ArrayList<InstrumentationInfo> finalList = 5392 new ArrayList<InstrumentationInfo>(); 5393 5394 // reader 5395 synchronized (mPackages) { 5396 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5397 while (i.hasNext()) { 5398 final PackageParser.Instrumentation p = i.next(); 5399 if (targetPackage == null 5400 || targetPackage.equals(p.info.targetPackage)) { 5401 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5402 flags); 5403 if (ii != null) { 5404 finalList.add(ii); 5405 } 5406 } 5407 } 5408 } 5409 5410 return finalList; 5411 } 5412 5413 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5414 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5415 if (overlays == null) { 5416 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5417 return; 5418 } 5419 for (PackageParser.Package opkg : overlays.values()) { 5420 // Not much to do if idmap fails: we already logged the error 5421 // and we certainly don't want to abort installation of pkg simply 5422 // because an overlay didn't fit properly. For these reasons, 5423 // ignore the return value of createIdmapForPackagePairLI. 5424 createIdmapForPackagePairLI(pkg, opkg); 5425 } 5426 } 5427 5428 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5429 PackageParser.Package opkg) { 5430 if (!opkg.mTrustedOverlay) { 5431 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5432 opkg.baseCodePath + ": overlay not trusted"); 5433 return false; 5434 } 5435 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5436 if (overlaySet == null) { 5437 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5438 opkg.baseCodePath + " but target package has no known overlays"); 5439 return false; 5440 } 5441 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5442 // TODO: generate idmap for split APKs 5443 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5444 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5445 + opkg.baseCodePath); 5446 return false; 5447 } 5448 PackageParser.Package[] overlayArray = 5449 overlaySet.values().toArray(new PackageParser.Package[0]); 5450 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5451 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5452 return p1.mOverlayPriority - p2.mOverlayPriority; 5453 } 5454 }; 5455 Arrays.sort(overlayArray, cmp); 5456 5457 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5458 int i = 0; 5459 for (PackageParser.Package p : overlayArray) { 5460 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5461 } 5462 return true; 5463 } 5464 5465 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5466 final File[] files = dir.listFiles(); 5467 if (ArrayUtils.isEmpty(files)) { 5468 Log.d(TAG, "No files in app dir " + dir); 5469 return; 5470 } 5471 5472 if (DEBUG_PACKAGE_SCANNING) { 5473 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5474 + " flags=0x" + Integer.toHexString(parseFlags)); 5475 } 5476 5477 for (File file : files) { 5478 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5479 && !PackageInstallerService.isStageName(file.getName()); 5480 if (!isPackage) { 5481 // Ignore entries which are not packages 5482 continue; 5483 } 5484 try { 5485 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5486 scanFlags, currentTime, null); 5487 } catch (PackageManagerException e) { 5488 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5489 5490 // Delete invalid userdata apps 5491 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5492 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5493 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5494 if (file.isDirectory()) { 5495 mInstaller.rmPackageDir(file.getAbsolutePath()); 5496 } else { 5497 file.delete(); 5498 } 5499 } 5500 } 5501 } 5502 } 5503 5504 private static File getSettingsProblemFile() { 5505 File dataDir = Environment.getDataDirectory(); 5506 File systemDir = new File(dataDir, "system"); 5507 File fname = new File(systemDir, "uiderrors.txt"); 5508 return fname; 5509 } 5510 5511 static void reportSettingsProblem(int priority, String msg) { 5512 logCriticalInfo(priority, msg); 5513 } 5514 5515 static void logCriticalInfo(int priority, String msg) { 5516 Slog.println(priority, TAG, msg); 5517 EventLogTags.writePmCriticalInfo(msg); 5518 try { 5519 File fname = getSettingsProblemFile(); 5520 FileOutputStream out = new FileOutputStream(fname, true); 5521 PrintWriter pw = new FastPrintWriter(out); 5522 SimpleDateFormat formatter = new SimpleDateFormat(); 5523 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5524 pw.println(dateString + ": " + msg); 5525 pw.close(); 5526 FileUtils.setPermissions( 5527 fname.toString(), 5528 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5529 -1, -1); 5530 } catch (java.io.IOException e) { 5531 } 5532 } 5533 5534 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5535 PackageParser.Package pkg, File srcFile, int parseFlags) 5536 throws PackageManagerException { 5537 if (ps != null 5538 && ps.codePath.equals(srcFile) 5539 && ps.timeStamp == srcFile.lastModified() 5540 && !isCompatSignatureUpdateNeeded(pkg) 5541 && !isRecoverSignatureUpdateNeeded(pkg)) { 5542 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5543 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5544 ArraySet<PublicKey> signingKs; 5545 synchronized (mPackages) { 5546 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5547 } 5548 if (ps.signatures.mSignatures != null 5549 && ps.signatures.mSignatures.length != 0 5550 && signingKs != null) { 5551 // Optimization: reuse the existing cached certificates 5552 // if the package appears to be unchanged. 5553 pkg.mSignatures = ps.signatures.mSignatures; 5554 pkg.mSigningKeys = signingKs; 5555 return; 5556 } 5557 5558 Slog.w(TAG, "PackageSetting for " + ps.name 5559 + " is missing signatures. Collecting certs again to recover them."); 5560 } else { 5561 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5562 } 5563 5564 try { 5565 pp.collectCertificates(pkg, parseFlags); 5566 pp.collectManifestDigest(pkg); 5567 } catch (PackageParserException e) { 5568 throw PackageManagerException.from(e); 5569 } 5570 } 5571 5572 /* 5573 * Scan a package and return the newly parsed package. 5574 * Returns null in case of errors and the error code is stored in mLastScanError 5575 */ 5576 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5577 long currentTime, UserHandle user) throws PackageManagerException { 5578 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5579 parseFlags |= mDefParseFlags; 5580 PackageParser pp = new PackageParser(); 5581 pp.setSeparateProcesses(mSeparateProcesses); 5582 pp.setOnlyCoreApps(mOnlyCore); 5583 pp.setDisplayMetrics(mMetrics); 5584 5585 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5586 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5587 } 5588 5589 final PackageParser.Package pkg; 5590 try { 5591 pkg = pp.parsePackage(scanFile, parseFlags); 5592 } catch (PackageParserException e) { 5593 throw PackageManagerException.from(e); 5594 } 5595 5596 PackageSetting ps = null; 5597 PackageSetting updatedPkg; 5598 // reader 5599 synchronized (mPackages) { 5600 // Look to see if we already know about this package. 5601 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5602 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5603 // This package has been renamed to its original name. Let's 5604 // use that. 5605 ps = mSettings.peekPackageLPr(oldName); 5606 } 5607 // If there was no original package, see one for the real package name. 5608 if (ps == null) { 5609 ps = mSettings.peekPackageLPr(pkg.packageName); 5610 } 5611 // Check to see if this package could be hiding/updating a system 5612 // package. Must look for it either under the original or real 5613 // package name depending on our state. 5614 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5615 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5616 } 5617 boolean updatedPkgBetter = false; 5618 // First check if this is a system package that may involve an update 5619 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5620 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5621 // it needs to drop FLAG_PRIVILEGED. 5622 if (locationIsPrivileged(scanFile)) { 5623 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5624 } else { 5625 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5626 } 5627 5628 if (ps != null && !ps.codePath.equals(scanFile)) { 5629 // The path has changed from what was last scanned... check the 5630 // version of the new path against what we have stored to determine 5631 // what to do. 5632 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5633 if (pkg.mVersionCode <= ps.versionCode) { 5634 // The system package has been updated and the code path does not match 5635 // Ignore entry. Skip it. 5636 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5637 + " ignored: updated version " + ps.versionCode 5638 + " better than this " + pkg.mVersionCode); 5639 if (!updatedPkg.codePath.equals(scanFile)) { 5640 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5641 + ps.name + " changing from " + updatedPkg.codePathString 5642 + " to " + scanFile); 5643 updatedPkg.codePath = scanFile; 5644 updatedPkg.codePathString = scanFile.toString(); 5645 updatedPkg.resourcePath = scanFile; 5646 updatedPkg.resourcePathString = scanFile.toString(); 5647 } 5648 updatedPkg.pkg = pkg; 5649 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5650 } else { 5651 // The current app on the system partition is better than 5652 // what we have updated to on the data partition; switch 5653 // back to the system partition version. 5654 // At this point, its safely assumed that package installation for 5655 // apps in system partition will go through. If not there won't be a working 5656 // version of the app 5657 // writer 5658 synchronized (mPackages) { 5659 // Just remove the loaded entries from package lists. 5660 mPackages.remove(ps.name); 5661 } 5662 5663 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5664 + " reverting from " + ps.codePathString 5665 + ": new version " + pkg.mVersionCode 5666 + " better than installed " + ps.versionCode); 5667 5668 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5669 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5670 synchronized (mInstallLock) { 5671 args.cleanUpResourcesLI(); 5672 } 5673 synchronized (mPackages) { 5674 mSettings.enableSystemPackageLPw(ps.name); 5675 } 5676 updatedPkgBetter = true; 5677 } 5678 } 5679 } 5680 5681 if (updatedPkg != null) { 5682 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5683 // initially 5684 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5685 5686 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5687 // flag set initially 5688 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5689 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5690 } 5691 } 5692 5693 // Verify certificates against what was last scanned 5694 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5695 5696 /* 5697 * A new system app appeared, but we already had a non-system one of the 5698 * same name installed earlier. 5699 */ 5700 boolean shouldHideSystemApp = false; 5701 if (updatedPkg == null && ps != null 5702 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5703 /* 5704 * Check to make sure the signatures match first. If they don't, 5705 * wipe the installed application and its data. 5706 */ 5707 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5708 != PackageManager.SIGNATURE_MATCH) { 5709 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5710 + " signatures don't match existing userdata copy; removing"); 5711 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5712 ps = null; 5713 } else { 5714 /* 5715 * If the newly-added system app is an older version than the 5716 * already installed version, hide it. It will be scanned later 5717 * and re-added like an update. 5718 */ 5719 if (pkg.mVersionCode <= ps.versionCode) { 5720 shouldHideSystemApp = true; 5721 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5722 + " but new version " + pkg.mVersionCode + " better than installed " 5723 + ps.versionCode + "; hiding system"); 5724 } else { 5725 /* 5726 * The newly found system app is a newer version that the 5727 * one previously installed. Simply remove the 5728 * already-installed application and replace it with our own 5729 * while keeping the application data. 5730 */ 5731 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5732 + " reverting from " + ps.codePathString + ": new version " 5733 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5734 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5735 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5736 synchronized (mInstallLock) { 5737 args.cleanUpResourcesLI(); 5738 } 5739 } 5740 } 5741 } 5742 5743 // The apk is forward locked (not public) if its code and resources 5744 // are kept in different files. (except for app in either system or 5745 // vendor path). 5746 // TODO grab this value from PackageSettings 5747 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5748 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5749 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5750 } 5751 } 5752 5753 // TODO: extend to support forward-locked splits 5754 String resourcePath = null; 5755 String baseResourcePath = null; 5756 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5757 if (ps != null && ps.resourcePathString != null) { 5758 resourcePath = ps.resourcePathString; 5759 baseResourcePath = ps.resourcePathString; 5760 } else { 5761 // Should not happen at all. Just log an error. 5762 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5763 } 5764 } else { 5765 resourcePath = pkg.codePath; 5766 baseResourcePath = pkg.baseCodePath; 5767 } 5768 5769 // Set application objects path explicitly. 5770 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5771 pkg.applicationInfo.setCodePath(pkg.codePath); 5772 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5773 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5774 pkg.applicationInfo.setResourcePath(resourcePath); 5775 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5776 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5777 5778 // Note that we invoke the following method only if we are about to unpack an application 5779 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5780 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5781 5782 /* 5783 * If the system app should be overridden by a previously installed 5784 * data, hide the system app now and let the /data/app scan pick it up 5785 * again. 5786 */ 5787 if (shouldHideSystemApp) { 5788 synchronized (mPackages) { 5789 /* 5790 * We have to grant systems permissions before we hide, because 5791 * grantPermissions will assume the package update is trying to 5792 * expand its permissions. 5793 */ 5794 grantPermissionsLPw(pkg, true, pkg.packageName); 5795 mSettings.disableSystemPackageLPw(pkg.packageName); 5796 } 5797 } 5798 5799 return scannedPkg; 5800 } 5801 5802 private static String fixProcessName(String defProcessName, 5803 String processName, int uid) { 5804 if (processName == null) { 5805 return defProcessName; 5806 } 5807 return processName; 5808 } 5809 5810 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5811 throws PackageManagerException { 5812 if (pkgSetting.signatures.mSignatures != null) { 5813 // Already existing package. Make sure signatures match 5814 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5815 == PackageManager.SIGNATURE_MATCH; 5816 if (!match) { 5817 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5818 == PackageManager.SIGNATURE_MATCH; 5819 } 5820 if (!match) { 5821 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5822 == PackageManager.SIGNATURE_MATCH; 5823 } 5824 if (!match) { 5825 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5826 + pkg.packageName + " signatures do not match the " 5827 + "previously installed version; ignoring!"); 5828 } 5829 } 5830 5831 // Check for shared user signatures 5832 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5833 // Already existing package. Make sure signatures match 5834 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5835 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5836 if (!match) { 5837 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5838 == PackageManager.SIGNATURE_MATCH; 5839 } 5840 if (!match) { 5841 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5842 == PackageManager.SIGNATURE_MATCH; 5843 } 5844 if (!match) { 5845 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5846 "Package " + pkg.packageName 5847 + " has no signatures that match those in shared user " 5848 + pkgSetting.sharedUser.name + "; ignoring!"); 5849 } 5850 } 5851 } 5852 5853 /** 5854 * Enforces that only the system UID or root's UID can call a method exposed 5855 * via Binder. 5856 * 5857 * @param message used as message if SecurityException is thrown 5858 * @throws SecurityException if the caller is not system or root 5859 */ 5860 private static final void enforceSystemOrRoot(String message) { 5861 final int uid = Binder.getCallingUid(); 5862 if (uid != Process.SYSTEM_UID && uid != 0) { 5863 throw new SecurityException(message); 5864 } 5865 } 5866 5867 @Override 5868 public void performBootDexOpt() { 5869 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5870 5871 // Before everything else, see whether we need to fstrim. 5872 try { 5873 IMountService ms = PackageHelper.getMountService(); 5874 if (ms != null) { 5875 final boolean isUpgrade = isUpgrade(); 5876 boolean doTrim = isUpgrade; 5877 if (doTrim) { 5878 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5879 } else { 5880 final long interval = android.provider.Settings.Global.getLong( 5881 mContext.getContentResolver(), 5882 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5883 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5884 if (interval > 0) { 5885 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5886 if (timeSinceLast > interval) { 5887 doTrim = true; 5888 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5889 + "; running immediately"); 5890 } 5891 } 5892 } 5893 if (doTrim) { 5894 if (!isFirstBoot()) { 5895 try { 5896 ActivityManagerNative.getDefault().showBootMessage( 5897 mContext.getResources().getString( 5898 R.string.android_upgrading_fstrim), true); 5899 } catch (RemoteException e) { 5900 } 5901 } 5902 ms.runMaintenance(); 5903 } 5904 } else { 5905 Slog.e(TAG, "Mount service unavailable!"); 5906 } 5907 } catch (RemoteException e) { 5908 // Can't happen; MountService is local 5909 } 5910 5911 final ArraySet<PackageParser.Package> pkgs; 5912 synchronized (mPackages) { 5913 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5914 } 5915 5916 if (pkgs != null) { 5917 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5918 // in case the device runs out of space. 5919 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5920 // Give priority to core apps. 5921 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5922 PackageParser.Package pkg = it.next(); 5923 if (pkg.coreApp) { 5924 if (DEBUG_DEXOPT) { 5925 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5926 } 5927 sortedPkgs.add(pkg); 5928 it.remove(); 5929 } 5930 } 5931 // Give priority to system apps that listen for pre boot complete. 5932 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5933 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5934 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5935 PackageParser.Package pkg = it.next(); 5936 if (pkgNames.contains(pkg.packageName)) { 5937 if (DEBUG_DEXOPT) { 5938 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5939 } 5940 sortedPkgs.add(pkg); 5941 it.remove(); 5942 } 5943 } 5944 // Give priority to system apps. 5945 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5946 PackageParser.Package pkg = it.next(); 5947 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5948 if (DEBUG_DEXOPT) { 5949 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5950 } 5951 sortedPkgs.add(pkg); 5952 it.remove(); 5953 } 5954 } 5955 // Give priority to updated system apps. 5956 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5957 PackageParser.Package pkg = it.next(); 5958 if (pkg.isUpdatedSystemApp()) { 5959 if (DEBUG_DEXOPT) { 5960 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5961 } 5962 sortedPkgs.add(pkg); 5963 it.remove(); 5964 } 5965 } 5966 // Give priority to apps that listen for boot complete. 5967 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5968 pkgNames = getPackageNamesForIntent(intent); 5969 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5970 PackageParser.Package pkg = it.next(); 5971 if (pkgNames.contains(pkg.packageName)) { 5972 if (DEBUG_DEXOPT) { 5973 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5974 } 5975 sortedPkgs.add(pkg); 5976 it.remove(); 5977 } 5978 } 5979 // Filter out packages that aren't recently used. 5980 filterRecentlyUsedApps(pkgs); 5981 // Add all remaining apps. 5982 for (PackageParser.Package pkg : pkgs) { 5983 if (DEBUG_DEXOPT) { 5984 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5985 } 5986 sortedPkgs.add(pkg); 5987 } 5988 5989 // If we want to be lazy, filter everything that wasn't recently used. 5990 if (mLazyDexOpt) { 5991 filterRecentlyUsedApps(sortedPkgs); 5992 } 5993 5994 int i = 0; 5995 int total = sortedPkgs.size(); 5996 File dataDir = Environment.getDataDirectory(); 5997 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5998 if (lowThreshold == 0) { 5999 throw new IllegalStateException("Invalid low memory threshold"); 6000 } 6001 for (PackageParser.Package pkg : sortedPkgs) { 6002 long usableSpace = dataDir.getUsableSpace(); 6003 if (usableSpace < lowThreshold) { 6004 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6005 break; 6006 } 6007 performBootDexOpt(pkg, ++i, total); 6008 } 6009 } 6010 } 6011 6012 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6013 // Filter out packages that aren't recently used. 6014 // 6015 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6016 // should do a full dexopt. 6017 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6018 int total = pkgs.size(); 6019 int skipped = 0; 6020 long now = System.currentTimeMillis(); 6021 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6022 PackageParser.Package pkg = i.next(); 6023 long then = pkg.mLastPackageUsageTimeInMills; 6024 if (then + mDexOptLRUThresholdInMills < now) { 6025 if (DEBUG_DEXOPT) { 6026 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6027 ((then == 0) ? "never" : new Date(then))); 6028 } 6029 i.remove(); 6030 skipped++; 6031 } 6032 } 6033 if (DEBUG_DEXOPT) { 6034 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6035 } 6036 } 6037 } 6038 6039 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6040 List<ResolveInfo> ris = null; 6041 try { 6042 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6043 intent, null, 0, UserHandle.USER_OWNER); 6044 } catch (RemoteException e) { 6045 } 6046 ArraySet<String> pkgNames = new ArraySet<String>(); 6047 if (ris != null) { 6048 for (ResolveInfo ri : ris) { 6049 pkgNames.add(ri.activityInfo.packageName); 6050 } 6051 } 6052 return pkgNames; 6053 } 6054 6055 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6056 if (DEBUG_DEXOPT) { 6057 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6058 } 6059 if (!isFirstBoot()) { 6060 try { 6061 ActivityManagerNative.getDefault().showBootMessage( 6062 mContext.getResources().getString(R.string.android_upgrading_apk, 6063 curr, total), true); 6064 } catch (RemoteException e) { 6065 } 6066 } 6067 PackageParser.Package p = pkg; 6068 synchronized (mInstallLock) { 6069 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6070 false /* force dex */, false /* defer */, true /* include dependencies */); 6071 } 6072 } 6073 6074 @Override 6075 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6076 return performDexOpt(packageName, instructionSet, false); 6077 } 6078 6079 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6080 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6081 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6082 if (!dexopt && !updateUsage) { 6083 // We aren't going to dexopt or update usage, so bail early. 6084 return false; 6085 } 6086 PackageParser.Package p; 6087 final String targetInstructionSet; 6088 synchronized (mPackages) { 6089 p = mPackages.get(packageName); 6090 if (p == null) { 6091 return false; 6092 } 6093 if (updateUsage) { 6094 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6095 } 6096 mPackageUsage.write(false); 6097 if (!dexopt) { 6098 // We aren't going to dexopt, so bail early. 6099 return false; 6100 } 6101 6102 targetInstructionSet = instructionSet != null ? instructionSet : 6103 getPrimaryInstructionSet(p.applicationInfo); 6104 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6105 return false; 6106 } 6107 } 6108 6109 synchronized (mInstallLock) { 6110 final String[] instructionSets = new String[] { targetInstructionSet }; 6111 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6112 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6113 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6114 } 6115 } 6116 6117 public ArraySet<String> getPackagesThatNeedDexOpt() { 6118 ArraySet<String> pkgs = null; 6119 synchronized (mPackages) { 6120 for (PackageParser.Package p : mPackages.values()) { 6121 if (DEBUG_DEXOPT) { 6122 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6123 } 6124 if (!p.mDexOptPerformed.isEmpty()) { 6125 continue; 6126 } 6127 if (pkgs == null) { 6128 pkgs = new ArraySet<String>(); 6129 } 6130 pkgs.add(p.packageName); 6131 } 6132 } 6133 return pkgs; 6134 } 6135 6136 public void shutdown() { 6137 mPackageUsage.write(true); 6138 } 6139 6140 @Override 6141 public void forceDexOpt(String packageName) { 6142 enforceSystemOrRoot("forceDexOpt"); 6143 6144 PackageParser.Package pkg; 6145 synchronized (mPackages) { 6146 pkg = mPackages.get(packageName); 6147 if (pkg == null) { 6148 throw new IllegalArgumentException("Missing package: " + packageName); 6149 } 6150 } 6151 6152 synchronized (mInstallLock) { 6153 final String[] instructionSets = new String[] { 6154 getPrimaryInstructionSet(pkg.applicationInfo) }; 6155 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6156 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6157 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6158 throw new IllegalStateException("Failed to dexopt: " + res); 6159 } 6160 } 6161 } 6162 6163 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6164 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6165 Slog.w(TAG, "Unable to update from " + oldPkg.name 6166 + " to " + newPkg.packageName 6167 + ": old package not in system partition"); 6168 return false; 6169 } else if (mPackages.get(oldPkg.name) != null) { 6170 Slog.w(TAG, "Unable to update from " + oldPkg.name 6171 + " to " + newPkg.packageName 6172 + ": old package still exists"); 6173 return false; 6174 } 6175 return true; 6176 } 6177 6178 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6179 int[] users = sUserManager.getUserIds(); 6180 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6181 if (res < 0) { 6182 return res; 6183 } 6184 for (int user : users) { 6185 if (user != 0) { 6186 res = mInstaller.createUserData(volumeUuid, packageName, 6187 UserHandle.getUid(user, uid), user, seinfo); 6188 if (res < 0) { 6189 return res; 6190 } 6191 } 6192 } 6193 return res; 6194 } 6195 6196 private int removeDataDirsLI(String volumeUuid, String packageName) { 6197 int[] users = sUserManager.getUserIds(); 6198 int res = 0; 6199 for (int user : users) { 6200 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6201 if (resInner < 0) { 6202 res = resInner; 6203 } 6204 } 6205 6206 return res; 6207 } 6208 6209 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6210 int[] users = sUserManager.getUserIds(); 6211 int res = 0; 6212 for (int user : users) { 6213 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6214 if (resInner < 0) { 6215 res = resInner; 6216 } 6217 } 6218 return res; 6219 } 6220 6221 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6222 PackageParser.Package changingLib) { 6223 if (file.path != null) { 6224 usesLibraryFiles.add(file.path); 6225 return; 6226 } 6227 PackageParser.Package p = mPackages.get(file.apk); 6228 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6229 // If we are doing this while in the middle of updating a library apk, 6230 // then we need to make sure to use that new apk for determining the 6231 // dependencies here. (We haven't yet finished committing the new apk 6232 // to the package manager state.) 6233 if (p == null || p.packageName.equals(changingLib.packageName)) { 6234 p = changingLib; 6235 } 6236 } 6237 if (p != null) { 6238 usesLibraryFiles.addAll(p.getAllCodePaths()); 6239 } 6240 } 6241 6242 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6243 PackageParser.Package changingLib) throws PackageManagerException { 6244 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6245 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6246 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6247 for (int i=0; i<N; i++) { 6248 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6249 if (file == null) { 6250 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6251 "Package " + pkg.packageName + " requires unavailable shared library " 6252 + pkg.usesLibraries.get(i) + "; failing!"); 6253 } 6254 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6255 } 6256 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6257 for (int i=0; i<N; i++) { 6258 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6259 if (file == null) { 6260 Slog.w(TAG, "Package " + pkg.packageName 6261 + " desires unavailable shared library " 6262 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6263 } else { 6264 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6265 } 6266 } 6267 N = usesLibraryFiles.size(); 6268 if (N > 0) { 6269 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6270 } else { 6271 pkg.usesLibraryFiles = null; 6272 } 6273 } 6274 } 6275 6276 private static boolean hasString(List<String> list, List<String> which) { 6277 if (list == null) { 6278 return false; 6279 } 6280 for (int i=list.size()-1; i>=0; i--) { 6281 for (int j=which.size()-1; j>=0; j--) { 6282 if (which.get(j).equals(list.get(i))) { 6283 return true; 6284 } 6285 } 6286 } 6287 return false; 6288 } 6289 6290 private void updateAllSharedLibrariesLPw() { 6291 for (PackageParser.Package pkg : mPackages.values()) { 6292 try { 6293 updateSharedLibrariesLPw(pkg, null); 6294 } catch (PackageManagerException e) { 6295 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6296 } 6297 } 6298 } 6299 6300 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6301 PackageParser.Package changingPkg) { 6302 ArrayList<PackageParser.Package> res = null; 6303 for (PackageParser.Package pkg : mPackages.values()) { 6304 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6305 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6306 if (res == null) { 6307 res = new ArrayList<PackageParser.Package>(); 6308 } 6309 res.add(pkg); 6310 try { 6311 updateSharedLibrariesLPw(pkg, changingPkg); 6312 } catch (PackageManagerException e) { 6313 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6314 } 6315 } 6316 } 6317 return res; 6318 } 6319 6320 /** 6321 * Derive the value of the {@code cpuAbiOverride} based on the provided 6322 * value and an optional stored value from the package settings. 6323 */ 6324 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6325 String cpuAbiOverride = null; 6326 6327 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6328 cpuAbiOverride = null; 6329 } else if (abiOverride != null) { 6330 cpuAbiOverride = abiOverride; 6331 } else if (settings != null) { 6332 cpuAbiOverride = settings.cpuAbiOverrideString; 6333 } 6334 6335 return cpuAbiOverride; 6336 } 6337 6338 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6339 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6340 boolean success = false; 6341 try { 6342 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6343 currentTime, user); 6344 success = true; 6345 return res; 6346 } finally { 6347 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6348 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6349 } 6350 } 6351 } 6352 6353 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6354 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6355 final File scanFile = new File(pkg.codePath); 6356 if (pkg.applicationInfo.getCodePath() == null || 6357 pkg.applicationInfo.getResourcePath() == null) { 6358 // Bail out. The resource and code paths haven't been set. 6359 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6360 "Code and resource paths haven't been set correctly"); 6361 } 6362 6363 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6364 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6365 } else { 6366 // Only allow system apps to be flagged as core apps. 6367 pkg.coreApp = false; 6368 } 6369 6370 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6371 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6372 } 6373 6374 if (mCustomResolverComponentName != null && 6375 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6376 setUpCustomResolverActivity(pkg); 6377 } 6378 6379 if (pkg.packageName.equals("android")) { 6380 synchronized (mPackages) { 6381 if (mAndroidApplication != null) { 6382 Slog.w(TAG, "*************************************************"); 6383 Slog.w(TAG, "Core android package being redefined. Skipping."); 6384 Slog.w(TAG, " file=" + scanFile); 6385 Slog.w(TAG, "*************************************************"); 6386 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6387 "Core android package being redefined. Skipping."); 6388 } 6389 6390 // Set up information for our fall-back user intent resolution activity. 6391 mPlatformPackage = pkg; 6392 pkg.mVersionCode = mSdkVersion; 6393 mAndroidApplication = pkg.applicationInfo; 6394 6395 if (!mResolverReplaced) { 6396 mResolveActivity.applicationInfo = mAndroidApplication; 6397 mResolveActivity.name = ResolverActivity.class.getName(); 6398 mResolveActivity.packageName = mAndroidApplication.packageName; 6399 mResolveActivity.processName = "system:ui"; 6400 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6401 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6402 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6403 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6404 mResolveActivity.exported = true; 6405 mResolveActivity.enabled = true; 6406 mResolveInfo.activityInfo = mResolveActivity; 6407 mResolveInfo.priority = 0; 6408 mResolveInfo.preferredOrder = 0; 6409 mResolveInfo.match = 0; 6410 mResolveComponentName = new ComponentName( 6411 mAndroidApplication.packageName, mResolveActivity.name); 6412 } 6413 } 6414 } 6415 6416 if (DEBUG_PACKAGE_SCANNING) { 6417 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6418 Log.d(TAG, "Scanning package " + pkg.packageName); 6419 } 6420 6421 if (mPackages.containsKey(pkg.packageName) 6422 || mSharedLibraries.containsKey(pkg.packageName)) { 6423 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6424 "Application package " + pkg.packageName 6425 + " already installed. Skipping duplicate."); 6426 } 6427 6428 // If we're only installing presumed-existing packages, require that the 6429 // scanned APK is both already known and at the path previously established 6430 // for it. Previously unknown packages we pick up normally, but if we have an 6431 // a priori expectation about this package's install presence, enforce it. 6432 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6433 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6434 if (known != null) { 6435 if (DEBUG_PACKAGE_SCANNING) { 6436 Log.d(TAG, "Examining " + pkg.codePath 6437 + " and requiring known paths " + known.codePathString 6438 + " & " + known.resourcePathString); 6439 } 6440 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6441 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6442 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6443 "Application package " + pkg.packageName 6444 + " found at " + pkg.applicationInfo.getCodePath() 6445 + " but expected at " + known.codePathString + "; ignoring."); 6446 } 6447 } 6448 } 6449 6450 // Initialize package source and resource directories 6451 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6452 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6453 6454 SharedUserSetting suid = null; 6455 PackageSetting pkgSetting = null; 6456 6457 if (!isSystemApp(pkg)) { 6458 // Only system apps can use these features. 6459 pkg.mOriginalPackages = null; 6460 pkg.mRealPackage = null; 6461 pkg.mAdoptPermissions = null; 6462 } 6463 6464 // writer 6465 synchronized (mPackages) { 6466 if (pkg.mSharedUserId != null) { 6467 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6468 if (suid == null) { 6469 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6470 "Creating application package " + pkg.packageName 6471 + " for shared user failed"); 6472 } 6473 if (DEBUG_PACKAGE_SCANNING) { 6474 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6475 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6476 + "): packages=" + suid.packages); 6477 } 6478 } 6479 6480 // Check if we are renaming from an original package name. 6481 PackageSetting origPackage = null; 6482 String realName = null; 6483 if (pkg.mOriginalPackages != null) { 6484 // This package may need to be renamed to a previously 6485 // installed name. Let's check on that... 6486 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6487 if (pkg.mOriginalPackages.contains(renamed)) { 6488 // This package had originally been installed as the 6489 // original name, and we have already taken care of 6490 // transitioning to the new one. Just update the new 6491 // one to continue using the old name. 6492 realName = pkg.mRealPackage; 6493 if (!pkg.packageName.equals(renamed)) { 6494 // Callers into this function may have already taken 6495 // care of renaming the package; only do it here if 6496 // it is not already done. 6497 pkg.setPackageName(renamed); 6498 } 6499 6500 } else { 6501 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6502 if ((origPackage = mSettings.peekPackageLPr( 6503 pkg.mOriginalPackages.get(i))) != null) { 6504 // We do have the package already installed under its 6505 // original name... should we use it? 6506 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6507 // New package is not compatible with original. 6508 origPackage = null; 6509 continue; 6510 } else if (origPackage.sharedUser != null) { 6511 // Make sure uid is compatible between packages. 6512 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6513 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6514 + " to " + pkg.packageName + ": old uid " 6515 + origPackage.sharedUser.name 6516 + " differs from " + pkg.mSharedUserId); 6517 origPackage = null; 6518 continue; 6519 } 6520 } else { 6521 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6522 + pkg.packageName + " to old name " + origPackage.name); 6523 } 6524 break; 6525 } 6526 } 6527 } 6528 } 6529 6530 if (mTransferedPackages.contains(pkg.packageName)) { 6531 Slog.w(TAG, "Package " + pkg.packageName 6532 + " was transferred to another, but its .apk remains"); 6533 } 6534 6535 // Just create the setting, don't add it yet. For already existing packages 6536 // the PkgSetting exists already and doesn't have to be created. 6537 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6538 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6539 pkg.applicationInfo.primaryCpuAbi, 6540 pkg.applicationInfo.secondaryCpuAbi, 6541 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6542 user, false); 6543 if (pkgSetting == null) { 6544 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6545 "Creating application package " + pkg.packageName + " failed"); 6546 } 6547 6548 if (pkgSetting.origPackage != null) { 6549 // If we are first transitioning from an original package, 6550 // fix up the new package's name now. We need to do this after 6551 // looking up the package under its new name, so getPackageLP 6552 // can take care of fiddling things correctly. 6553 pkg.setPackageName(origPackage.name); 6554 6555 // File a report about this. 6556 String msg = "New package " + pkgSetting.realName 6557 + " renamed to replace old package " + pkgSetting.name; 6558 reportSettingsProblem(Log.WARN, msg); 6559 6560 // Make a note of it. 6561 mTransferedPackages.add(origPackage.name); 6562 6563 // No longer need to retain this. 6564 pkgSetting.origPackage = null; 6565 } 6566 6567 if (realName != null) { 6568 // Make a note of it. 6569 mTransferedPackages.add(pkg.packageName); 6570 } 6571 6572 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6573 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6574 } 6575 6576 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6577 // Check all shared libraries and map to their actual file path. 6578 // We only do this here for apps not on a system dir, because those 6579 // are the only ones that can fail an install due to this. We 6580 // will take care of the system apps by updating all of their 6581 // library paths after the scan is done. 6582 updateSharedLibrariesLPw(pkg, null); 6583 } 6584 6585 if (mFoundPolicyFile) { 6586 SELinuxMMAC.assignSeinfoValue(pkg); 6587 } 6588 6589 pkg.applicationInfo.uid = pkgSetting.appId; 6590 pkg.mExtras = pkgSetting; 6591 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6592 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6593 // We just determined the app is signed correctly, so bring 6594 // over the latest parsed certs. 6595 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6596 } else { 6597 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6598 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6599 "Package " + pkg.packageName + " upgrade keys do not match the " 6600 + "previously installed version"); 6601 } else { 6602 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6603 String msg = "System package " + pkg.packageName 6604 + " signature changed; retaining data."; 6605 reportSettingsProblem(Log.WARN, msg); 6606 } 6607 } 6608 } else { 6609 try { 6610 verifySignaturesLP(pkgSetting, pkg); 6611 // We just determined the app is signed correctly, so bring 6612 // over the latest parsed certs. 6613 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6614 } catch (PackageManagerException e) { 6615 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6616 throw e; 6617 } 6618 // The signature has changed, but this package is in the system 6619 // image... let's recover! 6620 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6621 // However... if this package is part of a shared user, but it 6622 // doesn't match the signature of the shared user, let's fail. 6623 // What this means is that you can't change the signatures 6624 // associated with an overall shared user, which doesn't seem all 6625 // that unreasonable. 6626 if (pkgSetting.sharedUser != null) { 6627 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6628 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6629 throw new PackageManagerException( 6630 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6631 "Signature mismatch for shared user : " 6632 + pkgSetting.sharedUser); 6633 } 6634 } 6635 // File a report about this. 6636 String msg = "System package " + pkg.packageName 6637 + " signature changed; retaining data."; 6638 reportSettingsProblem(Log.WARN, msg); 6639 } 6640 } 6641 // Verify that this new package doesn't have any content providers 6642 // that conflict with existing packages. Only do this if the 6643 // package isn't already installed, since we don't want to break 6644 // things that are installed. 6645 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6646 final int N = pkg.providers.size(); 6647 int i; 6648 for (i=0; i<N; i++) { 6649 PackageParser.Provider p = pkg.providers.get(i); 6650 if (p.info.authority != null) { 6651 String names[] = p.info.authority.split(";"); 6652 for (int j = 0; j < names.length; j++) { 6653 if (mProvidersByAuthority.containsKey(names[j])) { 6654 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6655 final String otherPackageName = 6656 ((other != null && other.getComponentName() != null) ? 6657 other.getComponentName().getPackageName() : "?"); 6658 throw new PackageManagerException( 6659 INSTALL_FAILED_CONFLICTING_PROVIDER, 6660 "Can't install because provider name " + names[j] 6661 + " (in package " + pkg.applicationInfo.packageName 6662 + ") is already used by " + otherPackageName); 6663 } 6664 } 6665 } 6666 } 6667 } 6668 6669 if (pkg.mAdoptPermissions != null) { 6670 // This package wants to adopt ownership of permissions from 6671 // another package. 6672 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6673 final String origName = pkg.mAdoptPermissions.get(i); 6674 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6675 if (orig != null) { 6676 if (verifyPackageUpdateLPr(orig, pkg)) { 6677 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6678 + pkg.packageName); 6679 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6680 } 6681 } 6682 } 6683 } 6684 } 6685 6686 final String pkgName = pkg.packageName; 6687 6688 final long scanFileTime = scanFile.lastModified(); 6689 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6690 pkg.applicationInfo.processName = fixProcessName( 6691 pkg.applicationInfo.packageName, 6692 pkg.applicationInfo.processName, 6693 pkg.applicationInfo.uid); 6694 6695 File dataPath; 6696 if (mPlatformPackage == pkg) { 6697 // The system package is special. 6698 dataPath = new File(Environment.getDataDirectory(), "system"); 6699 6700 pkg.applicationInfo.dataDir = dataPath.getPath(); 6701 6702 } else { 6703 // This is a normal package, need to make its data directory. 6704 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6705 UserHandle.USER_OWNER, pkg.packageName); 6706 6707 boolean uidError = false; 6708 if (dataPath.exists()) { 6709 int currentUid = 0; 6710 try { 6711 StructStat stat = Os.stat(dataPath.getPath()); 6712 currentUid = stat.st_uid; 6713 } catch (ErrnoException e) { 6714 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6715 } 6716 6717 // If we have mismatched owners for the data path, we have a problem. 6718 if (currentUid != pkg.applicationInfo.uid) { 6719 boolean recovered = false; 6720 if (currentUid == 0) { 6721 // The directory somehow became owned by root. Wow. 6722 // This is probably because the system was stopped while 6723 // installd was in the middle of messing with its libs 6724 // directory. Ask installd to fix that. 6725 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6726 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6727 if (ret >= 0) { 6728 recovered = true; 6729 String msg = "Package " + pkg.packageName 6730 + " unexpectedly changed to uid 0; recovered to " + 6731 + pkg.applicationInfo.uid; 6732 reportSettingsProblem(Log.WARN, msg); 6733 } 6734 } 6735 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6736 || (scanFlags&SCAN_BOOTING) != 0)) { 6737 // If this is a system app, we can at least delete its 6738 // current data so the application will still work. 6739 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6740 if (ret >= 0) { 6741 // TODO: Kill the processes first 6742 // Old data gone! 6743 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6744 ? "System package " : "Third party package "; 6745 String msg = prefix + pkg.packageName 6746 + " has changed from uid: " 6747 + currentUid + " to " 6748 + pkg.applicationInfo.uid + "; old data erased"; 6749 reportSettingsProblem(Log.WARN, msg); 6750 recovered = true; 6751 6752 // And now re-install the app. 6753 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6754 pkg.applicationInfo.seinfo); 6755 if (ret == -1) { 6756 // Ack should not happen! 6757 msg = prefix + pkg.packageName 6758 + " could not have data directory re-created after delete."; 6759 reportSettingsProblem(Log.WARN, msg); 6760 throw new PackageManagerException( 6761 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6762 } 6763 } 6764 if (!recovered) { 6765 mHasSystemUidErrors = true; 6766 } 6767 } else if (!recovered) { 6768 // If we allow this install to proceed, we will be broken. 6769 // Abort, abort! 6770 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6771 "scanPackageLI"); 6772 } 6773 if (!recovered) { 6774 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6775 + pkg.applicationInfo.uid + "/fs_" 6776 + currentUid; 6777 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6778 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6779 String msg = "Package " + pkg.packageName 6780 + " has mismatched uid: " 6781 + currentUid + " on disk, " 6782 + pkg.applicationInfo.uid + " in settings"; 6783 // writer 6784 synchronized (mPackages) { 6785 mSettings.mReadMessages.append(msg); 6786 mSettings.mReadMessages.append('\n'); 6787 uidError = true; 6788 if (!pkgSetting.uidError) { 6789 reportSettingsProblem(Log.ERROR, msg); 6790 } 6791 } 6792 } 6793 } 6794 pkg.applicationInfo.dataDir = dataPath.getPath(); 6795 if (mShouldRestoreconData) { 6796 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6797 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6798 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6799 } 6800 } else { 6801 if (DEBUG_PACKAGE_SCANNING) { 6802 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6803 Log.v(TAG, "Want this data dir: " + dataPath); 6804 } 6805 //invoke installer to do the actual installation 6806 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6807 pkg.applicationInfo.seinfo); 6808 if (ret < 0) { 6809 // Error from installer 6810 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6811 "Unable to create data dirs [errorCode=" + ret + "]"); 6812 } 6813 6814 if (dataPath.exists()) { 6815 pkg.applicationInfo.dataDir = dataPath.getPath(); 6816 } else { 6817 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6818 pkg.applicationInfo.dataDir = null; 6819 } 6820 } 6821 6822 pkgSetting.uidError = uidError; 6823 } 6824 6825 final String path = scanFile.getPath(); 6826 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6827 6828 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6829 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6830 6831 // Some system apps still use directory structure for native libraries 6832 // in which case we might end up not detecting abi solely based on apk 6833 // structure. Try to detect abi based on directory structure. 6834 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6835 pkg.applicationInfo.primaryCpuAbi == null) { 6836 setBundledAppAbisAndRoots(pkg, pkgSetting); 6837 setNativeLibraryPaths(pkg); 6838 } 6839 6840 } else { 6841 if ((scanFlags & SCAN_MOVE) != 0) { 6842 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6843 // but we already have this packages package info in the PackageSetting. We just 6844 // use that and derive the native library path based on the new codepath. 6845 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6846 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6847 } 6848 6849 // Set native library paths again. For moves, the path will be updated based on the 6850 // ABIs we've determined above. For non-moves, the path will be updated based on the 6851 // ABIs we determined during compilation, but the path will depend on the final 6852 // package path (after the rename away from the stage path). 6853 setNativeLibraryPaths(pkg); 6854 } 6855 6856 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6857 final int[] userIds = sUserManager.getUserIds(); 6858 synchronized (mInstallLock) { 6859 // Make sure all user data directories are ready to roll; we're okay 6860 // if they already exist 6861 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6862 for (int userId : userIds) { 6863 if (userId != 0) { 6864 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6865 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6866 pkg.applicationInfo.seinfo); 6867 } 6868 } 6869 } 6870 6871 // Create a native library symlink only if we have native libraries 6872 // and if the native libraries are 32 bit libraries. We do not provide 6873 // this symlink for 64 bit libraries. 6874 if (pkg.applicationInfo.primaryCpuAbi != null && 6875 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6876 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6877 for (int userId : userIds) { 6878 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6879 nativeLibPath, userId) < 0) { 6880 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6881 "Failed linking native library dir (user=" + userId + ")"); 6882 } 6883 } 6884 } 6885 } 6886 6887 // This is a special case for the "system" package, where the ABI is 6888 // dictated by the zygote configuration (and init.rc). We should keep track 6889 // of this ABI so that we can deal with "normal" applications that run under 6890 // the same UID correctly. 6891 if (mPlatformPackage == pkg) { 6892 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6893 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6894 } 6895 6896 // If there's a mismatch between the abi-override in the package setting 6897 // and the abiOverride specified for the install. Warn about this because we 6898 // would've already compiled the app without taking the package setting into 6899 // account. 6900 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6901 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6902 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6903 " for package: " + pkg.packageName); 6904 } 6905 } 6906 6907 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6908 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6909 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6910 6911 // Copy the derived override back to the parsed package, so that we can 6912 // update the package settings accordingly. 6913 pkg.cpuAbiOverride = cpuAbiOverride; 6914 6915 if (DEBUG_ABI_SELECTION) { 6916 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6917 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6918 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6919 } 6920 6921 // Push the derived path down into PackageSettings so we know what to 6922 // clean up at uninstall time. 6923 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6924 6925 if (DEBUG_ABI_SELECTION) { 6926 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6927 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6928 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6929 } 6930 6931 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6932 // We don't do this here during boot because we can do it all 6933 // at once after scanning all existing packages. 6934 // 6935 // We also do this *before* we perform dexopt on this package, so that 6936 // we can avoid redundant dexopts, and also to make sure we've got the 6937 // code and package path correct. 6938 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6939 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6940 } 6941 6942 if ((scanFlags & SCAN_NO_DEX) == 0) { 6943 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6944 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6945 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6946 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6947 } 6948 } 6949 if (mFactoryTest && pkg.requestedPermissions.contains( 6950 android.Manifest.permission.FACTORY_TEST)) { 6951 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6952 } 6953 6954 ArrayList<PackageParser.Package> clientLibPkgs = null; 6955 6956 // writer 6957 synchronized (mPackages) { 6958 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6959 // Only system apps can add new shared libraries. 6960 if (pkg.libraryNames != null) { 6961 for (int i=0; i<pkg.libraryNames.size(); i++) { 6962 String name = pkg.libraryNames.get(i); 6963 boolean allowed = false; 6964 if (pkg.isUpdatedSystemApp()) { 6965 // New library entries can only be added through the 6966 // system image. This is important to get rid of a lot 6967 // of nasty edge cases: for example if we allowed a non- 6968 // system update of the app to add a library, then uninstalling 6969 // the update would make the library go away, and assumptions 6970 // we made such as through app install filtering would now 6971 // have allowed apps on the device which aren't compatible 6972 // with it. Better to just have the restriction here, be 6973 // conservative, and create many fewer cases that can negatively 6974 // impact the user experience. 6975 final PackageSetting sysPs = mSettings 6976 .getDisabledSystemPkgLPr(pkg.packageName); 6977 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6978 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6979 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6980 allowed = true; 6981 allowed = true; 6982 break; 6983 } 6984 } 6985 } 6986 } else { 6987 allowed = true; 6988 } 6989 if (allowed) { 6990 if (!mSharedLibraries.containsKey(name)) { 6991 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6992 } else if (!name.equals(pkg.packageName)) { 6993 Slog.w(TAG, "Package " + pkg.packageName + " library " 6994 + name + " already exists; skipping"); 6995 } 6996 } else { 6997 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6998 + name + " that is not declared on system image; skipping"); 6999 } 7000 } 7001 if ((scanFlags&SCAN_BOOTING) == 0) { 7002 // If we are not booting, we need to update any applications 7003 // that are clients of our shared library. If we are booting, 7004 // this will all be done once the scan is complete. 7005 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7006 } 7007 } 7008 } 7009 } 7010 7011 // We also need to dexopt any apps that are dependent on this library. Note that 7012 // if these fail, we should abort the install since installing the library will 7013 // result in some apps being broken. 7014 if (clientLibPkgs != null) { 7015 if ((scanFlags & SCAN_NO_DEX) == 0) { 7016 for (int i = 0; i < clientLibPkgs.size(); i++) { 7017 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7018 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7019 null /* instruction sets */, forceDex, 7020 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7021 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7022 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7023 "scanPackageLI failed to dexopt clientLibPkgs"); 7024 } 7025 } 7026 } 7027 } 7028 7029 // Also need to kill any apps that are dependent on the library. 7030 if (clientLibPkgs != null) { 7031 for (int i=0; i<clientLibPkgs.size(); i++) { 7032 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7033 killApplication(clientPkg.applicationInfo.packageName, 7034 clientPkg.applicationInfo.uid, "update lib"); 7035 } 7036 } 7037 7038 // Make sure we're not adding any bogus keyset info 7039 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7040 ksms.assertScannedPackageValid(pkg); 7041 7042 // writer 7043 synchronized (mPackages) { 7044 // We don't expect installation to fail beyond this point 7045 7046 // Add the new setting to mSettings 7047 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7048 // Add the new setting to mPackages 7049 mPackages.put(pkg.applicationInfo.packageName, pkg); 7050 // Make sure we don't accidentally delete its data. 7051 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7052 while (iter.hasNext()) { 7053 PackageCleanItem item = iter.next(); 7054 if (pkgName.equals(item.packageName)) { 7055 iter.remove(); 7056 } 7057 } 7058 7059 // Take care of first install / last update times. 7060 if (currentTime != 0) { 7061 if (pkgSetting.firstInstallTime == 0) { 7062 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7063 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7064 pkgSetting.lastUpdateTime = currentTime; 7065 } 7066 } else if (pkgSetting.firstInstallTime == 0) { 7067 // We need *something*. Take time time stamp of the file. 7068 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7069 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7070 if (scanFileTime != pkgSetting.timeStamp) { 7071 // A package on the system image has changed; consider this 7072 // to be an update. 7073 pkgSetting.lastUpdateTime = scanFileTime; 7074 } 7075 } 7076 7077 // Add the package's KeySets to the global KeySetManagerService 7078 ksms.addScannedPackageLPw(pkg); 7079 7080 int N = pkg.providers.size(); 7081 StringBuilder r = null; 7082 int i; 7083 for (i=0; i<N; i++) { 7084 PackageParser.Provider p = pkg.providers.get(i); 7085 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7086 p.info.processName, pkg.applicationInfo.uid); 7087 mProviders.addProvider(p); 7088 p.syncable = p.info.isSyncable; 7089 if (p.info.authority != null) { 7090 String names[] = p.info.authority.split(";"); 7091 p.info.authority = null; 7092 for (int j = 0; j < names.length; j++) { 7093 if (j == 1 && p.syncable) { 7094 // We only want the first authority for a provider to possibly be 7095 // syncable, so if we already added this provider using a different 7096 // authority clear the syncable flag. We copy the provider before 7097 // changing it because the mProviders object contains a reference 7098 // to a provider that we don't want to change. 7099 // Only do this for the second authority since the resulting provider 7100 // object can be the same for all future authorities for this provider. 7101 p = new PackageParser.Provider(p); 7102 p.syncable = false; 7103 } 7104 if (!mProvidersByAuthority.containsKey(names[j])) { 7105 mProvidersByAuthority.put(names[j], p); 7106 if (p.info.authority == null) { 7107 p.info.authority = names[j]; 7108 } else { 7109 p.info.authority = p.info.authority + ";" + names[j]; 7110 } 7111 if (DEBUG_PACKAGE_SCANNING) { 7112 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7113 Log.d(TAG, "Registered content provider: " + names[j] 7114 + ", className = " + p.info.name + ", isSyncable = " 7115 + p.info.isSyncable); 7116 } 7117 } else { 7118 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7119 Slog.w(TAG, "Skipping provider name " + names[j] + 7120 " (in package " + pkg.applicationInfo.packageName + 7121 "): name already used by " 7122 + ((other != null && other.getComponentName() != null) 7123 ? other.getComponentName().getPackageName() : "?")); 7124 } 7125 } 7126 } 7127 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7128 if (r == null) { 7129 r = new StringBuilder(256); 7130 } else { 7131 r.append(' '); 7132 } 7133 r.append(p.info.name); 7134 } 7135 } 7136 if (r != null) { 7137 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7138 } 7139 7140 N = pkg.services.size(); 7141 r = null; 7142 for (i=0; i<N; i++) { 7143 PackageParser.Service s = pkg.services.get(i); 7144 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7145 s.info.processName, pkg.applicationInfo.uid); 7146 mServices.addService(s); 7147 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7148 if (r == null) { 7149 r = new StringBuilder(256); 7150 } else { 7151 r.append(' '); 7152 } 7153 r.append(s.info.name); 7154 } 7155 } 7156 if (r != null) { 7157 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7158 } 7159 7160 N = pkg.receivers.size(); 7161 r = null; 7162 for (i=0; i<N; i++) { 7163 PackageParser.Activity a = pkg.receivers.get(i); 7164 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7165 a.info.processName, pkg.applicationInfo.uid); 7166 mReceivers.addActivity(a, "receiver"); 7167 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7168 if (r == null) { 7169 r = new StringBuilder(256); 7170 } else { 7171 r.append(' '); 7172 } 7173 r.append(a.info.name); 7174 } 7175 } 7176 if (r != null) { 7177 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7178 } 7179 7180 N = pkg.activities.size(); 7181 r = null; 7182 for (i=0; i<N; i++) { 7183 PackageParser.Activity a = pkg.activities.get(i); 7184 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7185 a.info.processName, pkg.applicationInfo.uid); 7186 mActivities.addActivity(a, "activity"); 7187 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7188 if (r == null) { 7189 r = new StringBuilder(256); 7190 } else { 7191 r.append(' '); 7192 } 7193 r.append(a.info.name); 7194 } 7195 } 7196 if (r != null) { 7197 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7198 } 7199 7200 N = pkg.permissionGroups.size(); 7201 r = null; 7202 for (i=0; i<N; i++) { 7203 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7204 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7205 if (cur == null) { 7206 mPermissionGroups.put(pg.info.name, pg); 7207 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7208 if (r == null) { 7209 r = new StringBuilder(256); 7210 } else { 7211 r.append(' '); 7212 } 7213 r.append(pg.info.name); 7214 } 7215 } else { 7216 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7217 + pg.info.packageName + " ignored: original from " 7218 + cur.info.packageName); 7219 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7220 if (r == null) { 7221 r = new StringBuilder(256); 7222 } else { 7223 r.append(' '); 7224 } 7225 r.append("DUP:"); 7226 r.append(pg.info.name); 7227 } 7228 } 7229 } 7230 if (r != null) { 7231 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7232 } 7233 7234 N = pkg.permissions.size(); 7235 r = null; 7236 for (i=0; i<N; i++) { 7237 PackageParser.Permission p = pkg.permissions.get(i); 7238 7239 // Now that permission groups have a special meaning, we ignore permission 7240 // groups for legacy apps to prevent unexpected behavior. In particular, 7241 // permissions for one app being granted to someone just becuase they happen 7242 // to be in a group defined by another app (before this had no implications). 7243 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7244 p.group = mPermissionGroups.get(p.info.group); 7245 // Warn for a permission in an unknown group. 7246 if (p.info.group != null && p.group == null) { 7247 Slog.w(TAG, "Permission " + p.info.name + " from package " 7248 + p.info.packageName + " in an unknown group " + p.info.group); 7249 } 7250 } 7251 7252 ArrayMap<String, BasePermission> permissionMap = 7253 p.tree ? mSettings.mPermissionTrees 7254 : mSettings.mPermissions; 7255 BasePermission bp = permissionMap.get(p.info.name); 7256 7257 // Allow system apps to redefine non-system permissions 7258 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7259 final boolean currentOwnerIsSystem = (bp.perm != null 7260 && isSystemApp(bp.perm.owner)); 7261 if (isSystemApp(p.owner)) { 7262 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7263 // It's a built-in permission and no owner, take ownership now 7264 bp.packageSetting = pkgSetting; 7265 bp.perm = p; 7266 bp.uid = pkg.applicationInfo.uid; 7267 bp.sourcePackage = p.info.packageName; 7268 } else if (!currentOwnerIsSystem) { 7269 String msg = "New decl " + p.owner + " of permission " 7270 + p.info.name + " is system; overriding " + bp.sourcePackage; 7271 reportSettingsProblem(Log.WARN, msg); 7272 bp = null; 7273 } 7274 } 7275 } 7276 7277 if (bp == null) { 7278 bp = new BasePermission(p.info.name, p.info.packageName, 7279 BasePermission.TYPE_NORMAL); 7280 permissionMap.put(p.info.name, bp); 7281 } 7282 7283 if (bp.perm == null) { 7284 if (bp.sourcePackage == null 7285 || bp.sourcePackage.equals(p.info.packageName)) { 7286 BasePermission tree = findPermissionTreeLP(p.info.name); 7287 if (tree == null 7288 || tree.sourcePackage.equals(p.info.packageName)) { 7289 bp.packageSetting = pkgSetting; 7290 bp.perm = p; 7291 bp.uid = pkg.applicationInfo.uid; 7292 bp.sourcePackage = p.info.packageName; 7293 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7294 if (r == null) { 7295 r = new StringBuilder(256); 7296 } else { 7297 r.append(' '); 7298 } 7299 r.append(p.info.name); 7300 } 7301 } else { 7302 Slog.w(TAG, "Permission " + p.info.name + " from package " 7303 + p.info.packageName + " ignored: base tree " 7304 + tree.name + " is from package " 7305 + tree.sourcePackage); 7306 } 7307 } else { 7308 Slog.w(TAG, "Permission " + p.info.name + " from package " 7309 + p.info.packageName + " ignored: original from " 7310 + bp.sourcePackage); 7311 } 7312 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7313 if (r == null) { 7314 r = new StringBuilder(256); 7315 } else { 7316 r.append(' '); 7317 } 7318 r.append("DUP:"); 7319 r.append(p.info.name); 7320 } 7321 if (bp.perm == p) { 7322 bp.protectionLevel = p.info.protectionLevel; 7323 } 7324 } 7325 7326 if (r != null) { 7327 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7328 } 7329 7330 N = pkg.instrumentation.size(); 7331 r = null; 7332 for (i=0; i<N; i++) { 7333 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7334 a.info.packageName = pkg.applicationInfo.packageName; 7335 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7336 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7337 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7338 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7339 a.info.dataDir = pkg.applicationInfo.dataDir; 7340 7341 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7342 // need other information about the application, like the ABI and what not ? 7343 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7344 mInstrumentation.put(a.getComponentName(), a); 7345 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7346 if (r == null) { 7347 r = new StringBuilder(256); 7348 } else { 7349 r.append(' '); 7350 } 7351 r.append(a.info.name); 7352 } 7353 } 7354 if (r != null) { 7355 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7356 } 7357 7358 if (pkg.protectedBroadcasts != null) { 7359 N = pkg.protectedBroadcasts.size(); 7360 for (i=0; i<N; i++) { 7361 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7362 } 7363 } 7364 7365 pkgSetting.setTimeStamp(scanFileTime); 7366 7367 // Create idmap files for pairs of (packages, overlay packages). 7368 // Note: "android", ie framework-res.apk, is handled by native layers. 7369 if (pkg.mOverlayTarget != null) { 7370 // This is an overlay package. 7371 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7372 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7373 mOverlays.put(pkg.mOverlayTarget, 7374 new ArrayMap<String, PackageParser.Package>()); 7375 } 7376 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7377 map.put(pkg.packageName, pkg); 7378 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7379 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7380 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7381 "scanPackageLI failed to createIdmap"); 7382 } 7383 } 7384 } else if (mOverlays.containsKey(pkg.packageName) && 7385 !pkg.packageName.equals("android")) { 7386 // This is a regular package, with one or more known overlay packages. 7387 createIdmapsForPackageLI(pkg); 7388 } 7389 } 7390 7391 return pkg; 7392 } 7393 7394 /** 7395 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7396 * is derived purely on the basis of the contents of {@code scanFile} and 7397 * {@code cpuAbiOverride}. 7398 * 7399 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7400 */ 7401 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7402 String cpuAbiOverride, boolean extractLibs) 7403 throws PackageManagerException { 7404 // TODO: We can probably be smarter about this stuff. For installed apps, 7405 // we can calculate this information at install time once and for all. For 7406 // system apps, we can probably assume that this information doesn't change 7407 // after the first boot scan. As things stand, we do lots of unnecessary work. 7408 7409 // Give ourselves some initial paths; we'll come back for another 7410 // pass once we've determined ABI below. 7411 setNativeLibraryPaths(pkg); 7412 7413 // We would never need to extract libs for forward-locked and external packages, 7414 // since the container service will do it for us. We shouldn't attempt to 7415 // extract libs from system app when it was not updated. 7416 if (pkg.isForwardLocked() || isExternal(pkg) || 7417 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7418 extractLibs = false; 7419 } 7420 7421 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7422 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7423 7424 NativeLibraryHelper.Handle handle = null; 7425 try { 7426 handle = NativeLibraryHelper.Handle.create(scanFile); 7427 // TODO(multiArch): This can be null for apps that didn't go through the 7428 // usual installation process. We can calculate it again, like we 7429 // do during install time. 7430 // 7431 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7432 // unnecessary. 7433 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7434 7435 // Null out the abis so that they can be recalculated. 7436 pkg.applicationInfo.primaryCpuAbi = null; 7437 pkg.applicationInfo.secondaryCpuAbi = null; 7438 if (isMultiArch(pkg.applicationInfo)) { 7439 // Warn if we've set an abiOverride for multi-lib packages.. 7440 // By definition, we need to copy both 32 and 64 bit libraries for 7441 // such packages. 7442 if (pkg.cpuAbiOverride != null 7443 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7444 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7445 } 7446 7447 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7448 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7449 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7450 if (extractLibs) { 7451 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7452 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7453 useIsaSpecificSubdirs); 7454 } else { 7455 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7456 } 7457 } 7458 7459 maybeThrowExceptionForMultiArchCopy( 7460 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7461 7462 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7463 if (extractLibs) { 7464 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7465 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7466 useIsaSpecificSubdirs); 7467 } else { 7468 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7469 } 7470 } 7471 7472 maybeThrowExceptionForMultiArchCopy( 7473 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7474 7475 if (abi64 >= 0) { 7476 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7477 } 7478 7479 if (abi32 >= 0) { 7480 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7481 if (abi64 >= 0) { 7482 pkg.applicationInfo.secondaryCpuAbi = abi; 7483 } else { 7484 pkg.applicationInfo.primaryCpuAbi = abi; 7485 } 7486 } 7487 } else { 7488 String[] abiList = (cpuAbiOverride != null) ? 7489 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7490 7491 // Enable gross and lame hacks for apps that are built with old 7492 // SDK tools. We must scan their APKs for renderscript bitcode and 7493 // not launch them if it's present. Don't bother checking on devices 7494 // that don't have 64 bit support. 7495 boolean needsRenderScriptOverride = false; 7496 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7497 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7498 abiList = Build.SUPPORTED_32_BIT_ABIS; 7499 needsRenderScriptOverride = true; 7500 } 7501 7502 final int copyRet; 7503 if (extractLibs) { 7504 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7505 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7506 } else { 7507 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7508 } 7509 7510 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7511 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7512 "Error unpackaging native libs for app, errorCode=" + copyRet); 7513 } 7514 7515 if (copyRet >= 0) { 7516 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7517 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7518 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7519 } else if (needsRenderScriptOverride) { 7520 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7521 } 7522 } 7523 } catch (IOException ioe) { 7524 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7525 } finally { 7526 IoUtils.closeQuietly(handle); 7527 } 7528 7529 // Now that we've calculated the ABIs and determined if it's an internal app, 7530 // we will go ahead and populate the nativeLibraryPath. 7531 setNativeLibraryPaths(pkg); 7532 } 7533 7534 /** 7535 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7536 * i.e, so that all packages can be run inside a single process if required. 7537 * 7538 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7539 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7540 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7541 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7542 * updating a package that belongs to a shared user. 7543 * 7544 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7545 * adds unnecessary complexity. 7546 */ 7547 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7548 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7549 String requiredInstructionSet = null; 7550 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7551 requiredInstructionSet = VMRuntime.getInstructionSet( 7552 scannedPackage.applicationInfo.primaryCpuAbi); 7553 } 7554 7555 PackageSetting requirer = null; 7556 for (PackageSetting ps : packagesForUser) { 7557 // If packagesForUser contains scannedPackage, we skip it. This will happen 7558 // when scannedPackage is an update of an existing package. Without this check, 7559 // we will never be able to change the ABI of any package belonging to a shared 7560 // user, even if it's compatible with other packages. 7561 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7562 if (ps.primaryCpuAbiString == null) { 7563 continue; 7564 } 7565 7566 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7567 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7568 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7569 // this but there's not much we can do. 7570 String errorMessage = "Instruction set mismatch, " 7571 + ((requirer == null) ? "[caller]" : requirer) 7572 + " requires " + requiredInstructionSet + " whereas " + ps 7573 + " requires " + instructionSet; 7574 Slog.w(TAG, errorMessage); 7575 } 7576 7577 if (requiredInstructionSet == null) { 7578 requiredInstructionSet = instructionSet; 7579 requirer = ps; 7580 } 7581 } 7582 } 7583 7584 if (requiredInstructionSet != null) { 7585 String adjustedAbi; 7586 if (requirer != null) { 7587 // requirer != null implies that either scannedPackage was null or that scannedPackage 7588 // did not require an ABI, in which case we have to adjust scannedPackage to match 7589 // the ABI of the set (which is the same as requirer's ABI) 7590 adjustedAbi = requirer.primaryCpuAbiString; 7591 if (scannedPackage != null) { 7592 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7593 } 7594 } else { 7595 // requirer == null implies that we're updating all ABIs in the set to 7596 // match scannedPackage. 7597 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7598 } 7599 7600 for (PackageSetting ps : packagesForUser) { 7601 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7602 if (ps.primaryCpuAbiString != null) { 7603 continue; 7604 } 7605 7606 ps.primaryCpuAbiString = adjustedAbi; 7607 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7608 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7609 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7610 7611 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7612 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7613 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7614 ps.primaryCpuAbiString = null; 7615 ps.pkg.applicationInfo.primaryCpuAbi = null; 7616 return; 7617 } else { 7618 mInstaller.rmdex(ps.codePathString, 7619 getDexCodeInstructionSet(getPreferredInstructionSet())); 7620 } 7621 } 7622 } 7623 } 7624 } 7625 } 7626 7627 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7628 synchronized (mPackages) { 7629 mResolverReplaced = true; 7630 // Set up information for custom user intent resolution activity. 7631 mResolveActivity.applicationInfo = pkg.applicationInfo; 7632 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7633 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7634 mResolveActivity.processName = pkg.applicationInfo.packageName; 7635 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7636 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7637 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7638 mResolveActivity.theme = 0; 7639 mResolveActivity.exported = true; 7640 mResolveActivity.enabled = true; 7641 mResolveInfo.activityInfo = mResolveActivity; 7642 mResolveInfo.priority = 0; 7643 mResolveInfo.preferredOrder = 0; 7644 mResolveInfo.match = 0; 7645 mResolveComponentName = mCustomResolverComponentName; 7646 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7647 mResolveComponentName); 7648 } 7649 } 7650 7651 private static String calculateBundledApkRoot(final String codePathString) { 7652 final File codePath = new File(codePathString); 7653 final File codeRoot; 7654 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7655 codeRoot = Environment.getRootDirectory(); 7656 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7657 codeRoot = Environment.getOemDirectory(); 7658 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7659 codeRoot = Environment.getVendorDirectory(); 7660 } else { 7661 // Unrecognized code path; take its top real segment as the apk root: 7662 // e.g. /something/app/blah.apk => /something 7663 try { 7664 File f = codePath.getCanonicalFile(); 7665 File parent = f.getParentFile(); // non-null because codePath is a file 7666 File tmp; 7667 while ((tmp = parent.getParentFile()) != null) { 7668 f = parent; 7669 parent = tmp; 7670 } 7671 codeRoot = f; 7672 Slog.w(TAG, "Unrecognized code path " 7673 + codePath + " - using " + codeRoot); 7674 } catch (IOException e) { 7675 // Can't canonicalize the code path -- shenanigans? 7676 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7677 return Environment.getRootDirectory().getPath(); 7678 } 7679 } 7680 return codeRoot.getPath(); 7681 } 7682 7683 /** 7684 * Derive and set the location of native libraries for the given package, 7685 * which varies depending on where and how the package was installed. 7686 */ 7687 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7688 final ApplicationInfo info = pkg.applicationInfo; 7689 final String codePath = pkg.codePath; 7690 final File codeFile = new File(codePath); 7691 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7692 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7693 7694 info.nativeLibraryRootDir = null; 7695 info.nativeLibraryRootRequiresIsa = false; 7696 info.nativeLibraryDir = null; 7697 info.secondaryNativeLibraryDir = null; 7698 7699 if (isApkFile(codeFile)) { 7700 // Monolithic install 7701 if (bundledApp) { 7702 // If "/system/lib64/apkname" exists, assume that is the per-package 7703 // native library directory to use; otherwise use "/system/lib/apkname". 7704 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7705 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7706 getPrimaryInstructionSet(info)); 7707 7708 // This is a bundled system app so choose the path based on the ABI. 7709 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7710 // is just the default path. 7711 final String apkName = deriveCodePathName(codePath); 7712 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7713 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7714 apkName).getAbsolutePath(); 7715 7716 if (info.secondaryCpuAbi != null) { 7717 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7718 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7719 secondaryLibDir, apkName).getAbsolutePath(); 7720 } 7721 } else if (asecApp) { 7722 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7723 .getAbsolutePath(); 7724 } else { 7725 final String apkName = deriveCodePathName(codePath); 7726 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7727 .getAbsolutePath(); 7728 } 7729 7730 info.nativeLibraryRootRequiresIsa = false; 7731 info.nativeLibraryDir = info.nativeLibraryRootDir; 7732 } else { 7733 // Cluster install 7734 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7735 info.nativeLibraryRootRequiresIsa = true; 7736 7737 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7738 getPrimaryInstructionSet(info)).getAbsolutePath(); 7739 7740 if (info.secondaryCpuAbi != null) { 7741 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7742 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7743 } 7744 } 7745 } 7746 7747 /** 7748 * Calculate the abis and roots for a bundled app. These can uniquely 7749 * be determined from the contents of the system partition, i.e whether 7750 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7751 * of this information, and instead assume that the system was built 7752 * sensibly. 7753 */ 7754 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7755 PackageSetting pkgSetting) { 7756 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7757 7758 // If "/system/lib64/apkname" exists, assume that is the per-package 7759 // native library directory to use; otherwise use "/system/lib/apkname". 7760 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7761 setBundledAppAbi(pkg, apkRoot, apkName); 7762 // pkgSetting might be null during rescan following uninstall of updates 7763 // to a bundled app, so accommodate that possibility. The settings in 7764 // that case will be established later from the parsed package. 7765 // 7766 // If the settings aren't null, sync them up with what we've just derived. 7767 // note that apkRoot isn't stored in the package settings. 7768 if (pkgSetting != null) { 7769 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7770 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7771 } 7772 } 7773 7774 /** 7775 * Deduces the ABI of a bundled app and sets the relevant fields on the 7776 * parsed pkg object. 7777 * 7778 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7779 * under which system libraries are installed. 7780 * @param apkName the name of the installed package. 7781 */ 7782 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7783 final File codeFile = new File(pkg.codePath); 7784 7785 final boolean has64BitLibs; 7786 final boolean has32BitLibs; 7787 if (isApkFile(codeFile)) { 7788 // Monolithic install 7789 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7790 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7791 } else { 7792 // Cluster install 7793 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7794 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7795 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7796 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7797 has64BitLibs = (new File(rootDir, isa)).exists(); 7798 } else { 7799 has64BitLibs = false; 7800 } 7801 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7802 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7803 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7804 has32BitLibs = (new File(rootDir, isa)).exists(); 7805 } else { 7806 has32BitLibs = false; 7807 } 7808 } 7809 7810 if (has64BitLibs && !has32BitLibs) { 7811 // The package has 64 bit libs, but not 32 bit libs. Its primary 7812 // ABI should be 64 bit. We can safely assume here that the bundled 7813 // native libraries correspond to the most preferred ABI in the list. 7814 7815 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7816 pkg.applicationInfo.secondaryCpuAbi = null; 7817 } else if (has32BitLibs && !has64BitLibs) { 7818 // The package has 32 bit libs but not 64 bit libs. Its primary 7819 // ABI should be 32 bit. 7820 7821 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7822 pkg.applicationInfo.secondaryCpuAbi = null; 7823 } else if (has32BitLibs && has64BitLibs) { 7824 // The application has both 64 and 32 bit bundled libraries. We check 7825 // here that the app declares multiArch support, and warn if it doesn't. 7826 // 7827 // We will be lenient here and record both ABIs. The primary will be the 7828 // ABI that's higher on the list, i.e, a device that's configured to prefer 7829 // 64 bit apps will see a 64 bit primary ABI, 7830 7831 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7832 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7833 } 7834 7835 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7836 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7837 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7838 } else { 7839 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7840 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7841 } 7842 } else { 7843 pkg.applicationInfo.primaryCpuAbi = null; 7844 pkg.applicationInfo.secondaryCpuAbi = null; 7845 } 7846 } 7847 7848 private void killApplication(String pkgName, int appId, String reason) { 7849 // Request the ActivityManager to kill the process(only for existing packages) 7850 // so that we do not end up in a confused state while the user is still using the older 7851 // version of the application while the new one gets installed. 7852 IActivityManager am = ActivityManagerNative.getDefault(); 7853 if (am != null) { 7854 try { 7855 am.killApplicationWithAppId(pkgName, appId, reason); 7856 } catch (RemoteException e) { 7857 } 7858 } 7859 } 7860 7861 void removePackageLI(PackageSetting ps, boolean chatty) { 7862 if (DEBUG_INSTALL) { 7863 if (chatty) 7864 Log.d(TAG, "Removing package " + ps.name); 7865 } 7866 7867 // writer 7868 synchronized (mPackages) { 7869 mPackages.remove(ps.name); 7870 final PackageParser.Package pkg = ps.pkg; 7871 if (pkg != null) { 7872 cleanPackageDataStructuresLILPw(pkg, chatty); 7873 } 7874 } 7875 } 7876 7877 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7878 if (DEBUG_INSTALL) { 7879 if (chatty) 7880 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7881 } 7882 7883 // writer 7884 synchronized (mPackages) { 7885 mPackages.remove(pkg.applicationInfo.packageName); 7886 cleanPackageDataStructuresLILPw(pkg, chatty); 7887 } 7888 } 7889 7890 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7891 int N = pkg.providers.size(); 7892 StringBuilder r = null; 7893 int i; 7894 for (i=0; i<N; i++) { 7895 PackageParser.Provider p = pkg.providers.get(i); 7896 mProviders.removeProvider(p); 7897 if (p.info.authority == null) { 7898 7899 /* There was another ContentProvider with this authority when 7900 * this app was installed so this authority is null, 7901 * Ignore it as we don't have to unregister the provider. 7902 */ 7903 continue; 7904 } 7905 String names[] = p.info.authority.split(";"); 7906 for (int j = 0; j < names.length; j++) { 7907 if (mProvidersByAuthority.get(names[j]) == p) { 7908 mProvidersByAuthority.remove(names[j]); 7909 if (DEBUG_REMOVE) { 7910 if (chatty) 7911 Log.d(TAG, "Unregistered content provider: " + names[j] 7912 + ", className = " + p.info.name + ", isSyncable = " 7913 + p.info.isSyncable); 7914 } 7915 } 7916 } 7917 if (DEBUG_REMOVE && chatty) { 7918 if (r == null) { 7919 r = new StringBuilder(256); 7920 } else { 7921 r.append(' '); 7922 } 7923 r.append(p.info.name); 7924 } 7925 } 7926 if (r != null) { 7927 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7928 } 7929 7930 N = pkg.services.size(); 7931 r = null; 7932 for (i=0; i<N; i++) { 7933 PackageParser.Service s = pkg.services.get(i); 7934 mServices.removeService(s); 7935 if (chatty) { 7936 if (r == null) { 7937 r = new StringBuilder(256); 7938 } else { 7939 r.append(' '); 7940 } 7941 r.append(s.info.name); 7942 } 7943 } 7944 if (r != null) { 7945 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7946 } 7947 7948 N = pkg.receivers.size(); 7949 r = null; 7950 for (i=0; i<N; i++) { 7951 PackageParser.Activity a = pkg.receivers.get(i); 7952 mReceivers.removeActivity(a, "receiver"); 7953 if (DEBUG_REMOVE && chatty) { 7954 if (r == null) { 7955 r = new StringBuilder(256); 7956 } else { 7957 r.append(' '); 7958 } 7959 r.append(a.info.name); 7960 } 7961 } 7962 if (r != null) { 7963 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7964 } 7965 7966 N = pkg.activities.size(); 7967 r = null; 7968 for (i=0; i<N; i++) { 7969 PackageParser.Activity a = pkg.activities.get(i); 7970 mActivities.removeActivity(a, "activity"); 7971 if (DEBUG_REMOVE && chatty) { 7972 if (r == null) { 7973 r = new StringBuilder(256); 7974 } else { 7975 r.append(' '); 7976 } 7977 r.append(a.info.name); 7978 } 7979 } 7980 if (r != null) { 7981 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7982 } 7983 7984 N = pkg.permissions.size(); 7985 r = null; 7986 for (i=0; i<N; i++) { 7987 PackageParser.Permission p = pkg.permissions.get(i); 7988 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7989 if (bp == null) { 7990 bp = mSettings.mPermissionTrees.get(p.info.name); 7991 } 7992 if (bp != null && bp.perm == p) { 7993 bp.perm = null; 7994 if (DEBUG_REMOVE && chatty) { 7995 if (r == null) { 7996 r = new StringBuilder(256); 7997 } else { 7998 r.append(' '); 7999 } 8000 r.append(p.info.name); 8001 } 8002 } 8003 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8004 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8005 if (appOpPerms != null) { 8006 appOpPerms.remove(pkg.packageName); 8007 } 8008 } 8009 } 8010 if (r != null) { 8011 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8012 } 8013 8014 N = pkg.requestedPermissions.size(); 8015 r = null; 8016 for (i=0; i<N; i++) { 8017 String perm = pkg.requestedPermissions.get(i); 8018 BasePermission bp = mSettings.mPermissions.get(perm); 8019 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8020 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8021 if (appOpPerms != null) { 8022 appOpPerms.remove(pkg.packageName); 8023 if (appOpPerms.isEmpty()) { 8024 mAppOpPermissionPackages.remove(perm); 8025 } 8026 } 8027 } 8028 } 8029 if (r != null) { 8030 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8031 } 8032 8033 N = pkg.instrumentation.size(); 8034 r = null; 8035 for (i=0; i<N; i++) { 8036 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8037 mInstrumentation.remove(a.getComponentName()); 8038 if (DEBUG_REMOVE && chatty) { 8039 if (r == null) { 8040 r = new StringBuilder(256); 8041 } else { 8042 r.append(' '); 8043 } 8044 r.append(a.info.name); 8045 } 8046 } 8047 if (r != null) { 8048 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8049 } 8050 8051 r = null; 8052 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8053 // Only system apps can hold shared libraries. 8054 if (pkg.libraryNames != null) { 8055 for (i=0; i<pkg.libraryNames.size(); i++) { 8056 String name = pkg.libraryNames.get(i); 8057 SharedLibraryEntry cur = mSharedLibraries.get(name); 8058 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8059 mSharedLibraries.remove(name); 8060 if (DEBUG_REMOVE && chatty) { 8061 if (r == null) { 8062 r = new StringBuilder(256); 8063 } else { 8064 r.append(' '); 8065 } 8066 r.append(name); 8067 } 8068 } 8069 } 8070 } 8071 } 8072 if (r != null) { 8073 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8074 } 8075 } 8076 8077 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8078 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8079 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8080 return true; 8081 } 8082 } 8083 return false; 8084 } 8085 8086 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8087 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8088 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8089 8090 private void updatePermissionsLPw(String changingPkg, 8091 PackageParser.Package pkgInfo, int flags) { 8092 // Make sure there are no dangling permission trees. 8093 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8094 while (it.hasNext()) { 8095 final BasePermission bp = it.next(); 8096 if (bp.packageSetting == null) { 8097 // We may not yet have parsed the package, so just see if 8098 // we still know about its settings. 8099 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8100 } 8101 if (bp.packageSetting == null) { 8102 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8103 + " from package " + bp.sourcePackage); 8104 it.remove(); 8105 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8106 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8107 Slog.i(TAG, "Removing old permission tree: " + bp.name 8108 + " from package " + bp.sourcePackage); 8109 flags |= UPDATE_PERMISSIONS_ALL; 8110 it.remove(); 8111 } 8112 } 8113 } 8114 8115 // Make sure all dynamic permissions have been assigned to a package, 8116 // and make sure there are no dangling permissions. 8117 it = mSettings.mPermissions.values().iterator(); 8118 while (it.hasNext()) { 8119 final BasePermission bp = it.next(); 8120 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8121 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8122 + bp.name + " pkg=" + bp.sourcePackage 8123 + " info=" + bp.pendingInfo); 8124 if (bp.packageSetting == null && bp.pendingInfo != null) { 8125 final BasePermission tree = findPermissionTreeLP(bp.name); 8126 if (tree != null && tree.perm != null) { 8127 bp.packageSetting = tree.packageSetting; 8128 bp.perm = new PackageParser.Permission(tree.perm.owner, 8129 new PermissionInfo(bp.pendingInfo)); 8130 bp.perm.info.packageName = tree.perm.info.packageName; 8131 bp.perm.info.name = bp.name; 8132 bp.uid = tree.uid; 8133 } 8134 } 8135 } 8136 if (bp.packageSetting == null) { 8137 // We may not yet have parsed the package, so just see if 8138 // we still know about its settings. 8139 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8140 } 8141 if (bp.packageSetting == null) { 8142 Slog.w(TAG, "Removing dangling permission: " + bp.name 8143 + " from package " + bp.sourcePackage); 8144 it.remove(); 8145 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8146 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8147 Slog.i(TAG, "Removing old permission: " + bp.name 8148 + " from package " + bp.sourcePackage); 8149 flags |= UPDATE_PERMISSIONS_ALL; 8150 it.remove(); 8151 } 8152 } 8153 } 8154 8155 // Now update the permissions for all packages, in particular 8156 // replace the granted permissions of the system packages. 8157 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8158 for (PackageParser.Package pkg : mPackages.values()) { 8159 if (pkg != pkgInfo) { 8160 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8161 changingPkg); 8162 } 8163 } 8164 } 8165 8166 if (pkgInfo != null) { 8167 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8168 } 8169 } 8170 8171 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8172 String packageOfInterest) { 8173 // IMPORTANT: There are two types of permissions: install and runtime. 8174 // Install time permissions are granted when the app is installed to 8175 // all device users and users added in the future. Runtime permissions 8176 // are granted at runtime explicitly to specific users. Normal and signature 8177 // protected permissions are install time permissions. Dangerous permissions 8178 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8179 // otherwise they are runtime permissions. This function does not manage 8180 // runtime permissions except for the case an app targeting Lollipop MR1 8181 // being upgraded to target a newer SDK, in which case dangerous permissions 8182 // are transformed from install time to runtime ones. 8183 8184 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8185 if (ps == null) { 8186 return; 8187 } 8188 8189 PermissionsState permissionsState = ps.getPermissionsState(); 8190 PermissionsState origPermissions = permissionsState; 8191 8192 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8193 8194 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8195 8196 boolean changedInstallPermission = false; 8197 8198 if (replace) { 8199 ps.installPermissionsFixed = false; 8200 if (!ps.isSharedUser()) { 8201 origPermissions = new PermissionsState(permissionsState); 8202 permissionsState.reset(); 8203 } 8204 } 8205 8206 permissionsState.setGlobalGids(mGlobalGids); 8207 8208 final int N = pkg.requestedPermissions.size(); 8209 for (int i=0; i<N; i++) { 8210 final String name = pkg.requestedPermissions.get(i); 8211 final BasePermission bp = mSettings.mPermissions.get(name); 8212 8213 if (DEBUG_INSTALL) { 8214 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8215 } 8216 8217 if (bp == null || bp.packageSetting == null) { 8218 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8219 Slog.w(TAG, "Unknown permission " + name 8220 + " in package " + pkg.packageName); 8221 } 8222 continue; 8223 } 8224 8225 final String perm = bp.name; 8226 boolean allowedSig = false; 8227 int grant = GRANT_DENIED; 8228 8229 // Keep track of app op permissions. 8230 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8231 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8232 if (pkgs == null) { 8233 pkgs = new ArraySet<>(); 8234 mAppOpPermissionPackages.put(bp.name, pkgs); 8235 } 8236 pkgs.add(pkg.packageName); 8237 } 8238 8239 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8240 switch (level) { 8241 case PermissionInfo.PROTECTION_NORMAL: { 8242 // For all apps normal permissions are install time ones. 8243 grant = GRANT_INSTALL; 8244 } break; 8245 8246 case PermissionInfo.PROTECTION_DANGEROUS: { 8247 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8248 // For legacy apps dangerous permissions are install time ones. 8249 grant = GRANT_INSTALL_LEGACY; 8250 } else if (origPermissions.hasInstallPermission(bp.name)) { 8251 // For legacy apps that became modern, install becomes runtime. 8252 grant = GRANT_UPGRADE; 8253 } else { 8254 // For modern apps keep runtime permissions unchanged. 8255 grant = GRANT_RUNTIME; 8256 } 8257 } break; 8258 8259 case PermissionInfo.PROTECTION_SIGNATURE: { 8260 // For all apps signature permissions are install time ones. 8261 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8262 if (allowedSig) { 8263 grant = GRANT_INSTALL; 8264 } 8265 } break; 8266 } 8267 8268 if (DEBUG_INSTALL) { 8269 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8270 } 8271 8272 if (grant != GRANT_DENIED) { 8273 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8274 // If this is an existing, non-system package, then 8275 // we can't add any new permissions to it. 8276 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8277 // Except... if this is a permission that was added 8278 // to the platform (note: need to only do this when 8279 // updating the platform). 8280 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8281 grant = GRANT_DENIED; 8282 } 8283 } 8284 } 8285 8286 switch (grant) { 8287 case GRANT_INSTALL: { 8288 // Revoke this as runtime permission to handle the case of 8289 // a runtime permission being downgraded to an install one. 8290 for (int userId : UserManagerService.getInstance().getUserIds()) { 8291 if (origPermissions.getRuntimePermissionState( 8292 bp.name, userId) != null) { 8293 // Revoke the runtime permission and clear the flags. 8294 origPermissions.revokeRuntimePermission(bp, userId); 8295 origPermissions.updatePermissionFlags(bp, userId, 8296 PackageManager.MASK_PERMISSION_FLAGS, 0); 8297 // If we revoked a permission permission, we have to write. 8298 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8299 changedRuntimePermissionUserIds, userId); 8300 } 8301 } 8302 // Grant an install permission. 8303 if (permissionsState.grantInstallPermission(bp) != 8304 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8305 changedInstallPermission = true; 8306 } 8307 } break; 8308 8309 case GRANT_INSTALL_LEGACY: { 8310 // Grant an install permission. 8311 if (permissionsState.grantInstallPermission(bp) != 8312 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8313 changedInstallPermission = true; 8314 } 8315 } break; 8316 8317 case GRANT_RUNTIME: { 8318 // Grant previously granted runtime permissions. 8319 for (int userId : UserManagerService.getInstance().getUserIds()) { 8320 PermissionState permissionState = origPermissions 8321 .getRuntimePermissionState(bp.name, userId); 8322 final int flags = permissionState != null 8323 ? permissionState.getFlags() : 0; 8324 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8325 if (permissionsState.grantRuntimePermission(bp, userId) == 8326 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8327 // If we cannot put the permission as it was, we have to write. 8328 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8329 changedRuntimePermissionUserIds, userId); 8330 } 8331 } 8332 // Propagate the permission flags. 8333 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8334 } 8335 } break; 8336 8337 case GRANT_UPGRADE: { 8338 // Grant runtime permissions for a previously held install permission. 8339 PermissionState permissionState = origPermissions 8340 .getInstallPermissionState(bp.name); 8341 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8342 8343 if (origPermissions.revokeInstallPermission(bp) 8344 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8345 // We will be transferring the permission flags, so clear them. 8346 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8347 PackageManager.MASK_PERMISSION_FLAGS, 0); 8348 changedInstallPermission = true; 8349 } 8350 8351 // If the permission is not to be promoted to runtime we ignore it and 8352 // also its other flags as they are not applicable to install permissions. 8353 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8354 for (int userId : currentUserIds) { 8355 if (permissionsState.grantRuntimePermission(bp, userId) != 8356 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8357 // Transfer the permission flags. 8358 permissionsState.updatePermissionFlags(bp, userId, 8359 flags, flags); 8360 // If we granted the permission, we have to write. 8361 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8362 changedRuntimePermissionUserIds, userId); 8363 } 8364 } 8365 } 8366 } break; 8367 8368 default: { 8369 if (packageOfInterest == null 8370 || packageOfInterest.equals(pkg.packageName)) { 8371 Slog.w(TAG, "Not granting permission " + perm 8372 + " to package " + pkg.packageName 8373 + " because it was previously installed without"); 8374 } 8375 } break; 8376 } 8377 } else { 8378 if (permissionsState.revokeInstallPermission(bp) != 8379 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8380 // Also drop the permission flags. 8381 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8382 PackageManager.MASK_PERMISSION_FLAGS, 0); 8383 changedInstallPermission = true; 8384 Slog.i(TAG, "Un-granting permission " + perm 8385 + " from package " + pkg.packageName 8386 + " (protectionLevel=" + bp.protectionLevel 8387 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8388 + ")"); 8389 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8390 // Don't print warning for app op permissions, since it is fine for them 8391 // not to be granted, there is a UI for the user to decide. 8392 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8393 Slog.w(TAG, "Not granting permission " + perm 8394 + " to package " + pkg.packageName 8395 + " (protectionLevel=" + bp.protectionLevel 8396 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8397 + ")"); 8398 } 8399 } 8400 } 8401 } 8402 8403 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8404 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8405 // This is the first that we have heard about this package, so the 8406 // permissions we have now selected are fixed until explicitly 8407 // changed. 8408 ps.installPermissionsFixed = true; 8409 } 8410 8411 // Persist the runtime permissions state for users with changes. 8412 for (int userId : changedRuntimePermissionUserIds) { 8413 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8414 } 8415 } 8416 8417 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8418 boolean allowed = false; 8419 final int NP = PackageParser.NEW_PERMISSIONS.length; 8420 for (int ip=0; ip<NP; ip++) { 8421 final PackageParser.NewPermissionInfo npi 8422 = PackageParser.NEW_PERMISSIONS[ip]; 8423 if (npi.name.equals(perm) 8424 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8425 allowed = true; 8426 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8427 + pkg.packageName); 8428 break; 8429 } 8430 } 8431 return allowed; 8432 } 8433 8434 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8435 BasePermission bp, PermissionsState origPermissions) { 8436 boolean allowed; 8437 allowed = (compareSignatures( 8438 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8439 == PackageManager.SIGNATURE_MATCH) 8440 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8441 == PackageManager.SIGNATURE_MATCH); 8442 if (!allowed && (bp.protectionLevel 8443 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8444 if (isSystemApp(pkg)) { 8445 // For updated system applications, a system permission 8446 // is granted only if it had been defined by the original application. 8447 if (pkg.isUpdatedSystemApp()) { 8448 final PackageSetting sysPs = mSettings 8449 .getDisabledSystemPkgLPr(pkg.packageName); 8450 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8451 // If the original was granted this permission, we take 8452 // that grant decision as read and propagate it to the 8453 // update. 8454 if (sysPs.isPrivileged()) { 8455 allowed = true; 8456 } 8457 } else { 8458 // The system apk may have been updated with an older 8459 // version of the one on the data partition, but which 8460 // granted a new system permission that it didn't have 8461 // before. In this case we do want to allow the app to 8462 // now get the new permission if the ancestral apk is 8463 // privileged to get it. 8464 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8465 for (int j=0; 8466 j<sysPs.pkg.requestedPermissions.size(); j++) { 8467 if (perm.equals( 8468 sysPs.pkg.requestedPermissions.get(j))) { 8469 allowed = true; 8470 break; 8471 } 8472 } 8473 } 8474 } 8475 } else { 8476 allowed = isPrivilegedApp(pkg); 8477 } 8478 } 8479 } 8480 if (!allowed) { 8481 if (!allowed && (bp.protectionLevel 8482 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8483 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8484 // If this was a previously normal/dangerous permission that got moved 8485 // to a system permission as part of the runtime permission redesign, then 8486 // we still want to blindly grant it to old apps. 8487 allowed = true; 8488 } 8489 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8490 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8491 // If this permission is to be granted to the system installer and 8492 // this app is an installer, then it gets the permission. 8493 allowed = true; 8494 } 8495 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8496 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8497 // If this permission is to be granted to the system verifier and 8498 // this app is a verifier, then it gets the permission. 8499 allowed = true; 8500 } 8501 if (!allowed && (bp.protectionLevel 8502 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8503 && isSystemApp(pkg)) { 8504 // Any pre-installed system app is allowed to get this permission. 8505 allowed = true; 8506 } 8507 if (!allowed && (bp.protectionLevel 8508 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8509 // For development permissions, a development permission 8510 // is granted only if it was already granted. 8511 allowed = origPermissions.hasInstallPermission(perm); 8512 } 8513 } 8514 return allowed; 8515 } 8516 8517 final class ActivityIntentResolver 8518 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8519 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8520 boolean defaultOnly, int userId) { 8521 if (!sUserManager.exists(userId)) return null; 8522 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8523 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8524 } 8525 8526 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8527 int userId) { 8528 if (!sUserManager.exists(userId)) return null; 8529 mFlags = flags; 8530 return super.queryIntent(intent, resolvedType, 8531 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8532 } 8533 8534 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8535 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8536 if (!sUserManager.exists(userId)) return null; 8537 if (packageActivities == null) { 8538 return null; 8539 } 8540 mFlags = flags; 8541 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8542 final int N = packageActivities.size(); 8543 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8544 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8545 8546 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8547 for (int i = 0; i < N; ++i) { 8548 intentFilters = packageActivities.get(i).intents; 8549 if (intentFilters != null && intentFilters.size() > 0) { 8550 PackageParser.ActivityIntentInfo[] array = 8551 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8552 intentFilters.toArray(array); 8553 listCut.add(array); 8554 } 8555 } 8556 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8557 } 8558 8559 public final void addActivity(PackageParser.Activity a, String type) { 8560 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8561 mActivities.put(a.getComponentName(), a); 8562 if (DEBUG_SHOW_INFO) 8563 Log.v( 8564 TAG, " " + type + " " + 8565 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8566 if (DEBUG_SHOW_INFO) 8567 Log.v(TAG, " Class=" + a.info.name); 8568 final int NI = a.intents.size(); 8569 for (int j=0; j<NI; j++) { 8570 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8571 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8572 intent.setPriority(0); 8573 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8574 + a.className + " with priority > 0, forcing to 0"); 8575 } 8576 if (DEBUG_SHOW_INFO) { 8577 Log.v(TAG, " IntentFilter:"); 8578 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8579 } 8580 if (!intent.debugCheck()) { 8581 Log.w(TAG, "==> For Activity " + a.info.name); 8582 } 8583 addFilter(intent); 8584 } 8585 } 8586 8587 public final void removeActivity(PackageParser.Activity a, String type) { 8588 mActivities.remove(a.getComponentName()); 8589 if (DEBUG_SHOW_INFO) { 8590 Log.v(TAG, " " + type + " " 8591 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8592 : a.info.name) + ":"); 8593 Log.v(TAG, " Class=" + a.info.name); 8594 } 8595 final int NI = a.intents.size(); 8596 for (int j=0; j<NI; j++) { 8597 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8598 if (DEBUG_SHOW_INFO) { 8599 Log.v(TAG, " IntentFilter:"); 8600 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8601 } 8602 removeFilter(intent); 8603 } 8604 } 8605 8606 @Override 8607 protected boolean allowFilterResult( 8608 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8609 ActivityInfo filterAi = filter.activity.info; 8610 for (int i=dest.size()-1; i>=0; i--) { 8611 ActivityInfo destAi = dest.get(i).activityInfo; 8612 if (destAi.name == filterAi.name 8613 && destAi.packageName == filterAi.packageName) { 8614 return false; 8615 } 8616 } 8617 return true; 8618 } 8619 8620 @Override 8621 protected ActivityIntentInfo[] newArray(int size) { 8622 return new ActivityIntentInfo[size]; 8623 } 8624 8625 @Override 8626 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8627 if (!sUserManager.exists(userId)) return true; 8628 PackageParser.Package p = filter.activity.owner; 8629 if (p != null) { 8630 PackageSetting ps = (PackageSetting)p.mExtras; 8631 if (ps != null) { 8632 // System apps are never considered stopped for purposes of 8633 // filtering, because there may be no way for the user to 8634 // actually re-launch them. 8635 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8636 && ps.getStopped(userId); 8637 } 8638 } 8639 return false; 8640 } 8641 8642 @Override 8643 protected boolean isPackageForFilter(String packageName, 8644 PackageParser.ActivityIntentInfo info) { 8645 return packageName.equals(info.activity.owner.packageName); 8646 } 8647 8648 @Override 8649 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8650 int match, int userId) { 8651 if (!sUserManager.exists(userId)) return null; 8652 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8653 return null; 8654 } 8655 final PackageParser.Activity activity = info.activity; 8656 if (mSafeMode && (activity.info.applicationInfo.flags 8657 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8658 return null; 8659 } 8660 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8661 if (ps == null) { 8662 return null; 8663 } 8664 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8665 ps.readUserState(userId), userId); 8666 if (ai == null) { 8667 return null; 8668 } 8669 final ResolveInfo res = new ResolveInfo(); 8670 res.activityInfo = ai; 8671 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8672 res.filter = info; 8673 } 8674 if (info != null) { 8675 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8676 } 8677 res.priority = info.getPriority(); 8678 res.preferredOrder = activity.owner.mPreferredOrder; 8679 //System.out.println("Result: " + res.activityInfo.className + 8680 // " = " + res.priority); 8681 res.match = match; 8682 res.isDefault = info.hasDefault; 8683 res.labelRes = info.labelRes; 8684 res.nonLocalizedLabel = info.nonLocalizedLabel; 8685 if (userNeedsBadging(userId)) { 8686 res.noResourceId = true; 8687 } else { 8688 res.icon = info.icon; 8689 } 8690 res.iconResourceId = info.icon; 8691 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8692 return res; 8693 } 8694 8695 @Override 8696 protected void sortResults(List<ResolveInfo> results) { 8697 Collections.sort(results, mResolvePrioritySorter); 8698 } 8699 8700 @Override 8701 protected void dumpFilter(PrintWriter out, String prefix, 8702 PackageParser.ActivityIntentInfo filter) { 8703 out.print(prefix); out.print( 8704 Integer.toHexString(System.identityHashCode(filter.activity))); 8705 out.print(' '); 8706 filter.activity.printComponentShortName(out); 8707 out.print(" filter "); 8708 out.println(Integer.toHexString(System.identityHashCode(filter))); 8709 } 8710 8711 @Override 8712 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8713 return filter.activity; 8714 } 8715 8716 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8717 PackageParser.Activity activity = (PackageParser.Activity)label; 8718 out.print(prefix); out.print( 8719 Integer.toHexString(System.identityHashCode(activity))); 8720 out.print(' '); 8721 activity.printComponentShortName(out); 8722 if (count > 1) { 8723 out.print(" ("); out.print(count); out.print(" filters)"); 8724 } 8725 out.println(); 8726 } 8727 8728// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8729// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8730// final List<ResolveInfo> retList = Lists.newArrayList(); 8731// while (i.hasNext()) { 8732// final ResolveInfo resolveInfo = i.next(); 8733// if (isEnabledLP(resolveInfo.activityInfo)) { 8734// retList.add(resolveInfo); 8735// } 8736// } 8737// return retList; 8738// } 8739 8740 // Keys are String (activity class name), values are Activity. 8741 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8742 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8743 private int mFlags; 8744 } 8745 8746 private final class ServiceIntentResolver 8747 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8748 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8749 boolean defaultOnly, int userId) { 8750 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8751 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8752 } 8753 8754 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8755 int userId) { 8756 if (!sUserManager.exists(userId)) return null; 8757 mFlags = flags; 8758 return super.queryIntent(intent, resolvedType, 8759 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8760 } 8761 8762 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8763 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8764 if (!sUserManager.exists(userId)) return null; 8765 if (packageServices == null) { 8766 return null; 8767 } 8768 mFlags = flags; 8769 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8770 final int N = packageServices.size(); 8771 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8772 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8773 8774 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8775 for (int i = 0; i < N; ++i) { 8776 intentFilters = packageServices.get(i).intents; 8777 if (intentFilters != null && intentFilters.size() > 0) { 8778 PackageParser.ServiceIntentInfo[] array = 8779 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8780 intentFilters.toArray(array); 8781 listCut.add(array); 8782 } 8783 } 8784 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8785 } 8786 8787 public final void addService(PackageParser.Service s) { 8788 mServices.put(s.getComponentName(), s); 8789 if (DEBUG_SHOW_INFO) { 8790 Log.v(TAG, " " 8791 + (s.info.nonLocalizedLabel != null 8792 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8793 Log.v(TAG, " Class=" + s.info.name); 8794 } 8795 final int NI = s.intents.size(); 8796 int j; 8797 for (j=0; j<NI; j++) { 8798 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8799 if (DEBUG_SHOW_INFO) { 8800 Log.v(TAG, " IntentFilter:"); 8801 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8802 } 8803 if (!intent.debugCheck()) { 8804 Log.w(TAG, "==> For Service " + s.info.name); 8805 } 8806 addFilter(intent); 8807 } 8808 } 8809 8810 public final void removeService(PackageParser.Service s) { 8811 mServices.remove(s.getComponentName()); 8812 if (DEBUG_SHOW_INFO) { 8813 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8814 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8815 Log.v(TAG, " Class=" + s.info.name); 8816 } 8817 final int NI = s.intents.size(); 8818 int j; 8819 for (j=0; j<NI; j++) { 8820 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8821 if (DEBUG_SHOW_INFO) { 8822 Log.v(TAG, " IntentFilter:"); 8823 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8824 } 8825 removeFilter(intent); 8826 } 8827 } 8828 8829 @Override 8830 protected boolean allowFilterResult( 8831 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8832 ServiceInfo filterSi = filter.service.info; 8833 for (int i=dest.size()-1; i>=0; i--) { 8834 ServiceInfo destAi = dest.get(i).serviceInfo; 8835 if (destAi.name == filterSi.name 8836 && destAi.packageName == filterSi.packageName) { 8837 return false; 8838 } 8839 } 8840 return true; 8841 } 8842 8843 @Override 8844 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8845 return new PackageParser.ServiceIntentInfo[size]; 8846 } 8847 8848 @Override 8849 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8850 if (!sUserManager.exists(userId)) return true; 8851 PackageParser.Package p = filter.service.owner; 8852 if (p != null) { 8853 PackageSetting ps = (PackageSetting)p.mExtras; 8854 if (ps != null) { 8855 // System apps are never considered stopped for purposes of 8856 // filtering, because there may be no way for the user to 8857 // actually re-launch them. 8858 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8859 && ps.getStopped(userId); 8860 } 8861 } 8862 return false; 8863 } 8864 8865 @Override 8866 protected boolean isPackageForFilter(String packageName, 8867 PackageParser.ServiceIntentInfo info) { 8868 return packageName.equals(info.service.owner.packageName); 8869 } 8870 8871 @Override 8872 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8873 int match, int userId) { 8874 if (!sUserManager.exists(userId)) return null; 8875 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8876 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8877 return null; 8878 } 8879 final PackageParser.Service service = info.service; 8880 if (mSafeMode && (service.info.applicationInfo.flags 8881 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8882 return null; 8883 } 8884 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8885 if (ps == null) { 8886 return null; 8887 } 8888 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8889 ps.readUserState(userId), userId); 8890 if (si == null) { 8891 return null; 8892 } 8893 final ResolveInfo res = new ResolveInfo(); 8894 res.serviceInfo = si; 8895 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8896 res.filter = filter; 8897 } 8898 res.priority = info.getPriority(); 8899 res.preferredOrder = service.owner.mPreferredOrder; 8900 res.match = match; 8901 res.isDefault = info.hasDefault; 8902 res.labelRes = info.labelRes; 8903 res.nonLocalizedLabel = info.nonLocalizedLabel; 8904 res.icon = info.icon; 8905 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8906 return res; 8907 } 8908 8909 @Override 8910 protected void sortResults(List<ResolveInfo> results) { 8911 Collections.sort(results, mResolvePrioritySorter); 8912 } 8913 8914 @Override 8915 protected void dumpFilter(PrintWriter out, String prefix, 8916 PackageParser.ServiceIntentInfo filter) { 8917 out.print(prefix); out.print( 8918 Integer.toHexString(System.identityHashCode(filter.service))); 8919 out.print(' '); 8920 filter.service.printComponentShortName(out); 8921 out.print(" filter "); 8922 out.println(Integer.toHexString(System.identityHashCode(filter))); 8923 } 8924 8925 @Override 8926 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8927 return filter.service; 8928 } 8929 8930 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8931 PackageParser.Service service = (PackageParser.Service)label; 8932 out.print(prefix); out.print( 8933 Integer.toHexString(System.identityHashCode(service))); 8934 out.print(' '); 8935 service.printComponentShortName(out); 8936 if (count > 1) { 8937 out.print(" ("); out.print(count); out.print(" filters)"); 8938 } 8939 out.println(); 8940 } 8941 8942// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8943// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8944// final List<ResolveInfo> retList = Lists.newArrayList(); 8945// while (i.hasNext()) { 8946// final ResolveInfo resolveInfo = (ResolveInfo) i; 8947// if (isEnabledLP(resolveInfo.serviceInfo)) { 8948// retList.add(resolveInfo); 8949// } 8950// } 8951// return retList; 8952// } 8953 8954 // Keys are String (activity class name), values are Activity. 8955 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8956 = new ArrayMap<ComponentName, PackageParser.Service>(); 8957 private int mFlags; 8958 }; 8959 8960 private final class ProviderIntentResolver 8961 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8962 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8963 boolean defaultOnly, int userId) { 8964 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8965 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8966 } 8967 8968 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8969 int userId) { 8970 if (!sUserManager.exists(userId)) 8971 return null; 8972 mFlags = flags; 8973 return super.queryIntent(intent, resolvedType, 8974 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8975 } 8976 8977 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8978 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8979 if (!sUserManager.exists(userId)) 8980 return null; 8981 if (packageProviders == null) { 8982 return null; 8983 } 8984 mFlags = flags; 8985 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8986 final int N = packageProviders.size(); 8987 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8988 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8989 8990 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8991 for (int i = 0; i < N; ++i) { 8992 intentFilters = packageProviders.get(i).intents; 8993 if (intentFilters != null && intentFilters.size() > 0) { 8994 PackageParser.ProviderIntentInfo[] array = 8995 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8996 intentFilters.toArray(array); 8997 listCut.add(array); 8998 } 8999 } 9000 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9001 } 9002 9003 public final void addProvider(PackageParser.Provider p) { 9004 if (mProviders.containsKey(p.getComponentName())) { 9005 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9006 return; 9007 } 9008 9009 mProviders.put(p.getComponentName(), p); 9010 if (DEBUG_SHOW_INFO) { 9011 Log.v(TAG, " " 9012 + (p.info.nonLocalizedLabel != null 9013 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9014 Log.v(TAG, " Class=" + p.info.name); 9015 } 9016 final int NI = p.intents.size(); 9017 int j; 9018 for (j = 0; j < NI; j++) { 9019 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9020 if (DEBUG_SHOW_INFO) { 9021 Log.v(TAG, " IntentFilter:"); 9022 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9023 } 9024 if (!intent.debugCheck()) { 9025 Log.w(TAG, "==> For Provider " + p.info.name); 9026 } 9027 addFilter(intent); 9028 } 9029 } 9030 9031 public final void removeProvider(PackageParser.Provider p) { 9032 mProviders.remove(p.getComponentName()); 9033 if (DEBUG_SHOW_INFO) { 9034 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9035 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9036 Log.v(TAG, " Class=" + p.info.name); 9037 } 9038 final int NI = p.intents.size(); 9039 int j; 9040 for (j = 0; j < NI; j++) { 9041 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9042 if (DEBUG_SHOW_INFO) { 9043 Log.v(TAG, " IntentFilter:"); 9044 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9045 } 9046 removeFilter(intent); 9047 } 9048 } 9049 9050 @Override 9051 protected boolean allowFilterResult( 9052 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9053 ProviderInfo filterPi = filter.provider.info; 9054 for (int i = dest.size() - 1; i >= 0; i--) { 9055 ProviderInfo destPi = dest.get(i).providerInfo; 9056 if (destPi.name == filterPi.name 9057 && destPi.packageName == filterPi.packageName) { 9058 return false; 9059 } 9060 } 9061 return true; 9062 } 9063 9064 @Override 9065 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9066 return new PackageParser.ProviderIntentInfo[size]; 9067 } 9068 9069 @Override 9070 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9071 if (!sUserManager.exists(userId)) 9072 return true; 9073 PackageParser.Package p = filter.provider.owner; 9074 if (p != null) { 9075 PackageSetting ps = (PackageSetting) p.mExtras; 9076 if (ps != null) { 9077 // System apps are never considered stopped for purposes of 9078 // filtering, because there may be no way for the user to 9079 // actually re-launch them. 9080 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9081 && ps.getStopped(userId); 9082 } 9083 } 9084 return false; 9085 } 9086 9087 @Override 9088 protected boolean isPackageForFilter(String packageName, 9089 PackageParser.ProviderIntentInfo info) { 9090 return packageName.equals(info.provider.owner.packageName); 9091 } 9092 9093 @Override 9094 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9095 int match, int userId) { 9096 if (!sUserManager.exists(userId)) 9097 return null; 9098 final PackageParser.ProviderIntentInfo info = filter; 9099 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9100 return null; 9101 } 9102 final PackageParser.Provider provider = info.provider; 9103 if (mSafeMode && (provider.info.applicationInfo.flags 9104 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9105 return null; 9106 } 9107 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9108 if (ps == null) { 9109 return null; 9110 } 9111 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9112 ps.readUserState(userId), userId); 9113 if (pi == null) { 9114 return null; 9115 } 9116 final ResolveInfo res = new ResolveInfo(); 9117 res.providerInfo = pi; 9118 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9119 res.filter = filter; 9120 } 9121 res.priority = info.getPriority(); 9122 res.preferredOrder = provider.owner.mPreferredOrder; 9123 res.match = match; 9124 res.isDefault = info.hasDefault; 9125 res.labelRes = info.labelRes; 9126 res.nonLocalizedLabel = info.nonLocalizedLabel; 9127 res.icon = info.icon; 9128 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9129 return res; 9130 } 9131 9132 @Override 9133 protected void sortResults(List<ResolveInfo> results) { 9134 Collections.sort(results, mResolvePrioritySorter); 9135 } 9136 9137 @Override 9138 protected void dumpFilter(PrintWriter out, String prefix, 9139 PackageParser.ProviderIntentInfo filter) { 9140 out.print(prefix); 9141 out.print( 9142 Integer.toHexString(System.identityHashCode(filter.provider))); 9143 out.print(' '); 9144 filter.provider.printComponentShortName(out); 9145 out.print(" filter "); 9146 out.println(Integer.toHexString(System.identityHashCode(filter))); 9147 } 9148 9149 @Override 9150 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9151 return filter.provider; 9152 } 9153 9154 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9155 PackageParser.Provider provider = (PackageParser.Provider)label; 9156 out.print(prefix); out.print( 9157 Integer.toHexString(System.identityHashCode(provider))); 9158 out.print(' '); 9159 provider.printComponentShortName(out); 9160 if (count > 1) { 9161 out.print(" ("); out.print(count); out.print(" filters)"); 9162 } 9163 out.println(); 9164 } 9165 9166 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9167 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9168 private int mFlags; 9169 }; 9170 9171 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9172 new Comparator<ResolveInfo>() { 9173 public int compare(ResolveInfo r1, ResolveInfo r2) { 9174 int v1 = r1.priority; 9175 int v2 = r2.priority; 9176 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9177 if (v1 != v2) { 9178 return (v1 > v2) ? -1 : 1; 9179 } 9180 v1 = r1.preferredOrder; 9181 v2 = r2.preferredOrder; 9182 if (v1 != v2) { 9183 return (v1 > v2) ? -1 : 1; 9184 } 9185 if (r1.isDefault != r2.isDefault) { 9186 return r1.isDefault ? -1 : 1; 9187 } 9188 v1 = r1.match; 9189 v2 = r2.match; 9190 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9191 if (v1 != v2) { 9192 return (v1 > v2) ? -1 : 1; 9193 } 9194 if (r1.system != r2.system) { 9195 return r1.system ? -1 : 1; 9196 } 9197 return 0; 9198 } 9199 }; 9200 9201 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9202 new Comparator<ProviderInfo>() { 9203 public int compare(ProviderInfo p1, ProviderInfo p2) { 9204 final int v1 = p1.initOrder; 9205 final int v2 = p2.initOrder; 9206 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9207 } 9208 }; 9209 9210 final void sendPackageBroadcast(final String action, final String pkg, 9211 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9212 final int[] userIds) { 9213 mHandler.post(new Runnable() { 9214 @Override 9215 public void run() { 9216 try { 9217 final IActivityManager am = ActivityManagerNative.getDefault(); 9218 if (am == null) return; 9219 final int[] resolvedUserIds; 9220 if (userIds == null) { 9221 resolvedUserIds = am.getRunningUserIds(); 9222 } else { 9223 resolvedUserIds = userIds; 9224 } 9225 for (int id : resolvedUserIds) { 9226 final Intent intent = new Intent(action, 9227 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9228 if (extras != null) { 9229 intent.putExtras(extras); 9230 } 9231 if (targetPkg != null) { 9232 intent.setPackage(targetPkg); 9233 } 9234 // Modify the UID when posting to other users 9235 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9236 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9237 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9238 intent.putExtra(Intent.EXTRA_UID, uid); 9239 } 9240 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9241 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9242 if (DEBUG_BROADCASTS) { 9243 RuntimeException here = new RuntimeException("here"); 9244 here.fillInStackTrace(); 9245 Slog.d(TAG, "Sending to user " + id + ": " 9246 + intent.toShortString(false, true, false, false) 9247 + " " + intent.getExtras(), here); 9248 } 9249 am.broadcastIntent(null, intent, null, finishedReceiver, 9250 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9251 null, finishedReceiver != null, false, id); 9252 } 9253 } catch (RemoteException ex) { 9254 } 9255 } 9256 }); 9257 } 9258 9259 /** 9260 * Check if the external storage media is available. This is true if there 9261 * is a mounted external storage medium or if the external storage is 9262 * emulated. 9263 */ 9264 private boolean isExternalMediaAvailable() { 9265 return mMediaMounted || Environment.isExternalStorageEmulated(); 9266 } 9267 9268 @Override 9269 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9270 // writer 9271 synchronized (mPackages) { 9272 if (!isExternalMediaAvailable()) { 9273 // If the external storage is no longer mounted at this point, 9274 // the caller may not have been able to delete all of this 9275 // packages files and can not delete any more. Bail. 9276 return null; 9277 } 9278 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9279 if (lastPackage != null) { 9280 pkgs.remove(lastPackage); 9281 } 9282 if (pkgs.size() > 0) { 9283 return pkgs.get(0); 9284 } 9285 } 9286 return null; 9287 } 9288 9289 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9290 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9291 userId, andCode ? 1 : 0, packageName); 9292 if (mSystemReady) { 9293 msg.sendToTarget(); 9294 } else { 9295 if (mPostSystemReadyMessages == null) { 9296 mPostSystemReadyMessages = new ArrayList<>(); 9297 } 9298 mPostSystemReadyMessages.add(msg); 9299 } 9300 } 9301 9302 void startCleaningPackages() { 9303 // reader 9304 synchronized (mPackages) { 9305 if (!isExternalMediaAvailable()) { 9306 return; 9307 } 9308 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9309 return; 9310 } 9311 } 9312 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9313 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9314 IActivityManager am = ActivityManagerNative.getDefault(); 9315 if (am != null) { 9316 try { 9317 am.startService(null, intent, null, mContext.getOpPackageName(), 9318 UserHandle.USER_OWNER); 9319 } catch (RemoteException e) { 9320 } 9321 } 9322 } 9323 9324 @Override 9325 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9326 int installFlags, String installerPackageName, VerificationParams verificationParams, 9327 String packageAbiOverride) { 9328 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9329 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9330 } 9331 9332 @Override 9333 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9334 int installFlags, String installerPackageName, VerificationParams verificationParams, 9335 String packageAbiOverride, int userId) { 9336 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9337 9338 final int callingUid = Binder.getCallingUid(); 9339 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9340 9341 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9342 try { 9343 if (observer != null) { 9344 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9345 } 9346 } catch (RemoteException re) { 9347 } 9348 return; 9349 } 9350 9351 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9352 installFlags |= PackageManager.INSTALL_FROM_ADB; 9353 9354 } else { 9355 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9356 // about installerPackageName. 9357 9358 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9359 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9360 } 9361 9362 UserHandle user; 9363 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9364 user = UserHandle.ALL; 9365 } else { 9366 user = new UserHandle(userId); 9367 } 9368 9369 // Only system components can circumvent runtime permissions when installing. 9370 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9371 && mContext.checkCallingOrSelfPermission(Manifest.permission 9372 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9373 throw new SecurityException("You need the " 9374 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9375 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9376 } 9377 9378 verificationParams.setInstallerUid(callingUid); 9379 9380 final File originFile = new File(originPath); 9381 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9382 9383 final Message msg = mHandler.obtainMessage(INIT_COPY); 9384 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9385 null, verificationParams, user, packageAbiOverride); 9386 mHandler.sendMessage(msg); 9387 } 9388 9389 void installStage(String packageName, File stagedDir, String stagedCid, 9390 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9391 String installerPackageName, int installerUid, UserHandle user) { 9392 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9393 params.referrerUri, installerUid, null); 9394 verifParams.setInstallerUid(installerUid); 9395 9396 final OriginInfo origin; 9397 if (stagedDir != null) { 9398 origin = OriginInfo.fromStagedFile(stagedDir); 9399 } else { 9400 origin = OriginInfo.fromStagedContainer(stagedCid); 9401 } 9402 9403 final Message msg = mHandler.obtainMessage(INIT_COPY); 9404 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9405 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9406 mHandler.sendMessage(msg); 9407 } 9408 9409 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9410 Bundle extras = new Bundle(1); 9411 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9412 9413 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9414 packageName, extras, null, null, new int[] {userId}); 9415 try { 9416 IActivityManager am = ActivityManagerNative.getDefault(); 9417 final boolean isSystem = 9418 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9419 if (isSystem && am.isUserRunning(userId, false)) { 9420 // The just-installed/enabled app is bundled on the system, so presumed 9421 // to be able to run automatically without needing an explicit launch. 9422 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9423 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9424 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9425 .setPackage(packageName); 9426 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9427 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9428 } 9429 } catch (RemoteException e) { 9430 // shouldn't happen 9431 Slog.w(TAG, "Unable to bootstrap installed package", e); 9432 } 9433 } 9434 9435 @Override 9436 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9437 int userId) { 9438 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9439 PackageSetting pkgSetting; 9440 final int uid = Binder.getCallingUid(); 9441 enforceCrossUserPermission(uid, userId, true, true, 9442 "setApplicationHiddenSetting for user " + userId); 9443 9444 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9445 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9446 return false; 9447 } 9448 9449 long callingId = Binder.clearCallingIdentity(); 9450 try { 9451 boolean sendAdded = false; 9452 boolean sendRemoved = false; 9453 // writer 9454 synchronized (mPackages) { 9455 pkgSetting = mSettings.mPackages.get(packageName); 9456 if (pkgSetting == null) { 9457 return false; 9458 } 9459 if (pkgSetting.getHidden(userId) != hidden) { 9460 pkgSetting.setHidden(hidden, userId); 9461 mSettings.writePackageRestrictionsLPr(userId); 9462 if (hidden) { 9463 sendRemoved = true; 9464 } else { 9465 sendAdded = true; 9466 } 9467 } 9468 } 9469 if (sendAdded) { 9470 sendPackageAddedForUser(packageName, pkgSetting, userId); 9471 return true; 9472 } 9473 if (sendRemoved) { 9474 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9475 "hiding pkg"); 9476 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9477 } 9478 } finally { 9479 Binder.restoreCallingIdentity(callingId); 9480 } 9481 return false; 9482 } 9483 9484 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9485 int userId) { 9486 final PackageRemovedInfo info = new PackageRemovedInfo(); 9487 info.removedPackage = packageName; 9488 info.removedUsers = new int[] {userId}; 9489 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9490 info.sendBroadcast(false, false, false); 9491 } 9492 9493 /** 9494 * Returns true if application is not found or there was an error. Otherwise it returns 9495 * the hidden state of the package for the given user. 9496 */ 9497 @Override 9498 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9499 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9500 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9501 false, "getApplicationHidden for user " + userId); 9502 PackageSetting pkgSetting; 9503 long callingId = Binder.clearCallingIdentity(); 9504 try { 9505 // writer 9506 synchronized (mPackages) { 9507 pkgSetting = mSettings.mPackages.get(packageName); 9508 if (pkgSetting == null) { 9509 return true; 9510 } 9511 return pkgSetting.getHidden(userId); 9512 } 9513 } finally { 9514 Binder.restoreCallingIdentity(callingId); 9515 } 9516 } 9517 9518 /** 9519 * @hide 9520 */ 9521 @Override 9522 public int installExistingPackageAsUser(String packageName, int userId) { 9523 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9524 null); 9525 PackageSetting pkgSetting; 9526 final int uid = Binder.getCallingUid(); 9527 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9528 + userId); 9529 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9530 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9531 } 9532 9533 long callingId = Binder.clearCallingIdentity(); 9534 try { 9535 boolean sendAdded = false; 9536 9537 // writer 9538 synchronized (mPackages) { 9539 pkgSetting = mSettings.mPackages.get(packageName); 9540 if (pkgSetting == null) { 9541 return PackageManager.INSTALL_FAILED_INVALID_URI; 9542 } 9543 if (!pkgSetting.getInstalled(userId)) { 9544 pkgSetting.setInstalled(true, userId); 9545 pkgSetting.setHidden(false, userId); 9546 mSettings.writePackageRestrictionsLPr(userId); 9547 sendAdded = true; 9548 } 9549 } 9550 9551 if (sendAdded) { 9552 sendPackageAddedForUser(packageName, pkgSetting, userId); 9553 } 9554 } finally { 9555 Binder.restoreCallingIdentity(callingId); 9556 } 9557 9558 return PackageManager.INSTALL_SUCCEEDED; 9559 } 9560 9561 boolean isUserRestricted(int userId, String restrictionKey) { 9562 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9563 if (restrictions.getBoolean(restrictionKey, false)) { 9564 Log.w(TAG, "User is restricted: " + restrictionKey); 9565 return true; 9566 } 9567 return false; 9568 } 9569 9570 @Override 9571 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9572 mContext.enforceCallingOrSelfPermission( 9573 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9574 "Only package verification agents can verify applications"); 9575 9576 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9577 final PackageVerificationResponse response = new PackageVerificationResponse( 9578 verificationCode, Binder.getCallingUid()); 9579 msg.arg1 = id; 9580 msg.obj = response; 9581 mHandler.sendMessage(msg); 9582 } 9583 9584 @Override 9585 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9586 long millisecondsToDelay) { 9587 mContext.enforceCallingOrSelfPermission( 9588 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9589 "Only package verification agents can extend verification timeouts"); 9590 9591 final PackageVerificationState state = mPendingVerification.get(id); 9592 final PackageVerificationResponse response = new PackageVerificationResponse( 9593 verificationCodeAtTimeout, Binder.getCallingUid()); 9594 9595 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9596 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9597 } 9598 if (millisecondsToDelay < 0) { 9599 millisecondsToDelay = 0; 9600 } 9601 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9602 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9603 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9604 } 9605 9606 if ((state != null) && !state.timeoutExtended()) { 9607 state.extendTimeout(); 9608 9609 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9610 msg.arg1 = id; 9611 msg.obj = response; 9612 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9613 } 9614 } 9615 9616 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9617 int verificationCode, UserHandle user) { 9618 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9619 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9620 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9621 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9622 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9623 9624 mContext.sendBroadcastAsUser(intent, user, 9625 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9626 } 9627 9628 private ComponentName matchComponentForVerifier(String packageName, 9629 List<ResolveInfo> receivers) { 9630 ActivityInfo targetReceiver = null; 9631 9632 final int NR = receivers.size(); 9633 for (int i = 0; i < NR; i++) { 9634 final ResolveInfo info = receivers.get(i); 9635 if (info.activityInfo == null) { 9636 continue; 9637 } 9638 9639 if (packageName.equals(info.activityInfo.packageName)) { 9640 targetReceiver = info.activityInfo; 9641 break; 9642 } 9643 } 9644 9645 if (targetReceiver == null) { 9646 return null; 9647 } 9648 9649 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9650 } 9651 9652 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9653 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9654 if (pkgInfo.verifiers.length == 0) { 9655 return null; 9656 } 9657 9658 final int N = pkgInfo.verifiers.length; 9659 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9660 for (int i = 0; i < N; i++) { 9661 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9662 9663 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9664 receivers); 9665 if (comp == null) { 9666 continue; 9667 } 9668 9669 final int verifierUid = getUidForVerifier(verifierInfo); 9670 if (verifierUid == -1) { 9671 continue; 9672 } 9673 9674 if (DEBUG_VERIFY) { 9675 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9676 + " with the correct signature"); 9677 } 9678 sufficientVerifiers.add(comp); 9679 verificationState.addSufficientVerifier(verifierUid); 9680 } 9681 9682 return sufficientVerifiers; 9683 } 9684 9685 private int getUidForVerifier(VerifierInfo verifierInfo) { 9686 synchronized (mPackages) { 9687 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9688 if (pkg == null) { 9689 return -1; 9690 } else if (pkg.mSignatures.length != 1) { 9691 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9692 + " has more than one signature; ignoring"); 9693 return -1; 9694 } 9695 9696 /* 9697 * If the public key of the package's signature does not match 9698 * our expected public key, then this is a different package and 9699 * we should skip. 9700 */ 9701 9702 final byte[] expectedPublicKey; 9703 try { 9704 final Signature verifierSig = pkg.mSignatures[0]; 9705 final PublicKey publicKey = verifierSig.getPublicKey(); 9706 expectedPublicKey = publicKey.getEncoded(); 9707 } catch (CertificateException e) { 9708 return -1; 9709 } 9710 9711 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9712 9713 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9714 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9715 + " does not have the expected public key; ignoring"); 9716 return -1; 9717 } 9718 9719 return pkg.applicationInfo.uid; 9720 } 9721 } 9722 9723 @Override 9724 public void finishPackageInstall(int token) { 9725 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9726 9727 if (DEBUG_INSTALL) { 9728 Slog.v(TAG, "BM finishing package install for " + token); 9729 } 9730 9731 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9732 mHandler.sendMessage(msg); 9733 } 9734 9735 /** 9736 * Get the verification agent timeout. 9737 * 9738 * @return verification timeout in milliseconds 9739 */ 9740 private long getVerificationTimeout() { 9741 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9742 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9743 DEFAULT_VERIFICATION_TIMEOUT); 9744 } 9745 9746 /** 9747 * Get the default verification agent response code. 9748 * 9749 * @return default verification response code 9750 */ 9751 private int getDefaultVerificationResponse() { 9752 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9753 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9754 DEFAULT_VERIFICATION_RESPONSE); 9755 } 9756 9757 /** 9758 * Check whether or not package verification has been enabled. 9759 * 9760 * @return true if verification should be performed 9761 */ 9762 private boolean isVerificationEnabled(int userId, int installFlags) { 9763 if (!DEFAULT_VERIFY_ENABLE) { 9764 return false; 9765 } 9766 9767 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9768 9769 // Check if installing from ADB 9770 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9771 // Do not run verification in a test harness environment 9772 if (ActivityManager.isRunningInTestHarness()) { 9773 return false; 9774 } 9775 if (ensureVerifyAppsEnabled) { 9776 return true; 9777 } 9778 // Check if the developer does not want package verification for ADB installs 9779 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9780 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9781 return false; 9782 } 9783 } 9784 9785 if (ensureVerifyAppsEnabled) { 9786 return true; 9787 } 9788 9789 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9790 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9791 } 9792 9793 @Override 9794 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9795 throws RemoteException { 9796 mContext.enforceCallingOrSelfPermission( 9797 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9798 "Only intentfilter verification agents can verify applications"); 9799 9800 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9801 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9802 Binder.getCallingUid(), verificationCode, failedDomains); 9803 msg.arg1 = id; 9804 msg.obj = response; 9805 mHandler.sendMessage(msg); 9806 } 9807 9808 @Override 9809 public int getIntentVerificationStatus(String packageName, int userId) { 9810 synchronized (mPackages) { 9811 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9812 } 9813 } 9814 9815 @Override 9816 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9817 mContext.enforceCallingOrSelfPermission( 9818 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9819 9820 boolean result = false; 9821 synchronized (mPackages) { 9822 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9823 } 9824 if (result) { 9825 scheduleWritePackageRestrictionsLocked(userId); 9826 } 9827 return result; 9828 } 9829 9830 @Override 9831 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9832 synchronized (mPackages) { 9833 return mSettings.getIntentFilterVerificationsLPr(packageName); 9834 } 9835 } 9836 9837 @Override 9838 public List<IntentFilter> getAllIntentFilters(String packageName) { 9839 if (TextUtils.isEmpty(packageName)) { 9840 return Collections.<IntentFilter>emptyList(); 9841 } 9842 synchronized (mPackages) { 9843 PackageParser.Package pkg = mPackages.get(packageName); 9844 if (pkg == null || pkg.activities == null) { 9845 return Collections.<IntentFilter>emptyList(); 9846 } 9847 final int count = pkg.activities.size(); 9848 ArrayList<IntentFilter> result = new ArrayList<>(); 9849 for (int n=0; n<count; n++) { 9850 PackageParser.Activity activity = pkg.activities.get(n); 9851 if (activity.intents != null || activity.intents.size() > 0) { 9852 result.addAll(activity.intents); 9853 } 9854 } 9855 return result; 9856 } 9857 } 9858 9859 @Override 9860 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9861 mContext.enforceCallingOrSelfPermission( 9862 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9863 9864 synchronized (mPackages) { 9865 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9866 if (packageName != null) { 9867 result |= updateIntentVerificationStatus(packageName, 9868 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9869 UserHandle.myUserId()); 9870 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9871 packageName, userId); 9872 } 9873 return result; 9874 } 9875 } 9876 9877 @Override 9878 public String getDefaultBrowserPackageName(int userId) { 9879 synchronized (mPackages) { 9880 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9881 } 9882 } 9883 9884 /** 9885 * Get the "allow unknown sources" setting. 9886 * 9887 * @return the current "allow unknown sources" setting 9888 */ 9889 private int getUnknownSourcesSettings() { 9890 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9891 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9892 -1); 9893 } 9894 9895 @Override 9896 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9897 final int uid = Binder.getCallingUid(); 9898 // writer 9899 synchronized (mPackages) { 9900 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9901 if (targetPackageSetting == null) { 9902 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9903 } 9904 9905 PackageSetting installerPackageSetting; 9906 if (installerPackageName != null) { 9907 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9908 if (installerPackageSetting == null) { 9909 throw new IllegalArgumentException("Unknown installer package: " 9910 + installerPackageName); 9911 } 9912 } else { 9913 installerPackageSetting = null; 9914 } 9915 9916 Signature[] callerSignature; 9917 Object obj = mSettings.getUserIdLPr(uid); 9918 if (obj != null) { 9919 if (obj instanceof SharedUserSetting) { 9920 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9921 } else if (obj instanceof PackageSetting) { 9922 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9923 } else { 9924 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9925 } 9926 } else { 9927 throw new SecurityException("Unknown calling uid " + uid); 9928 } 9929 9930 // Verify: can't set installerPackageName to a package that is 9931 // not signed with the same cert as the caller. 9932 if (installerPackageSetting != null) { 9933 if (compareSignatures(callerSignature, 9934 installerPackageSetting.signatures.mSignatures) 9935 != PackageManager.SIGNATURE_MATCH) { 9936 throw new SecurityException( 9937 "Caller does not have same cert as new installer package " 9938 + installerPackageName); 9939 } 9940 } 9941 9942 // Verify: if target already has an installer package, it must 9943 // be signed with the same cert as the caller. 9944 if (targetPackageSetting.installerPackageName != null) { 9945 PackageSetting setting = mSettings.mPackages.get( 9946 targetPackageSetting.installerPackageName); 9947 // If the currently set package isn't valid, then it's always 9948 // okay to change it. 9949 if (setting != null) { 9950 if (compareSignatures(callerSignature, 9951 setting.signatures.mSignatures) 9952 != PackageManager.SIGNATURE_MATCH) { 9953 throw new SecurityException( 9954 "Caller does not have same cert as old installer package " 9955 + targetPackageSetting.installerPackageName); 9956 } 9957 } 9958 } 9959 9960 // Okay! 9961 targetPackageSetting.installerPackageName = installerPackageName; 9962 scheduleWriteSettingsLocked(); 9963 } 9964 } 9965 9966 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9967 // Queue up an async operation since the package installation may take a little while. 9968 mHandler.post(new Runnable() { 9969 public void run() { 9970 mHandler.removeCallbacks(this); 9971 // Result object to be returned 9972 PackageInstalledInfo res = new PackageInstalledInfo(); 9973 res.returnCode = currentStatus; 9974 res.uid = -1; 9975 res.pkg = null; 9976 res.removedInfo = new PackageRemovedInfo(); 9977 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9978 args.doPreInstall(res.returnCode); 9979 synchronized (mInstallLock) { 9980 installPackageLI(args, res); 9981 } 9982 args.doPostInstall(res.returnCode, res.uid); 9983 } 9984 9985 // A restore should be performed at this point if (a) the install 9986 // succeeded, (b) the operation is not an update, and (c) the new 9987 // package has not opted out of backup participation. 9988 final boolean update = res.removedInfo.removedPackage != null; 9989 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9990 boolean doRestore = !update 9991 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9992 9993 // Set up the post-install work request bookkeeping. This will be used 9994 // and cleaned up by the post-install event handling regardless of whether 9995 // there's a restore pass performed. Token values are >= 1. 9996 int token; 9997 if (mNextInstallToken < 0) mNextInstallToken = 1; 9998 token = mNextInstallToken++; 9999 10000 PostInstallData data = new PostInstallData(args, res); 10001 mRunningInstalls.put(token, data); 10002 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10003 10004 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10005 // Pass responsibility to the Backup Manager. It will perform a 10006 // restore if appropriate, then pass responsibility back to the 10007 // Package Manager to run the post-install observer callbacks 10008 // and broadcasts. 10009 IBackupManager bm = IBackupManager.Stub.asInterface( 10010 ServiceManager.getService(Context.BACKUP_SERVICE)); 10011 if (bm != null) { 10012 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10013 + " to BM for possible restore"); 10014 try { 10015 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10016 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10017 } else { 10018 doRestore = false; 10019 } 10020 } catch (RemoteException e) { 10021 // can't happen; the backup manager is local 10022 } catch (Exception e) { 10023 Slog.e(TAG, "Exception trying to enqueue restore", e); 10024 doRestore = false; 10025 } 10026 } else { 10027 Slog.e(TAG, "Backup Manager not found!"); 10028 doRestore = false; 10029 } 10030 } 10031 10032 if (!doRestore) { 10033 // No restore possible, or the Backup Manager was mysteriously not 10034 // available -- just fire the post-install work request directly. 10035 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10036 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10037 mHandler.sendMessage(msg); 10038 } 10039 } 10040 }); 10041 } 10042 10043 private abstract class HandlerParams { 10044 private static final int MAX_RETRIES = 4; 10045 10046 /** 10047 * Number of times startCopy() has been attempted and had a non-fatal 10048 * error. 10049 */ 10050 private int mRetries = 0; 10051 10052 /** User handle for the user requesting the information or installation. */ 10053 private final UserHandle mUser; 10054 10055 HandlerParams(UserHandle user) { 10056 mUser = user; 10057 } 10058 10059 UserHandle getUser() { 10060 return mUser; 10061 } 10062 10063 final boolean startCopy() { 10064 boolean res; 10065 try { 10066 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10067 10068 if (++mRetries > MAX_RETRIES) { 10069 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10070 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10071 handleServiceError(); 10072 return false; 10073 } else { 10074 handleStartCopy(); 10075 res = true; 10076 } 10077 } catch (RemoteException e) { 10078 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10079 mHandler.sendEmptyMessage(MCS_RECONNECT); 10080 res = false; 10081 } 10082 handleReturnCode(); 10083 return res; 10084 } 10085 10086 final void serviceError() { 10087 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10088 handleServiceError(); 10089 handleReturnCode(); 10090 } 10091 10092 abstract void handleStartCopy() throws RemoteException; 10093 abstract void handleServiceError(); 10094 abstract void handleReturnCode(); 10095 } 10096 10097 class MeasureParams extends HandlerParams { 10098 private final PackageStats mStats; 10099 private boolean mSuccess; 10100 10101 private final IPackageStatsObserver mObserver; 10102 10103 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10104 super(new UserHandle(stats.userHandle)); 10105 mObserver = observer; 10106 mStats = stats; 10107 } 10108 10109 @Override 10110 public String toString() { 10111 return "MeasureParams{" 10112 + Integer.toHexString(System.identityHashCode(this)) 10113 + " " + mStats.packageName + "}"; 10114 } 10115 10116 @Override 10117 void handleStartCopy() throws RemoteException { 10118 synchronized (mInstallLock) { 10119 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10120 } 10121 10122 if (mSuccess) { 10123 final boolean mounted; 10124 if (Environment.isExternalStorageEmulated()) { 10125 mounted = true; 10126 } else { 10127 final String status = Environment.getExternalStorageState(); 10128 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10129 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10130 } 10131 10132 if (mounted) { 10133 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10134 10135 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10136 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10137 10138 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10139 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10140 10141 // Always subtract cache size, since it's a subdirectory 10142 mStats.externalDataSize -= mStats.externalCacheSize; 10143 10144 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10145 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10146 10147 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10148 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10149 } 10150 } 10151 } 10152 10153 @Override 10154 void handleReturnCode() { 10155 if (mObserver != null) { 10156 try { 10157 mObserver.onGetStatsCompleted(mStats, mSuccess); 10158 } catch (RemoteException e) { 10159 Slog.i(TAG, "Observer no longer exists."); 10160 } 10161 } 10162 } 10163 10164 @Override 10165 void handleServiceError() { 10166 Slog.e(TAG, "Could not measure application " + mStats.packageName 10167 + " external storage"); 10168 } 10169 } 10170 10171 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10172 throws RemoteException { 10173 long result = 0; 10174 for (File path : paths) { 10175 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10176 } 10177 return result; 10178 } 10179 10180 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10181 for (File path : paths) { 10182 try { 10183 mcs.clearDirectory(path.getAbsolutePath()); 10184 } catch (RemoteException e) { 10185 } 10186 } 10187 } 10188 10189 static class OriginInfo { 10190 /** 10191 * Location where install is coming from, before it has been 10192 * copied/renamed into place. This could be a single monolithic APK 10193 * file, or a cluster directory. This location may be untrusted. 10194 */ 10195 final File file; 10196 final String cid; 10197 10198 /** 10199 * Flag indicating that {@link #file} or {@link #cid} has already been 10200 * staged, meaning downstream users don't need to defensively copy the 10201 * contents. 10202 */ 10203 final boolean staged; 10204 10205 /** 10206 * Flag indicating that {@link #file} or {@link #cid} is an already 10207 * installed app that is being moved. 10208 */ 10209 final boolean existing; 10210 10211 final String resolvedPath; 10212 final File resolvedFile; 10213 10214 static OriginInfo fromNothing() { 10215 return new OriginInfo(null, null, false, false); 10216 } 10217 10218 static OriginInfo fromUntrustedFile(File file) { 10219 return new OriginInfo(file, null, false, false); 10220 } 10221 10222 static OriginInfo fromExistingFile(File file) { 10223 return new OriginInfo(file, null, false, true); 10224 } 10225 10226 static OriginInfo fromStagedFile(File file) { 10227 return new OriginInfo(file, null, true, false); 10228 } 10229 10230 static OriginInfo fromStagedContainer(String cid) { 10231 return new OriginInfo(null, cid, true, false); 10232 } 10233 10234 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10235 this.file = file; 10236 this.cid = cid; 10237 this.staged = staged; 10238 this.existing = existing; 10239 10240 if (cid != null) { 10241 resolvedPath = PackageHelper.getSdDir(cid); 10242 resolvedFile = new File(resolvedPath); 10243 } else if (file != null) { 10244 resolvedPath = file.getAbsolutePath(); 10245 resolvedFile = file; 10246 } else { 10247 resolvedPath = null; 10248 resolvedFile = null; 10249 } 10250 } 10251 } 10252 10253 class MoveInfo { 10254 final int moveId; 10255 final String fromUuid; 10256 final String toUuid; 10257 final String packageName; 10258 final String dataAppName; 10259 final int appId; 10260 final String seinfo; 10261 10262 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10263 String dataAppName, int appId, String seinfo) { 10264 this.moveId = moveId; 10265 this.fromUuid = fromUuid; 10266 this.toUuid = toUuid; 10267 this.packageName = packageName; 10268 this.dataAppName = dataAppName; 10269 this.appId = appId; 10270 this.seinfo = seinfo; 10271 } 10272 } 10273 10274 class InstallParams extends HandlerParams { 10275 final OriginInfo origin; 10276 final MoveInfo move; 10277 final IPackageInstallObserver2 observer; 10278 int installFlags; 10279 final String installerPackageName; 10280 final String volumeUuid; 10281 final VerificationParams verificationParams; 10282 private InstallArgs mArgs; 10283 private int mRet; 10284 final String packageAbiOverride; 10285 10286 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10287 int installFlags, String installerPackageName, String volumeUuid, 10288 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10289 super(user); 10290 this.origin = origin; 10291 this.move = move; 10292 this.observer = observer; 10293 this.installFlags = installFlags; 10294 this.installerPackageName = installerPackageName; 10295 this.volumeUuid = volumeUuid; 10296 this.verificationParams = verificationParams; 10297 this.packageAbiOverride = packageAbiOverride; 10298 } 10299 10300 @Override 10301 public String toString() { 10302 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10303 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10304 } 10305 10306 public ManifestDigest getManifestDigest() { 10307 if (verificationParams == null) { 10308 return null; 10309 } 10310 return verificationParams.getManifestDigest(); 10311 } 10312 10313 private int installLocationPolicy(PackageInfoLite pkgLite) { 10314 String packageName = pkgLite.packageName; 10315 int installLocation = pkgLite.installLocation; 10316 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10317 // reader 10318 synchronized (mPackages) { 10319 PackageParser.Package pkg = mPackages.get(packageName); 10320 if (pkg != null) { 10321 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10322 // Check for downgrading. 10323 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10324 try { 10325 checkDowngrade(pkg, pkgLite); 10326 } catch (PackageManagerException e) { 10327 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10328 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10329 } 10330 } 10331 // Check for updated system application. 10332 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10333 if (onSd) { 10334 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10335 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10336 } 10337 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10338 } else { 10339 if (onSd) { 10340 // Install flag overrides everything. 10341 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10342 } 10343 // If current upgrade specifies particular preference 10344 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10345 // Application explicitly specified internal. 10346 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10347 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10348 // App explictly prefers external. Let policy decide 10349 } else { 10350 // Prefer previous location 10351 if (isExternal(pkg)) { 10352 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10353 } 10354 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10355 } 10356 } 10357 } else { 10358 // Invalid install. Return error code 10359 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10360 } 10361 } 10362 } 10363 // All the special cases have been taken care of. 10364 // Return result based on recommended install location. 10365 if (onSd) { 10366 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10367 } 10368 return pkgLite.recommendedInstallLocation; 10369 } 10370 10371 /* 10372 * Invoke remote method to get package information and install 10373 * location values. Override install location based on default 10374 * policy if needed and then create install arguments based 10375 * on the install location. 10376 */ 10377 public void handleStartCopy() throws RemoteException { 10378 int ret = PackageManager.INSTALL_SUCCEEDED; 10379 10380 // If we're already staged, we've firmly committed to an install location 10381 if (origin.staged) { 10382 if (origin.file != null) { 10383 installFlags |= PackageManager.INSTALL_INTERNAL; 10384 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10385 } else if (origin.cid != null) { 10386 installFlags |= PackageManager.INSTALL_EXTERNAL; 10387 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10388 } else { 10389 throw new IllegalStateException("Invalid stage location"); 10390 } 10391 } 10392 10393 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10394 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10395 10396 PackageInfoLite pkgLite = null; 10397 10398 if (onInt && onSd) { 10399 // Check if both bits are set. 10400 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10401 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10402 } else { 10403 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10404 packageAbiOverride); 10405 10406 /* 10407 * If we have too little free space, try to free cache 10408 * before giving up. 10409 */ 10410 if (!origin.staged && pkgLite.recommendedInstallLocation 10411 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10412 // TODO: focus freeing disk space on the target device 10413 final StorageManager storage = StorageManager.from(mContext); 10414 final long lowThreshold = storage.getStorageLowBytes( 10415 Environment.getDataDirectory()); 10416 10417 final long sizeBytes = mContainerService.calculateInstalledSize( 10418 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10419 10420 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10421 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10422 installFlags, packageAbiOverride); 10423 } 10424 10425 /* 10426 * The cache free must have deleted the file we 10427 * downloaded to install. 10428 * 10429 * TODO: fix the "freeCache" call to not delete 10430 * the file we care about. 10431 */ 10432 if (pkgLite.recommendedInstallLocation 10433 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10434 pkgLite.recommendedInstallLocation 10435 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10436 } 10437 } 10438 } 10439 10440 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10441 int loc = pkgLite.recommendedInstallLocation; 10442 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10443 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10444 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10445 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10446 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10447 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10448 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10449 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10450 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10451 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10452 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10453 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10454 } else { 10455 // Override with defaults if needed. 10456 loc = installLocationPolicy(pkgLite); 10457 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10458 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10459 } else if (!onSd && !onInt) { 10460 // Override install location with flags 10461 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10462 // Set the flag to install on external media. 10463 installFlags |= PackageManager.INSTALL_EXTERNAL; 10464 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10465 } else { 10466 // Make sure the flag for installing on external 10467 // media is unset 10468 installFlags |= PackageManager.INSTALL_INTERNAL; 10469 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10470 } 10471 } 10472 } 10473 } 10474 10475 final InstallArgs args = createInstallArgs(this); 10476 mArgs = args; 10477 10478 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10479 /* 10480 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10481 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10482 */ 10483 int userIdentifier = getUser().getIdentifier(); 10484 if (userIdentifier == UserHandle.USER_ALL 10485 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10486 userIdentifier = UserHandle.USER_OWNER; 10487 } 10488 10489 /* 10490 * Determine if we have any installed package verifiers. If we 10491 * do, then we'll defer to them to verify the packages. 10492 */ 10493 final int requiredUid = mRequiredVerifierPackage == null ? -1 10494 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10495 if (!origin.existing && requiredUid != -1 10496 && isVerificationEnabled(userIdentifier, installFlags)) { 10497 final Intent verification = new Intent( 10498 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10499 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10500 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10501 PACKAGE_MIME_TYPE); 10502 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10503 10504 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10505 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10506 0 /* TODO: Which userId? */); 10507 10508 if (DEBUG_VERIFY) { 10509 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10510 + verification.toString() + " with " + pkgLite.verifiers.length 10511 + " optional verifiers"); 10512 } 10513 10514 final int verificationId = mPendingVerificationToken++; 10515 10516 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10517 10518 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10519 installerPackageName); 10520 10521 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10522 installFlags); 10523 10524 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10525 pkgLite.packageName); 10526 10527 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10528 pkgLite.versionCode); 10529 10530 if (verificationParams != null) { 10531 if (verificationParams.getVerificationURI() != null) { 10532 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10533 verificationParams.getVerificationURI()); 10534 } 10535 if (verificationParams.getOriginatingURI() != null) { 10536 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10537 verificationParams.getOriginatingURI()); 10538 } 10539 if (verificationParams.getReferrer() != null) { 10540 verification.putExtra(Intent.EXTRA_REFERRER, 10541 verificationParams.getReferrer()); 10542 } 10543 if (verificationParams.getOriginatingUid() >= 0) { 10544 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10545 verificationParams.getOriginatingUid()); 10546 } 10547 if (verificationParams.getInstallerUid() >= 0) { 10548 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10549 verificationParams.getInstallerUid()); 10550 } 10551 } 10552 10553 final PackageVerificationState verificationState = new PackageVerificationState( 10554 requiredUid, args); 10555 10556 mPendingVerification.append(verificationId, verificationState); 10557 10558 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10559 receivers, verificationState); 10560 10561 /* 10562 * If any sufficient verifiers were listed in the package 10563 * manifest, attempt to ask them. 10564 */ 10565 if (sufficientVerifiers != null) { 10566 final int N = sufficientVerifiers.size(); 10567 if (N == 0) { 10568 Slog.i(TAG, "Additional verifiers required, but none installed."); 10569 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10570 } else { 10571 for (int i = 0; i < N; i++) { 10572 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10573 10574 final Intent sufficientIntent = new Intent(verification); 10575 sufficientIntent.setComponent(verifierComponent); 10576 10577 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10578 } 10579 } 10580 } 10581 10582 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10583 mRequiredVerifierPackage, receivers); 10584 if (ret == PackageManager.INSTALL_SUCCEEDED 10585 && mRequiredVerifierPackage != null) { 10586 /* 10587 * Send the intent to the required verification agent, 10588 * but only start the verification timeout after the 10589 * target BroadcastReceivers have run. 10590 */ 10591 verification.setComponent(requiredVerifierComponent); 10592 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10593 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10594 new BroadcastReceiver() { 10595 @Override 10596 public void onReceive(Context context, Intent intent) { 10597 final Message msg = mHandler 10598 .obtainMessage(CHECK_PENDING_VERIFICATION); 10599 msg.arg1 = verificationId; 10600 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10601 } 10602 }, null, 0, null, null); 10603 10604 /* 10605 * We don't want the copy to proceed until verification 10606 * succeeds, so null out this field. 10607 */ 10608 mArgs = null; 10609 } 10610 } else { 10611 /* 10612 * No package verification is enabled, so immediately start 10613 * the remote call to initiate copy using temporary file. 10614 */ 10615 ret = args.copyApk(mContainerService, true); 10616 } 10617 } 10618 10619 mRet = ret; 10620 } 10621 10622 @Override 10623 void handleReturnCode() { 10624 // If mArgs is null, then MCS couldn't be reached. When it 10625 // reconnects, it will try again to install. At that point, this 10626 // will succeed. 10627 if (mArgs != null) { 10628 processPendingInstall(mArgs, mRet); 10629 } 10630 } 10631 10632 @Override 10633 void handleServiceError() { 10634 mArgs = createInstallArgs(this); 10635 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10636 } 10637 10638 public boolean isForwardLocked() { 10639 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10640 } 10641 } 10642 10643 /** 10644 * Used during creation of InstallArgs 10645 * 10646 * @param installFlags package installation flags 10647 * @return true if should be installed on external storage 10648 */ 10649 private static boolean installOnExternalAsec(int installFlags) { 10650 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10651 return false; 10652 } 10653 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10654 return true; 10655 } 10656 return false; 10657 } 10658 10659 /** 10660 * Used during creation of InstallArgs 10661 * 10662 * @param installFlags package installation flags 10663 * @return true if should be installed as forward locked 10664 */ 10665 private static boolean installForwardLocked(int installFlags) { 10666 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10667 } 10668 10669 private InstallArgs createInstallArgs(InstallParams params) { 10670 if (params.move != null) { 10671 return new MoveInstallArgs(params); 10672 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10673 return new AsecInstallArgs(params); 10674 } else { 10675 return new FileInstallArgs(params); 10676 } 10677 } 10678 10679 /** 10680 * Create args that describe an existing installed package. Typically used 10681 * when cleaning up old installs, or used as a move source. 10682 */ 10683 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10684 String resourcePath, String[] instructionSets) { 10685 final boolean isInAsec; 10686 if (installOnExternalAsec(installFlags)) { 10687 /* Apps on SD card are always in ASEC containers. */ 10688 isInAsec = true; 10689 } else if (installForwardLocked(installFlags) 10690 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10691 /* 10692 * Forward-locked apps are only in ASEC containers if they're the 10693 * new style 10694 */ 10695 isInAsec = true; 10696 } else { 10697 isInAsec = false; 10698 } 10699 10700 if (isInAsec) { 10701 return new AsecInstallArgs(codePath, instructionSets, 10702 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10703 } else { 10704 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10705 } 10706 } 10707 10708 static abstract class InstallArgs { 10709 /** @see InstallParams#origin */ 10710 final OriginInfo origin; 10711 /** @see InstallParams#move */ 10712 final MoveInfo move; 10713 10714 final IPackageInstallObserver2 observer; 10715 // Always refers to PackageManager flags only 10716 final int installFlags; 10717 final String installerPackageName; 10718 final String volumeUuid; 10719 final ManifestDigest manifestDigest; 10720 final UserHandle user; 10721 final String abiOverride; 10722 10723 // The list of instruction sets supported by this app. This is currently 10724 // only used during the rmdex() phase to clean up resources. We can get rid of this 10725 // if we move dex files under the common app path. 10726 /* nullable */ String[] instructionSets; 10727 10728 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10729 int installFlags, String installerPackageName, String volumeUuid, 10730 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10731 String abiOverride) { 10732 this.origin = origin; 10733 this.move = move; 10734 this.installFlags = installFlags; 10735 this.observer = observer; 10736 this.installerPackageName = installerPackageName; 10737 this.volumeUuid = volumeUuid; 10738 this.manifestDigest = manifestDigest; 10739 this.user = user; 10740 this.instructionSets = instructionSets; 10741 this.abiOverride = abiOverride; 10742 } 10743 10744 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10745 abstract int doPreInstall(int status); 10746 10747 /** 10748 * Rename package into final resting place. All paths on the given 10749 * scanned package should be updated to reflect the rename. 10750 */ 10751 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10752 abstract int doPostInstall(int status, int uid); 10753 10754 /** @see PackageSettingBase#codePathString */ 10755 abstract String getCodePath(); 10756 /** @see PackageSettingBase#resourcePathString */ 10757 abstract String getResourcePath(); 10758 10759 // Need installer lock especially for dex file removal. 10760 abstract void cleanUpResourcesLI(); 10761 abstract boolean doPostDeleteLI(boolean delete); 10762 10763 /** 10764 * Called before the source arguments are copied. This is used mostly 10765 * for MoveParams when it needs to read the source file to put it in the 10766 * destination. 10767 */ 10768 int doPreCopy() { 10769 return PackageManager.INSTALL_SUCCEEDED; 10770 } 10771 10772 /** 10773 * Called after the source arguments are copied. This is used mostly for 10774 * MoveParams when it needs to read the source file to put it in the 10775 * destination. 10776 * 10777 * @return 10778 */ 10779 int doPostCopy(int uid) { 10780 return PackageManager.INSTALL_SUCCEEDED; 10781 } 10782 10783 protected boolean isFwdLocked() { 10784 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10785 } 10786 10787 protected boolean isExternalAsec() { 10788 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10789 } 10790 10791 UserHandle getUser() { 10792 return user; 10793 } 10794 } 10795 10796 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10797 if (!allCodePaths.isEmpty()) { 10798 if (instructionSets == null) { 10799 throw new IllegalStateException("instructionSet == null"); 10800 } 10801 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10802 for (String codePath : allCodePaths) { 10803 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10804 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10805 if (retCode < 0) { 10806 Slog.w(TAG, "Couldn't remove dex file for package: " 10807 + " at location " + codePath + ", retcode=" + retCode); 10808 // we don't consider this to be a failure of the core package deletion 10809 } 10810 } 10811 } 10812 } 10813 } 10814 10815 /** 10816 * Logic to handle installation of non-ASEC applications, including copying 10817 * and renaming logic. 10818 */ 10819 class FileInstallArgs extends InstallArgs { 10820 private File codeFile; 10821 private File resourceFile; 10822 10823 // Example topology: 10824 // /data/app/com.example/base.apk 10825 // /data/app/com.example/split_foo.apk 10826 // /data/app/com.example/lib/arm/libfoo.so 10827 // /data/app/com.example/lib/arm64/libfoo.so 10828 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10829 10830 /** New install */ 10831 FileInstallArgs(InstallParams params) { 10832 super(params.origin, params.move, params.observer, params.installFlags, 10833 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10834 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10835 if (isFwdLocked()) { 10836 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10837 } 10838 } 10839 10840 /** Existing install */ 10841 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10842 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10843 null); 10844 this.codeFile = (codePath != null) ? new File(codePath) : null; 10845 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10846 } 10847 10848 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10849 if (origin.staged) { 10850 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10851 codeFile = origin.file; 10852 resourceFile = origin.file; 10853 return PackageManager.INSTALL_SUCCEEDED; 10854 } 10855 10856 try { 10857 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10858 codeFile = tempDir; 10859 resourceFile = tempDir; 10860 } catch (IOException e) { 10861 Slog.w(TAG, "Failed to create copy file: " + e); 10862 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10863 } 10864 10865 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10866 @Override 10867 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10868 if (!FileUtils.isValidExtFilename(name)) { 10869 throw new IllegalArgumentException("Invalid filename: " + name); 10870 } 10871 try { 10872 final File file = new File(codeFile, name); 10873 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10874 O_RDWR | O_CREAT, 0644); 10875 Os.chmod(file.getAbsolutePath(), 0644); 10876 return new ParcelFileDescriptor(fd); 10877 } catch (ErrnoException e) { 10878 throw new RemoteException("Failed to open: " + e.getMessage()); 10879 } 10880 } 10881 }; 10882 10883 int ret = PackageManager.INSTALL_SUCCEEDED; 10884 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10885 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10886 Slog.e(TAG, "Failed to copy package"); 10887 return ret; 10888 } 10889 10890 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10891 NativeLibraryHelper.Handle handle = null; 10892 try { 10893 handle = NativeLibraryHelper.Handle.create(codeFile); 10894 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10895 abiOverride); 10896 } catch (IOException e) { 10897 Slog.e(TAG, "Copying native libraries failed", e); 10898 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10899 } finally { 10900 IoUtils.closeQuietly(handle); 10901 } 10902 10903 return ret; 10904 } 10905 10906 int doPreInstall(int status) { 10907 if (status != PackageManager.INSTALL_SUCCEEDED) { 10908 cleanUp(); 10909 } 10910 return status; 10911 } 10912 10913 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10914 if (status != PackageManager.INSTALL_SUCCEEDED) { 10915 cleanUp(); 10916 return false; 10917 } 10918 10919 final File targetDir = codeFile.getParentFile(); 10920 final File beforeCodeFile = codeFile; 10921 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10922 10923 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10924 try { 10925 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10926 } catch (ErrnoException e) { 10927 Slog.w(TAG, "Failed to rename", e); 10928 return false; 10929 } 10930 10931 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10932 Slog.w(TAG, "Failed to restorecon"); 10933 return false; 10934 } 10935 10936 // Reflect the rename internally 10937 codeFile = afterCodeFile; 10938 resourceFile = afterCodeFile; 10939 10940 // Reflect the rename in scanned details 10941 pkg.codePath = afterCodeFile.getAbsolutePath(); 10942 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10943 pkg.baseCodePath); 10944 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10945 pkg.splitCodePaths); 10946 10947 // Reflect the rename in app info 10948 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10949 pkg.applicationInfo.setCodePath(pkg.codePath); 10950 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10951 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10952 pkg.applicationInfo.setResourcePath(pkg.codePath); 10953 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10954 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10955 10956 return true; 10957 } 10958 10959 int doPostInstall(int status, int uid) { 10960 if (status != PackageManager.INSTALL_SUCCEEDED) { 10961 cleanUp(); 10962 } 10963 return status; 10964 } 10965 10966 @Override 10967 String getCodePath() { 10968 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10969 } 10970 10971 @Override 10972 String getResourcePath() { 10973 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10974 } 10975 10976 private boolean cleanUp() { 10977 if (codeFile == null || !codeFile.exists()) { 10978 return false; 10979 } 10980 10981 if (codeFile.isDirectory()) { 10982 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10983 } else { 10984 codeFile.delete(); 10985 } 10986 10987 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10988 resourceFile.delete(); 10989 } 10990 10991 return true; 10992 } 10993 10994 void cleanUpResourcesLI() { 10995 // Try enumerating all code paths before deleting 10996 List<String> allCodePaths = Collections.EMPTY_LIST; 10997 if (codeFile != null && codeFile.exists()) { 10998 try { 10999 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11000 allCodePaths = pkg.getAllCodePaths(); 11001 } catch (PackageParserException e) { 11002 // Ignored; we tried our best 11003 } 11004 } 11005 11006 cleanUp(); 11007 removeDexFiles(allCodePaths, instructionSets); 11008 } 11009 11010 boolean doPostDeleteLI(boolean delete) { 11011 // XXX err, shouldn't we respect the delete flag? 11012 cleanUpResourcesLI(); 11013 return true; 11014 } 11015 } 11016 11017 private boolean isAsecExternal(String cid) { 11018 final String asecPath = PackageHelper.getSdFilesystem(cid); 11019 return !asecPath.startsWith(mAsecInternalPath); 11020 } 11021 11022 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11023 PackageManagerException { 11024 if (copyRet < 0) { 11025 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11026 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11027 throw new PackageManagerException(copyRet, message); 11028 } 11029 } 11030 } 11031 11032 /** 11033 * Extract the MountService "container ID" from the full code path of an 11034 * .apk. 11035 */ 11036 static String cidFromCodePath(String fullCodePath) { 11037 int eidx = fullCodePath.lastIndexOf("/"); 11038 String subStr1 = fullCodePath.substring(0, eidx); 11039 int sidx = subStr1.lastIndexOf("/"); 11040 return subStr1.substring(sidx+1, eidx); 11041 } 11042 11043 /** 11044 * Logic to handle installation of ASEC applications, including copying and 11045 * renaming logic. 11046 */ 11047 class AsecInstallArgs extends InstallArgs { 11048 static final String RES_FILE_NAME = "pkg.apk"; 11049 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11050 11051 String cid; 11052 String packagePath; 11053 String resourcePath; 11054 11055 /** New install */ 11056 AsecInstallArgs(InstallParams params) { 11057 super(params.origin, params.move, params.observer, params.installFlags, 11058 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11059 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11060 } 11061 11062 /** Existing install */ 11063 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11064 boolean isExternal, boolean isForwardLocked) { 11065 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11066 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11067 instructionSets, null); 11068 // Hackily pretend we're still looking at a full code path 11069 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11070 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11071 } 11072 11073 // Extract cid from fullCodePath 11074 int eidx = fullCodePath.lastIndexOf("/"); 11075 String subStr1 = fullCodePath.substring(0, eidx); 11076 int sidx = subStr1.lastIndexOf("/"); 11077 cid = subStr1.substring(sidx+1, eidx); 11078 setMountPath(subStr1); 11079 } 11080 11081 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11082 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11083 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11084 instructionSets, null); 11085 this.cid = cid; 11086 setMountPath(PackageHelper.getSdDir(cid)); 11087 } 11088 11089 void createCopyFile() { 11090 cid = mInstallerService.allocateExternalStageCidLegacy(); 11091 } 11092 11093 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11094 if (origin.staged) { 11095 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11096 cid = origin.cid; 11097 setMountPath(PackageHelper.getSdDir(cid)); 11098 return PackageManager.INSTALL_SUCCEEDED; 11099 } 11100 11101 if (temp) { 11102 createCopyFile(); 11103 } else { 11104 /* 11105 * Pre-emptively destroy the container since it's destroyed if 11106 * copying fails due to it existing anyway. 11107 */ 11108 PackageHelper.destroySdDir(cid); 11109 } 11110 11111 final String newMountPath = imcs.copyPackageToContainer( 11112 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11113 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11114 11115 if (newMountPath != null) { 11116 setMountPath(newMountPath); 11117 return PackageManager.INSTALL_SUCCEEDED; 11118 } else { 11119 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11120 } 11121 } 11122 11123 @Override 11124 String getCodePath() { 11125 return packagePath; 11126 } 11127 11128 @Override 11129 String getResourcePath() { 11130 return resourcePath; 11131 } 11132 11133 int doPreInstall(int status) { 11134 if (status != PackageManager.INSTALL_SUCCEEDED) { 11135 // Destroy container 11136 PackageHelper.destroySdDir(cid); 11137 } else { 11138 boolean mounted = PackageHelper.isContainerMounted(cid); 11139 if (!mounted) { 11140 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11141 Process.SYSTEM_UID); 11142 if (newMountPath != null) { 11143 setMountPath(newMountPath); 11144 } else { 11145 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11146 } 11147 } 11148 } 11149 return status; 11150 } 11151 11152 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11153 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11154 String newMountPath = null; 11155 if (PackageHelper.isContainerMounted(cid)) { 11156 // Unmount the container 11157 if (!PackageHelper.unMountSdDir(cid)) { 11158 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11159 return false; 11160 } 11161 } 11162 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11163 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11164 " which might be stale. Will try to clean up."); 11165 // Clean up the stale container and proceed to recreate. 11166 if (!PackageHelper.destroySdDir(newCacheId)) { 11167 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11168 return false; 11169 } 11170 // Successfully cleaned up stale container. Try to rename again. 11171 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11172 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11173 + " inspite of cleaning it up."); 11174 return false; 11175 } 11176 } 11177 if (!PackageHelper.isContainerMounted(newCacheId)) { 11178 Slog.w(TAG, "Mounting container " + newCacheId); 11179 newMountPath = PackageHelper.mountSdDir(newCacheId, 11180 getEncryptKey(), Process.SYSTEM_UID); 11181 } else { 11182 newMountPath = PackageHelper.getSdDir(newCacheId); 11183 } 11184 if (newMountPath == null) { 11185 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11186 return false; 11187 } 11188 Log.i(TAG, "Succesfully renamed " + cid + 11189 " to " + newCacheId + 11190 " at new path: " + newMountPath); 11191 cid = newCacheId; 11192 11193 final File beforeCodeFile = new File(packagePath); 11194 setMountPath(newMountPath); 11195 final File afterCodeFile = new File(packagePath); 11196 11197 // Reflect the rename in scanned details 11198 pkg.codePath = afterCodeFile.getAbsolutePath(); 11199 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11200 pkg.baseCodePath); 11201 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11202 pkg.splitCodePaths); 11203 11204 // Reflect the rename in app info 11205 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11206 pkg.applicationInfo.setCodePath(pkg.codePath); 11207 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11208 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11209 pkg.applicationInfo.setResourcePath(pkg.codePath); 11210 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11211 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11212 11213 return true; 11214 } 11215 11216 private void setMountPath(String mountPath) { 11217 final File mountFile = new File(mountPath); 11218 11219 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11220 if (monolithicFile.exists()) { 11221 packagePath = monolithicFile.getAbsolutePath(); 11222 if (isFwdLocked()) { 11223 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11224 } else { 11225 resourcePath = packagePath; 11226 } 11227 } else { 11228 packagePath = mountFile.getAbsolutePath(); 11229 resourcePath = packagePath; 11230 } 11231 } 11232 11233 int doPostInstall(int status, int uid) { 11234 if (status != PackageManager.INSTALL_SUCCEEDED) { 11235 cleanUp(); 11236 } else { 11237 final int groupOwner; 11238 final String protectedFile; 11239 if (isFwdLocked()) { 11240 groupOwner = UserHandle.getSharedAppGid(uid); 11241 protectedFile = RES_FILE_NAME; 11242 } else { 11243 groupOwner = -1; 11244 protectedFile = null; 11245 } 11246 11247 if (uid < Process.FIRST_APPLICATION_UID 11248 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11249 Slog.e(TAG, "Failed to finalize " + cid); 11250 PackageHelper.destroySdDir(cid); 11251 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11252 } 11253 11254 boolean mounted = PackageHelper.isContainerMounted(cid); 11255 if (!mounted) { 11256 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11257 } 11258 } 11259 return status; 11260 } 11261 11262 private void cleanUp() { 11263 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11264 11265 // Destroy secure container 11266 PackageHelper.destroySdDir(cid); 11267 } 11268 11269 private List<String> getAllCodePaths() { 11270 final File codeFile = new File(getCodePath()); 11271 if (codeFile != null && codeFile.exists()) { 11272 try { 11273 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11274 return pkg.getAllCodePaths(); 11275 } catch (PackageParserException e) { 11276 // Ignored; we tried our best 11277 } 11278 } 11279 return Collections.EMPTY_LIST; 11280 } 11281 11282 void cleanUpResourcesLI() { 11283 // Enumerate all code paths before deleting 11284 cleanUpResourcesLI(getAllCodePaths()); 11285 } 11286 11287 private void cleanUpResourcesLI(List<String> allCodePaths) { 11288 cleanUp(); 11289 removeDexFiles(allCodePaths, instructionSets); 11290 } 11291 11292 String getPackageName() { 11293 return getAsecPackageName(cid); 11294 } 11295 11296 boolean doPostDeleteLI(boolean delete) { 11297 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11298 final List<String> allCodePaths = getAllCodePaths(); 11299 boolean mounted = PackageHelper.isContainerMounted(cid); 11300 if (mounted) { 11301 // Unmount first 11302 if (PackageHelper.unMountSdDir(cid)) { 11303 mounted = false; 11304 } 11305 } 11306 if (!mounted && delete) { 11307 cleanUpResourcesLI(allCodePaths); 11308 } 11309 return !mounted; 11310 } 11311 11312 @Override 11313 int doPreCopy() { 11314 if (isFwdLocked()) { 11315 if (!PackageHelper.fixSdPermissions(cid, 11316 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11317 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11318 } 11319 } 11320 11321 return PackageManager.INSTALL_SUCCEEDED; 11322 } 11323 11324 @Override 11325 int doPostCopy(int uid) { 11326 if (isFwdLocked()) { 11327 if (uid < Process.FIRST_APPLICATION_UID 11328 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11329 RES_FILE_NAME)) { 11330 Slog.e(TAG, "Failed to finalize " + cid); 11331 PackageHelper.destroySdDir(cid); 11332 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11333 } 11334 } 11335 11336 return PackageManager.INSTALL_SUCCEEDED; 11337 } 11338 } 11339 11340 /** 11341 * Logic to handle movement of existing installed applications. 11342 */ 11343 class MoveInstallArgs extends InstallArgs { 11344 private File codeFile; 11345 private File resourceFile; 11346 11347 /** New install */ 11348 MoveInstallArgs(InstallParams params) { 11349 super(params.origin, params.move, params.observer, params.installFlags, 11350 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11351 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11352 } 11353 11354 int copyApk(IMediaContainerService imcs, boolean temp) { 11355 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11356 + move.fromUuid + " to " + move.toUuid); 11357 synchronized (mInstaller) { 11358 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11359 move.dataAppName, move.appId, move.seinfo) != 0) { 11360 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11361 } 11362 } 11363 11364 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11365 resourceFile = codeFile; 11366 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11367 11368 return PackageManager.INSTALL_SUCCEEDED; 11369 } 11370 11371 int doPreInstall(int status) { 11372 if (status != PackageManager.INSTALL_SUCCEEDED) { 11373 cleanUp(move.toUuid); 11374 } 11375 return status; 11376 } 11377 11378 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11379 if (status != PackageManager.INSTALL_SUCCEEDED) { 11380 cleanUp(move.toUuid); 11381 return false; 11382 } 11383 11384 // Reflect the move in app info 11385 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11386 pkg.applicationInfo.setCodePath(pkg.codePath); 11387 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11388 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11389 pkg.applicationInfo.setResourcePath(pkg.codePath); 11390 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11391 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11392 11393 return true; 11394 } 11395 11396 int doPostInstall(int status, int uid) { 11397 if (status == PackageManager.INSTALL_SUCCEEDED) { 11398 cleanUp(move.fromUuid); 11399 } else { 11400 cleanUp(move.toUuid); 11401 } 11402 return status; 11403 } 11404 11405 @Override 11406 String getCodePath() { 11407 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11408 } 11409 11410 @Override 11411 String getResourcePath() { 11412 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11413 } 11414 11415 private boolean cleanUp(String volumeUuid) { 11416 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11417 move.dataAppName); 11418 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11419 synchronized (mInstallLock) { 11420 // Clean up both app data and code 11421 removeDataDirsLI(volumeUuid, move.packageName); 11422 if (codeFile.isDirectory()) { 11423 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11424 } else { 11425 codeFile.delete(); 11426 } 11427 } 11428 return true; 11429 } 11430 11431 void cleanUpResourcesLI() { 11432 throw new UnsupportedOperationException(); 11433 } 11434 11435 boolean doPostDeleteLI(boolean delete) { 11436 throw new UnsupportedOperationException(); 11437 } 11438 } 11439 11440 static String getAsecPackageName(String packageCid) { 11441 int idx = packageCid.lastIndexOf("-"); 11442 if (idx == -1) { 11443 return packageCid; 11444 } 11445 return packageCid.substring(0, idx); 11446 } 11447 11448 // Utility method used to create code paths based on package name and available index. 11449 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11450 String idxStr = ""; 11451 int idx = 1; 11452 // Fall back to default value of idx=1 if prefix is not 11453 // part of oldCodePath 11454 if (oldCodePath != null) { 11455 String subStr = oldCodePath; 11456 // Drop the suffix right away 11457 if (suffix != null && subStr.endsWith(suffix)) { 11458 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11459 } 11460 // If oldCodePath already contains prefix find out the 11461 // ending index to either increment or decrement. 11462 int sidx = subStr.lastIndexOf(prefix); 11463 if (sidx != -1) { 11464 subStr = subStr.substring(sidx + prefix.length()); 11465 if (subStr != null) { 11466 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11467 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11468 } 11469 try { 11470 idx = Integer.parseInt(subStr); 11471 if (idx <= 1) { 11472 idx++; 11473 } else { 11474 idx--; 11475 } 11476 } catch(NumberFormatException e) { 11477 } 11478 } 11479 } 11480 } 11481 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11482 return prefix + idxStr; 11483 } 11484 11485 private File getNextCodePath(File targetDir, String packageName) { 11486 int suffix = 1; 11487 File result; 11488 do { 11489 result = new File(targetDir, packageName + "-" + suffix); 11490 suffix++; 11491 } while (result.exists()); 11492 return result; 11493 } 11494 11495 // Utility method that returns the relative package path with respect 11496 // to the installation directory. Like say for /data/data/com.test-1.apk 11497 // string com.test-1 is returned. 11498 static String deriveCodePathName(String codePath) { 11499 if (codePath == null) { 11500 return null; 11501 } 11502 final File codeFile = new File(codePath); 11503 final String name = codeFile.getName(); 11504 if (codeFile.isDirectory()) { 11505 return name; 11506 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11507 final int lastDot = name.lastIndexOf('.'); 11508 return name.substring(0, lastDot); 11509 } else { 11510 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11511 return null; 11512 } 11513 } 11514 11515 class PackageInstalledInfo { 11516 String name; 11517 int uid; 11518 // The set of users that originally had this package installed. 11519 int[] origUsers; 11520 // The set of users that now have this package installed. 11521 int[] newUsers; 11522 PackageParser.Package pkg; 11523 int returnCode; 11524 String returnMsg; 11525 PackageRemovedInfo removedInfo; 11526 11527 public void setError(int code, String msg) { 11528 returnCode = code; 11529 returnMsg = msg; 11530 Slog.w(TAG, msg); 11531 } 11532 11533 public void setError(String msg, PackageParserException e) { 11534 returnCode = e.error; 11535 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11536 Slog.w(TAG, msg, e); 11537 } 11538 11539 public void setError(String msg, PackageManagerException e) { 11540 returnCode = e.error; 11541 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11542 Slog.w(TAG, msg, e); 11543 } 11544 11545 // In some error cases we want to convey more info back to the observer 11546 String origPackage; 11547 String origPermission; 11548 } 11549 11550 /* 11551 * Install a non-existing package. 11552 */ 11553 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11554 UserHandle user, String installerPackageName, String volumeUuid, 11555 PackageInstalledInfo res) { 11556 // Remember this for later, in case we need to rollback this install 11557 String pkgName = pkg.packageName; 11558 11559 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11560 final boolean dataDirExists = Environment 11561 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11562 synchronized(mPackages) { 11563 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11564 // A package with the same name is already installed, though 11565 // it has been renamed to an older name. The package we 11566 // are trying to install should be installed as an update to 11567 // the existing one, but that has not been requested, so bail. 11568 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11569 + " without first uninstalling package running as " 11570 + mSettings.mRenamedPackages.get(pkgName)); 11571 return; 11572 } 11573 if (mPackages.containsKey(pkgName)) { 11574 // Don't allow installation over an existing package with the same name. 11575 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11576 + " without first uninstalling."); 11577 return; 11578 } 11579 } 11580 11581 try { 11582 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11583 System.currentTimeMillis(), user); 11584 11585 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11586 // delete the partially installed application. the data directory will have to be 11587 // restored if it was already existing 11588 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11589 // remove package from internal structures. Note that we want deletePackageX to 11590 // delete the package data and cache directories that it created in 11591 // scanPackageLocked, unless those directories existed before we even tried to 11592 // install. 11593 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11594 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11595 res.removedInfo, true); 11596 } 11597 11598 } catch (PackageManagerException e) { 11599 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11600 } 11601 } 11602 11603 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11604 // Can't rotate keys during boot or if sharedUser. 11605 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11606 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11607 return false; 11608 } 11609 // app is using upgradeKeySets; make sure all are valid 11610 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11611 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11612 for (int i = 0; i < upgradeKeySets.length; i++) { 11613 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11614 Slog.wtf(TAG, "Package " 11615 + (oldPs.name != null ? oldPs.name : "<null>") 11616 + " contains upgrade-key-set reference to unknown key-set: " 11617 + upgradeKeySets[i] 11618 + " reverting to signatures check."); 11619 return false; 11620 } 11621 } 11622 return true; 11623 } 11624 11625 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11626 // Upgrade keysets are being used. Determine if new package has a superset of the 11627 // required keys. 11628 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11629 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11630 for (int i = 0; i < upgradeKeySets.length; i++) { 11631 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11632 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11633 return true; 11634 } 11635 } 11636 return false; 11637 } 11638 11639 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11640 UserHandle user, String installerPackageName, String volumeUuid, 11641 PackageInstalledInfo res) { 11642 final PackageParser.Package oldPackage; 11643 final String pkgName = pkg.packageName; 11644 final int[] allUsers; 11645 final boolean[] perUserInstalled; 11646 final boolean weFroze; 11647 11648 // First find the old package info and check signatures 11649 synchronized(mPackages) { 11650 oldPackage = mPackages.get(pkgName); 11651 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11652 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11653 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11654 if(!checkUpgradeKeySetLP(ps, pkg)) { 11655 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11656 "New package not signed by keys specified by upgrade-keysets: " 11657 + pkgName); 11658 return; 11659 } 11660 } else { 11661 // default to original signature matching 11662 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11663 != PackageManager.SIGNATURE_MATCH) { 11664 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11665 "New package has a different signature: " + pkgName); 11666 return; 11667 } 11668 } 11669 11670 // In case of rollback, remember per-user/profile install state 11671 allUsers = sUserManager.getUserIds(); 11672 perUserInstalled = new boolean[allUsers.length]; 11673 for (int i = 0; i < allUsers.length; i++) { 11674 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11675 } 11676 11677 // Mark the app as frozen to prevent launching during the upgrade 11678 // process, and then kill all running instances 11679 if (!ps.frozen) { 11680 ps.frozen = true; 11681 weFroze = true; 11682 } else { 11683 weFroze = false; 11684 } 11685 } 11686 11687 // Now that we're guarded by frozen state, kill app during upgrade 11688 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11689 11690 try { 11691 boolean sysPkg = (isSystemApp(oldPackage)); 11692 if (sysPkg) { 11693 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11694 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11695 } else { 11696 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11697 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11698 } 11699 } finally { 11700 // Regardless of success or failure of upgrade steps above, always 11701 // unfreeze the package if we froze it 11702 if (weFroze) { 11703 unfreezePackage(pkgName); 11704 } 11705 } 11706 } 11707 11708 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11709 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11710 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11711 String volumeUuid, PackageInstalledInfo res) { 11712 String pkgName = deletedPackage.packageName; 11713 boolean deletedPkg = true; 11714 boolean updatedSettings = false; 11715 11716 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11717 + deletedPackage); 11718 long origUpdateTime; 11719 if (pkg.mExtras != null) { 11720 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11721 } else { 11722 origUpdateTime = 0; 11723 } 11724 11725 // First delete the existing package while retaining the data directory 11726 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11727 res.removedInfo, true)) { 11728 // If the existing package wasn't successfully deleted 11729 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11730 deletedPkg = false; 11731 } else { 11732 // Successfully deleted the old package; proceed with replace. 11733 11734 // If deleted package lived in a container, give users a chance to 11735 // relinquish resources before killing. 11736 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11737 if (DEBUG_INSTALL) { 11738 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11739 } 11740 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11741 final ArrayList<String> pkgList = new ArrayList<String>(1); 11742 pkgList.add(deletedPackage.applicationInfo.packageName); 11743 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11744 } 11745 11746 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11747 try { 11748 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11749 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11750 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11751 perUserInstalled, res, user); 11752 updatedSettings = true; 11753 } catch (PackageManagerException e) { 11754 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11755 } 11756 } 11757 11758 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11759 // remove package from internal structures. Note that we want deletePackageX to 11760 // delete the package data and cache directories that it created in 11761 // scanPackageLocked, unless those directories existed before we even tried to 11762 // install. 11763 if(updatedSettings) { 11764 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11765 deletePackageLI( 11766 pkgName, null, true, allUsers, perUserInstalled, 11767 PackageManager.DELETE_KEEP_DATA, 11768 res.removedInfo, true); 11769 } 11770 // Since we failed to install the new package we need to restore the old 11771 // package that we deleted. 11772 if (deletedPkg) { 11773 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11774 File restoreFile = new File(deletedPackage.codePath); 11775 // Parse old package 11776 boolean oldExternal = isExternal(deletedPackage); 11777 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11778 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11779 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11780 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11781 try { 11782 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11783 } catch (PackageManagerException e) { 11784 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11785 + e.getMessage()); 11786 return; 11787 } 11788 // Restore of old package succeeded. Update permissions. 11789 // writer 11790 synchronized (mPackages) { 11791 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11792 UPDATE_PERMISSIONS_ALL); 11793 // can downgrade to reader 11794 mSettings.writeLPr(); 11795 } 11796 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11797 } 11798 } 11799 } 11800 11801 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11802 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11803 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11804 String volumeUuid, PackageInstalledInfo res) { 11805 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11806 + ", old=" + deletedPackage); 11807 boolean disabledSystem = false; 11808 boolean updatedSettings = false; 11809 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11810 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11811 != 0) { 11812 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11813 } 11814 String packageName = deletedPackage.packageName; 11815 if (packageName == null) { 11816 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11817 "Attempt to delete null packageName."); 11818 return; 11819 } 11820 PackageParser.Package oldPkg; 11821 PackageSetting oldPkgSetting; 11822 // reader 11823 synchronized (mPackages) { 11824 oldPkg = mPackages.get(packageName); 11825 oldPkgSetting = mSettings.mPackages.get(packageName); 11826 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11827 (oldPkgSetting == null)) { 11828 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11829 "Couldn't find package:" + packageName + " information"); 11830 return; 11831 } 11832 } 11833 11834 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11835 res.removedInfo.removedPackage = packageName; 11836 // Remove existing system package 11837 removePackageLI(oldPkgSetting, true); 11838 // writer 11839 synchronized (mPackages) { 11840 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11841 if (!disabledSystem && deletedPackage != null) { 11842 // We didn't need to disable the .apk as a current system package, 11843 // which means we are replacing another update that is already 11844 // installed. We need to make sure to delete the older one's .apk. 11845 res.removedInfo.args = createInstallArgsForExisting(0, 11846 deletedPackage.applicationInfo.getCodePath(), 11847 deletedPackage.applicationInfo.getResourcePath(), 11848 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11849 } else { 11850 res.removedInfo.args = null; 11851 } 11852 } 11853 11854 // Successfully disabled the old package. Now proceed with re-installation 11855 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11856 11857 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11858 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11859 11860 PackageParser.Package newPackage = null; 11861 try { 11862 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11863 if (newPackage.mExtras != null) { 11864 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11865 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11866 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11867 11868 // is the update attempting to change shared user? that isn't going to work... 11869 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11870 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11871 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11872 + " to " + newPkgSetting.sharedUser); 11873 updatedSettings = true; 11874 } 11875 } 11876 11877 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11878 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11879 perUserInstalled, res, user); 11880 updatedSettings = true; 11881 } 11882 11883 } catch (PackageManagerException e) { 11884 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11885 } 11886 11887 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11888 // Re installation failed. Restore old information 11889 // Remove new pkg information 11890 if (newPackage != null) { 11891 removeInstalledPackageLI(newPackage, true); 11892 } 11893 // Add back the old system package 11894 try { 11895 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11896 } catch (PackageManagerException e) { 11897 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11898 } 11899 // Restore the old system information in Settings 11900 synchronized (mPackages) { 11901 if (disabledSystem) { 11902 mSettings.enableSystemPackageLPw(packageName); 11903 } 11904 if (updatedSettings) { 11905 mSettings.setInstallerPackageName(packageName, 11906 oldPkgSetting.installerPackageName); 11907 } 11908 mSettings.writeLPr(); 11909 } 11910 } 11911 } 11912 11913 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11914 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11915 UserHandle user) { 11916 String pkgName = newPackage.packageName; 11917 synchronized (mPackages) { 11918 //write settings. the installStatus will be incomplete at this stage. 11919 //note that the new package setting would have already been 11920 //added to mPackages. It hasn't been persisted yet. 11921 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11922 mSettings.writeLPr(); 11923 } 11924 11925 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11926 11927 synchronized (mPackages) { 11928 updatePermissionsLPw(newPackage.packageName, newPackage, 11929 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11930 ? UPDATE_PERMISSIONS_ALL : 0)); 11931 // For system-bundled packages, we assume that installing an upgraded version 11932 // of the package implies that the user actually wants to run that new code, 11933 // so we enable the package. 11934 PackageSetting ps = mSettings.mPackages.get(pkgName); 11935 if (ps != null) { 11936 if (isSystemApp(newPackage)) { 11937 // NB: implicit assumption that system package upgrades apply to all users 11938 if (DEBUG_INSTALL) { 11939 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11940 } 11941 if (res.origUsers != null) { 11942 for (int userHandle : res.origUsers) { 11943 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11944 userHandle, installerPackageName); 11945 } 11946 } 11947 // Also convey the prior install/uninstall state 11948 if (allUsers != null && perUserInstalled != null) { 11949 for (int i = 0; i < allUsers.length; i++) { 11950 if (DEBUG_INSTALL) { 11951 Slog.d(TAG, " user " + allUsers[i] 11952 + " => " + perUserInstalled[i]); 11953 } 11954 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11955 } 11956 // these install state changes will be persisted in the 11957 // upcoming call to mSettings.writeLPr(). 11958 } 11959 } 11960 // It's implied that when a user requests installation, they want the app to be 11961 // installed and enabled. 11962 int userId = user.getIdentifier(); 11963 if (userId != UserHandle.USER_ALL) { 11964 ps.setInstalled(true, userId); 11965 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11966 } 11967 } 11968 res.name = pkgName; 11969 res.uid = newPackage.applicationInfo.uid; 11970 res.pkg = newPackage; 11971 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11972 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11973 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11974 //to update install status 11975 mSettings.writeLPr(); 11976 } 11977 } 11978 11979 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11980 final int installFlags = args.installFlags; 11981 final String installerPackageName = args.installerPackageName; 11982 final String volumeUuid = args.volumeUuid; 11983 final File tmpPackageFile = new File(args.getCodePath()); 11984 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11985 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11986 || (args.volumeUuid != null)); 11987 boolean replace = false; 11988 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11989 if (args.move != null) { 11990 // moving a complete application; perfom an initial scan on the new install location 11991 scanFlags |= SCAN_INITIAL; 11992 } 11993 // Result object to be returned 11994 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11995 11996 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11997 // Retrieve PackageSettings and parse package 11998 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11999 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12000 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12001 PackageParser pp = new PackageParser(); 12002 pp.setSeparateProcesses(mSeparateProcesses); 12003 pp.setDisplayMetrics(mMetrics); 12004 12005 final PackageParser.Package pkg; 12006 try { 12007 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12008 } catch (PackageParserException e) { 12009 res.setError("Failed parse during installPackageLI", e); 12010 return; 12011 } 12012 12013 // Mark that we have an install time CPU ABI override. 12014 pkg.cpuAbiOverride = args.abiOverride; 12015 12016 String pkgName = res.name = pkg.packageName; 12017 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12018 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12019 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12020 return; 12021 } 12022 } 12023 12024 try { 12025 pp.collectCertificates(pkg, parseFlags); 12026 pp.collectManifestDigest(pkg); 12027 } catch (PackageParserException e) { 12028 res.setError("Failed collect during installPackageLI", e); 12029 return; 12030 } 12031 12032 /* If the installer passed in a manifest digest, compare it now. */ 12033 if (args.manifestDigest != null) { 12034 if (DEBUG_INSTALL) { 12035 final String parsedManifest = pkg.manifestDigest == null ? "null" 12036 : pkg.manifestDigest.toString(); 12037 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12038 + parsedManifest); 12039 } 12040 12041 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12042 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12043 return; 12044 } 12045 } else if (DEBUG_INSTALL) { 12046 final String parsedManifest = pkg.manifestDigest == null 12047 ? "null" : pkg.manifestDigest.toString(); 12048 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12049 } 12050 12051 // Get rid of all references to package scan path via parser. 12052 pp = null; 12053 String oldCodePath = null; 12054 boolean systemApp = false; 12055 synchronized (mPackages) { 12056 // Check if installing already existing package 12057 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12058 String oldName = mSettings.mRenamedPackages.get(pkgName); 12059 if (pkg.mOriginalPackages != null 12060 && pkg.mOriginalPackages.contains(oldName) 12061 && mPackages.containsKey(oldName)) { 12062 // This package is derived from an original package, 12063 // and this device has been updating from that original 12064 // name. We must continue using the original name, so 12065 // rename the new package here. 12066 pkg.setPackageName(oldName); 12067 pkgName = pkg.packageName; 12068 replace = true; 12069 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12070 + oldName + " pkgName=" + pkgName); 12071 } else if (mPackages.containsKey(pkgName)) { 12072 // This package, under its official name, already exists 12073 // on the device; we should replace it. 12074 replace = true; 12075 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12076 } 12077 12078 // Prevent apps opting out from runtime permissions 12079 if (replace) { 12080 PackageParser.Package oldPackage = mPackages.get(pkgName); 12081 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12082 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12083 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12084 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12085 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12086 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12087 + " doesn't support runtime permissions but the old" 12088 + " target SDK " + oldTargetSdk + " does."); 12089 return; 12090 } 12091 } 12092 } 12093 12094 PackageSetting ps = mSettings.mPackages.get(pkgName); 12095 if (ps != null) { 12096 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12097 12098 // Quick sanity check that we're signed correctly if updating; 12099 // we'll check this again later when scanning, but we want to 12100 // bail early here before tripping over redefined permissions. 12101 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12102 if (!checkUpgradeKeySetLP(ps, pkg)) { 12103 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12104 + pkg.packageName + " upgrade keys do not match the " 12105 + "previously installed version"); 12106 return; 12107 } 12108 } else { 12109 try { 12110 verifySignaturesLP(ps, pkg); 12111 } catch (PackageManagerException e) { 12112 res.setError(e.error, e.getMessage()); 12113 return; 12114 } 12115 } 12116 12117 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12118 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12119 systemApp = (ps.pkg.applicationInfo.flags & 12120 ApplicationInfo.FLAG_SYSTEM) != 0; 12121 } 12122 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12123 } 12124 12125 // Check whether the newly-scanned package wants to define an already-defined perm 12126 int N = pkg.permissions.size(); 12127 for (int i = N-1; i >= 0; i--) { 12128 PackageParser.Permission perm = pkg.permissions.get(i); 12129 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12130 if (bp != null) { 12131 // If the defining package is signed with our cert, it's okay. This 12132 // also includes the "updating the same package" case, of course. 12133 // "updating same package" could also involve key-rotation. 12134 final boolean sigsOk; 12135 if (bp.sourcePackage.equals(pkg.packageName) 12136 && (bp.packageSetting instanceof PackageSetting) 12137 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12138 scanFlags))) { 12139 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12140 } else { 12141 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12142 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12143 } 12144 if (!sigsOk) { 12145 // If the owning package is the system itself, we log but allow 12146 // install to proceed; we fail the install on all other permission 12147 // redefinitions. 12148 if (!bp.sourcePackage.equals("android")) { 12149 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12150 + pkg.packageName + " attempting to redeclare permission " 12151 + perm.info.name + " already owned by " + bp.sourcePackage); 12152 res.origPermission = perm.info.name; 12153 res.origPackage = bp.sourcePackage; 12154 return; 12155 } else { 12156 Slog.w(TAG, "Package " + pkg.packageName 12157 + " attempting to redeclare system permission " 12158 + perm.info.name + "; ignoring new declaration"); 12159 pkg.permissions.remove(i); 12160 } 12161 } 12162 } 12163 } 12164 12165 } 12166 12167 if (systemApp && onExternal) { 12168 // Disable updates to system apps on sdcard 12169 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12170 "Cannot install updates to system apps on sdcard"); 12171 return; 12172 } 12173 12174 if (args.move != null) { 12175 // We did an in-place move, so dex is ready to roll 12176 scanFlags |= SCAN_NO_DEX; 12177 scanFlags |= SCAN_MOVE; 12178 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12179 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12180 scanFlags |= SCAN_NO_DEX; 12181 12182 try { 12183 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12184 true /* extract libs */); 12185 } catch (PackageManagerException pme) { 12186 Slog.e(TAG, "Error deriving application ABI", pme); 12187 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12188 return; 12189 } 12190 12191 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12192 int result = mPackageDexOptimizer 12193 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12194 false /* defer */, false /* inclDependencies */); 12195 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12196 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12197 return; 12198 } 12199 } 12200 12201 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12202 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12203 return; 12204 } 12205 12206 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12207 12208 if (replace) { 12209 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12210 installerPackageName, volumeUuid, res); 12211 } else { 12212 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12213 args.user, installerPackageName, volumeUuid, res); 12214 } 12215 synchronized (mPackages) { 12216 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12217 if (ps != null) { 12218 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12219 } 12220 } 12221 } 12222 12223 private void startIntentFilterVerifications(int userId, boolean replacing, 12224 PackageParser.Package pkg) { 12225 if (mIntentFilterVerifierComponent == null) { 12226 Slog.w(TAG, "No IntentFilter verification will not be done as " 12227 + "there is no IntentFilterVerifier available!"); 12228 return; 12229 } 12230 12231 final int verifierUid = getPackageUid( 12232 mIntentFilterVerifierComponent.getPackageName(), 12233 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12234 12235 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12236 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12237 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12238 mHandler.sendMessage(msg); 12239 } 12240 12241 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12242 PackageParser.Package pkg) { 12243 int size = pkg.activities.size(); 12244 if (size == 0) { 12245 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12246 "No activity, so no need to verify any IntentFilter!"); 12247 return; 12248 } 12249 12250 final boolean hasDomainURLs = hasDomainURLs(pkg); 12251 if (!hasDomainURLs) { 12252 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12253 "No domain URLs, so no need to verify any IntentFilter!"); 12254 return; 12255 } 12256 12257 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12258 + " if any IntentFilter from the " + size 12259 + " Activities needs verification ..."); 12260 12261 int count = 0; 12262 final String packageName = pkg.packageName; 12263 12264 synchronized (mPackages) { 12265 // If this is a new install and we see that we've already run verification for this 12266 // package, we have nothing to do: it means the state was restored from backup. 12267 if (!replacing) { 12268 IntentFilterVerificationInfo ivi = 12269 mSettings.getIntentFilterVerificationLPr(packageName); 12270 if (ivi != null) { 12271 if (DEBUG_DOMAIN_VERIFICATION) { 12272 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12273 + ivi.getStatusString()); 12274 } 12275 return; 12276 } 12277 } 12278 12279 // If any filters need to be verified, then all need to be. 12280 boolean needToVerify = false; 12281 for (PackageParser.Activity a : pkg.activities) { 12282 for (ActivityIntentInfo filter : a.intents) { 12283 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12284 if (DEBUG_DOMAIN_VERIFICATION) { 12285 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12286 } 12287 needToVerify = true; 12288 break; 12289 } 12290 } 12291 } 12292 12293 if (needToVerify) { 12294 final int verificationId = mIntentFilterVerificationToken++; 12295 for (PackageParser.Activity a : pkg.activities) { 12296 for (ActivityIntentInfo filter : a.intents) { 12297 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12298 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12299 "Verification needed for IntentFilter:" + filter.toString()); 12300 mIntentFilterVerifier.addOneIntentFilterVerification( 12301 verifierUid, userId, verificationId, filter, packageName); 12302 count++; 12303 } 12304 } 12305 } 12306 } 12307 } 12308 12309 if (count > 0) { 12310 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12311 + " IntentFilter verification" + (count > 1 ? "s" : "") 12312 + " for userId:" + userId); 12313 mIntentFilterVerifier.startVerifications(userId); 12314 } else { 12315 if (DEBUG_DOMAIN_VERIFICATION) { 12316 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12317 } 12318 } 12319 } 12320 12321 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12322 final ComponentName cn = filter.activity.getComponentName(); 12323 final String packageName = cn.getPackageName(); 12324 12325 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12326 packageName); 12327 if (ivi == null) { 12328 return true; 12329 } 12330 int status = ivi.getStatus(); 12331 switch (status) { 12332 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12333 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12334 return true; 12335 12336 default: 12337 // Nothing to do 12338 return false; 12339 } 12340 } 12341 12342 private static boolean isMultiArch(PackageSetting ps) { 12343 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12344 } 12345 12346 private static boolean isMultiArch(ApplicationInfo info) { 12347 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12348 } 12349 12350 private static boolean isExternal(PackageParser.Package pkg) { 12351 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12352 } 12353 12354 private static boolean isExternal(PackageSetting ps) { 12355 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12356 } 12357 12358 private static boolean isExternal(ApplicationInfo info) { 12359 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12360 } 12361 12362 private static boolean isSystemApp(PackageParser.Package pkg) { 12363 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12364 } 12365 12366 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12367 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12368 } 12369 12370 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12371 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12372 } 12373 12374 private static boolean isSystemApp(PackageSetting ps) { 12375 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12376 } 12377 12378 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12379 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12380 } 12381 12382 private int packageFlagsToInstallFlags(PackageSetting ps) { 12383 int installFlags = 0; 12384 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12385 // This existing package was an external ASEC install when we have 12386 // the external flag without a UUID 12387 installFlags |= PackageManager.INSTALL_EXTERNAL; 12388 } 12389 if (ps.isForwardLocked()) { 12390 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12391 } 12392 return installFlags; 12393 } 12394 12395 private void deleteTempPackageFiles() { 12396 final FilenameFilter filter = new FilenameFilter() { 12397 public boolean accept(File dir, String name) { 12398 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12399 } 12400 }; 12401 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12402 file.delete(); 12403 } 12404 } 12405 12406 @Override 12407 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12408 int flags) { 12409 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12410 flags); 12411 } 12412 12413 @Override 12414 public void deletePackage(final String packageName, 12415 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12416 mContext.enforceCallingOrSelfPermission( 12417 android.Manifest.permission.DELETE_PACKAGES, null); 12418 Preconditions.checkNotNull(packageName); 12419 Preconditions.checkNotNull(observer); 12420 final int uid = Binder.getCallingUid(); 12421 if (UserHandle.getUserId(uid) != userId) { 12422 mContext.enforceCallingPermission( 12423 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12424 "deletePackage for user " + userId); 12425 } 12426 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12427 try { 12428 observer.onPackageDeleted(packageName, 12429 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12430 } catch (RemoteException re) { 12431 } 12432 return; 12433 } 12434 12435 boolean uninstallBlocked = false; 12436 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12437 int[] users = sUserManager.getUserIds(); 12438 for (int i = 0; i < users.length; ++i) { 12439 if (getBlockUninstallForUser(packageName, users[i])) { 12440 uninstallBlocked = true; 12441 break; 12442 } 12443 } 12444 } else { 12445 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12446 } 12447 if (uninstallBlocked) { 12448 try { 12449 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12450 null); 12451 } catch (RemoteException re) { 12452 } 12453 return; 12454 } 12455 12456 if (DEBUG_REMOVE) { 12457 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12458 } 12459 // Queue up an async operation since the package deletion may take a little while. 12460 mHandler.post(new Runnable() { 12461 public void run() { 12462 mHandler.removeCallbacks(this); 12463 final int returnCode = deletePackageX(packageName, userId, flags); 12464 if (observer != null) { 12465 try { 12466 observer.onPackageDeleted(packageName, returnCode, null); 12467 } catch (RemoteException e) { 12468 Log.i(TAG, "Observer no longer exists."); 12469 } //end catch 12470 } //end if 12471 } //end run 12472 }); 12473 } 12474 12475 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12476 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12477 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12478 try { 12479 if (dpm != null) { 12480 if (dpm.isDeviceOwner(packageName)) { 12481 return true; 12482 } 12483 int[] users; 12484 if (userId == UserHandle.USER_ALL) { 12485 users = sUserManager.getUserIds(); 12486 } else { 12487 users = new int[]{userId}; 12488 } 12489 for (int i = 0; i < users.length; ++i) { 12490 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12491 return true; 12492 } 12493 } 12494 } 12495 } catch (RemoteException e) { 12496 } 12497 return false; 12498 } 12499 12500 /** 12501 * This method is an internal method that could be get invoked either 12502 * to delete an installed package or to clean up a failed installation. 12503 * After deleting an installed package, a broadcast is sent to notify any 12504 * listeners that the package has been installed. For cleaning up a failed 12505 * installation, the broadcast is not necessary since the package's 12506 * installation wouldn't have sent the initial broadcast either 12507 * The key steps in deleting a package are 12508 * deleting the package information in internal structures like mPackages, 12509 * deleting the packages base directories through installd 12510 * updating mSettings to reflect current status 12511 * persisting settings for later use 12512 * sending a broadcast if necessary 12513 */ 12514 private int deletePackageX(String packageName, int userId, int flags) { 12515 final PackageRemovedInfo info = new PackageRemovedInfo(); 12516 final boolean res; 12517 12518 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12519 ? UserHandle.ALL : new UserHandle(userId); 12520 12521 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12522 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12523 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12524 } 12525 12526 boolean removedForAllUsers = false; 12527 boolean systemUpdate = false; 12528 12529 // for the uninstall-updates case and restricted profiles, remember the per- 12530 // userhandle installed state 12531 int[] allUsers; 12532 boolean[] perUserInstalled; 12533 synchronized (mPackages) { 12534 PackageSetting ps = mSettings.mPackages.get(packageName); 12535 allUsers = sUserManager.getUserIds(); 12536 perUserInstalled = new boolean[allUsers.length]; 12537 for (int i = 0; i < allUsers.length; i++) { 12538 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12539 } 12540 } 12541 12542 synchronized (mInstallLock) { 12543 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12544 res = deletePackageLI(packageName, removeForUser, 12545 true, allUsers, perUserInstalled, 12546 flags | REMOVE_CHATTY, info, true); 12547 systemUpdate = info.isRemovedPackageSystemUpdate; 12548 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12549 removedForAllUsers = true; 12550 } 12551 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12552 + " removedForAllUsers=" + removedForAllUsers); 12553 } 12554 12555 if (res) { 12556 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12557 12558 // If the removed package was a system update, the old system package 12559 // was re-enabled; we need to broadcast this information 12560 if (systemUpdate) { 12561 Bundle extras = new Bundle(1); 12562 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12563 ? info.removedAppId : info.uid); 12564 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12565 12566 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12567 extras, null, null, null); 12568 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12569 extras, null, null, null); 12570 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12571 null, packageName, null, null); 12572 } 12573 } 12574 // Force a gc here. 12575 Runtime.getRuntime().gc(); 12576 // Delete the resources here after sending the broadcast to let 12577 // other processes clean up before deleting resources. 12578 if (info.args != null) { 12579 synchronized (mInstallLock) { 12580 info.args.doPostDeleteLI(true); 12581 } 12582 } 12583 12584 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12585 } 12586 12587 class PackageRemovedInfo { 12588 String removedPackage; 12589 int uid = -1; 12590 int removedAppId = -1; 12591 int[] removedUsers = null; 12592 boolean isRemovedPackageSystemUpdate = false; 12593 // Clean up resources deleted packages. 12594 InstallArgs args = null; 12595 12596 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12597 Bundle extras = new Bundle(1); 12598 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12599 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12600 if (replacing) { 12601 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12602 } 12603 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12604 if (removedPackage != null) { 12605 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12606 extras, null, null, removedUsers); 12607 if (fullRemove && !replacing) { 12608 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12609 extras, null, null, removedUsers); 12610 } 12611 } 12612 if (removedAppId >= 0) { 12613 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12614 removedUsers); 12615 } 12616 } 12617 } 12618 12619 /* 12620 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12621 * flag is not set, the data directory is removed as well. 12622 * make sure this flag is set for partially installed apps. If not its meaningless to 12623 * delete a partially installed application. 12624 */ 12625 private void removePackageDataLI(PackageSetting ps, 12626 int[] allUserHandles, boolean[] perUserInstalled, 12627 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12628 String packageName = ps.name; 12629 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12630 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12631 // Retrieve object to delete permissions for shared user later on 12632 final PackageSetting deletedPs; 12633 // reader 12634 synchronized (mPackages) { 12635 deletedPs = mSettings.mPackages.get(packageName); 12636 if (outInfo != null) { 12637 outInfo.removedPackage = packageName; 12638 outInfo.removedUsers = deletedPs != null 12639 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12640 : null; 12641 } 12642 } 12643 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12644 removeDataDirsLI(ps.volumeUuid, packageName); 12645 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12646 } 12647 // writer 12648 synchronized (mPackages) { 12649 if (deletedPs != null) { 12650 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12651 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12652 clearDefaultBrowserIfNeeded(packageName); 12653 if (outInfo != null) { 12654 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12655 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12656 } 12657 updatePermissionsLPw(deletedPs.name, null, 0); 12658 if (deletedPs.sharedUser != null) { 12659 // Remove permissions associated with package. Since runtime 12660 // permissions are per user we have to kill the removed package 12661 // or packages running under the shared user of the removed 12662 // package if revoking the permissions requested only by the removed 12663 // package is successful and this causes a change in gids. 12664 for (int userId : UserManagerService.getInstance().getUserIds()) { 12665 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12666 userId); 12667 if (userIdToKill == UserHandle.USER_ALL 12668 || userIdToKill >= UserHandle.USER_OWNER) { 12669 // If gids changed for this user, kill all affected packages. 12670 mHandler.post(new Runnable() { 12671 @Override 12672 public void run() { 12673 // This has to happen with no lock held. 12674 killSettingPackagesForUser(deletedPs, userIdToKill, 12675 KILL_APP_REASON_GIDS_CHANGED); 12676 } 12677 }); 12678 break; 12679 } 12680 } 12681 } 12682 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12683 } 12684 // make sure to preserve per-user disabled state if this removal was just 12685 // a downgrade of a system app to the factory package 12686 if (allUserHandles != null && perUserInstalled != null) { 12687 if (DEBUG_REMOVE) { 12688 Slog.d(TAG, "Propagating install state across downgrade"); 12689 } 12690 for (int i = 0; i < allUserHandles.length; i++) { 12691 if (DEBUG_REMOVE) { 12692 Slog.d(TAG, " user " + allUserHandles[i] 12693 + " => " + perUserInstalled[i]); 12694 } 12695 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12696 } 12697 } 12698 } 12699 // can downgrade to reader 12700 if (writeSettings) { 12701 // Save settings now 12702 mSettings.writeLPr(); 12703 } 12704 } 12705 if (outInfo != null) { 12706 // A user ID was deleted here. Go through all users and remove it 12707 // from KeyStore. 12708 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12709 } 12710 } 12711 12712 static boolean locationIsPrivileged(File path) { 12713 try { 12714 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12715 .getCanonicalPath(); 12716 return path.getCanonicalPath().startsWith(privilegedAppDir); 12717 } catch (IOException e) { 12718 Slog.e(TAG, "Unable to access code path " + path); 12719 } 12720 return false; 12721 } 12722 12723 /* 12724 * Tries to delete system package. 12725 */ 12726 private boolean deleteSystemPackageLI(PackageSetting newPs, 12727 int[] allUserHandles, boolean[] perUserInstalled, 12728 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12729 final boolean applyUserRestrictions 12730 = (allUserHandles != null) && (perUserInstalled != null); 12731 PackageSetting disabledPs = null; 12732 // Confirm if the system package has been updated 12733 // An updated system app can be deleted. This will also have to restore 12734 // the system pkg from system partition 12735 // reader 12736 synchronized (mPackages) { 12737 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12738 } 12739 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12740 + " disabledPs=" + disabledPs); 12741 if (disabledPs == null) { 12742 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12743 return false; 12744 } else if (DEBUG_REMOVE) { 12745 Slog.d(TAG, "Deleting system pkg from data partition"); 12746 } 12747 if (DEBUG_REMOVE) { 12748 if (applyUserRestrictions) { 12749 Slog.d(TAG, "Remembering install states:"); 12750 for (int i = 0; i < allUserHandles.length; i++) { 12751 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12752 } 12753 } 12754 } 12755 // Delete the updated package 12756 outInfo.isRemovedPackageSystemUpdate = true; 12757 if (disabledPs.versionCode < newPs.versionCode) { 12758 // Delete data for downgrades 12759 flags &= ~PackageManager.DELETE_KEEP_DATA; 12760 } else { 12761 // Preserve data by setting flag 12762 flags |= PackageManager.DELETE_KEEP_DATA; 12763 } 12764 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12765 allUserHandles, perUserInstalled, outInfo, writeSettings); 12766 if (!ret) { 12767 return false; 12768 } 12769 // writer 12770 synchronized (mPackages) { 12771 // Reinstate the old system package 12772 mSettings.enableSystemPackageLPw(newPs.name); 12773 // Remove any native libraries from the upgraded package. 12774 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12775 } 12776 // Install the system package 12777 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12778 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12779 if (locationIsPrivileged(disabledPs.codePath)) { 12780 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12781 } 12782 12783 final PackageParser.Package newPkg; 12784 try { 12785 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12786 } catch (PackageManagerException e) { 12787 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12788 return false; 12789 } 12790 12791 // writer 12792 synchronized (mPackages) { 12793 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12794 12795 // Propagate the permissions state as we do want to drop on the floor 12796 // runtime permissions. The update permissions method below will take 12797 // care of removing obsolete permissions and grant install permissions. 12798 ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState()); 12799 updatePermissionsLPw(newPkg.packageName, newPkg, 12800 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12801 12802 if (applyUserRestrictions) { 12803 if (DEBUG_REMOVE) { 12804 Slog.d(TAG, "Propagating install state across reinstall"); 12805 } 12806 for (int i = 0; i < allUserHandles.length; i++) { 12807 if (DEBUG_REMOVE) { 12808 Slog.d(TAG, " user " + allUserHandles[i] 12809 + " => " + perUserInstalled[i]); 12810 } 12811 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12812 } 12813 // Regardless of writeSettings we need to ensure that this restriction 12814 // state propagation is persisted 12815 mSettings.writeAllUsersPackageRestrictionsLPr(); 12816 } 12817 // can downgrade to reader here 12818 if (writeSettings) { 12819 mSettings.writeLPr(); 12820 } 12821 } 12822 return true; 12823 } 12824 12825 private boolean deleteInstalledPackageLI(PackageSetting ps, 12826 boolean deleteCodeAndResources, int flags, 12827 int[] allUserHandles, boolean[] perUserInstalled, 12828 PackageRemovedInfo outInfo, boolean writeSettings) { 12829 if (outInfo != null) { 12830 outInfo.uid = ps.appId; 12831 } 12832 12833 // Delete package data from internal structures and also remove data if flag is set 12834 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12835 12836 // Delete application code and resources 12837 if (deleteCodeAndResources && (outInfo != null)) { 12838 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12839 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12840 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12841 } 12842 return true; 12843 } 12844 12845 @Override 12846 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12847 int userId) { 12848 mContext.enforceCallingOrSelfPermission( 12849 android.Manifest.permission.DELETE_PACKAGES, null); 12850 synchronized (mPackages) { 12851 PackageSetting ps = mSettings.mPackages.get(packageName); 12852 if (ps == null) { 12853 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12854 return false; 12855 } 12856 if (!ps.getInstalled(userId)) { 12857 // Can't block uninstall for an app that is not installed or enabled. 12858 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12859 return false; 12860 } 12861 ps.setBlockUninstall(blockUninstall, userId); 12862 mSettings.writePackageRestrictionsLPr(userId); 12863 } 12864 return true; 12865 } 12866 12867 @Override 12868 public boolean getBlockUninstallForUser(String packageName, int userId) { 12869 synchronized (mPackages) { 12870 PackageSetting ps = mSettings.mPackages.get(packageName); 12871 if (ps == null) { 12872 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12873 return false; 12874 } 12875 return ps.getBlockUninstall(userId); 12876 } 12877 } 12878 12879 /* 12880 * This method handles package deletion in general 12881 */ 12882 private boolean deletePackageLI(String packageName, UserHandle user, 12883 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12884 int flags, PackageRemovedInfo outInfo, 12885 boolean writeSettings) { 12886 if (packageName == null) { 12887 Slog.w(TAG, "Attempt to delete null packageName."); 12888 return false; 12889 } 12890 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12891 PackageSetting ps; 12892 boolean dataOnly = false; 12893 int removeUser = -1; 12894 int appId = -1; 12895 synchronized (mPackages) { 12896 ps = mSettings.mPackages.get(packageName); 12897 if (ps == null) { 12898 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12899 return false; 12900 } 12901 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12902 && user.getIdentifier() != UserHandle.USER_ALL) { 12903 // The caller is asking that the package only be deleted for a single 12904 // user. To do this, we just mark its uninstalled state and delete 12905 // its data. If this is a system app, we only allow this to happen if 12906 // they have set the special DELETE_SYSTEM_APP which requests different 12907 // semantics than normal for uninstalling system apps. 12908 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12909 ps.setUserState(user.getIdentifier(), 12910 COMPONENT_ENABLED_STATE_DEFAULT, 12911 false, //installed 12912 true, //stopped 12913 true, //notLaunched 12914 false, //hidden 12915 null, null, null, 12916 false, // blockUninstall 12917 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12918 if (!isSystemApp(ps)) { 12919 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12920 // Other user still have this package installed, so all 12921 // we need to do is clear this user's data and save that 12922 // it is uninstalled. 12923 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12924 removeUser = user.getIdentifier(); 12925 appId = ps.appId; 12926 scheduleWritePackageRestrictionsLocked(removeUser); 12927 } else { 12928 // We need to set it back to 'installed' so the uninstall 12929 // broadcasts will be sent correctly. 12930 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12931 ps.setInstalled(true, user.getIdentifier()); 12932 } 12933 } else { 12934 // This is a system app, so we assume that the 12935 // other users still have this package installed, so all 12936 // we need to do is clear this user's data and save that 12937 // it is uninstalled. 12938 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12939 removeUser = user.getIdentifier(); 12940 appId = ps.appId; 12941 scheduleWritePackageRestrictionsLocked(removeUser); 12942 } 12943 } 12944 } 12945 12946 if (removeUser >= 0) { 12947 // From above, we determined that we are deleting this only 12948 // for a single user. Continue the work here. 12949 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12950 if (outInfo != null) { 12951 outInfo.removedPackage = packageName; 12952 outInfo.removedAppId = appId; 12953 outInfo.removedUsers = new int[] {removeUser}; 12954 } 12955 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12956 removeKeystoreDataIfNeeded(removeUser, appId); 12957 schedulePackageCleaning(packageName, removeUser, false); 12958 synchronized (mPackages) { 12959 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12960 scheduleWritePackageRestrictionsLocked(removeUser); 12961 } 12962 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser); 12963 } 12964 return true; 12965 } 12966 12967 if (dataOnly) { 12968 // Delete application data first 12969 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12970 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12971 return true; 12972 } 12973 12974 boolean ret = false; 12975 if (isSystemApp(ps)) { 12976 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12977 // When an updated system application is deleted we delete the existing resources as well and 12978 // fall back to existing code in system partition 12979 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12980 flags, outInfo, writeSettings); 12981 } else { 12982 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12983 // Kill application pre-emptively especially for apps on sd. 12984 killApplication(packageName, ps.appId, "uninstall pkg"); 12985 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12986 allUserHandles, perUserInstalled, 12987 outInfo, writeSettings); 12988 } 12989 12990 return ret; 12991 } 12992 12993 private final class ClearStorageConnection implements ServiceConnection { 12994 IMediaContainerService mContainerService; 12995 12996 @Override 12997 public void onServiceConnected(ComponentName name, IBinder service) { 12998 synchronized (this) { 12999 mContainerService = IMediaContainerService.Stub.asInterface(service); 13000 notifyAll(); 13001 } 13002 } 13003 13004 @Override 13005 public void onServiceDisconnected(ComponentName name) { 13006 } 13007 } 13008 13009 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13010 final boolean mounted; 13011 if (Environment.isExternalStorageEmulated()) { 13012 mounted = true; 13013 } else { 13014 final String status = Environment.getExternalStorageState(); 13015 13016 mounted = status.equals(Environment.MEDIA_MOUNTED) 13017 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13018 } 13019 13020 if (!mounted) { 13021 return; 13022 } 13023 13024 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13025 int[] users; 13026 if (userId == UserHandle.USER_ALL) { 13027 users = sUserManager.getUserIds(); 13028 } else { 13029 users = new int[] { userId }; 13030 } 13031 final ClearStorageConnection conn = new ClearStorageConnection(); 13032 if (mContext.bindServiceAsUser( 13033 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13034 try { 13035 for (int curUser : users) { 13036 long timeout = SystemClock.uptimeMillis() + 5000; 13037 synchronized (conn) { 13038 long now = SystemClock.uptimeMillis(); 13039 while (conn.mContainerService == null && now < timeout) { 13040 try { 13041 conn.wait(timeout - now); 13042 } catch (InterruptedException e) { 13043 } 13044 } 13045 } 13046 if (conn.mContainerService == null) { 13047 return; 13048 } 13049 13050 final UserEnvironment userEnv = new UserEnvironment(curUser); 13051 clearDirectory(conn.mContainerService, 13052 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13053 if (allData) { 13054 clearDirectory(conn.mContainerService, 13055 userEnv.buildExternalStorageAppDataDirs(packageName)); 13056 clearDirectory(conn.mContainerService, 13057 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13058 } 13059 } 13060 } finally { 13061 mContext.unbindService(conn); 13062 } 13063 } 13064 } 13065 13066 @Override 13067 public void clearApplicationUserData(final String packageName, 13068 final IPackageDataObserver observer, final int userId) { 13069 mContext.enforceCallingOrSelfPermission( 13070 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13071 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13072 // Queue up an async operation since the package deletion may take a little while. 13073 mHandler.post(new Runnable() { 13074 public void run() { 13075 mHandler.removeCallbacks(this); 13076 final boolean succeeded; 13077 synchronized (mInstallLock) { 13078 succeeded = clearApplicationUserDataLI(packageName, userId); 13079 } 13080 clearExternalStorageDataSync(packageName, userId, true); 13081 if (succeeded) { 13082 // invoke DeviceStorageMonitor's update method to clear any notifications 13083 DeviceStorageMonitorInternal 13084 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13085 if (dsm != null) { 13086 dsm.checkMemory(); 13087 } 13088 } 13089 if(observer != null) { 13090 try { 13091 observer.onRemoveCompleted(packageName, succeeded); 13092 } catch (RemoteException e) { 13093 Log.i(TAG, "Observer no longer exists."); 13094 } 13095 } //end if observer 13096 } //end run 13097 }); 13098 } 13099 13100 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13101 if (packageName == null) { 13102 Slog.w(TAG, "Attempt to delete null packageName."); 13103 return false; 13104 } 13105 13106 // Try finding details about the requested package 13107 PackageParser.Package pkg; 13108 synchronized (mPackages) { 13109 pkg = mPackages.get(packageName); 13110 if (pkg == null) { 13111 final PackageSetting ps = mSettings.mPackages.get(packageName); 13112 if (ps != null) { 13113 pkg = ps.pkg; 13114 } 13115 } 13116 13117 if (pkg == null) { 13118 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13119 return false; 13120 } 13121 13122 PackageSetting ps = (PackageSetting) pkg.mExtras; 13123 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 13124 } 13125 13126 // Always delete data directories for package, even if we found no other 13127 // record of app. This helps users recover from UID mismatches without 13128 // resorting to a full data wipe. 13129 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13130 if (retCode < 0) { 13131 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13132 return false; 13133 } 13134 13135 final int appId = pkg.applicationInfo.uid; 13136 removeKeystoreDataIfNeeded(userId, appId); 13137 13138 // Create a native library symlink only if we have native libraries 13139 // and if the native libraries are 32 bit libraries. We do not provide 13140 // this symlink for 64 bit libraries. 13141 if (pkg.applicationInfo.primaryCpuAbi != null && 13142 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13143 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13144 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13145 nativeLibPath, userId) < 0) { 13146 Slog.w(TAG, "Failed linking native library dir"); 13147 return false; 13148 } 13149 } 13150 13151 return true; 13152 } 13153 13154 /** 13155 * Reverts user permission state changes (permissions and flags). 13156 * 13157 * @param ps The package for which to reset. 13158 * @param userId The device user for which to do a reset. 13159 */ 13160 private void resetUserChangesToRuntimePermissionsAndFlagsLocked( 13161 final PackageSetting ps, final int userId) { 13162 if (ps.pkg == null) { 13163 return; 13164 } 13165 13166 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13167 | FLAG_PERMISSION_USER_FIXED 13168 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13169 13170 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13171 | FLAG_PERMISSION_POLICY_FIXED; 13172 13173 boolean writeInstallPermissions = false; 13174 boolean writeRuntimePermissions = false; 13175 13176 final int permissionCount = ps.pkg.requestedPermissions.size(); 13177 for (int i = 0; i < permissionCount; i++) { 13178 String permission = ps.pkg.requestedPermissions.get(i); 13179 13180 BasePermission bp = mSettings.mPermissions.get(permission); 13181 if (bp == null) { 13182 continue; 13183 } 13184 13185 // If shared user we just reset the state to which only this app contributed. 13186 if (ps.sharedUser != null) { 13187 boolean used = false; 13188 final int packageCount = ps.sharedUser.packages.size(); 13189 for (int j = 0; j < packageCount; j++) { 13190 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13191 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13192 && pkg.pkg.requestedPermissions.contains(permission)) { 13193 used = true; 13194 break; 13195 } 13196 } 13197 if (used) { 13198 continue; 13199 } 13200 } 13201 13202 PermissionsState permissionsState = ps.getPermissionsState(); 13203 13204 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13205 13206 // Always clear the user settable flags. 13207 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13208 bp.name) != null; 13209 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13210 if (hasInstallState) { 13211 writeInstallPermissions = true; 13212 } else { 13213 writeRuntimePermissions = true; 13214 } 13215 } 13216 13217 // Below is only runtime permission handling. 13218 if (!bp.isRuntime()) { 13219 continue; 13220 } 13221 13222 // Never clobber system or policy. 13223 if ((oldFlags & policyOrSystemFlags) != 0) { 13224 continue; 13225 } 13226 13227 // If this permission was granted by default, make sure it is. 13228 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13229 if (permissionsState.grantRuntimePermission(bp, userId) 13230 != PERMISSION_OPERATION_FAILURE) { 13231 writeRuntimePermissions = true; 13232 } 13233 } else { 13234 // Otherwise, reset the permission. 13235 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13236 switch (revokeResult) { 13237 case PERMISSION_OPERATION_SUCCESS: { 13238 writeRuntimePermissions = true; 13239 } break; 13240 13241 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13242 writeRuntimePermissions = true; 13243 // If gids changed for this user, kill all affected packages. 13244 mHandler.post(new Runnable() { 13245 @Override 13246 public void run() { 13247 // This has to happen with no lock held. 13248 killSettingPackagesForUser(ps, userId, 13249 KILL_APP_REASON_GIDS_CHANGED); 13250 } 13251 }); 13252 } break; 13253 } 13254 } 13255 } 13256 13257 // Synchronously write as we are taking permissions away. 13258 if (writeRuntimePermissions) { 13259 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13260 } 13261 13262 // Synchronously write as we are taking permissions away. 13263 if (writeInstallPermissions) { 13264 mSettings.writeLPr(); 13265 } 13266 } 13267 13268 /** 13269 * Remove entries from the keystore daemon. Will only remove it if the 13270 * {@code appId} is valid. 13271 */ 13272 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13273 if (appId < 0) { 13274 return; 13275 } 13276 13277 final KeyStore keyStore = KeyStore.getInstance(); 13278 if (keyStore != null) { 13279 if (userId == UserHandle.USER_ALL) { 13280 for (final int individual : sUserManager.getUserIds()) { 13281 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13282 } 13283 } else { 13284 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13285 } 13286 } else { 13287 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13288 } 13289 } 13290 13291 @Override 13292 public void deleteApplicationCacheFiles(final String packageName, 13293 final IPackageDataObserver observer) { 13294 mContext.enforceCallingOrSelfPermission( 13295 android.Manifest.permission.DELETE_CACHE_FILES, null); 13296 // Queue up an async operation since the package deletion may take a little while. 13297 final int userId = UserHandle.getCallingUserId(); 13298 mHandler.post(new Runnable() { 13299 public void run() { 13300 mHandler.removeCallbacks(this); 13301 final boolean succeded; 13302 synchronized (mInstallLock) { 13303 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13304 } 13305 clearExternalStorageDataSync(packageName, userId, false); 13306 if (observer != null) { 13307 try { 13308 observer.onRemoveCompleted(packageName, succeded); 13309 } catch (RemoteException e) { 13310 Log.i(TAG, "Observer no longer exists."); 13311 } 13312 } //end if observer 13313 } //end run 13314 }); 13315 } 13316 13317 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13318 if (packageName == null) { 13319 Slog.w(TAG, "Attempt to delete null packageName."); 13320 return false; 13321 } 13322 PackageParser.Package p; 13323 synchronized (mPackages) { 13324 p = mPackages.get(packageName); 13325 } 13326 if (p == null) { 13327 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13328 return false; 13329 } 13330 final ApplicationInfo applicationInfo = p.applicationInfo; 13331 if (applicationInfo == null) { 13332 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13333 return false; 13334 } 13335 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13336 if (retCode < 0) { 13337 Slog.w(TAG, "Couldn't remove cache files for package: " 13338 + packageName + " u" + userId); 13339 return false; 13340 } 13341 return true; 13342 } 13343 13344 @Override 13345 public void getPackageSizeInfo(final String packageName, int userHandle, 13346 final IPackageStatsObserver observer) { 13347 mContext.enforceCallingOrSelfPermission( 13348 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13349 if (packageName == null) { 13350 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13351 } 13352 13353 PackageStats stats = new PackageStats(packageName, userHandle); 13354 13355 /* 13356 * Queue up an async operation since the package measurement may take a 13357 * little while. 13358 */ 13359 Message msg = mHandler.obtainMessage(INIT_COPY); 13360 msg.obj = new MeasureParams(stats, observer); 13361 mHandler.sendMessage(msg); 13362 } 13363 13364 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13365 PackageStats pStats) { 13366 if (packageName == null) { 13367 Slog.w(TAG, "Attempt to get size of null packageName."); 13368 return false; 13369 } 13370 PackageParser.Package p; 13371 boolean dataOnly = false; 13372 String libDirRoot = null; 13373 String asecPath = null; 13374 PackageSetting ps = null; 13375 synchronized (mPackages) { 13376 p = mPackages.get(packageName); 13377 ps = mSettings.mPackages.get(packageName); 13378 if(p == null) { 13379 dataOnly = true; 13380 if((ps == null) || (ps.pkg == null)) { 13381 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13382 return false; 13383 } 13384 p = ps.pkg; 13385 } 13386 if (ps != null) { 13387 libDirRoot = ps.legacyNativeLibraryPathString; 13388 } 13389 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13390 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13391 if (secureContainerId != null) { 13392 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13393 } 13394 } 13395 } 13396 String publicSrcDir = null; 13397 if(!dataOnly) { 13398 final ApplicationInfo applicationInfo = p.applicationInfo; 13399 if (applicationInfo == null) { 13400 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13401 return false; 13402 } 13403 if (p.isForwardLocked()) { 13404 publicSrcDir = applicationInfo.getBaseResourcePath(); 13405 } 13406 } 13407 // TODO: extend to measure size of split APKs 13408 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13409 // not just the first level. 13410 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13411 // just the primary. 13412 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13413 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13414 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13415 if (res < 0) { 13416 return false; 13417 } 13418 13419 // Fix-up for forward-locked applications in ASEC containers. 13420 if (!isExternal(p)) { 13421 pStats.codeSize += pStats.externalCodeSize; 13422 pStats.externalCodeSize = 0L; 13423 } 13424 13425 return true; 13426 } 13427 13428 13429 @Override 13430 public void addPackageToPreferred(String packageName) { 13431 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13432 } 13433 13434 @Override 13435 public void removePackageFromPreferred(String packageName) { 13436 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13437 } 13438 13439 @Override 13440 public List<PackageInfo> getPreferredPackages(int flags) { 13441 return new ArrayList<PackageInfo>(); 13442 } 13443 13444 private int getUidTargetSdkVersionLockedLPr(int uid) { 13445 Object obj = mSettings.getUserIdLPr(uid); 13446 if (obj instanceof SharedUserSetting) { 13447 final SharedUserSetting sus = (SharedUserSetting) obj; 13448 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13449 final Iterator<PackageSetting> it = sus.packages.iterator(); 13450 while (it.hasNext()) { 13451 final PackageSetting ps = it.next(); 13452 if (ps.pkg != null) { 13453 int v = ps.pkg.applicationInfo.targetSdkVersion; 13454 if (v < vers) vers = v; 13455 } 13456 } 13457 return vers; 13458 } else if (obj instanceof PackageSetting) { 13459 final PackageSetting ps = (PackageSetting) obj; 13460 if (ps.pkg != null) { 13461 return ps.pkg.applicationInfo.targetSdkVersion; 13462 } 13463 } 13464 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13465 } 13466 13467 @Override 13468 public void addPreferredActivity(IntentFilter filter, int match, 13469 ComponentName[] set, ComponentName activity, int userId) { 13470 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13471 "Adding preferred"); 13472 } 13473 13474 private void addPreferredActivityInternal(IntentFilter filter, int match, 13475 ComponentName[] set, ComponentName activity, boolean always, int userId, 13476 String opname) { 13477 // writer 13478 int callingUid = Binder.getCallingUid(); 13479 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13480 if (filter.countActions() == 0) { 13481 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13482 return; 13483 } 13484 synchronized (mPackages) { 13485 if (mContext.checkCallingOrSelfPermission( 13486 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13487 != PackageManager.PERMISSION_GRANTED) { 13488 if (getUidTargetSdkVersionLockedLPr(callingUid) 13489 < Build.VERSION_CODES.FROYO) { 13490 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13491 + callingUid); 13492 return; 13493 } 13494 mContext.enforceCallingOrSelfPermission( 13495 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13496 } 13497 13498 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13499 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13500 + userId + ":"); 13501 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13502 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13503 scheduleWritePackageRestrictionsLocked(userId); 13504 } 13505 } 13506 13507 @Override 13508 public void replacePreferredActivity(IntentFilter filter, int match, 13509 ComponentName[] set, ComponentName activity, int userId) { 13510 if (filter.countActions() != 1) { 13511 throw new IllegalArgumentException( 13512 "replacePreferredActivity expects filter to have only 1 action."); 13513 } 13514 if (filter.countDataAuthorities() != 0 13515 || filter.countDataPaths() != 0 13516 || filter.countDataSchemes() > 1 13517 || filter.countDataTypes() != 0) { 13518 throw new IllegalArgumentException( 13519 "replacePreferredActivity expects filter to have no data authorities, " + 13520 "paths, or types; and at most one scheme."); 13521 } 13522 13523 final int callingUid = Binder.getCallingUid(); 13524 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13525 synchronized (mPackages) { 13526 if (mContext.checkCallingOrSelfPermission( 13527 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13528 != PackageManager.PERMISSION_GRANTED) { 13529 if (getUidTargetSdkVersionLockedLPr(callingUid) 13530 < Build.VERSION_CODES.FROYO) { 13531 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13532 + Binder.getCallingUid()); 13533 return; 13534 } 13535 mContext.enforceCallingOrSelfPermission( 13536 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13537 } 13538 13539 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13540 if (pir != null) { 13541 // Get all of the existing entries that exactly match this filter. 13542 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13543 if (existing != null && existing.size() == 1) { 13544 PreferredActivity cur = existing.get(0); 13545 if (DEBUG_PREFERRED) { 13546 Slog.i(TAG, "Checking replace of preferred:"); 13547 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13548 if (!cur.mPref.mAlways) { 13549 Slog.i(TAG, " -- CUR; not mAlways!"); 13550 } else { 13551 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13552 Slog.i(TAG, " -- CUR: mSet=" 13553 + Arrays.toString(cur.mPref.mSetComponents)); 13554 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13555 Slog.i(TAG, " -- NEW: mMatch=" 13556 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13557 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13558 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13559 } 13560 } 13561 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13562 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13563 && cur.mPref.sameSet(set)) { 13564 // Setting the preferred activity to what it happens to be already 13565 if (DEBUG_PREFERRED) { 13566 Slog.i(TAG, "Replacing with same preferred activity " 13567 + cur.mPref.mShortComponent + " for user " 13568 + userId + ":"); 13569 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13570 } 13571 return; 13572 } 13573 } 13574 13575 if (existing != null) { 13576 if (DEBUG_PREFERRED) { 13577 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13578 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13579 } 13580 for (int i = 0; i < existing.size(); i++) { 13581 PreferredActivity pa = existing.get(i); 13582 if (DEBUG_PREFERRED) { 13583 Slog.i(TAG, "Removing existing preferred activity " 13584 + pa.mPref.mComponent + ":"); 13585 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13586 } 13587 pir.removeFilter(pa); 13588 } 13589 } 13590 } 13591 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13592 "Replacing preferred"); 13593 } 13594 } 13595 13596 @Override 13597 public void clearPackagePreferredActivities(String packageName) { 13598 final int uid = Binder.getCallingUid(); 13599 // writer 13600 synchronized (mPackages) { 13601 PackageParser.Package pkg = mPackages.get(packageName); 13602 if (pkg == null || pkg.applicationInfo.uid != uid) { 13603 if (mContext.checkCallingOrSelfPermission( 13604 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13605 != PackageManager.PERMISSION_GRANTED) { 13606 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13607 < Build.VERSION_CODES.FROYO) { 13608 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13609 + Binder.getCallingUid()); 13610 return; 13611 } 13612 mContext.enforceCallingOrSelfPermission( 13613 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13614 } 13615 } 13616 13617 int user = UserHandle.getCallingUserId(); 13618 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13619 scheduleWritePackageRestrictionsLocked(user); 13620 } 13621 } 13622 } 13623 13624 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13625 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13626 ArrayList<PreferredActivity> removed = null; 13627 boolean changed = false; 13628 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13629 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13630 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13631 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13632 continue; 13633 } 13634 Iterator<PreferredActivity> it = pir.filterIterator(); 13635 while (it.hasNext()) { 13636 PreferredActivity pa = it.next(); 13637 // Mark entry for removal only if it matches the package name 13638 // and the entry is of type "always". 13639 if (packageName == null || 13640 (pa.mPref.mComponent.getPackageName().equals(packageName) 13641 && pa.mPref.mAlways)) { 13642 if (removed == null) { 13643 removed = new ArrayList<PreferredActivity>(); 13644 } 13645 removed.add(pa); 13646 } 13647 } 13648 if (removed != null) { 13649 for (int j=0; j<removed.size(); j++) { 13650 PreferredActivity pa = removed.get(j); 13651 pir.removeFilter(pa); 13652 } 13653 changed = true; 13654 } 13655 } 13656 return changed; 13657 } 13658 13659 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13660 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13661 if (userId == UserHandle.USER_ALL) { 13662 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13663 sUserManager.getUserIds())) { 13664 for (int oneUserId : sUserManager.getUserIds()) { 13665 scheduleWritePackageRestrictionsLocked(oneUserId); 13666 } 13667 } 13668 } else { 13669 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13670 scheduleWritePackageRestrictionsLocked(userId); 13671 } 13672 } 13673 } 13674 13675 13676 void clearDefaultBrowserIfNeeded(String packageName) { 13677 for (int oneUserId : sUserManager.getUserIds()) { 13678 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13679 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13680 if (packageName.equals(defaultBrowserPackageName)) { 13681 setDefaultBrowserPackageName(null, oneUserId); 13682 } 13683 } 13684 } 13685 13686 @Override 13687 public void resetPreferredActivities(int userId) { 13688 mContext.enforceCallingOrSelfPermission( 13689 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13690 // writer 13691 synchronized (mPackages) { 13692 clearPackagePreferredActivitiesLPw(null, userId); 13693 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13694 applyFactoryDefaultBrowserLPw(userId); 13695 primeDomainVerificationsLPw(userId); 13696 13697 scheduleWritePackageRestrictionsLocked(userId); 13698 } 13699 } 13700 13701 @Override 13702 public int getPreferredActivities(List<IntentFilter> outFilters, 13703 List<ComponentName> outActivities, String packageName) { 13704 13705 int num = 0; 13706 final int userId = UserHandle.getCallingUserId(); 13707 // reader 13708 synchronized (mPackages) { 13709 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13710 if (pir != null) { 13711 final Iterator<PreferredActivity> it = pir.filterIterator(); 13712 while (it.hasNext()) { 13713 final PreferredActivity pa = it.next(); 13714 if (packageName == null 13715 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13716 && pa.mPref.mAlways)) { 13717 if (outFilters != null) { 13718 outFilters.add(new IntentFilter(pa)); 13719 } 13720 if (outActivities != null) { 13721 outActivities.add(pa.mPref.mComponent); 13722 } 13723 } 13724 } 13725 } 13726 } 13727 13728 return num; 13729 } 13730 13731 @Override 13732 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13733 int userId) { 13734 int callingUid = Binder.getCallingUid(); 13735 if (callingUid != Process.SYSTEM_UID) { 13736 throw new SecurityException( 13737 "addPersistentPreferredActivity can only be run by the system"); 13738 } 13739 if (filter.countActions() == 0) { 13740 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13741 return; 13742 } 13743 synchronized (mPackages) { 13744 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13745 " :"); 13746 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13747 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13748 new PersistentPreferredActivity(filter, activity)); 13749 scheduleWritePackageRestrictionsLocked(userId); 13750 } 13751 } 13752 13753 @Override 13754 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13755 int callingUid = Binder.getCallingUid(); 13756 if (callingUid != Process.SYSTEM_UID) { 13757 throw new SecurityException( 13758 "clearPackagePersistentPreferredActivities can only be run by the system"); 13759 } 13760 ArrayList<PersistentPreferredActivity> removed = null; 13761 boolean changed = false; 13762 synchronized (mPackages) { 13763 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13764 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13765 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13766 .valueAt(i); 13767 if (userId != thisUserId) { 13768 continue; 13769 } 13770 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13771 while (it.hasNext()) { 13772 PersistentPreferredActivity ppa = it.next(); 13773 // Mark entry for removal only if it matches the package name. 13774 if (ppa.mComponent.getPackageName().equals(packageName)) { 13775 if (removed == null) { 13776 removed = new ArrayList<PersistentPreferredActivity>(); 13777 } 13778 removed.add(ppa); 13779 } 13780 } 13781 if (removed != null) { 13782 for (int j=0; j<removed.size(); j++) { 13783 PersistentPreferredActivity ppa = removed.get(j); 13784 ppir.removeFilter(ppa); 13785 } 13786 changed = true; 13787 } 13788 } 13789 13790 if (changed) { 13791 scheduleWritePackageRestrictionsLocked(userId); 13792 } 13793 } 13794 } 13795 13796 /** 13797 * Common machinery for picking apart a restored XML blob and passing 13798 * it to a caller-supplied functor to be applied to the running system. 13799 */ 13800 private void restoreFromXml(XmlPullParser parser, int userId, 13801 String expectedStartTag, BlobXmlRestorer functor) 13802 throws IOException, XmlPullParserException { 13803 int type; 13804 while ((type = parser.next()) != XmlPullParser.START_TAG 13805 && type != XmlPullParser.END_DOCUMENT) { 13806 } 13807 if (type != XmlPullParser.START_TAG) { 13808 // oops didn't find a start tag?! 13809 if (DEBUG_BACKUP) { 13810 Slog.e(TAG, "Didn't find start tag during restore"); 13811 } 13812 return; 13813 } 13814 13815 // this is supposed to be TAG_PREFERRED_BACKUP 13816 if (!expectedStartTag.equals(parser.getName())) { 13817 if (DEBUG_BACKUP) { 13818 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13819 } 13820 return; 13821 } 13822 13823 // skip interfering stuff, then we're aligned with the backing implementation 13824 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13825 functor.apply(parser, userId); 13826 } 13827 13828 private interface BlobXmlRestorer { 13829 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13830 } 13831 13832 /** 13833 * Non-Binder method, support for the backup/restore mechanism: write the 13834 * full set of preferred activities in its canonical XML format. Returns the 13835 * XML output as a byte array, or null if there is none. 13836 */ 13837 @Override 13838 public byte[] getPreferredActivityBackup(int userId) { 13839 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13840 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13841 } 13842 13843 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13844 try { 13845 final XmlSerializer serializer = new FastXmlSerializer(); 13846 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13847 serializer.startDocument(null, true); 13848 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13849 13850 synchronized (mPackages) { 13851 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13852 } 13853 13854 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13855 serializer.endDocument(); 13856 serializer.flush(); 13857 } catch (Exception e) { 13858 if (DEBUG_BACKUP) { 13859 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13860 } 13861 return null; 13862 } 13863 13864 return dataStream.toByteArray(); 13865 } 13866 13867 @Override 13868 public void restorePreferredActivities(byte[] backup, int userId) { 13869 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13870 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13871 } 13872 13873 try { 13874 final XmlPullParser parser = Xml.newPullParser(); 13875 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13876 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13877 new BlobXmlRestorer() { 13878 @Override 13879 public void apply(XmlPullParser parser, int userId) 13880 throws XmlPullParserException, IOException { 13881 synchronized (mPackages) { 13882 mSettings.readPreferredActivitiesLPw(parser, userId); 13883 } 13884 } 13885 } ); 13886 } catch (Exception e) { 13887 if (DEBUG_BACKUP) { 13888 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13889 } 13890 } 13891 } 13892 13893 /** 13894 * Non-Binder method, support for the backup/restore mechanism: write the 13895 * default browser (etc) settings in its canonical XML format. Returns the default 13896 * browser XML representation as a byte array, or null if there is none. 13897 */ 13898 @Override 13899 public byte[] getDefaultAppsBackup(int userId) { 13900 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13901 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13902 } 13903 13904 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13905 try { 13906 final XmlSerializer serializer = new FastXmlSerializer(); 13907 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13908 serializer.startDocument(null, true); 13909 serializer.startTag(null, TAG_DEFAULT_APPS); 13910 13911 synchronized (mPackages) { 13912 mSettings.writeDefaultAppsLPr(serializer, userId); 13913 } 13914 13915 serializer.endTag(null, TAG_DEFAULT_APPS); 13916 serializer.endDocument(); 13917 serializer.flush(); 13918 } catch (Exception e) { 13919 if (DEBUG_BACKUP) { 13920 Slog.e(TAG, "Unable to write default apps for backup", e); 13921 } 13922 return null; 13923 } 13924 13925 return dataStream.toByteArray(); 13926 } 13927 13928 @Override 13929 public void restoreDefaultApps(byte[] backup, int userId) { 13930 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13931 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13932 } 13933 13934 try { 13935 final XmlPullParser parser = Xml.newPullParser(); 13936 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13937 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13938 new BlobXmlRestorer() { 13939 @Override 13940 public void apply(XmlPullParser parser, int userId) 13941 throws XmlPullParserException, IOException { 13942 synchronized (mPackages) { 13943 mSettings.readDefaultAppsLPw(parser, userId); 13944 } 13945 } 13946 } ); 13947 } catch (Exception e) { 13948 if (DEBUG_BACKUP) { 13949 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13950 } 13951 } 13952 } 13953 13954 @Override 13955 public byte[] getIntentFilterVerificationBackup(int userId) { 13956 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13957 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13958 } 13959 13960 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13961 try { 13962 final XmlSerializer serializer = new FastXmlSerializer(); 13963 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13964 serializer.startDocument(null, true); 13965 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13966 13967 synchronized (mPackages) { 13968 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13969 } 13970 13971 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13972 serializer.endDocument(); 13973 serializer.flush(); 13974 } catch (Exception e) { 13975 if (DEBUG_BACKUP) { 13976 Slog.e(TAG, "Unable to write default apps for backup", e); 13977 } 13978 return null; 13979 } 13980 13981 return dataStream.toByteArray(); 13982 } 13983 13984 @Override 13985 public void restoreIntentFilterVerification(byte[] backup, int userId) { 13986 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13987 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13988 } 13989 13990 try { 13991 final XmlPullParser parser = Xml.newPullParser(); 13992 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13993 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 13994 new BlobXmlRestorer() { 13995 @Override 13996 public void apply(XmlPullParser parser, int userId) 13997 throws XmlPullParserException, IOException { 13998 synchronized (mPackages) { 13999 mSettings.readAllDomainVerificationsLPr(parser, userId); 14000 mSettings.writeLPr(); 14001 } 14002 } 14003 } ); 14004 } catch (Exception e) { 14005 if (DEBUG_BACKUP) { 14006 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14007 } 14008 } 14009 } 14010 14011 @Override 14012 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14013 int sourceUserId, int targetUserId, int flags) { 14014 mContext.enforceCallingOrSelfPermission( 14015 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14016 int callingUid = Binder.getCallingUid(); 14017 enforceOwnerRights(ownerPackage, callingUid); 14018 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14019 if (intentFilter.countActions() == 0) { 14020 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14021 return; 14022 } 14023 synchronized (mPackages) { 14024 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14025 ownerPackage, targetUserId, flags); 14026 CrossProfileIntentResolver resolver = 14027 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14028 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14029 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14030 if (existing != null) { 14031 int size = existing.size(); 14032 for (int i = 0; i < size; i++) { 14033 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14034 return; 14035 } 14036 } 14037 } 14038 resolver.addFilter(newFilter); 14039 scheduleWritePackageRestrictionsLocked(sourceUserId); 14040 } 14041 } 14042 14043 @Override 14044 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14045 mContext.enforceCallingOrSelfPermission( 14046 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14047 int callingUid = Binder.getCallingUid(); 14048 enforceOwnerRights(ownerPackage, callingUid); 14049 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14050 synchronized (mPackages) { 14051 CrossProfileIntentResolver resolver = 14052 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14053 ArraySet<CrossProfileIntentFilter> set = 14054 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14055 for (CrossProfileIntentFilter filter : set) { 14056 if (filter.getOwnerPackage().equals(ownerPackage)) { 14057 resolver.removeFilter(filter); 14058 } 14059 } 14060 scheduleWritePackageRestrictionsLocked(sourceUserId); 14061 } 14062 } 14063 14064 // Enforcing that callingUid is owning pkg on userId 14065 private void enforceOwnerRights(String pkg, int callingUid) { 14066 // The system owns everything. 14067 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14068 return; 14069 } 14070 int callingUserId = UserHandle.getUserId(callingUid); 14071 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14072 if (pi == null) { 14073 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14074 + callingUserId); 14075 } 14076 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14077 throw new SecurityException("Calling uid " + callingUid 14078 + " does not own package " + pkg); 14079 } 14080 } 14081 14082 @Override 14083 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14084 Intent intent = new Intent(Intent.ACTION_MAIN); 14085 intent.addCategory(Intent.CATEGORY_HOME); 14086 14087 final int callingUserId = UserHandle.getCallingUserId(); 14088 List<ResolveInfo> list = queryIntentActivities(intent, null, 14089 PackageManager.GET_META_DATA, callingUserId); 14090 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14091 true, false, false, callingUserId); 14092 14093 allHomeCandidates.clear(); 14094 if (list != null) { 14095 for (ResolveInfo ri : list) { 14096 allHomeCandidates.add(ri); 14097 } 14098 } 14099 return (preferred == null || preferred.activityInfo == null) 14100 ? null 14101 : new ComponentName(preferred.activityInfo.packageName, 14102 preferred.activityInfo.name); 14103 } 14104 14105 @Override 14106 public void setApplicationEnabledSetting(String appPackageName, 14107 int newState, int flags, int userId, String callingPackage) { 14108 if (!sUserManager.exists(userId)) return; 14109 if (callingPackage == null) { 14110 callingPackage = Integer.toString(Binder.getCallingUid()); 14111 } 14112 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14113 } 14114 14115 @Override 14116 public void setComponentEnabledSetting(ComponentName componentName, 14117 int newState, int flags, int userId) { 14118 if (!sUserManager.exists(userId)) return; 14119 setEnabledSetting(componentName.getPackageName(), 14120 componentName.getClassName(), newState, flags, userId, null); 14121 } 14122 14123 private void setEnabledSetting(final String packageName, String className, int newState, 14124 final int flags, int userId, String callingPackage) { 14125 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14126 || newState == COMPONENT_ENABLED_STATE_ENABLED 14127 || newState == COMPONENT_ENABLED_STATE_DISABLED 14128 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14129 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14130 throw new IllegalArgumentException("Invalid new component state: " 14131 + newState); 14132 } 14133 PackageSetting pkgSetting; 14134 final int uid = Binder.getCallingUid(); 14135 final int permission = mContext.checkCallingOrSelfPermission( 14136 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14137 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14138 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14139 boolean sendNow = false; 14140 boolean isApp = (className == null); 14141 String componentName = isApp ? packageName : className; 14142 int packageUid = -1; 14143 ArrayList<String> components; 14144 14145 // writer 14146 synchronized (mPackages) { 14147 pkgSetting = mSettings.mPackages.get(packageName); 14148 if (pkgSetting == null) { 14149 if (className == null) { 14150 throw new IllegalArgumentException( 14151 "Unknown package: " + packageName); 14152 } 14153 throw new IllegalArgumentException( 14154 "Unknown component: " + packageName 14155 + "/" + className); 14156 } 14157 // Allow root and verify that userId is not being specified by a different user 14158 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14159 throw new SecurityException( 14160 "Permission Denial: attempt to change component state from pid=" 14161 + Binder.getCallingPid() 14162 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14163 } 14164 if (className == null) { 14165 // We're dealing with an application/package level state change 14166 if (pkgSetting.getEnabled(userId) == newState) { 14167 // Nothing to do 14168 return; 14169 } 14170 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14171 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14172 // Don't care about who enables an app. 14173 callingPackage = null; 14174 } 14175 pkgSetting.setEnabled(newState, userId, callingPackage); 14176 // pkgSetting.pkg.mSetEnabled = newState; 14177 } else { 14178 // We're dealing with a component level state change 14179 // First, verify that this is a valid class name. 14180 PackageParser.Package pkg = pkgSetting.pkg; 14181 if (pkg == null || !pkg.hasComponentClassName(className)) { 14182 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14183 throw new IllegalArgumentException("Component class " + className 14184 + " does not exist in " + packageName); 14185 } else { 14186 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14187 + className + " does not exist in " + packageName); 14188 } 14189 } 14190 switch (newState) { 14191 case COMPONENT_ENABLED_STATE_ENABLED: 14192 if (!pkgSetting.enableComponentLPw(className, userId)) { 14193 return; 14194 } 14195 break; 14196 case COMPONENT_ENABLED_STATE_DISABLED: 14197 if (!pkgSetting.disableComponentLPw(className, userId)) { 14198 return; 14199 } 14200 break; 14201 case COMPONENT_ENABLED_STATE_DEFAULT: 14202 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14203 return; 14204 } 14205 break; 14206 default: 14207 Slog.e(TAG, "Invalid new component state: " + newState); 14208 return; 14209 } 14210 } 14211 scheduleWritePackageRestrictionsLocked(userId); 14212 components = mPendingBroadcasts.get(userId, packageName); 14213 final boolean newPackage = components == null; 14214 if (newPackage) { 14215 components = new ArrayList<String>(); 14216 } 14217 if (!components.contains(componentName)) { 14218 components.add(componentName); 14219 } 14220 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14221 sendNow = true; 14222 // Purge entry from pending broadcast list if another one exists already 14223 // since we are sending one right away. 14224 mPendingBroadcasts.remove(userId, packageName); 14225 } else { 14226 if (newPackage) { 14227 mPendingBroadcasts.put(userId, packageName, components); 14228 } 14229 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14230 // Schedule a message 14231 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14232 } 14233 } 14234 } 14235 14236 long callingId = Binder.clearCallingIdentity(); 14237 try { 14238 if (sendNow) { 14239 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14240 sendPackageChangedBroadcast(packageName, 14241 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14242 } 14243 } finally { 14244 Binder.restoreCallingIdentity(callingId); 14245 } 14246 } 14247 14248 private void sendPackageChangedBroadcast(String packageName, 14249 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14250 if (DEBUG_INSTALL) 14251 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14252 + componentNames); 14253 Bundle extras = new Bundle(4); 14254 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14255 String nameList[] = new String[componentNames.size()]; 14256 componentNames.toArray(nameList); 14257 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14258 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14259 extras.putInt(Intent.EXTRA_UID, packageUid); 14260 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14261 new int[] {UserHandle.getUserId(packageUid)}); 14262 } 14263 14264 @Override 14265 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14266 if (!sUserManager.exists(userId)) return; 14267 final int uid = Binder.getCallingUid(); 14268 final int permission = mContext.checkCallingOrSelfPermission( 14269 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14270 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14271 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14272 // writer 14273 synchronized (mPackages) { 14274 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14275 allowedByPermission, uid, userId)) { 14276 scheduleWritePackageRestrictionsLocked(userId); 14277 } 14278 } 14279 } 14280 14281 @Override 14282 public String getInstallerPackageName(String packageName) { 14283 // reader 14284 synchronized (mPackages) { 14285 return mSettings.getInstallerPackageNameLPr(packageName); 14286 } 14287 } 14288 14289 @Override 14290 public int getApplicationEnabledSetting(String packageName, int userId) { 14291 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14292 int uid = Binder.getCallingUid(); 14293 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14294 // reader 14295 synchronized (mPackages) { 14296 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14297 } 14298 } 14299 14300 @Override 14301 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14302 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14303 int uid = Binder.getCallingUid(); 14304 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14305 // reader 14306 synchronized (mPackages) { 14307 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14308 } 14309 } 14310 14311 @Override 14312 public void enterSafeMode() { 14313 enforceSystemOrRoot("Only the system can request entering safe mode"); 14314 14315 if (!mSystemReady) { 14316 mSafeMode = true; 14317 } 14318 } 14319 14320 @Override 14321 public void systemReady() { 14322 mSystemReady = true; 14323 14324 // Read the compatibilty setting when the system is ready. 14325 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14326 mContext.getContentResolver(), 14327 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14328 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14329 if (DEBUG_SETTINGS) { 14330 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14331 } 14332 14333 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14334 14335 synchronized (mPackages) { 14336 // Verify that all of the preferred activity components actually 14337 // exist. It is possible for applications to be updated and at 14338 // that point remove a previously declared activity component that 14339 // had been set as a preferred activity. We try to clean this up 14340 // the next time we encounter that preferred activity, but it is 14341 // possible for the user flow to never be able to return to that 14342 // situation so here we do a sanity check to make sure we haven't 14343 // left any junk around. 14344 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14345 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14346 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14347 removed.clear(); 14348 for (PreferredActivity pa : pir.filterSet()) { 14349 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14350 removed.add(pa); 14351 } 14352 } 14353 if (removed.size() > 0) { 14354 for (int r=0; r<removed.size(); r++) { 14355 PreferredActivity pa = removed.get(r); 14356 Slog.w(TAG, "Removing dangling preferred activity: " 14357 + pa.mPref.mComponent); 14358 pir.removeFilter(pa); 14359 } 14360 mSettings.writePackageRestrictionsLPr( 14361 mSettings.mPreferredActivities.keyAt(i)); 14362 } 14363 } 14364 14365 for (int userId : UserManagerService.getInstance().getUserIds()) { 14366 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14367 grantPermissionsUserIds = ArrayUtils.appendInt( 14368 grantPermissionsUserIds, userId); 14369 } 14370 } 14371 } 14372 sUserManager.systemReady(); 14373 14374 // If we upgraded grant all default permissions before kicking off. 14375 for (int userId : grantPermissionsUserIds) { 14376 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14377 } 14378 14379 // Kick off any messages waiting for system ready 14380 if (mPostSystemReadyMessages != null) { 14381 for (Message msg : mPostSystemReadyMessages) { 14382 msg.sendToTarget(); 14383 } 14384 mPostSystemReadyMessages = null; 14385 } 14386 14387 // Watch for external volumes that come and go over time 14388 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14389 storage.registerListener(mStorageListener); 14390 14391 mInstallerService.systemReady(); 14392 mPackageDexOptimizer.systemReady(); 14393 } 14394 14395 @Override 14396 public boolean isSafeMode() { 14397 return mSafeMode; 14398 } 14399 14400 @Override 14401 public boolean hasSystemUidErrors() { 14402 return mHasSystemUidErrors; 14403 } 14404 14405 static String arrayToString(int[] array) { 14406 StringBuffer buf = new StringBuffer(128); 14407 buf.append('['); 14408 if (array != null) { 14409 for (int i=0; i<array.length; i++) { 14410 if (i > 0) buf.append(", "); 14411 buf.append(array[i]); 14412 } 14413 } 14414 buf.append(']'); 14415 return buf.toString(); 14416 } 14417 14418 static class DumpState { 14419 public static final int DUMP_LIBS = 1 << 0; 14420 public static final int DUMP_FEATURES = 1 << 1; 14421 public static final int DUMP_RESOLVERS = 1 << 2; 14422 public static final int DUMP_PERMISSIONS = 1 << 3; 14423 public static final int DUMP_PACKAGES = 1 << 4; 14424 public static final int DUMP_SHARED_USERS = 1 << 5; 14425 public static final int DUMP_MESSAGES = 1 << 6; 14426 public static final int DUMP_PROVIDERS = 1 << 7; 14427 public static final int DUMP_VERIFIERS = 1 << 8; 14428 public static final int DUMP_PREFERRED = 1 << 9; 14429 public static final int DUMP_PREFERRED_XML = 1 << 10; 14430 public static final int DUMP_KEYSETS = 1 << 11; 14431 public static final int DUMP_VERSION = 1 << 12; 14432 public static final int DUMP_INSTALLS = 1 << 13; 14433 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14434 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14435 14436 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14437 14438 private int mTypes; 14439 14440 private int mOptions; 14441 14442 private boolean mTitlePrinted; 14443 14444 private SharedUserSetting mSharedUser; 14445 14446 public boolean isDumping(int type) { 14447 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14448 return true; 14449 } 14450 14451 return (mTypes & type) != 0; 14452 } 14453 14454 public void setDump(int type) { 14455 mTypes |= type; 14456 } 14457 14458 public boolean isOptionEnabled(int option) { 14459 return (mOptions & option) != 0; 14460 } 14461 14462 public void setOptionEnabled(int option) { 14463 mOptions |= option; 14464 } 14465 14466 public boolean onTitlePrinted() { 14467 final boolean printed = mTitlePrinted; 14468 mTitlePrinted = true; 14469 return printed; 14470 } 14471 14472 public boolean getTitlePrinted() { 14473 return mTitlePrinted; 14474 } 14475 14476 public void setTitlePrinted(boolean enabled) { 14477 mTitlePrinted = enabled; 14478 } 14479 14480 public SharedUserSetting getSharedUser() { 14481 return mSharedUser; 14482 } 14483 14484 public void setSharedUser(SharedUserSetting user) { 14485 mSharedUser = user; 14486 } 14487 } 14488 14489 @Override 14490 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14491 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14492 != PackageManager.PERMISSION_GRANTED) { 14493 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14494 + Binder.getCallingPid() 14495 + ", uid=" + Binder.getCallingUid() 14496 + " without permission " 14497 + android.Manifest.permission.DUMP); 14498 return; 14499 } 14500 14501 DumpState dumpState = new DumpState(); 14502 boolean fullPreferred = false; 14503 boolean checkin = false; 14504 14505 String packageName = null; 14506 ArraySet<String> permissionNames = null; 14507 14508 int opti = 0; 14509 while (opti < args.length) { 14510 String opt = args[opti]; 14511 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14512 break; 14513 } 14514 opti++; 14515 14516 if ("-a".equals(opt)) { 14517 // Right now we only know how to print all. 14518 } else if ("-h".equals(opt)) { 14519 pw.println("Package manager dump options:"); 14520 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14521 pw.println(" --checkin: dump for a checkin"); 14522 pw.println(" -f: print details of intent filters"); 14523 pw.println(" -h: print this help"); 14524 pw.println(" cmd may be one of:"); 14525 pw.println(" l[ibraries]: list known shared libraries"); 14526 pw.println(" f[ibraries]: list device features"); 14527 pw.println(" k[eysets]: print known keysets"); 14528 pw.println(" r[esolvers]: dump intent resolvers"); 14529 pw.println(" perm[issions]: dump permissions"); 14530 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14531 pw.println(" pref[erred]: print preferred package settings"); 14532 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14533 pw.println(" prov[iders]: dump content providers"); 14534 pw.println(" p[ackages]: dump installed packages"); 14535 pw.println(" s[hared-users]: dump shared user IDs"); 14536 pw.println(" m[essages]: print collected runtime messages"); 14537 pw.println(" v[erifiers]: print package verifier info"); 14538 pw.println(" version: print database version info"); 14539 pw.println(" write: write current settings now"); 14540 pw.println(" <package.name>: info about given package"); 14541 pw.println(" installs: details about install sessions"); 14542 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14543 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14544 return; 14545 } else if ("--checkin".equals(opt)) { 14546 checkin = true; 14547 } else if ("-f".equals(opt)) { 14548 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14549 } else { 14550 pw.println("Unknown argument: " + opt + "; use -h for help"); 14551 } 14552 } 14553 14554 // Is the caller requesting to dump a particular piece of data? 14555 if (opti < args.length) { 14556 String cmd = args[opti]; 14557 opti++; 14558 // Is this a package name? 14559 if ("android".equals(cmd) || cmd.contains(".")) { 14560 packageName = cmd; 14561 // When dumping a single package, we always dump all of its 14562 // filter information since the amount of data will be reasonable. 14563 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14564 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14565 dumpState.setDump(DumpState.DUMP_LIBS); 14566 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14567 dumpState.setDump(DumpState.DUMP_FEATURES); 14568 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14569 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14570 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14571 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14572 } else if ("permission".equals(cmd)) { 14573 if (opti >= args.length) { 14574 pw.println("Error: permission requires permission name"); 14575 return; 14576 } 14577 permissionNames = new ArraySet<>(); 14578 while (opti < args.length) { 14579 permissionNames.add(args[opti]); 14580 opti++; 14581 } 14582 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14583 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14584 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14585 dumpState.setDump(DumpState.DUMP_PREFERRED); 14586 } else if ("preferred-xml".equals(cmd)) { 14587 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14588 if (opti < args.length && "--full".equals(args[opti])) { 14589 fullPreferred = true; 14590 opti++; 14591 } 14592 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14593 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14594 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14595 dumpState.setDump(DumpState.DUMP_PACKAGES); 14596 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14597 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14598 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14599 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14600 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14601 dumpState.setDump(DumpState.DUMP_MESSAGES); 14602 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14603 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14604 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14605 || "intent-filter-verifiers".equals(cmd)) { 14606 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14607 } else if ("version".equals(cmd)) { 14608 dumpState.setDump(DumpState.DUMP_VERSION); 14609 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14610 dumpState.setDump(DumpState.DUMP_KEYSETS); 14611 } else if ("installs".equals(cmd)) { 14612 dumpState.setDump(DumpState.DUMP_INSTALLS); 14613 } else if ("write".equals(cmd)) { 14614 synchronized (mPackages) { 14615 mSettings.writeLPr(); 14616 pw.println("Settings written."); 14617 return; 14618 } 14619 } 14620 } 14621 14622 if (checkin) { 14623 pw.println("vers,1"); 14624 } 14625 14626 // reader 14627 synchronized (mPackages) { 14628 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14629 if (!checkin) { 14630 if (dumpState.onTitlePrinted()) 14631 pw.println(); 14632 pw.println("Database versions:"); 14633 pw.print(" SDK Version:"); 14634 pw.print(" internal="); 14635 pw.print(mSettings.mInternalSdkPlatform); 14636 pw.print(" external="); 14637 pw.println(mSettings.mExternalSdkPlatform); 14638 pw.print(" DB Version:"); 14639 pw.print(" internal="); 14640 pw.print(mSettings.mInternalDatabaseVersion); 14641 pw.print(" external="); 14642 pw.println(mSettings.mExternalDatabaseVersion); 14643 } 14644 } 14645 14646 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14647 if (!checkin) { 14648 if (dumpState.onTitlePrinted()) 14649 pw.println(); 14650 pw.println("Verifiers:"); 14651 pw.print(" Required: "); 14652 pw.print(mRequiredVerifierPackage); 14653 pw.print(" (uid="); 14654 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14655 pw.println(")"); 14656 } else if (mRequiredVerifierPackage != null) { 14657 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14658 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14659 } 14660 } 14661 14662 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14663 packageName == null) { 14664 if (mIntentFilterVerifierComponent != null) { 14665 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14666 if (!checkin) { 14667 if (dumpState.onTitlePrinted()) 14668 pw.println(); 14669 pw.println("Intent Filter Verifier:"); 14670 pw.print(" Using: "); 14671 pw.print(verifierPackageName); 14672 pw.print(" (uid="); 14673 pw.print(getPackageUid(verifierPackageName, 0)); 14674 pw.println(")"); 14675 } else if (verifierPackageName != null) { 14676 pw.print("ifv,"); pw.print(verifierPackageName); 14677 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14678 } 14679 } else { 14680 pw.println(); 14681 pw.println("No Intent Filter Verifier available!"); 14682 } 14683 } 14684 14685 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14686 boolean printedHeader = false; 14687 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14688 while (it.hasNext()) { 14689 String name = it.next(); 14690 SharedLibraryEntry ent = mSharedLibraries.get(name); 14691 if (!checkin) { 14692 if (!printedHeader) { 14693 if (dumpState.onTitlePrinted()) 14694 pw.println(); 14695 pw.println("Libraries:"); 14696 printedHeader = true; 14697 } 14698 pw.print(" "); 14699 } else { 14700 pw.print("lib,"); 14701 } 14702 pw.print(name); 14703 if (!checkin) { 14704 pw.print(" -> "); 14705 } 14706 if (ent.path != null) { 14707 if (!checkin) { 14708 pw.print("(jar) "); 14709 pw.print(ent.path); 14710 } else { 14711 pw.print(",jar,"); 14712 pw.print(ent.path); 14713 } 14714 } else { 14715 if (!checkin) { 14716 pw.print("(apk) "); 14717 pw.print(ent.apk); 14718 } else { 14719 pw.print(",apk,"); 14720 pw.print(ent.apk); 14721 } 14722 } 14723 pw.println(); 14724 } 14725 } 14726 14727 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14728 if (dumpState.onTitlePrinted()) 14729 pw.println(); 14730 if (!checkin) { 14731 pw.println("Features:"); 14732 } 14733 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14734 while (it.hasNext()) { 14735 String name = it.next(); 14736 if (!checkin) { 14737 pw.print(" "); 14738 } else { 14739 pw.print("feat,"); 14740 } 14741 pw.println(name); 14742 } 14743 } 14744 14745 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14746 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14747 : "Activity Resolver Table:", " ", packageName, 14748 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14749 dumpState.setTitlePrinted(true); 14750 } 14751 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14752 : "Receiver Resolver Table:", " ", packageName, 14753 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14754 dumpState.setTitlePrinted(true); 14755 } 14756 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14757 : "Service Resolver Table:", " ", packageName, 14758 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14759 dumpState.setTitlePrinted(true); 14760 } 14761 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14762 : "Provider Resolver Table:", " ", packageName, 14763 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14764 dumpState.setTitlePrinted(true); 14765 } 14766 } 14767 14768 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14769 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14770 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14771 int user = mSettings.mPreferredActivities.keyAt(i); 14772 if (pir.dump(pw, 14773 dumpState.getTitlePrinted() 14774 ? "\nPreferred Activities User " + user + ":" 14775 : "Preferred Activities User " + user + ":", " ", 14776 packageName, true, false)) { 14777 dumpState.setTitlePrinted(true); 14778 } 14779 } 14780 } 14781 14782 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14783 pw.flush(); 14784 FileOutputStream fout = new FileOutputStream(fd); 14785 BufferedOutputStream str = new BufferedOutputStream(fout); 14786 XmlSerializer serializer = new FastXmlSerializer(); 14787 try { 14788 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14789 serializer.startDocument(null, true); 14790 serializer.setFeature( 14791 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14792 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14793 serializer.endDocument(); 14794 serializer.flush(); 14795 } catch (IllegalArgumentException e) { 14796 pw.println("Failed writing: " + e); 14797 } catch (IllegalStateException e) { 14798 pw.println("Failed writing: " + e); 14799 } catch (IOException e) { 14800 pw.println("Failed writing: " + e); 14801 } 14802 } 14803 14804 if (!checkin 14805 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14806 && packageName == null) { 14807 pw.println(); 14808 int count = mSettings.mPackages.size(); 14809 if (count == 0) { 14810 pw.println("No applications!"); 14811 pw.println(); 14812 } else { 14813 final String prefix = " "; 14814 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14815 if (allPackageSettings.size() == 0) { 14816 pw.println("No domain preferred apps!"); 14817 pw.println(); 14818 } else { 14819 pw.println("App verification status:"); 14820 pw.println(); 14821 count = 0; 14822 for (PackageSetting ps : allPackageSettings) { 14823 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14824 if (ivi == null || ivi.getPackageName() == null) continue; 14825 pw.println(prefix + "Package: " + ivi.getPackageName()); 14826 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14827 pw.println(prefix + "Status: " + ivi.getStatusString()); 14828 pw.println(); 14829 count++; 14830 } 14831 if (count == 0) { 14832 pw.println(prefix + "No app verification established."); 14833 pw.println(); 14834 } 14835 for (int userId : sUserManager.getUserIds()) { 14836 pw.println("App linkages for user " + userId + ":"); 14837 pw.println(); 14838 count = 0; 14839 for (PackageSetting ps : allPackageSettings) { 14840 final int status = ps.getDomainVerificationStatusForUser(userId); 14841 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14842 continue; 14843 } 14844 pw.println(prefix + "Package: " + ps.name); 14845 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 14846 String statusStr = IntentFilterVerificationInfo. 14847 getStatusStringFromValue(status); 14848 pw.println(prefix + "Status: " + statusStr); 14849 pw.println(); 14850 count++; 14851 } 14852 if (count == 0) { 14853 pw.println(prefix + "No configured app linkages."); 14854 pw.println(); 14855 } 14856 } 14857 } 14858 } 14859 } 14860 14861 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14862 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14863 if (packageName == null && permissionNames == null) { 14864 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14865 if (iperm == 0) { 14866 if (dumpState.onTitlePrinted()) 14867 pw.println(); 14868 pw.println("AppOp Permissions:"); 14869 } 14870 pw.print(" AppOp Permission "); 14871 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14872 pw.println(":"); 14873 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14874 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14875 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14876 } 14877 } 14878 } 14879 } 14880 14881 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14882 boolean printedSomething = false; 14883 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14884 if (packageName != null && !packageName.equals(p.info.packageName)) { 14885 continue; 14886 } 14887 if (!printedSomething) { 14888 if (dumpState.onTitlePrinted()) 14889 pw.println(); 14890 pw.println("Registered ContentProviders:"); 14891 printedSomething = true; 14892 } 14893 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14894 pw.print(" "); pw.println(p.toString()); 14895 } 14896 printedSomething = false; 14897 for (Map.Entry<String, PackageParser.Provider> entry : 14898 mProvidersByAuthority.entrySet()) { 14899 PackageParser.Provider p = entry.getValue(); 14900 if (packageName != null && !packageName.equals(p.info.packageName)) { 14901 continue; 14902 } 14903 if (!printedSomething) { 14904 if (dumpState.onTitlePrinted()) 14905 pw.println(); 14906 pw.println("ContentProvider Authorities:"); 14907 printedSomething = true; 14908 } 14909 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14910 pw.print(" "); pw.println(p.toString()); 14911 if (p.info != null && p.info.applicationInfo != null) { 14912 final String appInfo = p.info.applicationInfo.toString(); 14913 pw.print(" applicationInfo="); pw.println(appInfo); 14914 } 14915 } 14916 } 14917 14918 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14919 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14920 } 14921 14922 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14923 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14924 } 14925 14926 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14927 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14928 } 14929 14930 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14931 // XXX should handle packageName != null by dumping only install data that 14932 // the given package is involved with. 14933 if (dumpState.onTitlePrinted()) pw.println(); 14934 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14935 } 14936 14937 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14938 if (dumpState.onTitlePrinted()) pw.println(); 14939 mSettings.dumpReadMessagesLPr(pw, dumpState); 14940 14941 pw.println(); 14942 pw.println("Package warning messages:"); 14943 BufferedReader in = null; 14944 String line = null; 14945 try { 14946 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14947 while ((line = in.readLine()) != null) { 14948 if (line.contains("ignored: updated version")) continue; 14949 pw.println(line); 14950 } 14951 } catch (IOException ignored) { 14952 } finally { 14953 IoUtils.closeQuietly(in); 14954 } 14955 } 14956 14957 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14958 BufferedReader in = null; 14959 String line = null; 14960 try { 14961 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14962 while ((line = in.readLine()) != null) { 14963 if (line.contains("ignored: updated version")) continue; 14964 pw.print("msg,"); 14965 pw.println(line); 14966 } 14967 } catch (IOException ignored) { 14968 } finally { 14969 IoUtils.closeQuietly(in); 14970 } 14971 } 14972 } 14973 } 14974 14975 private String dumpDomainString(String packageName) { 14976 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 14977 List<IntentFilter> filters = getAllIntentFilters(packageName); 14978 14979 ArraySet<String> result = new ArraySet<>(); 14980 if (iviList.size() > 0) { 14981 for (IntentFilterVerificationInfo ivi : iviList) { 14982 for (String host : ivi.getDomains()) { 14983 result.add(host); 14984 } 14985 } 14986 } 14987 if (filters != null && filters.size() > 0) { 14988 for (IntentFilter filter : filters) { 14989 if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 14990 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) { 14991 result.addAll(filter.getHostsList()); 14992 } 14993 } 14994 } 14995 14996 StringBuilder sb = new StringBuilder(result.size() * 16); 14997 for (String domain : result) { 14998 if (sb.length() > 0) sb.append(" "); 14999 sb.append(domain); 15000 } 15001 return sb.toString(); 15002 } 15003 15004 // ------- apps on sdcard specific code ------- 15005 static final boolean DEBUG_SD_INSTALL = false; 15006 15007 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15008 15009 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15010 15011 private boolean mMediaMounted = false; 15012 15013 static String getEncryptKey() { 15014 try { 15015 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15016 SD_ENCRYPTION_KEYSTORE_NAME); 15017 if (sdEncKey == null) { 15018 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15019 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15020 if (sdEncKey == null) { 15021 Slog.e(TAG, "Failed to create encryption keys"); 15022 return null; 15023 } 15024 } 15025 return sdEncKey; 15026 } catch (NoSuchAlgorithmException nsae) { 15027 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15028 return null; 15029 } catch (IOException ioe) { 15030 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15031 return null; 15032 } 15033 } 15034 15035 /* 15036 * Update media status on PackageManager. 15037 */ 15038 @Override 15039 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15040 int callingUid = Binder.getCallingUid(); 15041 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15042 throw new SecurityException("Media status can only be updated by the system"); 15043 } 15044 // reader; this apparently protects mMediaMounted, but should probably 15045 // be a different lock in that case. 15046 synchronized (mPackages) { 15047 Log.i(TAG, "Updating external media status from " 15048 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15049 + (mediaStatus ? "mounted" : "unmounted")); 15050 if (DEBUG_SD_INSTALL) 15051 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15052 + ", mMediaMounted=" + mMediaMounted); 15053 if (mediaStatus == mMediaMounted) { 15054 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15055 : 0, -1); 15056 mHandler.sendMessage(msg); 15057 return; 15058 } 15059 mMediaMounted = mediaStatus; 15060 } 15061 // Queue up an async operation since the package installation may take a 15062 // little while. 15063 mHandler.post(new Runnable() { 15064 public void run() { 15065 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15066 } 15067 }); 15068 } 15069 15070 /** 15071 * Called by MountService when the initial ASECs to scan are available. 15072 * Should block until all the ASEC containers are finished being scanned. 15073 */ 15074 public void scanAvailableAsecs() { 15075 updateExternalMediaStatusInner(true, false, false); 15076 if (mShouldRestoreconData) { 15077 SELinuxMMAC.setRestoreconDone(); 15078 mShouldRestoreconData = false; 15079 } 15080 } 15081 15082 /* 15083 * Collect information of applications on external media, map them against 15084 * existing containers and update information based on current mount status. 15085 * Please note that we always have to report status if reportStatus has been 15086 * set to true especially when unloading packages. 15087 */ 15088 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15089 boolean externalStorage) { 15090 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15091 int[] uidArr = EmptyArray.INT; 15092 15093 final String[] list = PackageHelper.getSecureContainerList(); 15094 if (ArrayUtils.isEmpty(list)) { 15095 Log.i(TAG, "No secure containers found"); 15096 } else { 15097 // Process list of secure containers and categorize them 15098 // as active or stale based on their package internal state. 15099 15100 // reader 15101 synchronized (mPackages) { 15102 for (String cid : list) { 15103 // Leave stages untouched for now; installer service owns them 15104 if (PackageInstallerService.isStageName(cid)) continue; 15105 15106 if (DEBUG_SD_INSTALL) 15107 Log.i(TAG, "Processing container " + cid); 15108 String pkgName = getAsecPackageName(cid); 15109 if (pkgName == null) { 15110 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15111 continue; 15112 } 15113 if (DEBUG_SD_INSTALL) 15114 Log.i(TAG, "Looking for pkg : " + pkgName); 15115 15116 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15117 if (ps == null) { 15118 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15119 continue; 15120 } 15121 15122 /* 15123 * Skip packages that are not external if we're unmounting 15124 * external storage. 15125 */ 15126 if (externalStorage && !isMounted && !isExternal(ps)) { 15127 continue; 15128 } 15129 15130 final AsecInstallArgs args = new AsecInstallArgs(cid, 15131 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15132 // The package status is changed only if the code path 15133 // matches between settings and the container id. 15134 if (ps.codePathString != null 15135 && ps.codePathString.startsWith(args.getCodePath())) { 15136 if (DEBUG_SD_INSTALL) { 15137 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15138 + " at code path: " + ps.codePathString); 15139 } 15140 15141 // We do have a valid package installed on sdcard 15142 processCids.put(args, ps.codePathString); 15143 final int uid = ps.appId; 15144 if (uid != -1) { 15145 uidArr = ArrayUtils.appendInt(uidArr, uid); 15146 } 15147 } else { 15148 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15149 + ps.codePathString); 15150 } 15151 } 15152 } 15153 15154 Arrays.sort(uidArr); 15155 } 15156 15157 // Process packages with valid entries. 15158 if (isMounted) { 15159 if (DEBUG_SD_INSTALL) 15160 Log.i(TAG, "Loading packages"); 15161 loadMediaPackages(processCids, uidArr); 15162 startCleaningPackages(); 15163 mInstallerService.onSecureContainersAvailable(); 15164 } else { 15165 if (DEBUG_SD_INSTALL) 15166 Log.i(TAG, "Unloading packages"); 15167 unloadMediaPackages(processCids, uidArr, reportStatus); 15168 } 15169 } 15170 15171 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15172 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15173 final int size = infos.size(); 15174 final String[] packageNames = new String[size]; 15175 final int[] packageUids = new int[size]; 15176 for (int i = 0; i < size; i++) { 15177 final ApplicationInfo info = infos.get(i); 15178 packageNames[i] = info.packageName; 15179 packageUids[i] = info.uid; 15180 } 15181 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15182 finishedReceiver); 15183 } 15184 15185 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15186 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15187 sendResourcesChangedBroadcast(mediaStatus, replacing, 15188 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15189 } 15190 15191 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15192 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15193 int size = pkgList.length; 15194 if (size > 0) { 15195 // Send broadcasts here 15196 Bundle extras = new Bundle(); 15197 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15198 if (uidArr != null) { 15199 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15200 } 15201 if (replacing) { 15202 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15203 } 15204 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15205 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15206 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15207 } 15208 } 15209 15210 /* 15211 * Look at potentially valid container ids from processCids If package 15212 * information doesn't match the one on record or package scanning fails, 15213 * the cid is added to list of removeCids. We currently don't delete stale 15214 * containers. 15215 */ 15216 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15217 ArrayList<String> pkgList = new ArrayList<String>(); 15218 Set<AsecInstallArgs> keys = processCids.keySet(); 15219 15220 for (AsecInstallArgs args : keys) { 15221 String codePath = processCids.get(args); 15222 if (DEBUG_SD_INSTALL) 15223 Log.i(TAG, "Loading container : " + args.cid); 15224 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15225 try { 15226 // Make sure there are no container errors first. 15227 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15228 Slog.e(TAG, "Failed to mount cid : " + args.cid 15229 + " when installing from sdcard"); 15230 continue; 15231 } 15232 // Check code path here. 15233 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15234 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15235 + " does not match one in settings " + codePath); 15236 continue; 15237 } 15238 // Parse package 15239 int parseFlags = mDefParseFlags; 15240 if (args.isExternalAsec()) { 15241 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15242 } 15243 if (args.isFwdLocked()) { 15244 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15245 } 15246 15247 synchronized (mInstallLock) { 15248 PackageParser.Package pkg = null; 15249 try { 15250 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15251 } catch (PackageManagerException e) { 15252 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15253 } 15254 // Scan the package 15255 if (pkg != null) { 15256 /* 15257 * TODO why is the lock being held? doPostInstall is 15258 * called in other places without the lock. This needs 15259 * to be straightened out. 15260 */ 15261 // writer 15262 synchronized (mPackages) { 15263 retCode = PackageManager.INSTALL_SUCCEEDED; 15264 pkgList.add(pkg.packageName); 15265 // Post process args 15266 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15267 pkg.applicationInfo.uid); 15268 } 15269 } else { 15270 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15271 } 15272 } 15273 15274 } finally { 15275 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15276 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15277 } 15278 } 15279 } 15280 // writer 15281 synchronized (mPackages) { 15282 // If the platform SDK has changed since the last time we booted, 15283 // we need to re-grant app permission to catch any new ones that 15284 // appear. This is really a hack, and means that apps can in some 15285 // cases get permissions that the user didn't initially explicitly 15286 // allow... it would be nice to have some better way to handle 15287 // this situation. 15288 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15289 if (regrantPermissions) 15290 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15291 + mSdkVersion + "; regranting permissions for external storage"); 15292 mSettings.mExternalSdkPlatform = mSdkVersion; 15293 15294 // Make sure group IDs have been assigned, and any permission 15295 // changes in other apps are accounted for 15296 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15297 | (regrantPermissions 15298 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15299 : 0)); 15300 15301 mSettings.updateExternalDatabaseVersion(); 15302 15303 // can downgrade to reader 15304 // Persist settings 15305 mSettings.writeLPr(); 15306 } 15307 // Send a broadcast to let everyone know we are done processing 15308 if (pkgList.size() > 0) { 15309 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15310 } 15311 } 15312 15313 /* 15314 * Utility method to unload a list of specified containers 15315 */ 15316 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15317 // Just unmount all valid containers. 15318 for (AsecInstallArgs arg : cidArgs) { 15319 synchronized (mInstallLock) { 15320 arg.doPostDeleteLI(false); 15321 } 15322 } 15323 } 15324 15325 /* 15326 * Unload packages mounted on external media. This involves deleting package 15327 * data from internal structures, sending broadcasts about diabled packages, 15328 * gc'ing to free up references, unmounting all secure containers 15329 * corresponding to packages on external media, and posting a 15330 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15331 * that we always have to post this message if status has been requested no 15332 * matter what. 15333 */ 15334 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15335 final boolean reportStatus) { 15336 if (DEBUG_SD_INSTALL) 15337 Log.i(TAG, "unloading media packages"); 15338 ArrayList<String> pkgList = new ArrayList<String>(); 15339 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15340 final Set<AsecInstallArgs> keys = processCids.keySet(); 15341 for (AsecInstallArgs args : keys) { 15342 String pkgName = args.getPackageName(); 15343 if (DEBUG_SD_INSTALL) 15344 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15345 // Delete package internally 15346 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15347 synchronized (mInstallLock) { 15348 boolean res = deletePackageLI(pkgName, null, false, null, null, 15349 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15350 if (res) { 15351 pkgList.add(pkgName); 15352 } else { 15353 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15354 failedList.add(args); 15355 } 15356 } 15357 } 15358 15359 // reader 15360 synchronized (mPackages) { 15361 // We didn't update the settings after removing each package; 15362 // write them now for all packages. 15363 mSettings.writeLPr(); 15364 } 15365 15366 // We have to absolutely send UPDATED_MEDIA_STATUS only 15367 // after confirming that all the receivers processed the ordered 15368 // broadcast when packages get disabled, force a gc to clean things up. 15369 // and unload all the containers. 15370 if (pkgList.size() > 0) { 15371 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15372 new IIntentReceiver.Stub() { 15373 public void performReceive(Intent intent, int resultCode, String data, 15374 Bundle extras, boolean ordered, boolean sticky, 15375 int sendingUser) throws RemoteException { 15376 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15377 reportStatus ? 1 : 0, 1, keys); 15378 mHandler.sendMessage(msg); 15379 } 15380 }); 15381 } else { 15382 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15383 keys); 15384 mHandler.sendMessage(msg); 15385 } 15386 } 15387 15388 private void loadPrivatePackages(VolumeInfo vol) { 15389 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15390 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15391 synchronized (mInstallLock) { 15392 synchronized (mPackages) { 15393 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15394 for (PackageSetting ps : packages) { 15395 final PackageParser.Package pkg; 15396 try { 15397 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15398 loaded.add(pkg.applicationInfo); 15399 } catch (PackageManagerException e) { 15400 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15401 } 15402 } 15403 15404 // TODO: regrant any permissions that changed based since original install 15405 15406 mSettings.writeLPr(); 15407 } 15408 } 15409 15410 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15411 sendResourcesChangedBroadcast(true, false, loaded, null); 15412 } 15413 15414 private void unloadPrivatePackages(VolumeInfo vol) { 15415 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15416 synchronized (mInstallLock) { 15417 synchronized (mPackages) { 15418 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15419 for (PackageSetting ps : packages) { 15420 if (ps.pkg == null) continue; 15421 15422 final ApplicationInfo info = ps.pkg.applicationInfo; 15423 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15424 if (deletePackageLI(ps.name, null, false, null, null, 15425 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15426 unloaded.add(info); 15427 } else { 15428 Slog.w(TAG, "Failed to unload " + ps.codePath); 15429 } 15430 } 15431 15432 mSettings.writeLPr(); 15433 } 15434 } 15435 15436 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15437 sendResourcesChangedBroadcast(false, false, unloaded, null); 15438 } 15439 15440 /** 15441 * Examine all users present on given mounted volume, and destroy data 15442 * belonging to users that are no longer valid, or whose user ID has been 15443 * recycled. 15444 */ 15445 private void reconcileUsers(String volumeUuid) { 15446 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15447 if (ArrayUtils.isEmpty(files)) { 15448 Slog.d(TAG, "No users found on " + volumeUuid); 15449 return; 15450 } 15451 15452 for (File file : files) { 15453 if (!file.isDirectory()) continue; 15454 15455 final int userId; 15456 final UserInfo info; 15457 try { 15458 userId = Integer.parseInt(file.getName()); 15459 info = sUserManager.getUserInfo(userId); 15460 } catch (NumberFormatException e) { 15461 Slog.w(TAG, "Invalid user directory " + file); 15462 continue; 15463 } 15464 15465 boolean destroyUser = false; 15466 if (info == null) { 15467 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15468 + " because no matching user was found"); 15469 destroyUser = true; 15470 } else { 15471 try { 15472 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15473 } catch (IOException e) { 15474 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15475 + " because we failed to enforce serial number: " + e); 15476 destroyUser = true; 15477 } 15478 } 15479 15480 if (destroyUser) { 15481 synchronized (mInstallLock) { 15482 mInstaller.removeUserDataDirs(volumeUuid, userId); 15483 } 15484 } 15485 } 15486 15487 final UserManager um = mContext.getSystemService(UserManager.class); 15488 for (UserInfo user : um.getUsers()) { 15489 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15490 if (userDir.exists()) continue; 15491 15492 try { 15493 UserManagerService.prepareUserDirectory(userDir); 15494 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15495 } catch (IOException e) { 15496 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15497 } 15498 } 15499 } 15500 15501 /** 15502 * Examine all apps present on given mounted volume, and destroy apps that 15503 * aren't expected, either due to uninstallation or reinstallation on 15504 * another volume. 15505 */ 15506 private void reconcileApps(String volumeUuid) { 15507 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15508 if (ArrayUtils.isEmpty(files)) { 15509 Slog.d(TAG, "No apps found on " + volumeUuid); 15510 return; 15511 } 15512 15513 for (File file : files) { 15514 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15515 && !PackageInstallerService.isStageName(file.getName()); 15516 if (!isPackage) { 15517 // Ignore entries which are not packages 15518 continue; 15519 } 15520 15521 boolean destroyApp = false; 15522 String packageName = null; 15523 try { 15524 final PackageLite pkg = PackageParser.parsePackageLite(file, 15525 PackageParser.PARSE_MUST_BE_APK); 15526 packageName = pkg.packageName; 15527 15528 synchronized (mPackages) { 15529 final PackageSetting ps = mSettings.mPackages.get(packageName); 15530 if (ps == null) { 15531 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15532 + volumeUuid + " because we found no install record"); 15533 destroyApp = true; 15534 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15535 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15536 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15537 destroyApp = true; 15538 } 15539 } 15540 15541 } catch (PackageParserException e) { 15542 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15543 destroyApp = true; 15544 } 15545 15546 if (destroyApp) { 15547 synchronized (mInstallLock) { 15548 if (packageName != null) { 15549 removeDataDirsLI(volumeUuid, packageName); 15550 } 15551 if (file.isDirectory()) { 15552 mInstaller.rmPackageDir(file.getAbsolutePath()); 15553 } else { 15554 file.delete(); 15555 } 15556 } 15557 } 15558 } 15559 } 15560 15561 private void unfreezePackage(String packageName) { 15562 synchronized (mPackages) { 15563 final PackageSetting ps = mSettings.mPackages.get(packageName); 15564 if (ps != null) { 15565 ps.frozen = false; 15566 } 15567 } 15568 } 15569 15570 @Override 15571 public int movePackage(final String packageName, final String volumeUuid) { 15572 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15573 15574 final int moveId = mNextMoveId.getAndIncrement(); 15575 try { 15576 movePackageInternal(packageName, volumeUuid, moveId); 15577 } catch (PackageManagerException e) { 15578 Slog.w(TAG, "Failed to move " + packageName, e); 15579 mMoveCallbacks.notifyStatusChanged(moveId, 15580 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15581 } 15582 return moveId; 15583 } 15584 15585 private void movePackageInternal(final String packageName, final String volumeUuid, 15586 final int moveId) throws PackageManagerException { 15587 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15588 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15589 final PackageManager pm = mContext.getPackageManager(); 15590 15591 final boolean currentAsec; 15592 final String currentVolumeUuid; 15593 final File codeFile; 15594 final String installerPackageName; 15595 final String packageAbiOverride; 15596 final int appId; 15597 final String seinfo; 15598 final String label; 15599 15600 // reader 15601 synchronized (mPackages) { 15602 final PackageParser.Package pkg = mPackages.get(packageName); 15603 final PackageSetting ps = mSettings.mPackages.get(packageName); 15604 if (pkg == null || ps == null) { 15605 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15606 } 15607 15608 if (pkg.applicationInfo.isSystemApp()) { 15609 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15610 "Cannot move system application"); 15611 } 15612 15613 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15614 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15615 "Package already moved to " + volumeUuid); 15616 } 15617 15618 final File probe = new File(pkg.codePath); 15619 final File probeOat = new File(probe, "oat"); 15620 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15621 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15622 "Move only supported for modern cluster style installs"); 15623 } 15624 15625 if (ps.frozen) { 15626 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15627 "Failed to move already frozen package"); 15628 } 15629 ps.frozen = true; 15630 15631 currentAsec = pkg.applicationInfo.isForwardLocked() 15632 || pkg.applicationInfo.isExternalAsec(); 15633 currentVolumeUuid = ps.volumeUuid; 15634 codeFile = new File(pkg.codePath); 15635 installerPackageName = ps.installerPackageName; 15636 packageAbiOverride = ps.cpuAbiOverrideString; 15637 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15638 seinfo = pkg.applicationInfo.seinfo; 15639 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15640 } 15641 15642 // Now that we're guarded by frozen state, kill app during move 15643 killApplication(packageName, appId, "move pkg"); 15644 15645 final Bundle extras = new Bundle(); 15646 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15647 extras.putString(Intent.EXTRA_TITLE, label); 15648 mMoveCallbacks.notifyCreated(moveId, extras); 15649 15650 int installFlags; 15651 final boolean moveCompleteApp; 15652 final File measurePath; 15653 15654 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15655 installFlags = INSTALL_INTERNAL; 15656 moveCompleteApp = !currentAsec; 15657 measurePath = Environment.getDataAppDirectory(volumeUuid); 15658 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15659 installFlags = INSTALL_EXTERNAL; 15660 moveCompleteApp = false; 15661 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15662 } else { 15663 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15664 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15665 || !volume.isMountedWritable()) { 15666 unfreezePackage(packageName); 15667 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15668 "Move location not mounted private volume"); 15669 } 15670 15671 Preconditions.checkState(!currentAsec); 15672 15673 installFlags = INSTALL_INTERNAL; 15674 moveCompleteApp = true; 15675 measurePath = Environment.getDataAppDirectory(volumeUuid); 15676 } 15677 15678 final PackageStats stats = new PackageStats(null, -1); 15679 synchronized (mInstaller) { 15680 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15681 unfreezePackage(packageName); 15682 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15683 "Failed to measure package size"); 15684 } 15685 } 15686 15687 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15688 + stats.dataSize); 15689 15690 final long startFreeBytes = measurePath.getFreeSpace(); 15691 final long sizeBytes; 15692 if (moveCompleteApp) { 15693 sizeBytes = stats.codeSize + stats.dataSize; 15694 } else { 15695 sizeBytes = stats.codeSize; 15696 } 15697 15698 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15699 unfreezePackage(packageName); 15700 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15701 "Not enough free space to move"); 15702 } 15703 15704 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15705 15706 final CountDownLatch installedLatch = new CountDownLatch(1); 15707 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15708 @Override 15709 public void onUserActionRequired(Intent intent) throws RemoteException { 15710 throw new IllegalStateException(); 15711 } 15712 15713 @Override 15714 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15715 Bundle extras) throws RemoteException { 15716 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15717 + PackageManager.installStatusToString(returnCode, msg)); 15718 15719 installedLatch.countDown(); 15720 15721 // Regardless of success or failure of the move operation, 15722 // always unfreeze the package 15723 unfreezePackage(packageName); 15724 15725 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15726 switch (status) { 15727 case PackageInstaller.STATUS_SUCCESS: 15728 mMoveCallbacks.notifyStatusChanged(moveId, 15729 PackageManager.MOVE_SUCCEEDED); 15730 break; 15731 case PackageInstaller.STATUS_FAILURE_STORAGE: 15732 mMoveCallbacks.notifyStatusChanged(moveId, 15733 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15734 break; 15735 default: 15736 mMoveCallbacks.notifyStatusChanged(moveId, 15737 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15738 break; 15739 } 15740 } 15741 }; 15742 15743 final MoveInfo move; 15744 if (moveCompleteApp) { 15745 // Kick off a thread to report progress estimates 15746 new Thread() { 15747 @Override 15748 public void run() { 15749 while (true) { 15750 try { 15751 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15752 break; 15753 } 15754 } catch (InterruptedException ignored) { 15755 } 15756 15757 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15758 final int progress = 10 + (int) MathUtils.constrain( 15759 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15760 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15761 } 15762 } 15763 }.start(); 15764 15765 final String dataAppName = codeFile.getName(); 15766 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15767 dataAppName, appId, seinfo); 15768 } else { 15769 move = null; 15770 } 15771 15772 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15773 15774 final Message msg = mHandler.obtainMessage(INIT_COPY); 15775 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15776 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15777 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15778 mHandler.sendMessage(msg); 15779 } 15780 15781 @Override 15782 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15783 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15784 15785 final int realMoveId = mNextMoveId.getAndIncrement(); 15786 final Bundle extras = new Bundle(); 15787 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15788 mMoveCallbacks.notifyCreated(realMoveId, extras); 15789 15790 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15791 @Override 15792 public void onCreated(int moveId, Bundle extras) { 15793 // Ignored 15794 } 15795 15796 @Override 15797 public void onStatusChanged(int moveId, int status, long estMillis) { 15798 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15799 } 15800 }; 15801 15802 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15803 storage.setPrimaryStorageUuid(volumeUuid, callback); 15804 return realMoveId; 15805 } 15806 15807 @Override 15808 public int getMoveStatus(int moveId) { 15809 mContext.enforceCallingOrSelfPermission( 15810 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15811 return mMoveCallbacks.mLastStatus.get(moveId); 15812 } 15813 15814 @Override 15815 public void registerMoveCallback(IPackageMoveObserver callback) { 15816 mContext.enforceCallingOrSelfPermission( 15817 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15818 mMoveCallbacks.register(callback); 15819 } 15820 15821 @Override 15822 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15823 mContext.enforceCallingOrSelfPermission( 15824 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15825 mMoveCallbacks.unregister(callback); 15826 } 15827 15828 @Override 15829 public boolean setInstallLocation(int loc) { 15830 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15831 null); 15832 if (getInstallLocation() == loc) { 15833 return true; 15834 } 15835 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15836 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15837 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15838 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15839 return true; 15840 } 15841 return false; 15842 } 15843 15844 @Override 15845 public int getInstallLocation() { 15846 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15847 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15848 PackageHelper.APP_INSTALL_AUTO); 15849 } 15850 15851 /** Called by UserManagerService */ 15852 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15853 mDirtyUsers.remove(userHandle); 15854 mSettings.removeUserLPw(userHandle); 15855 mPendingBroadcasts.remove(userHandle); 15856 if (mInstaller != null) { 15857 // Technically, we shouldn't be doing this with the package lock 15858 // held. However, this is very rare, and there is already so much 15859 // other disk I/O going on, that we'll let it slide for now. 15860 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15861 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15862 final String volumeUuid = vol.getFsUuid(); 15863 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15864 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15865 } 15866 } 15867 mUserNeedsBadging.delete(userHandle); 15868 removeUnusedPackagesLILPw(userManager, userHandle); 15869 } 15870 15871 /** 15872 * We're removing userHandle and would like to remove any downloaded packages 15873 * that are no longer in use by any other user. 15874 * @param userHandle the user being removed 15875 */ 15876 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15877 final boolean DEBUG_CLEAN_APKS = false; 15878 int [] users = userManager.getUserIdsLPr(); 15879 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15880 while (psit.hasNext()) { 15881 PackageSetting ps = psit.next(); 15882 if (ps.pkg == null) { 15883 continue; 15884 } 15885 final String packageName = ps.pkg.packageName; 15886 // Skip over if system app 15887 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15888 continue; 15889 } 15890 if (DEBUG_CLEAN_APKS) { 15891 Slog.i(TAG, "Checking package " + packageName); 15892 } 15893 boolean keep = false; 15894 for (int i = 0; i < users.length; i++) { 15895 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15896 keep = true; 15897 if (DEBUG_CLEAN_APKS) { 15898 Slog.i(TAG, " Keeping package " + packageName + " for user " 15899 + users[i]); 15900 } 15901 break; 15902 } 15903 } 15904 if (!keep) { 15905 if (DEBUG_CLEAN_APKS) { 15906 Slog.i(TAG, " Removing package " + packageName); 15907 } 15908 mHandler.post(new Runnable() { 15909 public void run() { 15910 deletePackageX(packageName, userHandle, 0); 15911 } //end run 15912 }); 15913 } 15914 } 15915 } 15916 15917 /** Called by UserManagerService */ 15918 void createNewUserLILPw(int userHandle) { 15919 if (mInstaller != null) { 15920 mInstaller.createUserConfig(userHandle); 15921 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 15922 applyFactoryDefaultBrowserLPw(userHandle); 15923 primeDomainVerificationsLPw(userHandle); 15924 } 15925 } 15926 15927 void newUserCreatedLILPw(final int userHandle) { 15928 // We cannot grant the default permissions with a lock held as 15929 // we query providers from other components for default handlers 15930 // such as enabled IMEs, etc. 15931 mHandler.post(new Runnable() { 15932 @Override 15933 public void run() { 15934 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15935 } 15936 }); 15937 } 15938 15939 @Override 15940 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15941 mContext.enforceCallingOrSelfPermission( 15942 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15943 "Only package verification agents can read the verifier device identity"); 15944 15945 synchronized (mPackages) { 15946 return mSettings.getVerifierDeviceIdentityLPw(); 15947 } 15948 } 15949 15950 @Override 15951 public void setPermissionEnforced(String permission, boolean enforced) { 15952 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15953 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15954 synchronized (mPackages) { 15955 if (mSettings.mReadExternalStorageEnforced == null 15956 || mSettings.mReadExternalStorageEnforced != enforced) { 15957 mSettings.mReadExternalStorageEnforced = enforced; 15958 mSettings.writeLPr(); 15959 } 15960 } 15961 // kill any non-foreground processes so we restart them and 15962 // grant/revoke the GID. 15963 final IActivityManager am = ActivityManagerNative.getDefault(); 15964 if (am != null) { 15965 final long token = Binder.clearCallingIdentity(); 15966 try { 15967 am.killProcessesBelowForeground("setPermissionEnforcement"); 15968 } catch (RemoteException e) { 15969 } finally { 15970 Binder.restoreCallingIdentity(token); 15971 } 15972 } 15973 } else { 15974 throw new IllegalArgumentException("No selective enforcement for " + permission); 15975 } 15976 } 15977 15978 @Override 15979 @Deprecated 15980 public boolean isPermissionEnforced(String permission) { 15981 return true; 15982 } 15983 15984 @Override 15985 public boolean isStorageLow() { 15986 final long token = Binder.clearCallingIdentity(); 15987 try { 15988 final DeviceStorageMonitorInternal 15989 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15990 if (dsm != null) { 15991 return dsm.isMemoryLow(); 15992 } else { 15993 return false; 15994 } 15995 } finally { 15996 Binder.restoreCallingIdentity(token); 15997 } 15998 } 15999 16000 @Override 16001 public IPackageInstaller getPackageInstaller() { 16002 return mInstallerService; 16003 } 16004 16005 private boolean userNeedsBadging(int userId) { 16006 int index = mUserNeedsBadging.indexOfKey(userId); 16007 if (index < 0) { 16008 final UserInfo userInfo; 16009 final long token = Binder.clearCallingIdentity(); 16010 try { 16011 userInfo = sUserManager.getUserInfo(userId); 16012 } finally { 16013 Binder.restoreCallingIdentity(token); 16014 } 16015 final boolean b; 16016 if (userInfo != null && userInfo.isManagedProfile()) { 16017 b = true; 16018 } else { 16019 b = false; 16020 } 16021 mUserNeedsBadging.put(userId, b); 16022 return b; 16023 } 16024 return mUserNeedsBadging.valueAt(index); 16025 } 16026 16027 @Override 16028 public KeySet getKeySetByAlias(String packageName, String alias) { 16029 if (packageName == null || alias == null) { 16030 return null; 16031 } 16032 synchronized(mPackages) { 16033 final PackageParser.Package pkg = mPackages.get(packageName); 16034 if (pkg == null) { 16035 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16036 throw new IllegalArgumentException("Unknown package: " + packageName); 16037 } 16038 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16039 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16040 } 16041 } 16042 16043 @Override 16044 public KeySet getSigningKeySet(String packageName) { 16045 if (packageName == null) { 16046 return null; 16047 } 16048 synchronized(mPackages) { 16049 final PackageParser.Package pkg = mPackages.get(packageName); 16050 if (pkg == null) { 16051 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16052 throw new IllegalArgumentException("Unknown package: " + packageName); 16053 } 16054 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16055 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16056 throw new SecurityException("May not access signing KeySet of other apps."); 16057 } 16058 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16059 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16060 } 16061 } 16062 16063 @Override 16064 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16065 if (packageName == null || ks == null) { 16066 return false; 16067 } 16068 synchronized(mPackages) { 16069 final PackageParser.Package pkg = mPackages.get(packageName); 16070 if (pkg == null) { 16071 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16072 throw new IllegalArgumentException("Unknown package: " + packageName); 16073 } 16074 IBinder ksh = ks.getToken(); 16075 if (ksh instanceof KeySetHandle) { 16076 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16077 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16078 } 16079 return false; 16080 } 16081 } 16082 16083 @Override 16084 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16085 if (packageName == null || ks == null) { 16086 return false; 16087 } 16088 synchronized(mPackages) { 16089 final PackageParser.Package pkg = mPackages.get(packageName); 16090 if (pkg == null) { 16091 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16092 throw new IllegalArgumentException("Unknown package: " + packageName); 16093 } 16094 IBinder ksh = ks.getToken(); 16095 if (ksh instanceof KeySetHandle) { 16096 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16097 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16098 } 16099 return false; 16100 } 16101 } 16102 16103 public void getUsageStatsIfNoPackageUsageInfo() { 16104 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16105 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16106 if (usm == null) { 16107 throw new IllegalStateException("UsageStatsManager must be initialized"); 16108 } 16109 long now = System.currentTimeMillis(); 16110 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16111 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16112 String packageName = entry.getKey(); 16113 PackageParser.Package pkg = mPackages.get(packageName); 16114 if (pkg == null) { 16115 continue; 16116 } 16117 UsageStats usage = entry.getValue(); 16118 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16119 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16120 } 16121 } 16122 } 16123 16124 /** 16125 * Check and throw if the given before/after packages would be considered a 16126 * downgrade. 16127 */ 16128 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16129 throws PackageManagerException { 16130 if (after.versionCode < before.mVersionCode) { 16131 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16132 "Update version code " + after.versionCode + " is older than current " 16133 + before.mVersionCode); 16134 } else if (after.versionCode == before.mVersionCode) { 16135 if (after.baseRevisionCode < before.baseRevisionCode) { 16136 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16137 "Update base revision code " + after.baseRevisionCode 16138 + " is older than current " + before.baseRevisionCode); 16139 } 16140 16141 if (!ArrayUtils.isEmpty(after.splitNames)) { 16142 for (int i = 0; i < after.splitNames.length; i++) { 16143 final String splitName = after.splitNames[i]; 16144 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16145 if (j != -1) { 16146 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16147 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16148 "Update split " + splitName + " revision code " 16149 + after.splitRevisionCodes[i] + " is older than current " 16150 + before.splitRevisionCodes[j]); 16151 } 16152 } 16153 } 16154 } 16155 } 16156 } 16157 16158 private static class MoveCallbacks extends Handler { 16159 private static final int MSG_CREATED = 1; 16160 private static final int MSG_STATUS_CHANGED = 2; 16161 16162 private final RemoteCallbackList<IPackageMoveObserver> 16163 mCallbacks = new RemoteCallbackList<>(); 16164 16165 private final SparseIntArray mLastStatus = new SparseIntArray(); 16166 16167 public MoveCallbacks(Looper looper) { 16168 super(looper); 16169 } 16170 16171 public void register(IPackageMoveObserver callback) { 16172 mCallbacks.register(callback); 16173 } 16174 16175 public void unregister(IPackageMoveObserver callback) { 16176 mCallbacks.unregister(callback); 16177 } 16178 16179 @Override 16180 public void handleMessage(Message msg) { 16181 final SomeArgs args = (SomeArgs) msg.obj; 16182 final int n = mCallbacks.beginBroadcast(); 16183 for (int i = 0; i < n; i++) { 16184 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16185 try { 16186 invokeCallback(callback, msg.what, args); 16187 } catch (RemoteException ignored) { 16188 } 16189 } 16190 mCallbacks.finishBroadcast(); 16191 args.recycle(); 16192 } 16193 16194 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16195 throws RemoteException { 16196 switch (what) { 16197 case MSG_CREATED: { 16198 callback.onCreated(args.argi1, (Bundle) args.arg2); 16199 break; 16200 } 16201 case MSG_STATUS_CHANGED: { 16202 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16203 break; 16204 } 16205 } 16206 } 16207 16208 private void notifyCreated(int moveId, Bundle extras) { 16209 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16210 16211 final SomeArgs args = SomeArgs.obtain(); 16212 args.argi1 = moveId; 16213 args.arg2 = extras; 16214 obtainMessage(MSG_CREATED, args).sendToTarget(); 16215 } 16216 16217 private void notifyStatusChanged(int moveId, int status) { 16218 notifyStatusChanged(moveId, status, -1); 16219 } 16220 16221 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16222 Slog.v(TAG, "Move " + moveId + " status " + status); 16223 16224 final SomeArgs args = SomeArgs.obtain(); 16225 args.argi1 = moveId; 16226 args.argi2 = status; 16227 args.arg3 = estMillis; 16228 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16229 16230 synchronized (mLastStatus) { 16231 mLastStatus.put(moveId, status); 16232 } 16233 } 16234 } 16235 16236 private final class OnPermissionChangeListeners extends Handler { 16237 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16238 16239 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16240 new RemoteCallbackList<>(); 16241 16242 public OnPermissionChangeListeners(Looper looper) { 16243 super(looper); 16244 } 16245 16246 @Override 16247 public void handleMessage(Message msg) { 16248 switch (msg.what) { 16249 case MSG_ON_PERMISSIONS_CHANGED: { 16250 final int uid = msg.arg1; 16251 handleOnPermissionsChanged(uid); 16252 } break; 16253 } 16254 } 16255 16256 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16257 mPermissionListeners.register(listener); 16258 16259 } 16260 16261 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16262 mPermissionListeners.unregister(listener); 16263 } 16264 16265 public void onPermissionsChanged(int uid) { 16266 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16267 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16268 } 16269 } 16270 16271 private void handleOnPermissionsChanged(int uid) { 16272 final int count = mPermissionListeners.beginBroadcast(); 16273 try { 16274 for (int i = 0; i < count; i++) { 16275 IOnPermissionsChangeListener callback = mPermissionListeners 16276 .getBroadcastItem(i); 16277 try { 16278 callback.onPermissionsChanged(uid); 16279 } catch (RemoteException e) { 16280 Log.e(TAG, "Permission listener is dead", e); 16281 } 16282 } 16283 } finally { 16284 mPermissionListeners.finishBroadcast(); 16285 } 16286 } 16287 } 16288 16289 private class PackageManagerInternalImpl extends PackageManagerInternal { 16290 @Override 16291 public void setLocationPackagesProvider(PackagesProvider provider) { 16292 synchronized (mPackages) { 16293 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16294 } 16295 } 16296 16297 @Override 16298 public void setImePackagesProvider(PackagesProvider provider) { 16299 synchronized (mPackages) { 16300 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16301 } 16302 } 16303 16304 @Override 16305 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16306 synchronized (mPackages) { 16307 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16308 } 16309 } 16310 16311 @Override 16312 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16313 synchronized (mPackages) { 16314 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16315 } 16316 } 16317 16318 @Override 16319 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16320 synchronized (mPackages) { 16321 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16322 } 16323 } 16324 16325 @Override 16326 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16327 synchronized (mPackages) { 16328 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 16329 } 16330 } 16331 16332 @Override 16333 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16334 synchronized (mPackages) { 16335 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16336 packageName, userId); 16337 } 16338 } 16339 16340 @Override 16341 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16342 synchronized (mPackages) { 16343 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16344 packageName, userId); 16345 } 16346 } 16347 } 16348 16349 @Override 16350 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16351 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16352 synchronized (mPackages) { 16353 final long identity = Binder.clearCallingIdentity(); 16354 try { 16355 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16356 packageNames, userId); 16357 } finally { 16358 Binder.restoreCallingIdentity(identity); 16359 } 16360 } 16361 } 16362 16363 private static void enforceSystemOrPhoneCaller(String tag) { 16364 int callingUid = Binder.getCallingUid(); 16365 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16366 throw new SecurityException( 16367 "Cannot call " + tag + " from UID " + callingUid); 16368 } 16369 } 16370} 16371