PackageManagerService.java revision d80cf9109aa6b560e473f0197034085ed9062eaa
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 /** 481 * Tracks new system packages [receiving in an OTA] that we expect to 482 * find updated user-installed versions. Keys are package name, values 483 * are package location. 484 */ 485 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 486 487 final Settings mSettings; 488 boolean mRestoredSettings; 489 490 // System configuration read by SystemConfig. 491 final int[] mGlobalGids; 492 final SparseArray<ArraySet<String>> mSystemPermissions; 493 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 494 495 // If mac_permissions.xml was found for seinfo labeling. 496 boolean mFoundPolicyFile; 497 498 // If a recursive restorecon of /data/data/<pkg> is needed. 499 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 500 501 public static final class SharedLibraryEntry { 502 public final String path; 503 public final String apk; 504 505 SharedLibraryEntry(String _path, String _apk) { 506 path = _path; 507 apk = _apk; 508 } 509 } 510 511 // Currently known shared libraries. 512 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 513 new ArrayMap<String, SharedLibraryEntry>(); 514 515 // All available activities, for your resolving pleasure. 516 final ActivityIntentResolver mActivities = 517 new ActivityIntentResolver(); 518 519 // All available receivers, for your resolving pleasure. 520 final ActivityIntentResolver mReceivers = 521 new ActivityIntentResolver(); 522 523 // All available services, for your resolving pleasure. 524 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 525 526 // All available providers, for your resolving pleasure. 527 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 528 529 // Mapping from provider base names (first directory in content URI codePath) 530 // to the provider information. 531 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 532 new ArrayMap<String, PackageParser.Provider>(); 533 534 // Mapping from instrumentation class names to info about them. 535 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 536 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 537 538 // Mapping from permission names to info about them. 539 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 540 new ArrayMap<String, PackageParser.PermissionGroup>(); 541 542 // Packages whose data we have transfered into another package, thus 543 // should no longer exist. 544 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 545 546 // Broadcast actions that are only available to the system. 547 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 548 549 /** List of packages waiting for verification. */ 550 final SparseArray<PackageVerificationState> mPendingVerification 551 = new SparseArray<PackageVerificationState>(); 552 553 /** Set of packages associated with each app op permission. */ 554 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 555 556 final PackageInstallerService mInstallerService; 557 558 private final PackageDexOptimizer mPackageDexOptimizer; 559 560 private AtomicInteger mNextMoveId = new AtomicInteger(); 561 private final MoveCallbacks mMoveCallbacks; 562 563 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 564 565 // Cache of users who need badging. 566 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 567 568 /** Token for keys in mPendingVerification. */ 569 private int mPendingVerificationToken = 0; 570 571 volatile boolean mSystemReady; 572 volatile boolean mSafeMode; 573 volatile boolean mHasSystemUidErrors; 574 575 ApplicationInfo mAndroidApplication; 576 final ActivityInfo mResolveActivity = new ActivityInfo(); 577 final ResolveInfo mResolveInfo = new ResolveInfo(); 578 ComponentName mResolveComponentName; 579 PackageParser.Package mPlatformPackage; 580 ComponentName mCustomResolverComponentName; 581 582 boolean mResolverReplaced = false; 583 584 private final ComponentName mIntentFilterVerifierComponent; 585 private int mIntentFilterVerificationToken = 0; 586 587 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 588 = new SparseArray<IntentFilterVerificationState>(); 589 590 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 591 new DefaultPermissionGrantPolicy(this); 592 593 private static class IFVerificationParams { 594 PackageParser.Package pkg; 595 boolean replacing; 596 int userId; 597 int verifierUid; 598 599 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 600 int _userId, int _verifierUid) { 601 pkg = _pkg; 602 replacing = _replacing; 603 userId = _userId; 604 replacing = _replacing; 605 verifierUid = _verifierUid; 606 } 607 } 608 609 private interface IntentFilterVerifier<T extends IntentFilter> { 610 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 611 T filter, String packageName); 612 void startVerifications(int userId); 613 void receiveVerificationResponse(int verificationId); 614 } 615 616 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 617 private Context mContext; 618 private ComponentName mIntentFilterVerifierComponent; 619 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 620 621 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 622 mContext = context; 623 mIntentFilterVerifierComponent = verifierComponent; 624 } 625 626 private String getDefaultScheme() { 627 return IntentFilter.SCHEME_HTTPS; 628 } 629 630 @Override 631 public void startVerifications(int userId) { 632 // Launch verifications requests 633 int count = mCurrentIntentFilterVerifications.size(); 634 for (int n=0; n<count; n++) { 635 int verificationId = mCurrentIntentFilterVerifications.get(n); 636 final IntentFilterVerificationState ivs = 637 mIntentFilterVerificationStates.get(verificationId); 638 639 String packageName = ivs.getPackageName(); 640 641 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 642 final int filterCount = filters.size(); 643 ArraySet<String> domainsSet = new ArraySet<>(); 644 for (int m=0; m<filterCount; m++) { 645 PackageParser.ActivityIntentInfo filter = filters.get(m); 646 domainsSet.addAll(filter.getHostsList()); 647 } 648 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 649 synchronized (mPackages) { 650 if (mSettings.createIntentFilterVerificationIfNeededLPw( 651 packageName, domainsList) != null) { 652 scheduleWriteSettingsLocked(); 653 } 654 } 655 sendVerificationRequest(userId, verificationId, ivs); 656 } 657 mCurrentIntentFilterVerifications.clear(); 658 } 659 660 private void sendVerificationRequest(int userId, int verificationId, 661 IntentFilterVerificationState ivs) { 662 663 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 664 verificationIntent.putExtra( 665 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 666 verificationId); 667 verificationIntent.putExtra( 668 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 669 getDefaultScheme()); 670 verificationIntent.putExtra( 671 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 672 ivs.getHostsString()); 673 verificationIntent.putExtra( 674 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 675 ivs.getPackageName()); 676 verificationIntent.setComponent(mIntentFilterVerifierComponent); 677 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 678 679 UserHandle user = new UserHandle(userId); 680 mContext.sendBroadcastAsUser(verificationIntent, user); 681 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 682 "Sending IntentFilter verification broadcast"); 683 } 684 685 public void receiveVerificationResponse(int verificationId) { 686 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 687 688 final boolean verified = ivs.isVerified(); 689 690 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 691 final int count = filters.size(); 692 if (DEBUG_DOMAIN_VERIFICATION) { 693 Slog.i(TAG, "Received verification response " + verificationId 694 + " for " + count + " filters, verified=" + verified); 695 } 696 for (int n=0; n<count; n++) { 697 PackageParser.ActivityIntentInfo filter = filters.get(n); 698 filter.setVerified(verified); 699 700 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 701 + " verified with result:" + verified + " and hosts:" 702 + ivs.getHostsString()); 703 } 704 705 mIntentFilterVerificationStates.remove(verificationId); 706 707 final String packageName = ivs.getPackageName(); 708 IntentFilterVerificationInfo ivi = null; 709 710 synchronized (mPackages) { 711 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 712 } 713 if (ivi == null) { 714 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 715 + verificationId + " packageName:" + packageName); 716 return; 717 } 718 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 719 "Updating IntentFilterVerificationInfo for package " + packageName 720 +" verificationId:" + verificationId); 721 722 synchronized (mPackages) { 723 if (verified) { 724 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 725 } else { 726 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 727 } 728 scheduleWriteSettingsLocked(); 729 730 final int userId = ivs.getUserId(); 731 if (userId != UserHandle.USER_ALL) { 732 final int userStatus = 733 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 734 735 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 736 boolean needUpdate = false; 737 738 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 739 // already been set by the User thru the Disambiguation dialog 740 switch (userStatus) { 741 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 742 if (verified) { 743 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 744 } else { 745 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 746 } 747 needUpdate = true; 748 break; 749 750 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 751 if (verified) { 752 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 753 needUpdate = true; 754 } 755 break; 756 757 default: 758 // Nothing to do 759 } 760 761 if (needUpdate) { 762 mSettings.updateIntentFilterVerificationStatusLPw( 763 packageName, updatedStatus, userId); 764 scheduleWritePackageRestrictionsLocked(userId); 765 } 766 } 767 } 768 } 769 770 @Override 771 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 772 ActivityIntentInfo filter, String packageName) { 773 if (!hasValidDomains(filter)) { 774 return false; 775 } 776 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 777 if (ivs == null) { 778 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 779 packageName); 780 } 781 if (DEBUG_DOMAIN_VERIFICATION) { 782 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 783 } 784 ivs.addFilter(filter); 785 return true; 786 } 787 788 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 789 int userId, int verificationId, String packageName) { 790 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 791 verifierUid, userId, packageName); 792 ivs.setPendingState(); 793 synchronized (mPackages) { 794 mIntentFilterVerificationStates.append(verificationId, ivs); 795 mCurrentIntentFilterVerifications.add(verificationId); 796 } 797 return ivs; 798 } 799 } 800 801 private static boolean hasValidDomains(ActivityIntentInfo filter) { 802 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 803 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 804 if (!hasHTTPorHTTPS) { 805 return false; 806 } 807 return true; 808 } 809 810 private IntentFilterVerifier mIntentFilterVerifier; 811 812 // Set of pending broadcasts for aggregating enable/disable of components. 813 static class PendingPackageBroadcasts { 814 // for each user id, a map of <package name -> components within that package> 815 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 816 817 public PendingPackageBroadcasts() { 818 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 819 } 820 821 public ArrayList<String> get(int userId, String packageName) { 822 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 823 return packages.get(packageName); 824 } 825 826 public void put(int userId, String packageName, ArrayList<String> components) { 827 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 828 packages.put(packageName, components); 829 } 830 831 public void remove(int userId, String packageName) { 832 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 833 if (packages != null) { 834 packages.remove(packageName); 835 } 836 } 837 838 public void remove(int userId) { 839 mUidMap.remove(userId); 840 } 841 842 public int userIdCount() { 843 return mUidMap.size(); 844 } 845 846 public int userIdAt(int n) { 847 return mUidMap.keyAt(n); 848 } 849 850 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 851 return mUidMap.get(userId); 852 } 853 854 public int size() { 855 // total number of pending broadcast entries across all userIds 856 int num = 0; 857 for (int i = 0; i< mUidMap.size(); i++) { 858 num += mUidMap.valueAt(i).size(); 859 } 860 return num; 861 } 862 863 public void clear() { 864 mUidMap.clear(); 865 } 866 867 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 868 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 869 if (map == null) { 870 map = new ArrayMap<String, ArrayList<String>>(); 871 mUidMap.put(userId, map); 872 } 873 return map; 874 } 875 } 876 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 877 878 // Service Connection to remote media container service to copy 879 // package uri's from external media onto secure containers 880 // or internal storage. 881 private IMediaContainerService mContainerService = null; 882 883 static final int SEND_PENDING_BROADCAST = 1; 884 static final int MCS_BOUND = 3; 885 static final int END_COPY = 4; 886 static final int INIT_COPY = 5; 887 static final int MCS_UNBIND = 6; 888 static final int START_CLEANING_PACKAGE = 7; 889 static final int FIND_INSTALL_LOC = 8; 890 static final int POST_INSTALL = 9; 891 static final int MCS_RECONNECT = 10; 892 static final int MCS_GIVE_UP = 11; 893 static final int UPDATED_MEDIA_STATUS = 12; 894 static final int WRITE_SETTINGS = 13; 895 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 896 static final int PACKAGE_VERIFIED = 15; 897 static final int CHECK_PENDING_VERIFICATION = 16; 898 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 899 static final int INTENT_FILTER_VERIFIED = 18; 900 901 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 902 903 // Delay time in millisecs 904 static final int BROADCAST_DELAY = 10 * 1000; 905 906 static UserManagerService sUserManager; 907 908 // Stores a list of users whose package restrictions file needs to be updated 909 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 910 911 final private DefaultContainerConnection mDefContainerConn = 912 new DefaultContainerConnection(); 913 class DefaultContainerConnection implements ServiceConnection { 914 public void onServiceConnected(ComponentName name, IBinder service) { 915 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 916 IMediaContainerService imcs = 917 IMediaContainerService.Stub.asInterface(service); 918 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 919 } 920 921 public void onServiceDisconnected(ComponentName name) { 922 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 923 } 924 } 925 926 // Recordkeeping of restore-after-install operations that are currently in flight 927 // between the Package Manager and the Backup Manager 928 class PostInstallData { 929 public InstallArgs args; 930 public PackageInstalledInfo res; 931 932 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 933 args = _a; 934 res = _r; 935 } 936 } 937 938 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 939 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 940 941 // XML tags for backup/restore of various bits of state 942 private static final String TAG_PREFERRED_BACKUP = "pa"; 943 private static final String TAG_DEFAULT_APPS = "da"; 944 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 945 946 final String mRequiredVerifierPackage; 947 final String mRequiredInstallerPackage; 948 949 private final PackageUsage mPackageUsage = new PackageUsage(); 950 951 private class PackageUsage { 952 private static final int WRITE_INTERVAL 953 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 954 955 private final Object mFileLock = new Object(); 956 private final AtomicLong mLastWritten = new AtomicLong(0); 957 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 958 959 private boolean mIsHistoricalPackageUsageAvailable = true; 960 961 boolean isHistoricalPackageUsageAvailable() { 962 return mIsHistoricalPackageUsageAvailable; 963 } 964 965 void write(boolean force) { 966 if (force) { 967 writeInternal(); 968 return; 969 } 970 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 971 && !DEBUG_DEXOPT) { 972 return; 973 } 974 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 975 new Thread("PackageUsage_DiskWriter") { 976 @Override 977 public void run() { 978 try { 979 writeInternal(); 980 } finally { 981 mBackgroundWriteRunning.set(false); 982 } 983 } 984 }.start(); 985 } 986 } 987 988 private void writeInternal() { 989 synchronized (mPackages) { 990 synchronized (mFileLock) { 991 AtomicFile file = getFile(); 992 FileOutputStream f = null; 993 try { 994 f = file.startWrite(); 995 BufferedOutputStream out = new BufferedOutputStream(f); 996 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 997 StringBuilder sb = new StringBuilder(); 998 for (PackageParser.Package pkg : mPackages.values()) { 999 if (pkg.mLastPackageUsageTimeInMills == 0) { 1000 continue; 1001 } 1002 sb.setLength(0); 1003 sb.append(pkg.packageName); 1004 sb.append(' '); 1005 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1006 sb.append('\n'); 1007 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1008 } 1009 out.flush(); 1010 file.finishWrite(f); 1011 } catch (IOException e) { 1012 if (f != null) { 1013 file.failWrite(f); 1014 } 1015 Log.e(TAG, "Failed to write package usage times", e); 1016 } 1017 } 1018 } 1019 mLastWritten.set(SystemClock.elapsedRealtime()); 1020 } 1021 1022 void readLP() { 1023 synchronized (mFileLock) { 1024 AtomicFile file = getFile(); 1025 BufferedInputStream in = null; 1026 try { 1027 in = new BufferedInputStream(file.openRead()); 1028 StringBuffer sb = new StringBuffer(); 1029 while (true) { 1030 String packageName = readToken(in, sb, ' '); 1031 if (packageName == null) { 1032 break; 1033 } 1034 String timeInMillisString = readToken(in, sb, '\n'); 1035 if (timeInMillisString == null) { 1036 throw new IOException("Failed to find last usage time for package " 1037 + packageName); 1038 } 1039 PackageParser.Package pkg = mPackages.get(packageName); 1040 if (pkg == null) { 1041 continue; 1042 } 1043 long timeInMillis; 1044 try { 1045 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1046 } catch (NumberFormatException e) { 1047 throw new IOException("Failed to parse " + timeInMillisString 1048 + " as a long.", e); 1049 } 1050 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1051 } 1052 } catch (FileNotFoundException expected) { 1053 mIsHistoricalPackageUsageAvailable = false; 1054 } catch (IOException e) { 1055 Log.w(TAG, "Failed to read package usage times", e); 1056 } finally { 1057 IoUtils.closeQuietly(in); 1058 } 1059 } 1060 mLastWritten.set(SystemClock.elapsedRealtime()); 1061 } 1062 1063 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1064 throws IOException { 1065 sb.setLength(0); 1066 while (true) { 1067 int ch = in.read(); 1068 if (ch == -1) { 1069 if (sb.length() == 0) { 1070 return null; 1071 } 1072 throw new IOException("Unexpected EOF"); 1073 } 1074 if (ch == endOfToken) { 1075 return sb.toString(); 1076 } 1077 sb.append((char)ch); 1078 } 1079 } 1080 1081 private AtomicFile getFile() { 1082 File dataDir = Environment.getDataDirectory(); 1083 File systemDir = new File(dataDir, "system"); 1084 File fname = new File(systemDir, "package-usage.list"); 1085 return new AtomicFile(fname); 1086 } 1087 } 1088 1089 class PackageHandler extends Handler { 1090 private boolean mBound = false; 1091 final ArrayList<HandlerParams> mPendingInstalls = 1092 new ArrayList<HandlerParams>(); 1093 1094 private boolean connectToService() { 1095 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1096 " DefaultContainerService"); 1097 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1098 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1099 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1100 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1101 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1102 mBound = true; 1103 return true; 1104 } 1105 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1106 return false; 1107 } 1108 1109 private void disconnectService() { 1110 mContainerService = null; 1111 mBound = false; 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1113 mContext.unbindService(mDefContainerConn); 1114 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1115 } 1116 1117 PackageHandler(Looper looper) { 1118 super(looper); 1119 } 1120 1121 public void handleMessage(Message msg) { 1122 try { 1123 doHandleMessage(msg); 1124 } finally { 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } 1127 } 1128 1129 void doHandleMessage(Message msg) { 1130 switch (msg.what) { 1131 case INIT_COPY: { 1132 HandlerParams params = (HandlerParams) msg.obj; 1133 int idx = mPendingInstalls.size(); 1134 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1135 // If a bind was already initiated we dont really 1136 // need to do anything. The pending install 1137 // will be processed later on. 1138 if (!mBound) { 1139 // If this is the only one pending we might 1140 // have to bind to the service again. 1141 if (!connectToService()) { 1142 Slog.e(TAG, "Failed to bind to media container service"); 1143 params.serviceError(); 1144 return; 1145 } else { 1146 // Once we bind to the service, the first 1147 // pending request will be processed. 1148 mPendingInstalls.add(idx, params); 1149 } 1150 } else { 1151 mPendingInstalls.add(idx, params); 1152 // Already bound to the service. Just make 1153 // sure we trigger off processing the first request. 1154 if (idx == 0) { 1155 mHandler.sendEmptyMessage(MCS_BOUND); 1156 } 1157 } 1158 break; 1159 } 1160 case MCS_BOUND: { 1161 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1162 if (msg.obj != null) { 1163 mContainerService = (IMediaContainerService) msg.obj; 1164 } 1165 if (mContainerService == null) { 1166 if (!mBound) { 1167 // Something seriously wrong since we are not bound and we are not 1168 // waiting for connection. Bail out. 1169 Slog.e(TAG, "Cannot bind to media container service"); 1170 for (HandlerParams params : mPendingInstalls) { 1171 // Indicate service bind error 1172 params.serviceError(); 1173 } 1174 mPendingInstalls.clear(); 1175 } else { 1176 Slog.w(TAG, "Waiting to connect to media container service"); 1177 } 1178 } else if (mPendingInstalls.size() > 0) { 1179 HandlerParams params = mPendingInstalls.get(0); 1180 if (params != null) { 1181 if (params.startCopy()) { 1182 // We are done... look for more work or to 1183 // go idle. 1184 if (DEBUG_SD_INSTALL) Log.i(TAG, 1185 "Checking for more work or unbind..."); 1186 // Delete pending install 1187 if (mPendingInstalls.size() > 0) { 1188 mPendingInstalls.remove(0); 1189 } 1190 if (mPendingInstalls.size() == 0) { 1191 if (mBound) { 1192 if (DEBUG_SD_INSTALL) Log.i(TAG, 1193 "Posting delayed MCS_UNBIND"); 1194 removeMessages(MCS_UNBIND); 1195 Message ubmsg = obtainMessage(MCS_UNBIND); 1196 // Unbind after a little delay, to avoid 1197 // continual thrashing. 1198 sendMessageDelayed(ubmsg, 10000); 1199 } 1200 } else { 1201 // There are more pending requests in queue. 1202 // Just post MCS_BOUND message to trigger processing 1203 // of next pending install. 1204 if (DEBUG_SD_INSTALL) Log.i(TAG, 1205 "Posting MCS_BOUND for next work"); 1206 mHandler.sendEmptyMessage(MCS_BOUND); 1207 } 1208 } 1209 } 1210 } else { 1211 // Should never happen ideally. 1212 Slog.w(TAG, "Empty queue"); 1213 } 1214 break; 1215 } 1216 case MCS_RECONNECT: { 1217 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1218 if (mPendingInstalls.size() > 0) { 1219 if (mBound) { 1220 disconnectService(); 1221 } 1222 if (!connectToService()) { 1223 Slog.e(TAG, "Failed to bind to media container service"); 1224 for (HandlerParams params : mPendingInstalls) { 1225 // Indicate service bind error 1226 params.serviceError(); 1227 } 1228 mPendingInstalls.clear(); 1229 } 1230 } 1231 break; 1232 } 1233 case MCS_UNBIND: { 1234 // If there is no actual work left, then time to unbind. 1235 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1236 1237 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1238 if (mBound) { 1239 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1240 1241 disconnectService(); 1242 } 1243 } else if (mPendingInstalls.size() > 0) { 1244 // There are more pending requests in queue. 1245 // Just post MCS_BOUND message to trigger processing 1246 // of next pending install. 1247 mHandler.sendEmptyMessage(MCS_BOUND); 1248 } 1249 1250 break; 1251 } 1252 case MCS_GIVE_UP: { 1253 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1254 mPendingInstalls.remove(0); 1255 break; 1256 } 1257 case SEND_PENDING_BROADCAST: { 1258 String packages[]; 1259 ArrayList<String> components[]; 1260 int size = 0; 1261 int uids[]; 1262 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1263 synchronized (mPackages) { 1264 if (mPendingBroadcasts == null) { 1265 return; 1266 } 1267 size = mPendingBroadcasts.size(); 1268 if (size <= 0) { 1269 // Nothing to be done. Just return 1270 return; 1271 } 1272 packages = new String[size]; 1273 components = new ArrayList[size]; 1274 uids = new int[size]; 1275 int i = 0; // filling out the above arrays 1276 1277 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1278 int packageUserId = mPendingBroadcasts.userIdAt(n); 1279 Iterator<Map.Entry<String, ArrayList<String>>> it 1280 = mPendingBroadcasts.packagesForUserId(packageUserId) 1281 .entrySet().iterator(); 1282 while (it.hasNext() && i < size) { 1283 Map.Entry<String, ArrayList<String>> ent = it.next(); 1284 packages[i] = ent.getKey(); 1285 components[i] = ent.getValue(); 1286 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1287 uids[i] = (ps != null) 1288 ? UserHandle.getUid(packageUserId, ps.appId) 1289 : -1; 1290 i++; 1291 } 1292 } 1293 size = i; 1294 mPendingBroadcasts.clear(); 1295 } 1296 // Send broadcasts 1297 for (int i = 0; i < size; i++) { 1298 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1299 } 1300 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1301 break; 1302 } 1303 case START_CLEANING_PACKAGE: { 1304 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1305 final String packageName = (String)msg.obj; 1306 final int userId = msg.arg1; 1307 final boolean andCode = msg.arg2 != 0; 1308 synchronized (mPackages) { 1309 if (userId == UserHandle.USER_ALL) { 1310 int[] users = sUserManager.getUserIds(); 1311 for (int user : users) { 1312 mSettings.addPackageToCleanLPw( 1313 new PackageCleanItem(user, packageName, andCode)); 1314 } 1315 } else { 1316 mSettings.addPackageToCleanLPw( 1317 new PackageCleanItem(userId, packageName, andCode)); 1318 } 1319 } 1320 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1321 startCleaningPackages(); 1322 } break; 1323 case POST_INSTALL: { 1324 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1325 PostInstallData data = mRunningInstalls.get(msg.arg1); 1326 mRunningInstalls.delete(msg.arg1); 1327 boolean deleteOld = false; 1328 1329 if (data != null) { 1330 InstallArgs args = data.args; 1331 PackageInstalledInfo res = data.res; 1332 1333 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1334 final String packageName = res.pkg.applicationInfo.packageName; 1335 res.removedInfo.sendBroadcast(false, true, false); 1336 Bundle extras = new Bundle(1); 1337 extras.putInt(Intent.EXTRA_UID, res.uid); 1338 1339 // Now that we successfully installed the package, grant runtime 1340 // permissions if requested before broadcasting the install. 1341 if ((args.installFlags 1342 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1343 grantRequestedRuntimePermissions(res.pkg, 1344 args.user.getIdentifier()); 1345 } 1346 1347 // Determine the set of users who are adding this 1348 // package for the first time vs. those who are seeing 1349 // an update. 1350 int[] firstUsers; 1351 int[] updateUsers = new int[0]; 1352 if (res.origUsers == null || res.origUsers.length == 0) { 1353 firstUsers = res.newUsers; 1354 } else { 1355 firstUsers = new int[0]; 1356 for (int i=0; i<res.newUsers.length; i++) { 1357 int user = res.newUsers[i]; 1358 boolean isNew = true; 1359 for (int j=0; j<res.origUsers.length; j++) { 1360 if (res.origUsers[j] == user) { 1361 isNew = false; 1362 break; 1363 } 1364 } 1365 if (isNew) { 1366 int[] newFirst = new int[firstUsers.length+1]; 1367 System.arraycopy(firstUsers, 0, newFirst, 0, 1368 firstUsers.length); 1369 newFirst[firstUsers.length] = user; 1370 firstUsers = newFirst; 1371 } else { 1372 int[] newUpdate = new int[updateUsers.length+1]; 1373 System.arraycopy(updateUsers, 0, newUpdate, 0, 1374 updateUsers.length); 1375 newUpdate[updateUsers.length] = user; 1376 updateUsers = newUpdate; 1377 } 1378 } 1379 } 1380 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1381 packageName, extras, null, null, firstUsers); 1382 final boolean update = res.removedInfo.removedPackage != null; 1383 if (update) { 1384 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1385 } 1386 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1387 packageName, extras, null, null, updateUsers); 1388 if (update) { 1389 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1390 packageName, extras, null, null, updateUsers); 1391 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1392 null, null, packageName, null, updateUsers); 1393 1394 // treat asec-hosted packages like removable media on upgrade 1395 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1396 if (DEBUG_INSTALL) { 1397 Slog.i(TAG, "upgrading pkg " + res.pkg 1398 + " is ASEC-hosted -> AVAILABLE"); 1399 } 1400 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1401 ArrayList<String> pkgList = new ArrayList<String>(1); 1402 pkgList.add(packageName); 1403 sendResourcesChangedBroadcast(true, true, 1404 pkgList,uidArray, null); 1405 } 1406 } 1407 if (res.removedInfo.args != null) { 1408 // Remove the replaced package's older resources safely now 1409 deleteOld = true; 1410 } 1411 1412 // If this app is a browser and it's newly-installed for some 1413 // users, clear any default-browser state in those users 1414 if (firstUsers.length > 0) { 1415 // the app's nature doesn't depend on the user, so we can just 1416 // check its browser nature in any user and generalize. 1417 if (packageIsBrowser(packageName, firstUsers[0])) { 1418 synchronized (mPackages) { 1419 for (int userId : firstUsers) { 1420 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1421 } 1422 } 1423 } 1424 } 1425 // Log current value of "unknown sources" setting 1426 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1427 getUnknownSourcesSettings()); 1428 } 1429 // Force a gc to clear up things 1430 Runtime.getRuntime().gc(); 1431 // We delete after a gc for applications on sdcard. 1432 if (deleteOld) { 1433 synchronized (mInstallLock) { 1434 res.removedInfo.args.doPostDeleteLI(true); 1435 } 1436 } 1437 if (args.observer != null) { 1438 try { 1439 Bundle extras = extrasForInstallResult(res); 1440 args.observer.onPackageInstalled(res.name, res.returnCode, 1441 res.returnMsg, extras); 1442 } catch (RemoteException e) { 1443 Slog.i(TAG, "Observer no longer exists."); 1444 } 1445 } 1446 } else { 1447 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1448 } 1449 } break; 1450 case UPDATED_MEDIA_STATUS: { 1451 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1452 boolean reportStatus = msg.arg1 == 1; 1453 boolean doGc = msg.arg2 == 1; 1454 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1455 if (doGc) { 1456 // Force a gc to clear up stale containers. 1457 Runtime.getRuntime().gc(); 1458 } 1459 if (msg.obj != null) { 1460 @SuppressWarnings("unchecked") 1461 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1462 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1463 // Unload containers 1464 unloadAllContainers(args); 1465 } 1466 if (reportStatus) { 1467 try { 1468 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1469 PackageHelper.getMountService().finishMediaUpdate(); 1470 } catch (RemoteException e) { 1471 Log.e(TAG, "MountService not running?"); 1472 } 1473 } 1474 } break; 1475 case WRITE_SETTINGS: { 1476 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1477 synchronized (mPackages) { 1478 removeMessages(WRITE_SETTINGS); 1479 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1480 mSettings.writeLPr(); 1481 mDirtyUsers.clear(); 1482 } 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1484 } break; 1485 case WRITE_PACKAGE_RESTRICTIONS: { 1486 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1487 synchronized (mPackages) { 1488 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1489 for (int userId : mDirtyUsers) { 1490 mSettings.writePackageRestrictionsLPr(userId); 1491 } 1492 mDirtyUsers.clear(); 1493 } 1494 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1495 } break; 1496 case CHECK_PENDING_VERIFICATION: { 1497 final int verificationId = msg.arg1; 1498 final PackageVerificationState state = mPendingVerification.get(verificationId); 1499 1500 if ((state != null) && !state.timeoutExtended()) { 1501 final InstallArgs args = state.getInstallArgs(); 1502 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1503 1504 Slog.i(TAG, "Verification timed out for " + originUri); 1505 mPendingVerification.remove(verificationId); 1506 1507 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1508 1509 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1510 Slog.i(TAG, "Continuing with installation of " + originUri); 1511 state.setVerifierResponse(Binder.getCallingUid(), 1512 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1513 broadcastPackageVerified(verificationId, originUri, 1514 PackageManager.VERIFICATION_ALLOW, 1515 state.getInstallArgs().getUser()); 1516 try { 1517 ret = args.copyApk(mContainerService, true); 1518 } catch (RemoteException e) { 1519 Slog.e(TAG, "Could not contact the ContainerService"); 1520 } 1521 } else { 1522 broadcastPackageVerified(verificationId, originUri, 1523 PackageManager.VERIFICATION_REJECT, 1524 state.getInstallArgs().getUser()); 1525 } 1526 1527 processPendingInstall(args, ret); 1528 mHandler.sendEmptyMessage(MCS_UNBIND); 1529 } 1530 break; 1531 } 1532 case PACKAGE_VERIFIED: { 1533 final int verificationId = msg.arg1; 1534 1535 final PackageVerificationState state = mPendingVerification.get(verificationId); 1536 if (state == null) { 1537 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1538 break; 1539 } 1540 1541 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1542 1543 state.setVerifierResponse(response.callerUid, response.code); 1544 1545 if (state.isVerificationComplete()) { 1546 mPendingVerification.remove(verificationId); 1547 1548 final InstallArgs args = state.getInstallArgs(); 1549 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1550 1551 int ret; 1552 if (state.isInstallAllowed()) { 1553 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1554 broadcastPackageVerified(verificationId, originUri, 1555 response.code, state.getInstallArgs().getUser()); 1556 try { 1557 ret = args.copyApk(mContainerService, true); 1558 } catch (RemoteException e) { 1559 Slog.e(TAG, "Could not contact the ContainerService"); 1560 } 1561 } else { 1562 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1563 } 1564 1565 processPendingInstall(args, ret); 1566 1567 mHandler.sendEmptyMessage(MCS_UNBIND); 1568 } 1569 1570 break; 1571 } 1572 case START_INTENT_FILTER_VERIFICATIONS: { 1573 IFVerificationParams params = (IFVerificationParams) msg.obj; 1574 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1575 params.replacing, params.pkg); 1576 break; 1577 } 1578 case INTENT_FILTER_VERIFIED: { 1579 final int verificationId = msg.arg1; 1580 1581 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1582 verificationId); 1583 if (state == null) { 1584 Slog.w(TAG, "Invalid IntentFilter verification token " 1585 + verificationId + " received"); 1586 break; 1587 } 1588 1589 final int userId = state.getUserId(); 1590 1591 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1592 "Processing IntentFilter verification with token:" 1593 + verificationId + " and userId:" + userId); 1594 1595 final IntentFilterVerificationResponse response = 1596 (IntentFilterVerificationResponse) msg.obj; 1597 1598 state.setVerifierResponse(response.callerUid, response.code); 1599 1600 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1601 "IntentFilter verification with token:" + verificationId 1602 + " and userId:" + userId 1603 + " is settings verifier response with response code:" 1604 + response.code); 1605 1606 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1607 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1608 + response.getFailedDomainsString()); 1609 } 1610 1611 if (state.isVerificationComplete()) { 1612 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1613 } else { 1614 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1615 "IntentFilter verification with token:" + verificationId 1616 + " was not said to be complete"); 1617 } 1618 1619 break; 1620 } 1621 } 1622 } 1623 } 1624 1625 private StorageEventListener mStorageListener = new StorageEventListener() { 1626 @Override 1627 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1628 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1629 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1630 final String volumeUuid = vol.getFsUuid(); 1631 1632 // Clean up any users or apps that were removed or recreated 1633 // while this volume was missing 1634 reconcileUsers(volumeUuid); 1635 reconcileApps(volumeUuid); 1636 1637 // Clean up any install sessions that expired or were 1638 // cancelled while this volume was missing 1639 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1640 1641 loadPrivatePackages(vol); 1642 1643 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1644 unloadPrivatePackages(vol); 1645 } 1646 } 1647 1648 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1649 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1650 updateExternalMediaStatus(true, false); 1651 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1652 updateExternalMediaStatus(false, false); 1653 } 1654 } 1655 } 1656 1657 @Override 1658 public void onVolumeForgotten(String fsUuid) { 1659 // Remove any apps installed on the forgotten volume 1660 synchronized (mPackages) { 1661 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1662 for (PackageSetting ps : packages) { 1663 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1664 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1665 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1666 } 1667 1668 mSettings.writeLPr(); 1669 } 1670 } 1671 }; 1672 1673 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1674 if (userId >= UserHandle.USER_OWNER) { 1675 grantRequestedRuntimePermissionsForUser(pkg, userId); 1676 } else if (userId == UserHandle.USER_ALL) { 1677 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1678 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1679 } 1680 } 1681 1682 // We could have touched GID membership, so flush out packages.list 1683 synchronized (mPackages) { 1684 mSettings.writePackageListLPr(); 1685 } 1686 } 1687 1688 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1689 SettingBase sb = (SettingBase) pkg.mExtras; 1690 if (sb == null) { 1691 return; 1692 } 1693 1694 PermissionsState permissionsState = sb.getPermissionsState(); 1695 1696 for (String permission : pkg.requestedPermissions) { 1697 BasePermission bp = mSettings.mPermissions.get(permission); 1698 if (bp != null && bp.isRuntime()) { 1699 permissionsState.grantRuntimePermission(bp, userId); 1700 } 1701 } 1702 } 1703 1704 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1705 Bundle extras = null; 1706 switch (res.returnCode) { 1707 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1708 extras = new Bundle(); 1709 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1710 res.origPermission); 1711 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1712 res.origPackage); 1713 break; 1714 } 1715 case PackageManager.INSTALL_SUCCEEDED: { 1716 extras = new Bundle(); 1717 extras.putBoolean(Intent.EXTRA_REPLACING, 1718 res.removedInfo != null && res.removedInfo.removedPackage != null); 1719 break; 1720 } 1721 } 1722 return extras; 1723 } 1724 1725 void scheduleWriteSettingsLocked() { 1726 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1727 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1728 } 1729 } 1730 1731 void scheduleWritePackageRestrictionsLocked(int userId) { 1732 if (!sUserManager.exists(userId)) return; 1733 mDirtyUsers.add(userId); 1734 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1735 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1736 } 1737 } 1738 1739 public static PackageManagerService main(Context context, Installer installer, 1740 boolean factoryTest, boolean onlyCore) { 1741 PackageManagerService m = new PackageManagerService(context, installer, 1742 factoryTest, onlyCore); 1743 ServiceManager.addService("package", m); 1744 return m; 1745 } 1746 1747 static String[] splitString(String str, char sep) { 1748 int count = 1; 1749 int i = 0; 1750 while ((i=str.indexOf(sep, i)) >= 0) { 1751 count++; 1752 i++; 1753 } 1754 1755 String[] res = new String[count]; 1756 i=0; 1757 count = 0; 1758 int lastI=0; 1759 while ((i=str.indexOf(sep, i)) >= 0) { 1760 res[count] = str.substring(lastI, i); 1761 count++; 1762 i++; 1763 lastI = i; 1764 } 1765 res[count] = str.substring(lastI, str.length()); 1766 return res; 1767 } 1768 1769 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1770 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1771 Context.DISPLAY_SERVICE); 1772 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1773 } 1774 1775 public PackageManagerService(Context context, Installer installer, 1776 boolean factoryTest, boolean onlyCore) { 1777 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1778 SystemClock.uptimeMillis()); 1779 1780 if (mSdkVersion <= 0) { 1781 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1782 } 1783 1784 mContext = context; 1785 mFactoryTest = factoryTest; 1786 mOnlyCore = onlyCore; 1787 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1788 mMetrics = new DisplayMetrics(); 1789 mSettings = new Settings(mPackages); 1790 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1791 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1792 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1793 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1794 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1795 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1796 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1797 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1798 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1799 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1800 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1801 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1802 1803 // TODO: add a property to control this? 1804 long dexOptLRUThresholdInMinutes; 1805 if (mLazyDexOpt) { 1806 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1807 } else { 1808 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1809 } 1810 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1811 1812 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1813 if (separateProcesses != null && separateProcesses.length() > 0) { 1814 if ("*".equals(separateProcesses)) { 1815 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1816 mSeparateProcesses = null; 1817 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1818 } else { 1819 mDefParseFlags = 0; 1820 mSeparateProcesses = separateProcesses.split(","); 1821 Slog.w(TAG, "Running with debug.separate_processes: " 1822 + separateProcesses); 1823 } 1824 } else { 1825 mDefParseFlags = 0; 1826 mSeparateProcesses = null; 1827 } 1828 1829 mInstaller = installer; 1830 mPackageDexOptimizer = new PackageDexOptimizer(this); 1831 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1832 1833 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1834 FgThread.get().getLooper()); 1835 1836 getDefaultDisplayMetrics(context, mMetrics); 1837 1838 SystemConfig systemConfig = SystemConfig.getInstance(); 1839 mGlobalGids = systemConfig.getGlobalGids(); 1840 mSystemPermissions = systemConfig.getSystemPermissions(); 1841 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1842 1843 synchronized (mInstallLock) { 1844 // writer 1845 synchronized (mPackages) { 1846 mHandlerThread = new ServiceThread(TAG, 1847 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1848 mHandlerThread.start(); 1849 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1850 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1851 1852 File dataDir = Environment.getDataDirectory(); 1853 mAppDataDir = new File(dataDir, "data"); 1854 mAppInstallDir = new File(dataDir, "app"); 1855 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1856 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1857 mUserAppDataDir = new File(dataDir, "user"); 1858 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1859 1860 sUserManager = new UserManagerService(context, this, 1861 mInstallLock, mPackages); 1862 1863 // Propagate permission configuration in to package manager. 1864 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1865 = systemConfig.getPermissions(); 1866 for (int i=0; i<permConfig.size(); i++) { 1867 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1868 BasePermission bp = mSettings.mPermissions.get(perm.name); 1869 if (bp == null) { 1870 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1871 mSettings.mPermissions.put(perm.name, bp); 1872 } 1873 if (perm.gids != null) { 1874 bp.setGids(perm.gids, perm.perUser); 1875 } 1876 } 1877 1878 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1879 for (int i=0; i<libConfig.size(); i++) { 1880 mSharedLibraries.put(libConfig.keyAt(i), 1881 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1882 } 1883 1884 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1885 1886 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1887 mSdkVersion, mOnlyCore); 1888 1889 String customResolverActivity = Resources.getSystem().getString( 1890 R.string.config_customResolverActivity); 1891 if (TextUtils.isEmpty(customResolverActivity)) { 1892 customResolverActivity = null; 1893 } else { 1894 mCustomResolverComponentName = ComponentName.unflattenFromString( 1895 customResolverActivity); 1896 } 1897 1898 long startTime = SystemClock.uptimeMillis(); 1899 1900 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1901 startTime); 1902 1903 // Set flag to monitor and not change apk file paths when 1904 // scanning install directories. 1905 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1906 1907 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1908 1909 /** 1910 * Add everything in the in the boot class path to the 1911 * list of process files because dexopt will have been run 1912 * if necessary during zygote startup. 1913 */ 1914 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1915 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1916 1917 if (bootClassPath != null) { 1918 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1919 for (String element : bootClassPathElements) { 1920 alreadyDexOpted.add(element); 1921 } 1922 } else { 1923 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1924 } 1925 1926 if (systemServerClassPath != null) { 1927 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1928 for (String element : systemServerClassPathElements) { 1929 alreadyDexOpted.add(element); 1930 } 1931 } else { 1932 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1933 } 1934 1935 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1936 final String[] dexCodeInstructionSets = 1937 getDexCodeInstructionSets( 1938 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1939 1940 /** 1941 * Ensure all external libraries have had dexopt run on them. 1942 */ 1943 if (mSharedLibraries.size() > 0) { 1944 // NOTE: For now, we're compiling these system "shared libraries" 1945 // (and framework jars) into all available architectures. It's possible 1946 // to compile them only when we come across an app that uses them (there's 1947 // already logic for that in scanPackageLI) but that adds some complexity. 1948 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1949 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1950 final String lib = libEntry.path; 1951 if (lib == null) { 1952 continue; 1953 } 1954 1955 try { 1956 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1957 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1958 alreadyDexOpted.add(lib); 1959 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1960 } 1961 } catch (FileNotFoundException e) { 1962 Slog.w(TAG, "Library not found: " + lib); 1963 } catch (IOException e) { 1964 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1965 + e.getMessage()); 1966 } 1967 } 1968 } 1969 } 1970 1971 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1972 1973 // Gross hack for now: we know this file doesn't contain any 1974 // code, so don't dexopt it to avoid the resulting log spew. 1975 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1976 1977 // Gross hack for now: we know this file is only part of 1978 // the boot class path for art, so don't dexopt it to 1979 // avoid the resulting log spew. 1980 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1981 1982 /** 1983 * There are a number of commands implemented in Java, which 1984 * we currently need to do the dexopt on so that they can be 1985 * run from a non-root shell. 1986 */ 1987 String[] frameworkFiles = frameworkDir.list(); 1988 if (frameworkFiles != null) { 1989 // TODO: We could compile these only for the most preferred ABI. We should 1990 // first double check that the dex files for these commands are not referenced 1991 // by other system apps. 1992 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1993 for (int i=0; i<frameworkFiles.length; i++) { 1994 File libPath = new File(frameworkDir, frameworkFiles[i]); 1995 String path = libPath.getPath(); 1996 // Skip the file if we already did it. 1997 if (alreadyDexOpted.contains(path)) { 1998 continue; 1999 } 2000 // Skip the file if it is not a type we want to dexopt. 2001 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2002 continue; 2003 } 2004 try { 2005 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2006 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2007 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2008 } 2009 } catch (FileNotFoundException e) { 2010 Slog.w(TAG, "Jar not found: " + path); 2011 } catch (IOException e) { 2012 Slog.w(TAG, "Exception reading jar: " + path, e); 2013 } 2014 } 2015 } 2016 } 2017 2018 // Collect vendor overlay packages. 2019 // (Do this before scanning any apps.) 2020 // For security and version matching reason, only consider 2021 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2022 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2023 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2024 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2025 2026 // Find base frameworks (resource packages without code). 2027 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2028 | PackageParser.PARSE_IS_SYSTEM_DIR 2029 | PackageParser.PARSE_IS_PRIVILEGED, 2030 scanFlags | SCAN_NO_DEX, 0); 2031 2032 // Collected privileged system packages. 2033 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2034 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2035 | PackageParser.PARSE_IS_SYSTEM_DIR 2036 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2037 2038 // Collect ordinary system packages. 2039 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2040 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2041 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2042 2043 // Collect all vendor packages. 2044 File vendorAppDir = new File("/vendor/app"); 2045 try { 2046 vendorAppDir = vendorAppDir.getCanonicalFile(); 2047 } catch (IOException e) { 2048 // failed to look up canonical path, continue with original one 2049 } 2050 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2051 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2052 2053 // Collect all OEM packages. 2054 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2055 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2056 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2057 2058 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2059 mInstaller.moveFiles(); 2060 2061 // Prune any system packages that no longer exist. 2062 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2063 if (!mOnlyCore) { 2064 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2065 while (psit.hasNext()) { 2066 PackageSetting ps = psit.next(); 2067 2068 /* 2069 * If this is not a system app, it can't be a 2070 * disable system app. 2071 */ 2072 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2073 continue; 2074 } 2075 2076 /* 2077 * If the package is scanned, it's not erased. 2078 */ 2079 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2080 if (scannedPkg != null) { 2081 /* 2082 * If the system app is both scanned and in the 2083 * disabled packages list, then it must have been 2084 * added via OTA. Remove it from the currently 2085 * scanned package so the previously user-installed 2086 * application can be scanned. 2087 */ 2088 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2089 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2090 + ps.name + "; removing system app. Last known codePath=" 2091 + ps.codePathString + ", installStatus=" + ps.installStatus 2092 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2093 + scannedPkg.mVersionCode); 2094 removePackageLI(ps, true); 2095 mExpectingBetter.put(ps.name, ps.codePath); 2096 } 2097 2098 continue; 2099 } 2100 2101 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2102 psit.remove(); 2103 logCriticalInfo(Log.WARN, "System package " + ps.name 2104 + " no longer exists; wiping its data"); 2105 removeDataDirsLI(null, ps.name); 2106 } else { 2107 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2108 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2109 possiblyDeletedUpdatedSystemApps.add(ps.name); 2110 } 2111 } 2112 } 2113 } 2114 2115 //look for any incomplete package installations 2116 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2117 //clean up list 2118 for(int i = 0; i < deletePkgsList.size(); i++) { 2119 //clean up here 2120 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2121 } 2122 //delete tmp files 2123 deleteTempPackageFiles(); 2124 2125 // Remove any shared userIDs that have no associated packages 2126 mSettings.pruneSharedUsersLPw(); 2127 2128 if (!mOnlyCore) { 2129 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2130 SystemClock.uptimeMillis()); 2131 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2132 2133 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2134 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2135 2136 /** 2137 * Remove disable package settings for any updated system 2138 * apps that were removed via an OTA. If they're not a 2139 * previously-updated app, remove them completely. 2140 * Otherwise, just revoke their system-level permissions. 2141 */ 2142 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2143 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2144 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2145 2146 String msg; 2147 if (deletedPkg == null) { 2148 msg = "Updated system package " + deletedAppName 2149 + " no longer exists; wiping its data"; 2150 removeDataDirsLI(null, deletedAppName); 2151 } else { 2152 msg = "Updated system app + " + deletedAppName 2153 + " no longer present; removing system privileges for " 2154 + deletedAppName; 2155 2156 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2157 2158 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2159 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2160 } 2161 logCriticalInfo(Log.WARN, msg); 2162 } 2163 2164 /** 2165 * Make sure all system apps that we expected to appear on 2166 * the userdata partition actually showed up. If they never 2167 * appeared, crawl back and revive the system version. 2168 */ 2169 for (int i = 0; i < mExpectingBetter.size(); i++) { 2170 final String packageName = mExpectingBetter.keyAt(i); 2171 if (!mPackages.containsKey(packageName)) { 2172 final File scanFile = mExpectingBetter.valueAt(i); 2173 2174 logCriticalInfo(Log.WARN, "Expected better " + packageName 2175 + " but never showed up; reverting to system"); 2176 2177 final int reparseFlags; 2178 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2179 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2180 | PackageParser.PARSE_IS_SYSTEM_DIR 2181 | PackageParser.PARSE_IS_PRIVILEGED; 2182 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2183 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2184 | PackageParser.PARSE_IS_SYSTEM_DIR; 2185 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2186 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2187 | PackageParser.PARSE_IS_SYSTEM_DIR; 2188 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2189 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2190 | PackageParser.PARSE_IS_SYSTEM_DIR; 2191 } else { 2192 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2193 continue; 2194 } 2195 2196 mSettings.enableSystemPackageLPw(packageName); 2197 2198 try { 2199 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2200 } catch (PackageManagerException e) { 2201 Slog.e(TAG, "Failed to parse original system package: " 2202 + e.getMessage()); 2203 } 2204 } 2205 } 2206 } 2207 mExpectingBetter.clear(); 2208 2209 // Now that we know all of the shared libraries, update all clients to have 2210 // the correct library paths. 2211 updateAllSharedLibrariesLPw(); 2212 2213 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2214 // NOTE: We ignore potential failures here during a system scan (like 2215 // the rest of the commands above) because there's precious little we 2216 // can do about it. A settings error is reported, though. 2217 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2218 false /* force dexopt */, false /* defer dexopt */); 2219 } 2220 2221 // Now that we know all the packages we are keeping, 2222 // read and update their last usage times. 2223 mPackageUsage.readLP(); 2224 2225 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2226 SystemClock.uptimeMillis()); 2227 Slog.i(TAG, "Time to scan packages: " 2228 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2229 + " seconds"); 2230 2231 // If the platform SDK has changed since the last time we booted, 2232 // we need to re-grant app permission to catch any new ones that 2233 // appear. This is really a hack, and means that apps can in some 2234 // cases get permissions that the user didn't initially explicitly 2235 // allow... it would be nice to have some better way to handle 2236 // this situation. 2237 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2238 != mSdkVersion; 2239 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2240 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2241 + "; regranting permissions for internal storage"); 2242 mSettings.mInternalSdkPlatform = mSdkVersion; 2243 2244 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2245 | (regrantPermissions 2246 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2247 : 0)); 2248 2249 // If this is the first boot, and it is a normal boot, then 2250 // we need to initialize the default preferred apps. 2251 if (!mRestoredSettings && !onlyCore) { 2252 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2253 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2254 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2255 } 2256 2257 // If this is first boot after an OTA, and a normal boot, then 2258 // we need to clear code cache directories. 2259 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2260 if (mIsUpgrade && !onlyCore) { 2261 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2262 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2263 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2264 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2265 } 2266 mSettings.mFingerprint = Build.FINGERPRINT; 2267 } 2268 2269 checkDefaultBrowser(); 2270 2271 // All the changes are done during package scanning. 2272 mSettings.updateInternalDatabaseVersion(); 2273 2274 // can downgrade to reader 2275 mSettings.writeLPr(); 2276 2277 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2278 SystemClock.uptimeMillis()); 2279 2280 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2281 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2282 2283 mInstallerService = new PackageInstallerService(context, this); 2284 2285 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2286 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2287 mIntentFilterVerifierComponent); 2288 2289 } // synchronized (mPackages) 2290 } // synchronized (mInstallLock) 2291 2292 // Now after opening every single application zip, make sure they 2293 // are all flushed. Not really needed, but keeps things nice and 2294 // tidy. 2295 Runtime.getRuntime().gc(); 2296 2297 // Expose private service for system components to use. 2298 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2299 } 2300 2301 @Override 2302 public boolean isFirstBoot() { 2303 return !mRestoredSettings; 2304 } 2305 2306 @Override 2307 public boolean isOnlyCoreApps() { 2308 return mOnlyCore; 2309 } 2310 2311 @Override 2312 public boolean isUpgrade() { 2313 return mIsUpgrade; 2314 } 2315 2316 private String getRequiredVerifierLPr() { 2317 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2318 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2319 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2320 2321 String requiredVerifier = null; 2322 2323 final int N = receivers.size(); 2324 for (int i = 0; i < N; i++) { 2325 final ResolveInfo info = receivers.get(i); 2326 2327 if (info.activityInfo == null) { 2328 continue; 2329 } 2330 2331 final String packageName = info.activityInfo.packageName; 2332 2333 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2334 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2335 continue; 2336 } 2337 2338 if (requiredVerifier != null) { 2339 throw new RuntimeException("There can be only one required verifier"); 2340 } 2341 2342 requiredVerifier = packageName; 2343 } 2344 2345 return requiredVerifier; 2346 } 2347 2348 private String getRequiredInstallerLPr() { 2349 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2350 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2351 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2352 2353 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2354 PACKAGE_MIME_TYPE, 0, 0); 2355 2356 String requiredInstaller = null; 2357 2358 final int N = installers.size(); 2359 for (int i = 0; i < N; i++) { 2360 final ResolveInfo info = installers.get(i); 2361 final String packageName = info.activityInfo.packageName; 2362 2363 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2364 continue; 2365 } 2366 2367 if (requiredInstaller != null) { 2368 throw new RuntimeException("There must be one required installer"); 2369 } 2370 2371 requiredInstaller = packageName; 2372 } 2373 2374 if (requiredInstaller == null) { 2375 throw new RuntimeException("There must be one required installer"); 2376 } 2377 2378 return requiredInstaller; 2379 } 2380 2381 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2382 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2383 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2384 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2385 2386 ComponentName verifierComponentName = null; 2387 2388 int priority = -1000; 2389 final int N = receivers.size(); 2390 for (int i = 0; i < N; i++) { 2391 final ResolveInfo info = receivers.get(i); 2392 2393 if (info.activityInfo == null) { 2394 continue; 2395 } 2396 2397 final String packageName = info.activityInfo.packageName; 2398 2399 final PackageSetting ps = mSettings.mPackages.get(packageName); 2400 if (ps == null) { 2401 continue; 2402 } 2403 2404 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2405 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2406 continue; 2407 } 2408 2409 // Select the IntentFilterVerifier with the highest priority 2410 if (priority < info.priority) { 2411 priority = info.priority; 2412 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2413 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2414 + verifierComponentName + " with priority: " + info.priority); 2415 } 2416 } 2417 2418 return verifierComponentName; 2419 } 2420 2421 private void primeDomainVerificationsLPw(int userId) { 2422 if (DEBUG_DOMAIN_VERIFICATION) { 2423 Slog.d(TAG, "Priming domain verifications in user " + userId); 2424 } 2425 2426 SystemConfig systemConfig = SystemConfig.getInstance(); 2427 ArraySet<String> packages = systemConfig.getLinkedApps(); 2428 ArraySet<String> domains = new ArraySet<String>(); 2429 2430 for (String packageName : packages) { 2431 PackageParser.Package pkg = mPackages.get(packageName); 2432 if (pkg != null) { 2433 if (!pkg.isSystemApp()) { 2434 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2435 continue; 2436 } 2437 2438 domains.clear(); 2439 for (PackageParser.Activity a : pkg.activities) { 2440 for (ActivityIntentInfo filter : a.intents) { 2441 if (hasValidDomains(filter)) { 2442 domains.addAll(filter.getHostsList()); 2443 } 2444 } 2445 } 2446 2447 if (domains.size() > 0) { 2448 if (DEBUG_DOMAIN_VERIFICATION) { 2449 Slog.v(TAG, " + " + packageName); 2450 } 2451 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2452 // state w.r.t. the formal app-linkage "no verification attempted" state; 2453 // and then 'always' in the per-user state actually used for intent resolution. 2454 final IntentFilterVerificationInfo ivi; 2455 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2456 new ArrayList<String>(domains)); 2457 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2458 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2459 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2460 } else { 2461 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2462 + "' does not handle web links"); 2463 } 2464 } else { 2465 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2466 } 2467 } 2468 2469 scheduleWritePackageRestrictionsLocked(userId); 2470 scheduleWriteSettingsLocked(); 2471 } 2472 2473 private void applyFactoryDefaultBrowserLPw(int userId) { 2474 // The default browser app's package name is stored in a string resource, 2475 // with a product-specific overlay used for vendor customization. 2476 String browserPkg = mContext.getResources().getString( 2477 com.android.internal.R.string.default_browser); 2478 if (!TextUtils.isEmpty(browserPkg)) { 2479 // non-empty string => required to be a known package 2480 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2481 if (ps == null) { 2482 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2483 browserPkg = null; 2484 } else { 2485 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2486 } 2487 } 2488 2489 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2490 // default. If there's more than one, just leave everything alone. 2491 if (browserPkg == null) { 2492 calculateDefaultBrowserLPw(userId); 2493 } 2494 } 2495 2496 private void calculateDefaultBrowserLPw(int userId) { 2497 List<String> allBrowsers = resolveAllBrowserApps(userId); 2498 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2499 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2500 } 2501 2502 private List<String> resolveAllBrowserApps(int userId) { 2503 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2504 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2505 PackageManager.MATCH_ALL, userId); 2506 2507 final int count = list.size(); 2508 List<String> result = new ArrayList<String>(count); 2509 for (int i=0; i<count; i++) { 2510 ResolveInfo info = list.get(i); 2511 if (info.activityInfo == null 2512 || !info.handleAllWebDataURI 2513 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2514 || result.contains(info.activityInfo.packageName)) { 2515 continue; 2516 } 2517 result.add(info.activityInfo.packageName); 2518 } 2519 2520 return result; 2521 } 2522 2523 private boolean packageIsBrowser(String packageName, int userId) { 2524 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2525 PackageManager.MATCH_ALL, userId); 2526 final int N = list.size(); 2527 for (int i = 0; i < N; i++) { 2528 ResolveInfo info = list.get(i); 2529 if (packageName.equals(info.activityInfo.packageName)) { 2530 return true; 2531 } 2532 } 2533 return false; 2534 } 2535 2536 private void checkDefaultBrowser() { 2537 final int myUserId = UserHandle.myUserId(); 2538 final String packageName = getDefaultBrowserPackageName(myUserId); 2539 if (packageName != null) { 2540 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2541 if (info == null) { 2542 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2543 synchronized (mPackages) { 2544 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2545 } 2546 } 2547 } 2548 } 2549 2550 @Override 2551 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2552 throws RemoteException { 2553 try { 2554 return super.onTransact(code, data, reply, flags); 2555 } catch (RuntimeException e) { 2556 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2557 Slog.wtf(TAG, "Package Manager Crash", e); 2558 } 2559 throw e; 2560 } 2561 } 2562 2563 void cleanupInstallFailedPackage(PackageSetting ps) { 2564 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2565 2566 removeDataDirsLI(ps.volumeUuid, ps.name); 2567 if (ps.codePath != null) { 2568 if (ps.codePath.isDirectory()) { 2569 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2570 } else { 2571 ps.codePath.delete(); 2572 } 2573 } 2574 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2575 if (ps.resourcePath.isDirectory()) { 2576 FileUtils.deleteContents(ps.resourcePath); 2577 } 2578 ps.resourcePath.delete(); 2579 } 2580 mSettings.removePackageLPw(ps.name); 2581 } 2582 2583 static int[] appendInts(int[] cur, int[] add) { 2584 if (add == null) return cur; 2585 if (cur == null) return add; 2586 final int N = add.length; 2587 for (int i=0; i<N; i++) { 2588 cur = appendInt(cur, add[i]); 2589 } 2590 return cur; 2591 } 2592 2593 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2594 if (!sUserManager.exists(userId)) return null; 2595 final PackageSetting ps = (PackageSetting) p.mExtras; 2596 if (ps == null) { 2597 return null; 2598 } 2599 2600 final PermissionsState permissionsState = ps.getPermissionsState(); 2601 2602 final int[] gids = permissionsState.computeGids(userId); 2603 final Set<String> permissions = permissionsState.getPermissions(userId); 2604 final PackageUserState state = ps.readUserState(userId); 2605 2606 return PackageParser.generatePackageInfo(p, gids, flags, 2607 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2608 } 2609 2610 @Override 2611 public boolean isPackageFrozen(String packageName) { 2612 synchronized (mPackages) { 2613 final PackageSetting ps = mSettings.mPackages.get(packageName); 2614 if (ps != null) { 2615 return ps.frozen; 2616 } 2617 } 2618 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2619 return true; 2620 } 2621 2622 @Override 2623 public boolean isPackageAvailable(String packageName, int userId) { 2624 if (!sUserManager.exists(userId)) return false; 2625 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2626 synchronized (mPackages) { 2627 PackageParser.Package p = mPackages.get(packageName); 2628 if (p != null) { 2629 final PackageSetting ps = (PackageSetting) p.mExtras; 2630 if (ps != null) { 2631 final PackageUserState state = ps.readUserState(userId); 2632 if (state != null) { 2633 return PackageParser.isAvailable(state); 2634 } 2635 } 2636 } 2637 } 2638 return false; 2639 } 2640 2641 @Override 2642 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2643 if (!sUserManager.exists(userId)) return null; 2644 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2645 // reader 2646 synchronized (mPackages) { 2647 PackageParser.Package p = mPackages.get(packageName); 2648 if (DEBUG_PACKAGE_INFO) 2649 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2650 if (p != null) { 2651 return generatePackageInfo(p, flags, userId); 2652 } 2653 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2654 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2655 } 2656 } 2657 return null; 2658 } 2659 2660 @Override 2661 public String[] currentToCanonicalPackageNames(String[] names) { 2662 String[] out = new String[names.length]; 2663 // reader 2664 synchronized (mPackages) { 2665 for (int i=names.length-1; i>=0; i--) { 2666 PackageSetting ps = mSettings.mPackages.get(names[i]); 2667 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2668 } 2669 } 2670 return out; 2671 } 2672 2673 @Override 2674 public String[] canonicalToCurrentPackageNames(String[] names) { 2675 String[] out = new String[names.length]; 2676 // reader 2677 synchronized (mPackages) { 2678 for (int i=names.length-1; i>=0; i--) { 2679 String cur = mSettings.mRenamedPackages.get(names[i]); 2680 out[i] = cur != null ? cur : names[i]; 2681 } 2682 } 2683 return out; 2684 } 2685 2686 @Override 2687 public int getPackageUid(String packageName, int userId) { 2688 if (!sUserManager.exists(userId)) return -1; 2689 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2690 2691 // reader 2692 synchronized (mPackages) { 2693 PackageParser.Package p = mPackages.get(packageName); 2694 if(p != null) { 2695 return UserHandle.getUid(userId, p.applicationInfo.uid); 2696 } 2697 PackageSetting ps = mSettings.mPackages.get(packageName); 2698 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2699 return -1; 2700 } 2701 p = ps.pkg; 2702 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2703 } 2704 } 2705 2706 @Override 2707 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2708 if (!sUserManager.exists(userId)) { 2709 return null; 2710 } 2711 2712 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2713 "getPackageGids"); 2714 2715 // reader 2716 synchronized (mPackages) { 2717 PackageParser.Package p = mPackages.get(packageName); 2718 if (DEBUG_PACKAGE_INFO) { 2719 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2720 } 2721 if (p != null) { 2722 PackageSetting ps = (PackageSetting) p.mExtras; 2723 return ps.getPermissionsState().computeGids(userId); 2724 } 2725 } 2726 2727 return null; 2728 } 2729 2730 @Override 2731 public int getMountExternalMode(int uid) { 2732 if (Process.isIsolated(uid)) { 2733 return Zygote.MOUNT_EXTERNAL_NONE; 2734 } else { 2735 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 2736 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2737 } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2738 return Zygote.MOUNT_EXTERNAL_WRITE; 2739 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2740 return Zygote.MOUNT_EXTERNAL_READ; 2741 } else { 2742 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2743 } 2744 } 2745 } 2746 2747 static PermissionInfo generatePermissionInfo( 2748 BasePermission bp, int flags) { 2749 if (bp.perm != null) { 2750 return PackageParser.generatePermissionInfo(bp.perm, flags); 2751 } 2752 PermissionInfo pi = new PermissionInfo(); 2753 pi.name = bp.name; 2754 pi.packageName = bp.sourcePackage; 2755 pi.nonLocalizedLabel = bp.name; 2756 pi.protectionLevel = bp.protectionLevel; 2757 return pi; 2758 } 2759 2760 @Override 2761 public PermissionInfo getPermissionInfo(String name, int flags) { 2762 // reader 2763 synchronized (mPackages) { 2764 final BasePermission p = mSettings.mPermissions.get(name); 2765 if (p != null) { 2766 return generatePermissionInfo(p, flags); 2767 } 2768 return null; 2769 } 2770 } 2771 2772 @Override 2773 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2774 // reader 2775 synchronized (mPackages) { 2776 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2777 for (BasePermission p : mSettings.mPermissions.values()) { 2778 if (group == null) { 2779 if (p.perm == null || p.perm.info.group == null) { 2780 out.add(generatePermissionInfo(p, flags)); 2781 } 2782 } else { 2783 if (p.perm != null && group.equals(p.perm.info.group)) { 2784 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2785 } 2786 } 2787 } 2788 2789 if (out.size() > 0) { 2790 return out; 2791 } 2792 return mPermissionGroups.containsKey(group) ? out : null; 2793 } 2794 } 2795 2796 @Override 2797 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2798 // reader 2799 synchronized (mPackages) { 2800 return PackageParser.generatePermissionGroupInfo( 2801 mPermissionGroups.get(name), flags); 2802 } 2803 } 2804 2805 @Override 2806 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2807 // reader 2808 synchronized (mPackages) { 2809 final int N = mPermissionGroups.size(); 2810 ArrayList<PermissionGroupInfo> out 2811 = new ArrayList<PermissionGroupInfo>(N); 2812 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2813 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2814 } 2815 return out; 2816 } 2817 } 2818 2819 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2820 int userId) { 2821 if (!sUserManager.exists(userId)) return null; 2822 PackageSetting ps = mSettings.mPackages.get(packageName); 2823 if (ps != null) { 2824 if (ps.pkg == null) { 2825 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2826 flags, userId); 2827 if (pInfo != null) { 2828 return pInfo.applicationInfo; 2829 } 2830 return null; 2831 } 2832 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2833 ps.readUserState(userId), userId); 2834 } 2835 return null; 2836 } 2837 2838 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2839 int userId) { 2840 if (!sUserManager.exists(userId)) return null; 2841 PackageSetting ps = mSettings.mPackages.get(packageName); 2842 if (ps != null) { 2843 PackageParser.Package pkg = ps.pkg; 2844 if (pkg == null) { 2845 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2846 return null; 2847 } 2848 // Only data remains, so we aren't worried about code paths 2849 pkg = new PackageParser.Package(packageName); 2850 pkg.applicationInfo.packageName = packageName; 2851 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2852 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2853 pkg.applicationInfo.dataDir = Environment 2854 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2855 .getAbsolutePath(); 2856 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2857 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2858 } 2859 return generatePackageInfo(pkg, flags, userId); 2860 } 2861 return null; 2862 } 2863 2864 @Override 2865 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2866 if (!sUserManager.exists(userId)) return null; 2867 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2868 // writer 2869 synchronized (mPackages) { 2870 PackageParser.Package p = mPackages.get(packageName); 2871 if (DEBUG_PACKAGE_INFO) Log.v( 2872 TAG, "getApplicationInfo " + packageName 2873 + ": " + p); 2874 if (p != null) { 2875 PackageSetting ps = mSettings.mPackages.get(packageName); 2876 if (ps == null) return null; 2877 // Note: isEnabledLP() does not apply here - always return info 2878 return PackageParser.generateApplicationInfo( 2879 p, flags, ps.readUserState(userId), userId); 2880 } 2881 if ("android".equals(packageName)||"system".equals(packageName)) { 2882 return mAndroidApplication; 2883 } 2884 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2885 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2886 } 2887 } 2888 return null; 2889 } 2890 2891 @Override 2892 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2893 final IPackageDataObserver observer) { 2894 mContext.enforceCallingOrSelfPermission( 2895 android.Manifest.permission.CLEAR_APP_CACHE, null); 2896 // Queue up an async operation since clearing cache may take a little while. 2897 mHandler.post(new Runnable() { 2898 public void run() { 2899 mHandler.removeCallbacks(this); 2900 int retCode = -1; 2901 synchronized (mInstallLock) { 2902 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2903 if (retCode < 0) { 2904 Slog.w(TAG, "Couldn't clear application caches"); 2905 } 2906 } 2907 if (observer != null) { 2908 try { 2909 observer.onRemoveCompleted(null, (retCode >= 0)); 2910 } catch (RemoteException e) { 2911 Slog.w(TAG, "RemoveException when invoking call back"); 2912 } 2913 } 2914 } 2915 }); 2916 } 2917 2918 @Override 2919 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2920 final IntentSender pi) { 2921 mContext.enforceCallingOrSelfPermission( 2922 android.Manifest.permission.CLEAR_APP_CACHE, null); 2923 // Queue up an async operation since clearing cache may take a little while. 2924 mHandler.post(new Runnable() { 2925 public void run() { 2926 mHandler.removeCallbacks(this); 2927 int retCode = -1; 2928 synchronized (mInstallLock) { 2929 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2930 if (retCode < 0) { 2931 Slog.w(TAG, "Couldn't clear application caches"); 2932 } 2933 } 2934 if(pi != null) { 2935 try { 2936 // Callback via pending intent 2937 int code = (retCode >= 0) ? 1 : 0; 2938 pi.sendIntent(null, code, null, 2939 null, null); 2940 } catch (SendIntentException e1) { 2941 Slog.i(TAG, "Failed to send pending intent"); 2942 } 2943 } 2944 } 2945 }); 2946 } 2947 2948 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2949 synchronized (mInstallLock) { 2950 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2951 throw new IOException("Failed to free enough space"); 2952 } 2953 } 2954 } 2955 2956 @Override 2957 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2958 if (!sUserManager.exists(userId)) return null; 2959 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2960 synchronized (mPackages) { 2961 PackageParser.Activity a = mActivities.mActivities.get(component); 2962 2963 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2964 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2965 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2966 if (ps == null) return null; 2967 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2968 userId); 2969 } 2970 if (mResolveComponentName.equals(component)) { 2971 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2972 new PackageUserState(), userId); 2973 } 2974 } 2975 return null; 2976 } 2977 2978 @Override 2979 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2980 String resolvedType) { 2981 synchronized (mPackages) { 2982 PackageParser.Activity a = mActivities.mActivities.get(component); 2983 if (a == null) { 2984 return false; 2985 } 2986 for (int i=0; i<a.intents.size(); i++) { 2987 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2988 intent.getData(), intent.getCategories(), TAG) >= 0) { 2989 return true; 2990 } 2991 } 2992 return false; 2993 } 2994 } 2995 2996 @Override 2997 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2998 if (!sUserManager.exists(userId)) return null; 2999 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3000 synchronized (mPackages) { 3001 PackageParser.Activity a = mReceivers.mActivities.get(component); 3002 if (DEBUG_PACKAGE_INFO) Log.v( 3003 TAG, "getReceiverInfo " + component + ": " + a); 3004 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3005 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3006 if (ps == null) return null; 3007 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3008 userId); 3009 } 3010 } 3011 return null; 3012 } 3013 3014 @Override 3015 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3016 if (!sUserManager.exists(userId)) return null; 3017 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3018 synchronized (mPackages) { 3019 PackageParser.Service s = mServices.mServices.get(component); 3020 if (DEBUG_PACKAGE_INFO) Log.v( 3021 TAG, "getServiceInfo " + component + ": " + s); 3022 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3023 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3024 if (ps == null) return null; 3025 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3026 userId); 3027 } 3028 } 3029 return null; 3030 } 3031 3032 @Override 3033 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3034 if (!sUserManager.exists(userId)) return null; 3035 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3036 synchronized (mPackages) { 3037 PackageParser.Provider p = mProviders.mProviders.get(component); 3038 if (DEBUG_PACKAGE_INFO) Log.v( 3039 TAG, "getProviderInfo " + component + ": " + p); 3040 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3041 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3042 if (ps == null) return null; 3043 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3044 userId); 3045 } 3046 } 3047 return null; 3048 } 3049 3050 @Override 3051 public String[] getSystemSharedLibraryNames() { 3052 Set<String> libSet; 3053 synchronized (mPackages) { 3054 libSet = mSharedLibraries.keySet(); 3055 int size = libSet.size(); 3056 if (size > 0) { 3057 String[] libs = new String[size]; 3058 libSet.toArray(libs); 3059 return libs; 3060 } 3061 } 3062 return null; 3063 } 3064 3065 /** 3066 * @hide 3067 */ 3068 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3069 synchronized (mPackages) { 3070 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3071 if (lib != null && lib.apk != null) { 3072 return mPackages.get(lib.apk); 3073 } 3074 } 3075 return null; 3076 } 3077 3078 @Override 3079 public FeatureInfo[] getSystemAvailableFeatures() { 3080 Collection<FeatureInfo> featSet; 3081 synchronized (mPackages) { 3082 featSet = mAvailableFeatures.values(); 3083 int size = featSet.size(); 3084 if (size > 0) { 3085 FeatureInfo[] features = new FeatureInfo[size+1]; 3086 featSet.toArray(features); 3087 FeatureInfo fi = new FeatureInfo(); 3088 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3089 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3090 features[size] = fi; 3091 return features; 3092 } 3093 } 3094 return null; 3095 } 3096 3097 @Override 3098 public boolean hasSystemFeature(String name) { 3099 synchronized (mPackages) { 3100 return mAvailableFeatures.containsKey(name); 3101 } 3102 } 3103 3104 private void checkValidCaller(int uid, int userId) { 3105 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3106 return; 3107 3108 throw new SecurityException("Caller uid=" + uid 3109 + " is not privileged to communicate with user=" + userId); 3110 } 3111 3112 @Override 3113 public int checkPermission(String permName, String pkgName, int userId) { 3114 if (!sUserManager.exists(userId)) { 3115 return PackageManager.PERMISSION_DENIED; 3116 } 3117 3118 synchronized (mPackages) { 3119 final PackageParser.Package p = mPackages.get(pkgName); 3120 if (p != null && p.mExtras != null) { 3121 final PackageSetting ps = (PackageSetting) p.mExtras; 3122 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3123 return PackageManager.PERMISSION_GRANTED; 3124 } 3125 } 3126 } 3127 3128 return PackageManager.PERMISSION_DENIED; 3129 } 3130 3131 @Override 3132 public int checkUidPermission(String permName, int uid) { 3133 final int userId = UserHandle.getUserId(uid); 3134 3135 if (!sUserManager.exists(userId)) { 3136 return PackageManager.PERMISSION_DENIED; 3137 } 3138 3139 synchronized (mPackages) { 3140 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3141 if (obj != null) { 3142 final SettingBase ps = (SettingBase) obj; 3143 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3144 return PackageManager.PERMISSION_GRANTED; 3145 } 3146 } else { 3147 ArraySet<String> perms = mSystemPermissions.get(uid); 3148 if (perms != null && perms.contains(permName)) { 3149 return PackageManager.PERMISSION_GRANTED; 3150 } 3151 } 3152 } 3153 3154 return PackageManager.PERMISSION_DENIED; 3155 } 3156 3157 /** 3158 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3159 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3160 * @param checkShell TODO(yamasani): 3161 * @param message the message to log on security exception 3162 */ 3163 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3164 boolean checkShell, String message) { 3165 if (userId < 0) { 3166 throw new IllegalArgumentException("Invalid userId " + userId); 3167 } 3168 if (checkShell) { 3169 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3170 } 3171 if (userId == UserHandle.getUserId(callingUid)) return; 3172 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3173 if (requireFullPermission) { 3174 mContext.enforceCallingOrSelfPermission( 3175 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3176 } else { 3177 try { 3178 mContext.enforceCallingOrSelfPermission( 3179 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3180 } catch (SecurityException se) { 3181 mContext.enforceCallingOrSelfPermission( 3182 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3183 } 3184 } 3185 } 3186 } 3187 3188 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3189 if (callingUid == Process.SHELL_UID) { 3190 if (userHandle >= 0 3191 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3192 throw new SecurityException("Shell does not have permission to access user " 3193 + userHandle); 3194 } else if (userHandle < 0) { 3195 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3196 + Debug.getCallers(3)); 3197 } 3198 } 3199 } 3200 3201 private BasePermission findPermissionTreeLP(String permName) { 3202 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3203 if (permName.startsWith(bp.name) && 3204 permName.length() > bp.name.length() && 3205 permName.charAt(bp.name.length()) == '.') { 3206 return bp; 3207 } 3208 } 3209 return null; 3210 } 3211 3212 private BasePermission checkPermissionTreeLP(String permName) { 3213 if (permName != null) { 3214 BasePermission bp = findPermissionTreeLP(permName); 3215 if (bp != null) { 3216 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3217 return bp; 3218 } 3219 throw new SecurityException("Calling uid " 3220 + Binder.getCallingUid() 3221 + " is not allowed to add to permission tree " 3222 + bp.name + " owned by uid " + bp.uid); 3223 } 3224 } 3225 throw new SecurityException("No permission tree found for " + permName); 3226 } 3227 3228 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3229 if (s1 == null) { 3230 return s2 == null; 3231 } 3232 if (s2 == null) { 3233 return false; 3234 } 3235 if (s1.getClass() != s2.getClass()) { 3236 return false; 3237 } 3238 return s1.equals(s2); 3239 } 3240 3241 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3242 if (pi1.icon != pi2.icon) return false; 3243 if (pi1.logo != pi2.logo) return false; 3244 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3245 if (!compareStrings(pi1.name, pi2.name)) return false; 3246 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3247 // We'll take care of setting this one. 3248 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3249 // These are not currently stored in settings. 3250 //if (!compareStrings(pi1.group, pi2.group)) return false; 3251 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3252 //if (pi1.labelRes != pi2.labelRes) return false; 3253 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3254 return true; 3255 } 3256 3257 int permissionInfoFootprint(PermissionInfo info) { 3258 int size = info.name.length(); 3259 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3260 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3261 return size; 3262 } 3263 3264 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3265 int size = 0; 3266 for (BasePermission perm : mSettings.mPermissions.values()) { 3267 if (perm.uid == tree.uid) { 3268 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3269 } 3270 } 3271 return size; 3272 } 3273 3274 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3275 // We calculate the max size of permissions defined by this uid and throw 3276 // if that plus the size of 'info' would exceed our stated maximum. 3277 if (tree.uid != Process.SYSTEM_UID) { 3278 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3279 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3280 throw new SecurityException("Permission tree size cap exceeded"); 3281 } 3282 } 3283 } 3284 3285 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3286 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3287 throw new SecurityException("Label must be specified in permission"); 3288 } 3289 BasePermission tree = checkPermissionTreeLP(info.name); 3290 BasePermission bp = mSettings.mPermissions.get(info.name); 3291 boolean added = bp == null; 3292 boolean changed = true; 3293 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3294 if (added) { 3295 enforcePermissionCapLocked(info, tree); 3296 bp = new BasePermission(info.name, tree.sourcePackage, 3297 BasePermission.TYPE_DYNAMIC); 3298 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3299 throw new SecurityException( 3300 "Not allowed to modify non-dynamic permission " 3301 + info.name); 3302 } else { 3303 if (bp.protectionLevel == fixedLevel 3304 && bp.perm.owner.equals(tree.perm.owner) 3305 && bp.uid == tree.uid 3306 && comparePermissionInfos(bp.perm.info, info)) { 3307 changed = false; 3308 } 3309 } 3310 bp.protectionLevel = fixedLevel; 3311 info = new PermissionInfo(info); 3312 info.protectionLevel = fixedLevel; 3313 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3314 bp.perm.info.packageName = tree.perm.info.packageName; 3315 bp.uid = tree.uid; 3316 if (added) { 3317 mSettings.mPermissions.put(info.name, bp); 3318 } 3319 if (changed) { 3320 if (!async) { 3321 mSettings.writeLPr(); 3322 } else { 3323 scheduleWriteSettingsLocked(); 3324 } 3325 } 3326 return added; 3327 } 3328 3329 @Override 3330 public boolean addPermission(PermissionInfo info) { 3331 synchronized (mPackages) { 3332 return addPermissionLocked(info, false); 3333 } 3334 } 3335 3336 @Override 3337 public boolean addPermissionAsync(PermissionInfo info) { 3338 synchronized (mPackages) { 3339 return addPermissionLocked(info, true); 3340 } 3341 } 3342 3343 @Override 3344 public void removePermission(String name) { 3345 synchronized (mPackages) { 3346 checkPermissionTreeLP(name); 3347 BasePermission bp = mSettings.mPermissions.get(name); 3348 if (bp != null) { 3349 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3350 throw new SecurityException( 3351 "Not allowed to modify non-dynamic permission " 3352 + name); 3353 } 3354 mSettings.mPermissions.remove(name); 3355 mSettings.writeLPr(); 3356 } 3357 } 3358 } 3359 3360 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3361 BasePermission bp) { 3362 int index = pkg.requestedPermissions.indexOf(bp.name); 3363 if (index == -1) { 3364 throw new SecurityException("Package " + pkg.packageName 3365 + " has not requested permission " + bp.name); 3366 } 3367 if (!bp.isRuntime()) { 3368 throw new SecurityException("Permission " + bp.name 3369 + " is not a changeable permission type"); 3370 } 3371 } 3372 3373 @Override 3374 public void grantRuntimePermission(String packageName, String name, final int userId) { 3375 if (!sUserManager.exists(userId)) { 3376 Log.e(TAG, "No such user:" + userId); 3377 return; 3378 } 3379 3380 mContext.enforceCallingOrSelfPermission( 3381 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3382 "grantRuntimePermission"); 3383 3384 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3385 "grantRuntimePermission"); 3386 3387 final int uid; 3388 final SettingBase sb; 3389 3390 synchronized (mPackages) { 3391 final PackageParser.Package pkg = mPackages.get(packageName); 3392 if (pkg == null) { 3393 throw new IllegalArgumentException("Unknown package: " + packageName); 3394 } 3395 3396 final BasePermission bp = mSettings.mPermissions.get(name); 3397 if (bp == null) { 3398 throw new IllegalArgumentException("Unknown permission: " + name); 3399 } 3400 3401 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3402 3403 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3404 sb = (SettingBase) pkg.mExtras; 3405 if (sb == null) { 3406 throw new IllegalArgumentException("Unknown package: " + packageName); 3407 } 3408 3409 final PermissionsState permissionsState = sb.getPermissionsState(); 3410 3411 final int flags = permissionsState.getPermissionFlags(name, userId); 3412 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3413 throw new SecurityException("Cannot grant system fixed permission: " 3414 + name + " for package: " + packageName); 3415 } 3416 3417 final int result = permissionsState.grantRuntimePermission(bp, userId); 3418 switch (result) { 3419 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3420 return; 3421 } 3422 3423 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3424 mHandler.post(new Runnable() { 3425 @Override 3426 public void run() { 3427 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3428 } 3429 }); 3430 } break; 3431 } 3432 3433 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3434 3435 // Not critical if that is lost - app has to request again. 3436 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3437 } 3438 3439 if (READ_EXTERNAL_STORAGE.equals(name) 3440 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3441 final long token = Binder.clearCallingIdentity(); 3442 try { 3443 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3444 storage.remountUid(uid); 3445 } finally { 3446 Binder.restoreCallingIdentity(token); 3447 } 3448 } 3449 } 3450 3451 @Override 3452 public void revokeRuntimePermission(String packageName, String name, int userId) { 3453 if (!sUserManager.exists(userId)) { 3454 Log.e(TAG, "No such user:" + userId); 3455 return; 3456 } 3457 3458 mContext.enforceCallingOrSelfPermission( 3459 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3460 "revokeRuntimePermission"); 3461 3462 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3463 "revokeRuntimePermission"); 3464 3465 final SettingBase sb; 3466 3467 synchronized (mPackages) { 3468 final PackageParser.Package pkg = mPackages.get(packageName); 3469 if (pkg == null) { 3470 throw new IllegalArgumentException("Unknown package: " + packageName); 3471 } 3472 3473 final BasePermission bp = mSettings.mPermissions.get(name); 3474 if (bp == null) { 3475 throw new IllegalArgumentException("Unknown permission: " + name); 3476 } 3477 3478 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3479 3480 sb = (SettingBase) pkg.mExtras; 3481 if (sb == null) { 3482 throw new IllegalArgumentException("Unknown package: " + packageName); 3483 } 3484 3485 final PermissionsState permissionsState = sb.getPermissionsState(); 3486 3487 final int flags = permissionsState.getPermissionFlags(name, userId); 3488 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3489 throw new SecurityException("Cannot revoke system fixed permission: " 3490 + name + " for package: " + packageName); 3491 } 3492 3493 if (permissionsState.revokeRuntimePermission(bp, userId) == 3494 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3495 return; 3496 } 3497 3498 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3499 3500 // Critical, after this call app should never have the permission. 3501 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3502 } 3503 3504 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3505 } 3506 3507 @Override 3508 public void resetRuntimePermissions() { 3509 mContext.enforceCallingOrSelfPermission( 3510 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3511 "revokeRuntimePermission"); 3512 3513 int callingUid = Binder.getCallingUid(); 3514 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3515 mContext.enforceCallingOrSelfPermission( 3516 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3517 "resetRuntimePermissions"); 3518 } 3519 3520 final int[] userIds; 3521 3522 synchronized (mPackages) { 3523 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3524 final int userCount = UserManagerService.getInstance().getUserIds().length; 3525 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3526 } 3527 3528 for (int userId : userIds) { 3529 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3530 } 3531 } 3532 3533 @Override 3534 public int getPermissionFlags(String name, String packageName, int userId) { 3535 if (!sUserManager.exists(userId)) { 3536 return 0; 3537 } 3538 3539 mContext.enforceCallingOrSelfPermission( 3540 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3541 "getPermissionFlags"); 3542 3543 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3544 "getPermissionFlags"); 3545 3546 synchronized (mPackages) { 3547 final PackageParser.Package pkg = mPackages.get(packageName); 3548 if (pkg == null) { 3549 throw new IllegalArgumentException("Unknown package: " + packageName); 3550 } 3551 3552 final BasePermission bp = mSettings.mPermissions.get(name); 3553 if (bp == null) { 3554 throw new IllegalArgumentException("Unknown permission: " + name); 3555 } 3556 3557 SettingBase sb = (SettingBase) pkg.mExtras; 3558 if (sb == null) { 3559 throw new IllegalArgumentException("Unknown package: " + packageName); 3560 } 3561 3562 PermissionsState permissionsState = sb.getPermissionsState(); 3563 return permissionsState.getPermissionFlags(name, userId); 3564 } 3565 } 3566 3567 @Override 3568 public void updatePermissionFlags(String name, String packageName, int flagMask, 3569 int flagValues, int userId) { 3570 if (!sUserManager.exists(userId)) { 3571 return; 3572 } 3573 3574 mContext.enforceCallingOrSelfPermission( 3575 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3576 "updatePermissionFlags"); 3577 3578 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3579 "updatePermissionFlags"); 3580 3581 // Only the system can change system fixed flags. 3582 if (getCallingUid() != Process.SYSTEM_UID) { 3583 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3584 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3585 } 3586 3587 synchronized (mPackages) { 3588 final PackageParser.Package pkg = mPackages.get(packageName); 3589 if (pkg == null) { 3590 throw new IllegalArgumentException("Unknown package: " + packageName); 3591 } 3592 3593 final BasePermission bp = mSettings.mPermissions.get(name); 3594 if (bp == null) { 3595 throw new IllegalArgumentException("Unknown permission: " + name); 3596 } 3597 3598 SettingBase sb = (SettingBase) pkg.mExtras; 3599 if (sb == null) { 3600 throw new IllegalArgumentException("Unknown package: " + packageName); 3601 } 3602 3603 PermissionsState permissionsState = sb.getPermissionsState(); 3604 3605 // Only the package manager can change flags for system component permissions. 3606 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3607 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3608 return; 3609 } 3610 3611 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3612 3613 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3614 // Install and runtime permissions are stored in different places, 3615 // so figure out what permission changed and persist the change. 3616 if (permissionsState.getInstallPermissionState(name) != null) { 3617 scheduleWriteSettingsLocked(); 3618 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3619 || hadState) { 3620 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3621 } 3622 } 3623 } 3624 } 3625 3626 /** 3627 * Update the permission flags for all packages and runtime permissions of a user in order 3628 * to allow device or profile owner to remove POLICY_FIXED. 3629 */ 3630 @Override 3631 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3632 if (!sUserManager.exists(userId)) { 3633 return; 3634 } 3635 3636 mContext.enforceCallingOrSelfPermission( 3637 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3638 "updatePermissionFlagsForAllApps"); 3639 3640 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3641 "updatePermissionFlagsForAllApps"); 3642 3643 // Only the system can change system fixed flags. 3644 if (getCallingUid() != Process.SYSTEM_UID) { 3645 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3646 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3647 } 3648 3649 synchronized (mPackages) { 3650 boolean changed = false; 3651 final int packageCount = mPackages.size(); 3652 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3653 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3654 SettingBase sb = (SettingBase) pkg.mExtras; 3655 if (sb == null) { 3656 continue; 3657 } 3658 PermissionsState permissionsState = sb.getPermissionsState(); 3659 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3660 userId, flagMask, flagValues); 3661 } 3662 if (changed) { 3663 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3664 } 3665 } 3666 } 3667 3668 @Override 3669 public boolean shouldShowRequestPermissionRationale(String permissionName, 3670 String packageName, int userId) { 3671 if (UserHandle.getCallingUserId() != userId) { 3672 mContext.enforceCallingPermission( 3673 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3674 "canShowRequestPermissionRationale for user " + userId); 3675 } 3676 3677 final int uid = getPackageUid(packageName, userId); 3678 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3679 return false; 3680 } 3681 3682 if (checkPermission(permissionName, packageName, userId) 3683 == PackageManager.PERMISSION_GRANTED) { 3684 return false; 3685 } 3686 3687 final int flags; 3688 3689 final long identity = Binder.clearCallingIdentity(); 3690 try { 3691 flags = getPermissionFlags(permissionName, 3692 packageName, userId); 3693 } finally { 3694 Binder.restoreCallingIdentity(identity); 3695 } 3696 3697 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3698 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3699 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3700 3701 if ((flags & fixedFlags) != 0) { 3702 return false; 3703 } 3704 3705 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3706 } 3707 3708 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3709 BasePermission bp = mSettings.mPermissions.get(permission); 3710 if (bp == null) { 3711 throw new SecurityException("Missing " + permission + " permission"); 3712 } 3713 3714 SettingBase sb = (SettingBase) pkg.mExtras; 3715 PermissionsState permissionsState = sb.getPermissionsState(); 3716 3717 if (permissionsState.grantInstallPermission(bp) != 3718 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3719 scheduleWriteSettingsLocked(); 3720 } 3721 } 3722 3723 @Override 3724 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3725 mContext.enforceCallingOrSelfPermission( 3726 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3727 "addOnPermissionsChangeListener"); 3728 3729 synchronized (mPackages) { 3730 mOnPermissionChangeListeners.addListenerLocked(listener); 3731 } 3732 } 3733 3734 @Override 3735 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3736 synchronized (mPackages) { 3737 mOnPermissionChangeListeners.removeListenerLocked(listener); 3738 } 3739 } 3740 3741 @Override 3742 public boolean isProtectedBroadcast(String actionName) { 3743 synchronized (mPackages) { 3744 return mProtectedBroadcasts.contains(actionName); 3745 } 3746 } 3747 3748 @Override 3749 public int checkSignatures(String pkg1, String pkg2) { 3750 synchronized (mPackages) { 3751 final PackageParser.Package p1 = mPackages.get(pkg1); 3752 final PackageParser.Package p2 = mPackages.get(pkg2); 3753 if (p1 == null || p1.mExtras == null 3754 || p2 == null || p2.mExtras == null) { 3755 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3756 } 3757 return compareSignatures(p1.mSignatures, p2.mSignatures); 3758 } 3759 } 3760 3761 @Override 3762 public int checkUidSignatures(int uid1, int uid2) { 3763 // Map to base uids. 3764 uid1 = UserHandle.getAppId(uid1); 3765 uid2 = UserHandle.getAppId(uid2); 3766 // reader 3767 synchronized (mPackages) { 3768 Signature[] s1; 3769 Signature[] s2; 3770 Object obj = mSettings.getUserIdLPr(uid1); 3771 if (obj != null) { 3772 if (obj instanceof SharedUserSetting) { 3773 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3774 } else if (obj instanceof PackageSetting) { 3775 s1 = ((PackageSetting)obj).signatures.mSignatures; 3776 } else { 3777 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3778 } 3779 } else { 3780 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3781 } 3782 obj = mSettings.getUserIdLPr(uid2); 3783 if (obj != null) { 3784 if (obj instanceof SharedUserSetting) { 3785 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3786 } else if (obj instanceof PackageSetting) { 3787 s2 = ((PackageSetting)obj).signatures.mSignatures; 3788 } else { 3789 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3790 } 3791 } else { 3792 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3793 } 3794 return compareSignatures(s1, s2); 3795 } 3796 } 3797 3798 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3799 final long identity = Binder.clearCallingIdentity(); 3800 try { 3801 if (sb instanceof SharedUserSetting) { 3802 SharedUserSetting sus = (SharedUserSetting) sb; 3803 final int packageCount = sus.packages.size(); 3804 for (int i = 0; i < packageCount; i++) { 3805 PackageSetting susPs = sus.packages.valueAt(i); 3806 if (userId == UserHandle.USER_ALL) { 3807 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3808 } else { 3809 final int uid = UserHandle.getUid(userId, susPs.appId); 3810 killUid(uid, reason); 3811 } 3812 } 3813 } else if (sb instanceof PackageSetting) { 3814 PackageSetting ps = (PackageSetting) sb; 3815 if (userId == UserHandle.USER_ALL) { 3816 killApplication(ps.pkg.packageName, ps.appId, reason); 3817 } else { 3818 final int uid = UserHandle.getUid(userId, ps.appId); 3819 killUid(uid, reason); 3820 } 3821 } 3822 } finally { 3823 Binder.restoreCallingIdentity(identity); 3824 } 3825 } 3826 3827 private static void killUid(int uid, String reason) { 3828 IActivityManager am = ActivityManagerNative.getDefault(); 3829 if (am != null) { 3830 try { 3831 am.killUid(uid, reason); 3832 } catch (RemoteException e) { 3833 /* ignore - same process */ 3834 } 3835 } 3836 } 3837 3838 /** 3839 * Compares two sets of signatures. Returns: 3840 * <br /> 3841 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3842 * <br /> 3843 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3844 * <br /> 3845 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3846 * <br /> 3847 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3848 * <br /> 3849 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3850 */ 3851 static int compareSignatures(Signature[] s1, Signature[] s2) { 3852 if (s1 == null) { 3853 return s2 == null 3854 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3855 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3856 } 3857 3858 if (s2 == null) { 3859 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3860 } 3861 3862 if (s1.length != s2.length) { 3863 return PackageManager.SIGNATURE_NO_MATCH; 3864 } 3865 3866 // Since both signature sets are of size 1, we can compare without HashSets. 3867 if (s1.length == 1) { 3868 return s1[0].equals(s2[0]) ? 3869 PackageManager.SIGNATURE_MATCH : 3870 PackageManager.SIGNATURE_NO_MATCH; 3871 } 3872 3873 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3874 for (Signature sig : s1) { 3875 set1.add(sig); 3876 } 3877 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3878 for (Signature sig : s2) { 3879 set2.add(sig); 3880 } 3881 // Make sure s2 contains all signatures in s1. 3882 if (set1.equals(set2)) { 3883 return PackageManager.SIGNATURE_MATCH; 3884 } 3885 return PackageManager.SIGNATURE_NO_MATCH; 3886 } 3887 3888 /** 3889 * If the database version for this type of package (internal storage or 3890 * external storage) is less than the version where package signatures 3891 * were updated, return true. 3892 */ 3893 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3894 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3895 DatabaseVersion.SIGNATURE_END_ENTITY)) 3896 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3897 DatabaseVersion.SIGNATURE_END_ENTITY)); 3898 } 3899 3900 /** 3901 * Used for backward compatibility to make sure any packages with 3902 * certificate chains get upgraded to the new style. {@code existingSigs} 3903 * will be in the old format (since they were stored on disk from before the 3904 * system upgrade) and {@code scannedSigs} will be in the newer format. 3905 */ 3906 private int compareSignaturesCompat(PackageSignatures existingSigs, 3907 PackageParser.Package scannedPkg) { 3908 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3909 return PackageManager.SIGNATURE_NO_MATCH; 3910 } 3911 3912 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3913 for (Signature sig : existingSigs.mSignatures) { 3914 existingSet.add(sig); 3915 } 3916 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3917 for (Signature sig : scannedPkg.mSignatures) { 3918 try { 3919 Signature[] chainSignatures = sig.getChainSignatures(); 3920 for (Signature chainSig : chainSignatures) { 3921 scannedCompatSet.add(chainSig); 3922 } 3923 } catch (CertificateEncodingException e) { 3924 scannedCompatSet.add(sig); 3925 } 3926 } 3927 /* 3928 * Make sure the expanded scanned set contains all signatures in the 3929 * existing one. 3930 */ 3931 if (scannedCompatSet.equals(existingSet)) { 3932 // Migrate the old signatures to the new scheme. 3933 existingSigs.assignSignatures(scannedPkg.mSignatures); 3934 // The new KeySets will be re-added later in the scanning process. 3935 synchronized (mPackages) { 3936 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3937 } 3938 return PackageManager.SIGNATURE_MATCH; 3939 } 3940 return PackageManager.SIGNATURE_NO_MATCH; 3941 } 3942 3943 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3944 if (isExternal(scannedPkg)) { 3945 return mSettings.isExternalDatabaseVersionOlderThan( 3946 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3947 } else { 3948 return mSettings.isInternalDatabaseVersionOlderThan( 3949 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3950 } 3951 } 3952 3953 private int compareSignaturesRecover(PackageSignatures existingSigs, 3954 PackageParser.Package scannedPkg) { 3955 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3956 return PackageManager.SIGNATURE_NO_MATCH; 3957 } 3958 3959 String msg = null; 3960 try { 3961 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3962 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3963 + scannedPkg.packageName); 3964 return PackageManager.SIGNATURE_MATCH; 3965 } 3966 } catch (CertificateException e) { 3967 msg = e.getMessage(); 3968 } 3969 3970 logCriticalInfo(Log.INFO, 3971 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3972 return PackageManager.SIGNATURE_NO_MATCH; 3973 } 3974 3975 @Override 3976 public String[] getPackagesForUid(int uid) { 3977 uid = UserHandle.getAppId(uid); 3978 // reader 3979 synchronized (mPackages) { 3980 Object obj = mSettings.getUserIdLPr(uid); 3981 if (obj instanceof SharedUserSetting) { 3982 final SharedUserSetting sus = (SharedUserSetting) obj; 3983 final int N = sus.packages.size(); 3984 final String[] res = new String[N]; 3985 final Iterator<PackageSetting> it = sus.packages.iterator(); 3986 int i = 0; 3987 while (it.hasNext()) { 3988 res[i++] = it.next().name; 3989 } 3990 return res; 3991 } else if (obj instanceof PackageSetting) { 3992 final PackageSetting ps = (PackageSetting) obj; 3993 return new String[] { ps.name }; 3994 } 3995 } 3996 return null; 3997 } 3998 3999 @Override 4000 public String getNameForUid(int uid) { 4001 // reader 4002 synchronized (mPackages) { 4003 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4004 if (obj instanceof SharedUserSetting) { 4005 final SharedUserSetting sus = (SharedUserSetting) obj; 4006 return sus.name + ":" + sus.userId; 4007 } else if (obj instanceof PackageSetting) { 4008 final PackageSetting ps = (PackageSetting) obj; 4009 return ps.name; 4010 } 4011 } 4012 return null; 4013 } 4014 4015 @Override 4016 public int getUidForSharedUser(String sharedUserName) { 4017 if(sharedUserName == null) { 4018 return -1; 4019 } 4020 // reader 4021 synchronized (mPackages) { 4022 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4023 if (suid == null) { 4024 return -1; 4025 } 4026 return suid.userId; 4027 } 4028 } 4029 4030 @Override 4031 public int getFlagsForUid(int uid) { 4032 synchronized (mPackages) { 4033 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4034 if (obj instanceof SharedUserSetting) { 4035 final SharedUserSetting sus = (SharedUserSetting) obj; 4036 return sus.pkgFlags; 4037 } else if (obj instanceof PackageSetting) { 4038 final PackageSetting ps = (PackageSetting) obj; 4039 return ps.pkgFlags; 4040 } 4041 } 4042 return 0; 4043 } 4044 4045 @Override 4046 public int getPrivateFlagsForUid(int uid) { 4047 synchronized (mPackages) { 4048 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4049 if (obj instanceof SharedUserSetting) { 4050 final SharedUserSetting sus = (SharedUserSetting) obj; 4051 return sus.pkgPrivateFlags; 4052 } else if (obj instanceof PackageSetting) { 4053 final PackageSetting ps = (PackageSetting) obj; 4054 return ps.pkgPrivateFlags; 4055 } 4056 } 4057 return 0; 4058 } 4059 4060 @Override 4061 public boolean isUidPrivileged(int uid) { 4062 uid = UserHandle.getAppId(uid); 4063 // reader 4064 synchronized (mPackages) { 4065 Object obj = mSettings.getUserIdLPr(uid); 4066 if (obj instanceof SharedUserSetting) { 4067 final SharedUserSetting sus = (SharedUserSetting) obj; 4068 final Iterator<PackageSetting> it = sus.packages.iterator(); 4069 while (it.hasNext()) { 4070 if (it.next().isPrivileged()) { 4071 return true; 4072 } 4073 } 4074 } else if (obj instanceof PackageSetting) { 4075 final PackageSetting ps = (PackageSetting) obj; 4076 return ps.isPrivileged(); 4077 } 4078 } 4079 return false; 4080 } 4081 4082 @Override 4083 public String[] getAppOpPermissionPackages(String permissionName) { 4084 synchronized (mPackages) { 4085 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4086 if (pkgs == null) { 4087 return null; 4088 } 4089 return pkgs.toArray(new String[pkgs.size()]); 4090 } 4091 } 4092 4093 @Override 4094 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4095 int flags, int userId) { 4096 if (!sUserManager.exists(userId)) return null; 4097 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4098 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4099 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4100 } 4101 4102 @Override 4103 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4104 IntentFilter filter, int match, ComponentName activity) { 4105 final int userId = UserHandle.getCallingUserId(); 4106 if (DEBUG_PREFERRED) { 4107 Log.v(TAG, "setLastChosenActivity intent=" + intent 4108 + " resolvedType=" + resolvedType 4109 + " flags=" + flags 4110 + " filter=" + filter 4111 + " match=" + match 4112 + " activity=" + activity); 4113 filter.dump(new PrintStreamPrinter(System.out), " "); 4114 } 4115 intent.setComponent(null); 4116 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4117 // Find any earlier preferred or last chosen entries and nuke them 4118 findPreferredActivity(intent, resolvedType, 4119 flags, query, 0, false, true, false, userId); 4120 // Add the new activity as the last chosen for this filter 4121 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4122 "Setting last chosen"); 4123 } 4124 4125 @Override 4126 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4127 final int userId = UserHandle.getCallingUserId(); 4128 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4129 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4130 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4131 false, false, false, userId); 4132 } 4133 4134 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4135 int flags, List<ResolveInfo> query, int userId) { 4136 if (query != null) { 4137 final int N = query.size(); 4138 if (N == 1) { 4139 return query.get(0); 4140 } else if (N > 1) { 4141 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4142 // If there is more than one activity with the same priority, 4143 // then let the user decide between them. 4144 ResolveInfo r0 = query.get(0); 4145 ResolveInfo r1 = query.get(1); 4146 if (DEBUG_INTENT_MATCHING || debug) { 4147 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4148 + r1.activityInfo.name + "=" + r1.priority); 4149 } 4150 // If the first activity has a higher priority, or a different 4151 // default, then it is always desireable to pick it. 4152 if (r0.priority != r1.priority 4153 || r0.preferredOrder != r1.preferredOrder 4154 || r0.isDefault != r1.isDefault) { 4155 return query.get(0); 4156 } 4157 // If we have saved a preference for a preferred activity for 4158 // this Intent, use that. 4159 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4160 flags, query, r0.priority, true, false, debug, userId); 4161 if (ri != null) { 4162 return ri; 4163 } 4164 if (userId != 0) { 4165 ri = new ResolveInfo(mResolveInfo); 4166 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4167 ri.activityInfo.applicationInfo = new ApplicationInfo( 4168 ri.activityInfo.applicationInfo); 4169 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4170 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4171 return ri; 4172 } 4173 return mResolveInfo; 4174 } 4175 } 4176 return null; 4177 } 4178 4179 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4180 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4181 final int N = query.size(); 4182 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4183 .get(userId); 4184 // Get the list of persistent preferred activities that handle the intent 4185 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4186 List<PersistentPreferredActivity> pprefs = ppir != null 4187 ? ppir.queryIntent(intent, resolvedType, 4188 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4189 : null; 4190 if (pprefs != null && pprefs.size() > 0) { 4191 final int M = pprefs.size(); 4192 for (int i=0; i<M; i++) { 4193 final PersistentPreferredActivity ppa = pprefs.get(i); 4194 if (DEBUG_PREFERRED || debug) { 4195 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4196 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4197 + "\n component=" + ppa.mComponent); 4198 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4199 } 4200 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4201 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4202 if (DEBUG_PREFERRED || debug) { 4203 Slog.v(TAG, "Found persistent preferred activity:"); 4204 if (ai != null) { 4205 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4206 } else { 4207 Slog.v(TAG, " null"); 4208 } 4209 } 4210 if (ai == null) { 4211 // This previously registered persistent preferred activity 4212 // component is no longer known. Ignore it and do NOT remove it. 4213 continue; 4214 } 4215 for (int j=0; j<N; j++) { 4216 final ResolveInfo ri = query.get(j); 4217 if (!ri.activityInfo.applicationInfo.packageName 4218 .equals(ai.applicationInfo.packageName)) { 4219 continue; 4220 } 4221 if (!ri.activityInfo.name.equals(ai.name)) { 4222 continue; 4223 } 4224 // Found a persistent preference that can handle the intent. 4225 if (DEBUG_PREFERRED || debug) { 4226 Slog.v(TAG, "Returning persistent preferred activity: " + 4227 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4228 } 4229 return ri; 4230 } 4231 } 4232 } 4233 return null; 4234 } 4235 4236 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4237 List<ResolveInfo> query, int priority, boolean always, 4238 boolean removeMatches, boolean debug, int userId) { 4239 if (!sUserManager.exists(userId)) return null; 4240 // writer 4241 synchronized (mPackages) { 4242 if (intent.getSelector() != null) { 4243 intent = intent.getSelector(); 4244 } 4245 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4246 4247 // Try to find a matching persistent preferred activity. 4248 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4249 debug, userId); 4250 4251 // If a persistent preferred activity matched, use it. 4252 if (pri != null) { 4253 return pri; 4254 } 4255 4256 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4257 // Get the list of preferred activities that handle the intent 4258 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4259 List<PreferredActivity> prefs = pir != null 4260 ? pir.queryIntent(intent, resolvedType, 4261 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4262 : null; 4263 if (prefs != null && prefs.size() > 0) { 4264 boolean changed = false; 4265 try { 4266 // First figure out how good the original match set is. 4267 // We will only allow preferred activities that came 4268 // from the same match quality. 4269 int match = 0; 4270 4271 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4272 4273 final int N = query.size(); 4274 for (int j=0; j<N; j++) { 4275 final ResolveInfo ri = query.get(j); 4276 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4277 + ": 0x" + Integer.toHexString(match)); 4278 if (ri.match > match) { 4279 match = ri.match; 4280 } 4281 } 4282 4283 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4284 + Integer.toHexString(match)); 4285 4286 match &= IntentFilter.MATCH_CATEGORY_MASK; 4287 final int M = prefs.size(); 4288 for (int i=0; i<M; i++) { 4289 final PreferredActivity pa = prefs.get(i); 4290 if (DEBUG_PREFERRED || debug) { 4291 Slog.v(TAG, "Checking PreferredActivity ds=" 4292 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4293 + "\n component=" + pa.mPref.mComponent); 4294 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4295 } 4296 if (pa.mPref.mMatch != match) { 4297 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4298 + Integer.toHexString(pa.mPref.mMatch)); 4299 continue; 4300 } 4301 // If it's not an "always" type preferred activity and that's what we're 4302 // looking for, skip it. 4303 if (always && !pa.mPref.mAlways) { 4304 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4305 continue; 4306 } 4307 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4308 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4309 if (DEBUG_PREFERRED || debug) { 4310 Slog.v(TAG, "Found preferred activity:"); 4311 if (ai != null) { 4312 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4313 } else { 4314 Slog.v(TAG, " null"); 4315 } 4316 } 4317 if (ai == null) { 4318 // This previously registered preferred activity 4319 // component is no longer known. Most likely an update 4320 // to the app was installed and in the new version this 4321 // component no longer exists. Clean it up by removing 4322 // it from the preferred activities list, and skip it. 4323 Slog.w(TAG, "Removing dangling preferred activity: " 4324 + pa.mPref.mComponent); 4325 pir.removeFilter(pa); 4326 changed = true; 4327 continue; 4328 } 4329 for (int j=0; j<N; j++) { 4330 final ResolveInfo ri = query.get(j); 4331 if (!ri.activityInfo.applicationInfo.packageName 4332 .equals(ai.applicationInfo.packageName)) { 4333 continue; 4334 } 4335 if (!ri.activityInfo.name.equals(ai.name)) { 4336 continue; 4337 } 4338 4339 if (removeMatches) { 4340 pir.removeFilter(pa); 4341 changed = true; 4342 if (DEBUG_PREFERRED) { 4343 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4344 } 4345 break; 4346 } 4347 4348 // Okay we found a previously set preferred or last chosen app. 4349 // If the result set is different from when this 4350 // was created, we need to clear it and re-ask the 4351 // user their preference, if we're looking for an "always" type entry. 4352 if (always && !pa.mPref.sameSet(query)) { 4353 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4354 + intent + " type " + resolvedType); 4355 if (DEBUG_PREFERRED) { 4356 Slog.v(TAG, "Removing preferred activity since set changed " 4357 + pa.mPref.mComponent); 4358 } 4359 pir.removeFilter(pa); 4360 // Re-add the filter as a "last chosen" entry (!always) 4361 PreferredActivity lastChosen = new PreferredActivity( 4362 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4363 pir.addFilter(lastChosen); 4364 changed = true; 4365 return null; 4366 } 4367 4368 // Yay! Either the set matched or we're looking for the last chosen 4369 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4370 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4371 return ri; 4372 } 4373 } 4374 } finally { 4375 if (changed) { 4376 if (DEBUG_PREFERRED) { 4377 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4378 } 4379 scheduleWritePackageRestrictionsLocked(userId); 4380 } 4381 } 4382 } 4383 } 4384 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4385 return null; 4386 } 4387 4388 /* 4389 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4390 */ 4391 @Override 4392 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4393 int targetUserId) { 4394 mContext.enforceCallingOrSelfPermission( 4395 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4396 List<CrossProfileIntentFilter> matches = 4397 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4398 if (matches != null) { 4399 int size = matches.size(); 4400 for (int i = 0; i < size; i++) { 4401 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4402 } 4403 } 4404 if (hasWebURI(intent)) { 4405 // cross-profile app linking works only towards the parent. 4406 final UserInfo parent = getProfileParent(sourceUserId); 4407 synchronized(mPackages) { 4408 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4409 parent.id) != null; 4410 } 4411 } 4412 return false; 4413 } 4414 4415 private UserInfo getProfileParent(int userId) { 4416 final long identity = Binder.clearCallingIdentity(); 4417 try { 4418 return sUserManager.getProfileParent(userId); 4419 } finally { 4420 Binder.restoreCallingIdentity(identity); 4421 } 4422 } 4423 4424 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4425 String resolvedType, int userId) { 4426 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4427 if (resolver != null) { 4428 return resolver.queryIntent(intent, resolvedType, false, userId); 4429 } 4430 return null; 4431 } 4432 4433 @Override 4434 public List<ResolveInfo> queryIntentActivities(Intent intent, 4435 String resolvedType, int flags, int userId) { 4436 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4437 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4438 ComponentName comp = intent.getComponent(); 4439 if (comp == null) { 4440 if (intent.getSelector() != null) { 4441 intent = intent.getSelector(); 4442 comp = intent.getComponent(); 4443 } 4444 } 4445 4446 if (comp != null) { 4447 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4448 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4449 if (ai != null) { 4450 final ResolveInfo ri = new ResolveInfo(); 4451 ri.activityInfo = ai; 4452 list.add(ri); 4453 } 4454 return list; 4455 } 4456 4457 // reader 4458 synchronized (mPackages) { 4459 final String pkgName = intent.getPackage(); 4460 if (pkgName == null) { 4461 List<CrossProfileIntentFilter> matchingFilters = 4462 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4463 // Check for results that need to skip the current profile. 4464 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4465 resolvedType, flags, userId); 4466 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4467 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4468 result.add(xpResolveInfo); 4469 return filterIfNotPrimaryUser(result, userId); 4470 } 4471 4472 // Check for results in the current profile. 4473 List<ResolveInfo> result = mActivities.queryIntent( 4474 intent, resolvedType, flags, userId); 4475 4476 // Check for cross profile results. 4477 xpResolveInfo = queryCrossProfileIntents( 4478 matchingFilters, intent, resolvedType, flags, userId); 4479 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4480 result.add(xpResolveInfo); 4481 Collections.sort(result, mResolvePrioritySorter); 4482 } 4483 result = filterIfNotPrimaryUser(result, userId); 4484 if (hasWebURI(intent)) { 4485 CrossProfileDomainInfo xpDomainInfo = null; 4486 final UserInfo parent = getProfileParent(userId); 4487 if (parent != null) { 4488 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4489 flags, userId, parent.id); 4490 } 4491 if (xpDomainInfo != null) { 4492 if (xpResolveInfo != null) { 4493 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4494 // in the result. 4495 result.remove(xpResolveInfo); 4496 } 4497 if (result.size() == 0) { 4498 result.add(xpDomainInfo.resolveInfo); 4499 return result; 4500 } 4501 } else if (result.size() <= 1) { 4502 return result; 4503 } 4504 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4505 xpDomainInfo); 4506 Collections.sort(result, mResolvePrioritySorter); 4507 } 4508 return result; 4509 } 4510 final PackageParser.Package pkg = mPackages.get(pkgName); 4511 if (pkg != null) { 4512 return filterIfNotPrimaryUser( 4513 mActivities.queryIntentForPackage( 4514 intent, resolvedType, flags, pkg.activities, userId), 4515 userId); 4516 } 4517 return new ArrayList<ResolveInfo>(); 4518 } 4519 } 4520 4521 private static class CrossProfileDomainInfo { 4522 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4523 ResolveInfo resolveInfo; 4524 /* Best domain verification status of the activities found in the other profile */ 4525 int bestDomainVerificationStatus; 4526 } 4527 4528 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4529 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4530 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4531 sourceUserId)) { 4532 return null; 4533 } 4534 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4535 resolvedType, flags, parentUserId); 4536 4537 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4538 return null; 4539 } 4540 CrossProfileDomainInfo result = null; 4541 int size = resultTargetUser.size(); 4542 for (int i = 0; i < size; i++) { 4543 ResolveInfo riTargetUser = resultTargetUser.get(i); 4544 // Intent filter verification is only for filters that specify a host. So don't return 4545 // those that handle all web uris. 4546 if (riTargetUser.handleAllWebDataURI) { 4547 continue; 4548 } 4549 String packageName = riTargetUser.activityInfo.packageName; 4550 PackageSetting ps = mSettings.mPackages.get(packageName); 4551 if (ps == null) { 4552 continue; 4553 } 4554 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4555 if (result == null) { 4556 result = new CrossProfileDomainInfo(); 4557 result.resolveInfo = 4558 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4559 result.bestDomainVerificationStatus = status; 4560 } else { 4561 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4562 result.bestDomainVerificationStatus); 4563 } 4564 } 4565 return result; 4566 } 4567 4568 /** 4569 * Verification statuses are ordered from the worse to the best, except for 4570 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4571 */ 4572 private int bestDomainVerificationStatus(int status1, int status2) { 4573 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4574 return status2; 4575 } 4576 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4577 return status1; 4578 } 4579 return (int) MathUtils.max(status1, status2); 4580 } 4581 4582 private boolean isUserEnabled(int userId) { 4583 long callingId = Binder.clearCallingIdentity(); 4584 try { 4585 UserInfo userInfo = sUserManager.getUserInfo(userId); 4586 return userInfo != null && userInfo.isEnabled(); 4587 } finally { 4588 Binder.restoreCallingIdentity(callingId); 4589 } 4590 } 4591 4592 /** 4593 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4594 * 4595 * @return filtered list 4596 */ 4597 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4598 if (userId == UserHandle.USER_OWNER) { 4599 return resolveInfos; 4600 } 4601 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4602 ResolveInfo info = resolveInfos.get(i); 4603 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4604 resolveInfos.remove(i); 4605 } 4606 } 4607 return resolveInfos; 4608 } 4609 4610 private static boolean hasWebURI(Intent intent) { 4611 if (intent.getData() == null) { 4612 return false; 4613 } 4614 final String scheme = intent.getScheme(); 4615 if (TextUtils.isEmpty(scheme)) { 4616 return false; 4617 } 4618 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4619 } 4620 4621 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4622 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4623 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4624 Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " + 4625 candidates.size()); 4626 } 4627 4628 final int userId = UserHandle.getCallingUserId(); 4629 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4630 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4631 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4632 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4633 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4634 4635 synchronized (mPackages) { 4636 final int count = candidates.size(); 4637 // First, try to use linked apps. Partition the candidates into four lists: 4638 // one for the final results, one for the "do not use ever", one for "undefined status" 4639 // and finally one for "browser app type". 4640 for (int n=0; n<count; n++) { 4641 ResolveInfo info = candidates.get(n); 4642 String packageName = info.activityInfo.packageName; 4643 PackageSetting ps = mSettings.mPackages.get(packageName); 4644 if (ps != null) { 4645 // Add to the special match all list (Browser use case) 4646 if (info.handleAllWebDataURI) { 4647 matchAllList.add(info); 4648 continue; 4649 } 4650 // Try to get the status from User settings first 4651 int status = getDomainVerificationStatusLPr(ps, userId); 4652 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4653 if (DEBUG_DOMAIN_VERIFICATION) { 4654 Slog.i(TAG, " + always: " + info.activityInfo.packageName); 4655 } 4656 alwaysList.add(info); 4657 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4658 if (DEBUG_DOMAIN_VERIFICATION) { 4659 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4660 } 4661 neverList.add(info); 4662 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4663 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4664 if (DEBUG_DOMAIN_VERIFICATION) { 4665 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4666 } 4667 undefinedList.add(info); 4668 } 4669 } 4670 } 4671 // First try to add the "always" resolution for the current user if there is any 4672 if (alwaysList.size() > 0) { 4673 result.addAll(alwaysList); 4674 // if there is an "always" for the parent user, add it. 4675 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4676 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4677 result.add(xpDomainInfo.resolveInfo); 4678 } else { 4679 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4680 result.addAll(undefinedList); 4681 if (xpDomainInfo != null && ( 4682 xpDomainInfo.bestDomainVerificationStatus 4683 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4684 || xpDomainInfo.bestDomainVerificationStatus 4685 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4686 result.add(xpDomainInfo.resolveInfo); 4687 } 4688 // Also add Browsers (all of them or only the default one) 4689 if ((flags & MATCH_ALL) != 0) { 4690 result.addAll(matchAllList); 4691 } else { 4692 // Try to add the Default Browser if we can 4693 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4694 UserHandle.myUserId()); 4695 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4696 boolean defaultBrowserFound = false; 4697 final int browserCount = matchAllList.size(); 4698 for (int n=0; n<browserCount; n++) { 4699 ResolveInfo browser = matchAllList.get(n); 4700 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4701 result.add(browser); 4702 defaultBrowserFound = true; 4703 break; 4704 } 4705 } 4706 if (!defaultBrowserFound) { 4707 result.addAll(matchAllList); 4708 } 4709 } else { 4710 result.addAll(matchAllList); 4711 } 4712 } 4713 4714 // If there is nothing selected, add all candidates and remove the ones that the user 4715 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4716 if (result.size() == 0) { 4717 result.addAll(candidates); 4718 result.removeAll(neverList); 4719 } 4720 } 4721 } 4722 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4723 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4724 result.size()); 4725 for (ResolveInfo info : result) { 4726 Slog.v(TAG, " + " + info.activityInfo); 4727 } 4728 } 4729 return result; 4730 } 4731 4732 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4733 int status = ps.getDomainVerificationStatusForUser(userId); 4734 // if none available, get the master status 4735 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4736 if (ps.getIntentFilterVerificationInfo() != null) { 4737 status = ps.getIntentFilterVerificationInfo().getStatus(); 4738 } 4739 } 4740 return status; 4741 } 4742 4743 private ResolveInfo querySkipCurrentProfileIntents( 4744 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4745 int flags, int sourceUserId) { 4746 if (matchingFilters != null) { 4747 int size = matchingFilters.size(); 4748 for (int i = 0; i < size; i ++) { 4749 CrossProfileIntentFilter filter = matchingFilters.get(i); 4750 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4751 // Checking if there are activities in the target user that can handle the 4752 // intent. 4753 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4754 flags, sourceUserId); 4755 if (resolveInfo != null) { 4756 return resolveInfo; 4757 } 4758 } 4759 } 4760 } 4761 return null; 4762 } 4763 4764 // Return matching ResolveInfo if any for skip current profile intent filters. 4765 private ResolveInfo queryCrossProfileIntents( 4766 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4767 int flags, int sourceUserId) { 4768 if (matchingFilters != null) { 4769 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4770 // match the same intent. For performance reasons, it is better not to 4771 // run queryIntent twice for the same userId 4772 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4773 int size = matchingFilters.size(); 4774 for (int i = 0; i < size; i++) { 4775 CrossProfileIntentFilter filter = matchingFilters.get(i); 4776 int targetUserId = filter.getTargetUserId(); 4777 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4778 && !alreadyTriedUserIds.get(targetUserId)) { 4779 // Checking if there are activities in the target user that can handle the 4780 // intent. 4781 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4782 flags, sourceUserId); 4783 if (resolveInfo != null) return resolveInfo; 4784 alreadyTriedUserIds.put(targetUserId, true); 4785 } 4786 } 4787 } 4788 return null; 4789 } 4790 4791 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4792 String resolvedType, int flags, int sourceUserId) { 4793 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4794 resolvedType, flags, filter.getTargetUserId()); 4795 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4796 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4797 } 4798 return null; 4799 } 4800 4801 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4802 int sourceUserId, int targetUserId) { 4803 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4804 String className; 4805 if (targetUserId == UserHandle.USER_OWNER) { 4806 className = FORWARD_INTENT_TO_USER_OWNER; 4807 } else { 4808 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4809 } 4810 ComponentName forwardingActivityComponentName = new ComponentName( 4811 mAndroidApplication.packageName, className); 4812 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4813 sourceUserId); 4814 if (targetUserId == UserHandle.USER_OWNER) { 4815 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4816 forwardingResolveInfo.noResourceId = true; 4817 } 4818 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4819 forwardingResolveInfo.priority = 0; 4820 forwardingResolveInfo.preferredOrder = 0; 4821 forwardingResolveInfo.match = 0; 4822 forwardingResolveInfo.isDefault = true; 4823 forwardingResolveInfo.filter = filter; 4824 forwardingResolveInfo.targetUserId = targetUserId; 4825 return forwardingResolveInfo; 4826 } 4827 4828 @Override 4829 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4830 Intent[] specifics, String[] specificTypes, Intent intent, 4831 String resolvedType, int flags, int userId) { 4832 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4833 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4834 false, "query intent activity options"); 4835 final String resultsAction = intent.getAction(); 4836 4837 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4838 | PackageManager.GET_RESOLVED_FILTER, userId); 4839 4840 if (DEBUG_INTENT_MATCHING) { 4841 Log.v(TAG, "Query " + intent + ": " + results); 4842 } 4843 4844 int specificsPos = 0; 4845 int N; 4846 4847 // todo: note that the algorithm used here is O(N^2). This 4848 // isn't a problem in our current environment, but if we start running 4849 // into situations where we have more than 5 or 10 matches then this 4850 // should probably be changed to something smarter... 4851 4852 // First we go through and resolve each of the specific items 4853 // that were supplied, taking care of removing any corresponding 4854 // duplicate items in the generic resolve list. 4855 if (specifics != null) { 4856 for (int i=0; i<specifics.length; i++) { 4857 final Intent sintent = specifics[i]; 4858 if (sintent == null) { 4859 continue; 4860 } 4861 4862 if (DEBUG_INTENT_MATCHING) { 4863 Log.v(TAG, "Specific #" + i + ": " + sintent); 4864 } 4865 4866 String action = sintent.getAction(); 4867 if (resultsAction != null && resultsAction.equals(action)) { 4868 // If this action was explicitly requested, then don't 4869 // remove things that have it. 4870 action = null; 4871 } 4872 4873 ResolveInfo ri = null; 4874 ActivityInfo ai = null; 4875 4876 ComponentName comp = sintent.getComponent(); 4877 if (comp == null) { 4878 ri = resolveIntent( 4879 sintent, 4880 specificTypes != null ? specificTypes[i] : null, 4881 flags, userId); 4882 if (ri == null) { 4883 continue; 4884 } 4885 if (ri == mResolveInfo) { 4886 // ACK! Must do something better with this. 4887 } 4888 ai = ri.activityInfo; 4889 comp = new ComponentName(ai.applicationInfo.packageName, 4890 ai.name); 4891 } else { 4892 ai = getActivityInfo(comp, flags, userId); 4893 if (ai == null) { 4894 continue; 4895 } 4896 } 4897 4898 // Look for any generic query activities that are duplicates 4899 // of this specific one, and remove them from the results. 4900 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4901 N = results.size(); 4902 int j; 4903 for (j=specificsPos; j<N; j++) { 4904 ResolveInfo sri = results.get(j); 4905 if ((sri.activityInfo.name.equals(comp.getClassName()) 4906 && sri.activityInfo.applicationInfo.packageName.equals( 4907 comp.getPackageName())) 4908 || (action != null && sri.filter.matchAction(action))) { 4909 results.remove(j); 4910 if (DEBUG_INTENT_MATCHING) Log.v( 4911 TAG, "Removing duplicate item from " + j 4912 + " due to specific " + specificsPos); 4913 if (ri == null) { 4914 ri = sri; 4915 } 4916 j--; 4917 N--; 4918 } 4919 } 4920 4921 // Add this specific item to its proper place. 4922 if (ri == null) { 4923 ri = new ResolveInfo(); 4924 ri.activityInfo = ai; 4925 } 4926 results.add(specificsPos, ri); 4927 ri.specificIndex = i; 4928 specificsPos++; 4929 } 4930 } 4931 4932 // Now we go through the remaining generic results and remove any 4933 // duplicate actions that are found here. 4934 N = results.size(); 4935 for (int i=specificsPos; i<N-1; i++) { 4936 final ResolveInfo rii = results.get(i); 4937 if (rii.filter == null) { 4938 continue; 4939 } 4940 4941 // Iterate over all of the actions of this result's intent 4942 // filter... typically this should be just one. 4943 final Iterator<String> it = rii.filter.actionsIterator(); 4944 if (it == null) { 4945 continue; 4946 } 4947 while (it.hasNext()) { 4948 final String action = it.next(); 4949 if (resultsAction != null && resultsAction.equals(action)) { 4950 // If this action was explicitly requested, then don't 4951 // remove things that have it. 4952 continue; 4953 } 4954 for (int j=i+1; j<N; j++) { 4955 final ResolveInfo rij = results.get(j); 4956 if (rij.filter != null && rij.filter.hasAction(action)) { 4957 results.remove(j); 4958 if (DEBUG_INTENT_MATCHING) Log.v( 4959 TAG, "Removing duplicate item from " + j 4960 + " due to action " + action + " at " + i); 4961 j--; 4962 N--; 4963 } 4964 } 4965 } 4966 4967 // If the caller didn't request filter information, drop it now 4968 // so we don't have to marshall/unmarshall it. 4969 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4970 rii.filter = null; 4971 } 4972 } 4973 4974 // Filter out the caller activity if so requested. 4975 if (caller != null) { 4976 N = results.size(); 4977 for (int i=0; i<N; i++) { 4978 ActivityInfo ainfo = results.get(i).activityInfo; 4979 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4980 && caller.getClassName().equals(ainfo.name)) { 4981 results.remove(i); 4982 break; 4983 } 4984 } 4985 } 4986 4987 // If the caller didn't request filter information, 4988 // drop them now so we don't have to 4989 // marshall/unmarshall it. 4990 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4991 N = results.size(); 4992 for (int i=0; i<N; i++) { 4993 results.get(i).filter = null; 4994 } 4995 } 4996 4997 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4998 return results; 4999 } 5000 5001 @Override 5002 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5003 int userId) { 5004 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5005 ComponentName comp = intent.getComponent(); 5006 if (comp == null) { 5007 if (intent.getSelector() != null) { 5008 intent = intent.getSelector(); 5009 comp = intent.getComponent(); 5010 } 5011 } 5012 if (comp != null) { 5013 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5014 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5015 if (ai != null) { 5016 ResolveInfo ri = new ResolveInfo(); 5017 ri.activityInfo = ai; 5018 list.add(ri); 5019 } 5020 return list; 5021 } 5022 5023 // reader 5024 synchronized (mPackages) { 5025 String pkgName = intent.getPackage(); 5026 if (pkgName == null) { 5027 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5028 } 5029 final PackageParser.Package pkg = mPackages.get(pkgName); 5030 if (pkg != null) { 5031 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5032 userId); 5033 } 5034 return null; 5035 } 5036 } 5037 5038 @Override 5039 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5040 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5041 if (!sUserManager.exists(userId)) return null; 5042 if (query != null) { 5043 if (query.size() >= 1) { 5044 // If there is more than one service with the same priority, 5045 // just arbitrarily pick the first one. 5046 return query.get(0); 5047 } 5048 } 5049 return null; 5050 } 5051 5052 @Override 5053 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5054 int userId) { 5055 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5056 ComponentName comp = intent.getComponent(); 5057 if (comp == null) { 5058 if (intent.getSelector() != null) { 5059 intent = intent.getSelector(); 5060 comp = intent.getComponent(); 5061 } 5062 } 5063 if (comp != null) { 5064 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5065 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5066 if (si != null) { 5067 final ResolveInfo ri = new ResolveInfo(); 5068 ri.serviceInfo = si; 5069 list.add(ri); 5070 } 5071 return list; 5072 } 5073 5074 // reader 5075 synchronized (mPackages) { 5076 String pkgName = intent.getPackage(); 5077 if (pkgName == null) { 5078 return mServices.queryIntent(intent, resolvedType, flags, userId); 5079 } 5080 final PackageParser.Package pkg = mPackages.get(pkgName); 5081 if (pkg != null) { 5082 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5083 userId); 5084 } 5085 return null; 5086 } 5087 } 5088 5089 @Override 5090 public List<ResolveInfo> queryIntentContentProviders( 5091 Intent intent, String resolvedType, int flags, int userId) { 5092 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5093 ComponentName comp = intent.getComponent(); 5094 if (comp == null) { 5095 if (intent.getSelector() != null) { 5096 intent = intent.getSelector(); 5097 comp = intent.getComponent(); 5098 } 5099 } 5100 if (comp != null) { 5101 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5102 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5103 if (pi != null) { 5104 final ResolveInfo ri = new ResolveInfo(); 5105 ri.providerInfo = pi; 5106 list.add(ri); 5107 } 5108 return list; 5109 } 5110 5111 // reader 5112 synchronized (mPackages) { 5113 String pkgName = intent.getPackage(); 5114 if (pkgName == null) { 5115 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5116 } 5117 final PackageParser.Package pkg = mPackages.get(pkgName); 5118 if (pkg != null) { 5119 return mProviders.queryIntentForPackage( 5120 intent, resolvedType, flags, pkg.providers, userId); 5121 } 5122 return null; 5123 } 5124 } 5125 5126 @Override 5127 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5128 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5129 5130 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5131 5132 // writer 5133 synchronized (mPackages) { 5134 ArrayList<PackageInfo> list; 5135 if (listUninstalled) { 5136 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5137 for (PackageSetting ps : mSettings.mPackages.values()) { 5138 PackageInfo pi; 5139 if (ps.pkg != null) { 5140 pi = generatePackageInfo(ps.pkg, flags, userId); 5141 } else { 5142 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5143 } 5144 if (pi != null) { 5145 list.add(pi); 5146 } 5147 } 5148 } else { 5149 list = new ArrayList<PackageInfo>(mPackages.size()); 5150 for (PackageParser.Package p : mPackages.values()) { 5151 PackageInfo pi = generatePackageInfo(p, flags, userId); 5152 if (pi != null) { 5153 list.add(pi); 5154 } 5155 } 5156 } 5157 5158 return new ParceledListSlice<PackageInfo>(list); 5159 } 5160 } 5161 5162 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5163 String[] permissions, boolean[] tmp, int flags, int userId) { 5164 int numMatch = 0; 5165 final PermissionsState permissionsState = ps.getPermissionsState(); 5166 for (int i=0; i<permissions.length; i++) { 5167 final String permission = permissions[i]; 5168 if (permissionsState.hasPermission(permission, userId)) { 5169 tmp[i] = true; 5170 numMatch++; 5171 } else { 5172 tmp[i] = false; 5173 } 5174 } 5175 if (numMatch == 0) { 5176 return; 5177 } 5178 PackageInfo pi; 5179 if (ps.pkg != null) { 5180 pi = generatePackageInfo(ps.pkg, flags, userId); 5181 } else { 5182 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5183 } 5184 // The above might return null in cases of uninstalled apps or install-state 5185 // skew across users/profiles. 5186 if (pi != null) { 5187 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5188 if (numMatch == permissions.length) { 5189 pi.requestedPermissions = permissions; 5190 } else { 5191 pi.requestedPermissions = new String[numMatch]; 5192 numMatch = 0; 5193 for (int i=0; i<permissions.length; i++) { 5194 if (tmp[i]) { 5195 pi.requestedPermissions[numMatch] = permissions[i]; 5196 numMatch++; 5197 } 5198 } 5199 } 5200 } 5201 list.add(pi); 5202 } 5203 } 5204 5205 @Override 5206 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5207 String[] permissions, int flags, int userId) { 5208 if (!sUserManager.exists(userId)) return null; 5209 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5210 5211 // writer 5212 synchronized (mPackages) { 5213 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5214 boolean[] tmpBools = new boolean[permissions.length]; 5215 if (listUninstalled) { 5216 for (PackageSetting ps : mSettings.mPackages.values()) { 5217 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5218 } 5219 } else { 5220 for (PackageParser.Package pkg : mPackages.values()) { 5221 PackageSetting ps = (PackageSetting)pkg.mExtras; 5222 if (ps != null) { 5223 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5224 userId); 5225 } 5226 } 5227 } 5228 5229 return new ParceledListSlice<PackageInfo>(list); 5230 } 5231 } 5232 5233 @Override 5234 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5235 if (!sUserManager.exists(userId)) return null; 5236 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5237 5238 // writer 5239 synchronized (mPackages) { 5240 ArrayList<ApplicationInfo> list; 5241 if (listUninstalled) { 5242 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5243 for (PackageSetting ps : mSettings.mPackages.values()) { 5244 ApplicationInfo ai; 5245 if (ps.pkg != null) { 5246 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5247 ps.readUserState(userId), userId); 5248 } else { 5249 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5250 } 5251 if (ai != null) { 5252 list.add(ai); 5253 } 5254 } 5255 } else { 5256 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5257 for (PackageParser.Package p : mPackages.values()) { 5258 if (p.mExtras != null) { 5259 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5260 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5261 if (ai != null) { 5262 list.add(ai); 5263 } 5264 } 5265 } 5266 } 5267 5268 return new ParceledListSlice<ApplicationInfo>(list); 5269 } 5270 } 5271 5272 public List<ApplicationInfo> getPersistentApplications(int flags) { 5273 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5274 5275 // reader 5276 synchronized (mPackages) { 5277 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5278 final int userId = UserHandle.getCallingUserId(); 5279 while (i.hasNext()) { 5280 final PackageParser.Package p = i.next(); 5281 if (p.applicationInfo != null 5282 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5283 && (!mSafeMode || isSystemApp(p))) { 5284 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5285 if (ps != null) { 5286 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5287 ps.readUserState(userId), userId); 5288 if (ai != null) { 5289 finalList.add(ai); 5290 } 5291 } 5292 } 5293 } 5294 } 5295 5296 return finalList; 5297 } 5298 5299 @Override 5300 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5301 if (!sUserManager.exists(userId)) return null; 5302 // reader 5303 synchronized (mPackages) { 5304 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5305 PackageSetting ps = provider != null 5306 ? mSettings.mPackages.get(provider.owner.packageName) 5307 : null; 5308 return ps != null 5309 && mSettings.isEnabledLPr(provider.info, flags, userId) 5310 && (!mSafeMode || (provider.info.applicationInfo.flags 5311 &ApplicationInfo.FLAG_SYSTEM) != 0) 5312 ? PackageParser.generateProviderInfo(provider, flags, 5313 ps.readUserState(userId), userId) 5314 : null; 5315 } 5316 } 5317 5318 /** 5319 * @deprecated 5320 */ 5321 @Deprecated 5322 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5323 // reader 5324 synchronized (mPackages) { 5325 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5326 .entrySet().iterator(); 5327 final int userId = UserHandle.getCallingUserId(); 5328 while (i.hasNext()) { 5329 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5330 PackageParser.Provider p = entry.getValue(); 5331 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5332 5333 if (ps != null && p.syncable 5334 && (!mSafeMode || (p.info.applicationInfo.flags 5335 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5336 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5337 ps.readUserState(userId), userId); 5338 if (info != null) { 5339 outNames.add(entry.getKey()); 5340 outInfo.add(info); 5341 } 5342 } 5343 } 5344 } 5345 } 5346 5347 @Override 5348 public List<ProviderInfo> queryContentProviders(String processName, 5349 int uid, int flags) { 5350 ArrayList<ProviderInfo> finalList = null; 5351 // reader 5352 synchronized (mPackages) { 5353 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5354 final int userId = processName != null ? 5355 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5356 while (i.hasNext()) { 5357 final PackageParser.Provider p = i.next(); 5358 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5359 if (ps != null && p.info.authority != null 5360 && (processName == null 5361 || (p.info.processName.equals(processName) 5362 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5363 && mSettings.isEnabledLPr(p.info, flags, userId) 5364 && (!mSafeMode 5365 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5366 if (finalList == null) { 5367 finalList = new ArrayList<ProviderInfo>(3); 5368 } 5369 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5370 ps.readUserState(userId), userId); 5371 if (info != null) { 5372 finalList.add(info); 5373 } 5374 } 5375 } 5376 } 5377 5378 if (finalList != null) { 5379 Collections.sort(finalList, mProviderInitOrderSorter); 5380 } 5381 5382 return finalList; 5383 } 5384 5385 @Override 5386 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5387 int flags) { 5388 // reader 5389 synchronized (mPackages) { 5390 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5391 return PackageParser.generateInstrumentationInfo(i, flags); 5392 } 5393 } 5394 5395 @Override 5396 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5397 int flags) { 5398 ArrayList<InstrumentationInfo> finalList = 5399 new ArrayList<InstrumentationInfo>(); 5400 5401 // reader 5402 synchronized (mPackages) { 5403 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5404 while (i.hasNext()) { 5405 final PackageParser.Instrumentation p = i.next(); 5406 if (targetPackage == null 5407 || targetPackage.equals(p.info.targetPackage)) { 5408 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5409 flags); 5410 if (ii != null) { 5411 finalList.add(ii); 5412 } 5413 } 5414 } 5415 } 5416 5417 return finalList; 5418 } 5419 5420 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5421 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5422 if (overlays == null) { 5423 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5424 return; 5425 } 5426 for (PackageParser.Package opkg : overlays.values()) { 5427 // Not much to do if idmap fails: we already logged the error 5428 // and we certainly don't want to abort installation of pkg simply 5429 // because an overlay didn't fit properly. For these reasons, 5430 // ignore the return value of createIdmapForPackagePairLI. 5431 createIdmapForPackagePairLI(pkg, opkg); 5432 } 5433 } 5434 5435 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5436 PackageParser.Package opkg) { 5437 if (!opkg.mTrustedOverlay) { 5438 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5439 opkg.baseCodePath + ": overlay not trusted"); 5440 return false; 5441 } 5442 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5443 if (overlaySet == null) { 5444 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5445 opkg.baseCodePath + " but target package has no known overlays"); 5446 return false; 5447 } 5448 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5449 // TODO: generate idmap for split APKs 5450 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5451 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5452 + opkg.baseCodePath); 5453 return false; 5454 } 5455 PackageParser.Package[] overlayArray = 5456 overlaySet.values().toArray(new PackageParser.Package[0]); 5457 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5458 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5459 return p1.mOverlayPriority - p2.mOverlayPriority; 5460 } 5461 }; 5462 Arrays.sort(overlayArray, cmp); 5463 5464 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5465 int i = 0; 5466 for (PackageParser.Package p : overlayArray) { 5467 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5468 } 5469 return true; 5470 } 5471 5472 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5473 final File[] files = dir.listFiles(); 5474 if (ArrayUtils.isEmpty(files)) { 5475 Log.d(TAG, "No files in app dir " + dir); 5476 return; 5477 } 5478 5479 if (DEBUG_PACKAGE_SCANNING) { 5480 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5481 + " flags=0x" + Integer.toHexString(parseFlags)); 5482 } 5483 5484 for (File file : files) { 5485 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5486 && !PackageInstallerService.isStageName(file.getName()); 5487 if (!isPackage) { 5488 // Ignore entries which are not packages 5489 continue; 5490 } 5491 try { 5492 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5493 scanFlags, currentTime, null); 5494 } catch (PackageManagerException e) { 5495 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5496 5497 // Delete invalid userdata apps 5498 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5499 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5500 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5501 if (file.isDirectory()) { 5502 mInstaller.rmPackageDir(file.getAbsolutePath()); 5503 } else { 5504 file.delete(); 5505 } 5506 } 5507 } 5508 } 5509 } 5510 5511 private static File getSettingsProblemFile() { 5512 File dataDir = Environment.getDataDirectory(); 5513 File systemDir = new File(dataDir, "system"); 5514 File fname = new File(systemDir, "uiderrors.txt"); 5515 return fname; 5516 } 5517 5518 static void reportSettingsProblem(int priority, String msg) { 5519 logCriticalInfo(priority, msg); 5520 } 5521 5522 static void logCriticalInfo(int priority, String msg) { 5523 Slog.println(priority, TAG, msg); 5524 EventLogTags.writePmCriticalInfo(msg); 5525 try { 5526 File fname = getSettingsProblemFile(); 5527 FileOutputStream out = new FileOutputStream(fname, true); 5528 PrintWriter pw = new FastPrintWriter(out); 5529 SimpleDateFormat formatter = new SimpleDateFormat(); 5530 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5531 pw.println(dateString + ": " + msg); 5532 pw.close(); 5533 FileUtils.setPermissions( 5534 fname.toString(), 5535 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5536 -1, -1); 5537 } catch (java.io.IOException e) { 5538 } 5539 } 5540 5541 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5542 PackageParser.Package pkg, File srcFile, int parseFlags) 5543 throws PackageManagerException { 5544 if (ps != null 5545 && ps.codePath.equals(srcFile) 5546 && ps.timeStamp == srcFile.lastModified() 5547 && !isCompatSignatureUpdateNeeded(pkg) 5548 && !isRecoverSignatureUpdateNeeded(pkg)) { 5549 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5550 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5551 ArraySet<PublicKey> signingKs; 5552 synchronized (mPackages) { 5553 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5554 } 5555 if (ps.signatures.mSignatures != null 5556 && ps.signatures.mSignatures.length != 0 5557 && signingKs != null) { 5558 // Optimization: reuse the existing cached certificates 5559 // if the package appears to be unchanged. 5560 pkg.mSignatures = ps.signatures.mSignatures; 5561 pkg.mSigningKeys = signingKs; 5562 return; 5563 } 5564 5565 Slog.w(TAG, "PackageSetting for " + ps.name 5566 + " is missing signatures. Collecting certs again to recover them."); 5567 } else { 5568 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5569 } 5570 5571 try { 5572 pp.collectCertificates(pkg, parseFlags); 5573 pp.collectManifestDigest(pkg); 5574 } catch (PackageParserException e) { 5575 throw PackageManagerException.from(e); 5576 } 5577 } 5578 5579 /* 5580 * Scan a package and return the newly parsed package. 5581 * Returns null in case of errors and the error code is stored in mLastScanError 5582 */ 5583 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5584 long currentTime, UserHandle user) throws PackageManagerException { 5585 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5586 parseFlags |= mDefParseFlags; 5587 PackageParser pp = new PackageParser(); 5588 pp.setSeparateProcesses(mSeparateProcesses); 5589 pp.setOnlyCoreApps(mOnlyCore); 5590 pp.setDisplayMetrics(mMetrics); 5591 5592 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5593 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5594 } 5595 5596 final PackageParser.Package pkg; 5597 try { 5598 pkg = pp.parsePackage(scanFile, parseFlags); 5599 } catch (PackageParserException e) { 5600 throw PackageManagerException.from(e); 5601 } 5602 5603 PackageSetting ps = null; 5604 PackageSetting updatedPkg; 5605 // reader 5606 synchronized (mPackages) { 5607 // Look to see if we already know about this package. 5608 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5609 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5610 // This package has been renamed to its original name. Let's 5611 // use that. 5612 ps = mSettings.peekPackageLPr(oldName); 5613 } 5614 // If there was no original package, see one for the real package name. 5615 if (ps == null) { 5616 ps = mSettings.peekPackageLPr(pkg.packageName); 5617 } 5618 // Check to see if this package could be hiding/updating a system 5619 // package. Must look for it either under the original or real 5620 // package name depending on our state. 5621 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5622 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5623 } 5624 boolean updatedPkgBetter = false; 5625 // First check if this is a system package that may involve an update 5626 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5627 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5628 // it needs to drop FLAG_PRIVILEGED. 5629 if (locationIsPrivileged(scanFile)) { 5630 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5631 } else { 5632 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5633 } 5634 5635 if (ps != null && !ps.codePath.equals(scanFile)) { 5636 // The path has changed from what was last scanned... check the 5637 // version of the new path against what we have stored to determine 5638 // what to do. 5639 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5640 if (pkg.mVersionCode <= ps.versionCode) { 5641 // The system package has been updated and the code path does not match 5642 // Ignore entry. Skip it. 5643 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5644 + " ignored: updated version " + ps.versionCode 5645 + " better than this " + pkg.mVersionCode); 5646 if (!updatedPkg.codePath.equals(scanFile)) { 5647 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5648 + ps.name + " changing from " + updatedPkg.codePathString 5649 + " to " + scanFile); 5650 updatedPkg.codePath = scanFile; 5651 updatedPkg.codePathString = scanFile.toString(); 5652 updatedPkg.resourcePath = scanFile; 5653 updatedPkg.resourcePathString = scanFile.toString(); 5654 } 5655 updatedPkg.pkg = pkg; 5656 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5657 "Package " + ps.name + " at " + scanFile 5658 + " ignored: updated version " + ps.versionCode 5659 + " better than this " + pkg.mVersionCode); 5660 } else { 5661 // The current app on the system partition is better than 5662 // what we have updated to on the data partition; switch 5663 // back to the system partition version. 5664 // At this point, its safely assumed that package installation for 5665 // apps in system partition will go through. If not there won't be a working 5666 // version of the app 5667 // writer 5668 synchronized (mPackages) { 5669 // Just remove the loaded entries from package lists. 5670 mPackages.remove(ps.name); 5671 } 5672 5673 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5674 + " reverting from " + ps.codePathString 5675 + ": new version " + pkg.mVersionCode 5676 + " better than installed " + ps.versionCode); 5677 5678 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5679 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5680 synchronized (mInstallLock) { 5681 args.cleanUpResourcesLI(); 5682 } 5683 synchronized (mPackages) { 5684 mSettings.enableSystemPackageLPw(ps.name); 5685 } 5686 updatedPkgBetter = true; 5687 } 5688 } 5689 } 5690 5691 if (updatedPkg != null) { 5692 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5693 // initially 5694 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5695 5696 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5697 // flag set initially 5698 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5699 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5700 } 5701 } 5702 5703 // Verify certificates against what was last scanned 5704 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5705 5706 /* 5707 * A new system app appeared, but we already had a non-system one of the 5708 * same name installed earlier. 5709 */ 5710 boolean shouldHideSystemApp = false; 5711 if (updatedPkg == null && ps != null 5712 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5713 /* 5714 * Check to make sure the signatures match first. If they don't, 5715 * wipe the installed application and its data. 5716 */ 5717 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5718 != PackageManager.SIGNATURE_MATCH) { 5719 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5720 + " signatures don't match existing userdata copy; removing"); 5721 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5722 ps = null; 5723 } else { 5724 /* 5725 * If the newly-added system app is an older version than the 5726 * already installed version, hide it. It will be scanned later 5727 * and re-added like an update. 5728 */ 5729 if (pkg.mVersionCode <= ps.versionCode) { 5730 shouldHideSystemApp = true; 5731 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5732 + " but new version " + pkg.mVersionCode + " better than installed " 5733 + ps.versionCode + "; hiding system"); 5734 } else { 5735 /* 5736 * The newly found system app is a newer version that the 5737 * one previously installed. Simply remove the 5738 * already-installed application and replace it with our own 5739 * while keeping the application data. 5740 */ 5741 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5742 + " reverting from " + ps.codePathString + ": new version " 5743 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5744 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5745 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5746 synchronized (mInstallLock) { 5747 args.cleanUpResourcesLI(); 5748 } 5749 } 5750 } 5751 } 5752 5753 // The apk is forward locked (not public) if its code and resources 5754 // are kept in different files. (except for app in either system or 5755 // vendor path). 5756 // TODO grab this value from PackageSettings 5757 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5758 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5759 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5760 } 5761 } 5762 5763 // TODO: extend to support forward-locked splits 5764 String resourcePath = null; 5765 String baseResourcePath = null; 5766 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5767 if (ps != null && ps.resourcePathString != null) { 5768 resourcePath = ps.resourcePathString; 5769 baseResourcePath = ps.resourcePathString; 5770 } else { 5771 // Should not happen at all. Just log an error. 5772 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5773 } 5774 } else { 5775 resourcePath = pkg.codePath; 5776 baseResourcePath = pkg.baseCodePath; 5777 } 5778 5779 // Set application objects path explicitly. 5780 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5781 pkg.applicationInfo.setCodePath(pkg.codePath); 5782 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5783 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5784 pkg.applicationInfo.setResourcePath(resourcePath); 5785 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5786 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5787 5788 // Note that we invoke the following method only if we are about to unpack an application 5789 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5790 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5791 5792 /* 5793 * If the system app should be overridden by a previously installed 5794 * data, hide the system app now and let the /data/app scan pick it up 5795 * again. 5796 */ 5797 if (shouldHideSystemApp) { 5798 synchronized (mPackages) { 5799 /* 5800 * We have to grant systems permissions before we hide, because 5801 * grantPermissions will assume the package update is trying to 5802 * expand its permissions. 5803 */ 5804 grantPermissionsLPw(pkg, true, pkg.packageName); 5805 mSettings.disableSystemPackageLPw(pkg.packageName); 5806 } 5807 } 5808 5809 return scannedPkg; 5810 } 5811 5812 private static String fixProcessName(String defProcessName, 5813 String processName, int uid) { 5814 if (processName == null) { 5815 return defProcessName; 5816 } 5817 return processName; 5818 } 5819 5820 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5821 throws PackageManagerException { 5822 if (pkgSetting.signatures.mSignatures != null) { 5823 // Already existing package. Make sure signatures match 5824 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5825 == PackageManager.SIGNATURE_MATCH; 5826 if (!match) { 5827 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5828 == PackageManager.SIGNATURE_MATCH; 5829 } 5830 if (!match) { 5831 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5832 == PackageManager.SIGNATURE_MATCH; 5833 } 5834 if (!match) { 5835 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5836 + pkg.packageName + " signatures do not match the " 5837 + "previously installed version; ignoring!"); 5838 } 5839 } 5840 5841 // Check for shared user signatures 5842 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5843 // Already existing package. Make sure signatures match 5844 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5845 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5846 if (!match) { 5847 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5848 == PackageManager.SIGNATURE_MATCH; 5849 } 5850 if (!match) { 5851 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5852 == PackageManager.SIGNATURE_MATCH; 5853 } 5854 if (!match) { 5855 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5856 "Package " + pkg.packageName 5857 + " has no signatures that match those in shared user " 5858 + pkgSetting.sharedUser.name + "; ignoring!"); 5859 } 5860 } 5861 } 5862 5863 /** 5864 * Enforces that only the system UID or root's UID can call a method exposed 5865 * via Binder. 5866 * 5867 * @param message used as message if SecurityException is thrown 5868 * @throws SecurityException if the caller is not system or root 5869 */ 5870 private static final void enforceSystemOrRoot(String message) { 5871 final int uid = Binder.getCallingUid(); 5872 if (uid != Process.SYSTEM_UID && uid != 0) { 5873 throw new SecurityException(message); 5874 } 5875 } 5876 5877 @Override 5878 public void performBootDexOpt() { 5879 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5880 5881 // Before everything else, see whether we need to fstrim. 5882 try { 5883 IMountService ms = PackageHelper.getMountService(); 5884 if (ms != null) { 5885 final boolean isUpgrade = isUpgrade(); 5886 boolean doTrim = isUpgrade; 5887 if (doTrim) { 5888 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5889 } else { 5890 final long interval = android.provider.Settings.Global.getLong( 5891 mContext.getContentResolver(), 5892 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5893 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5894 if (interval > 0) { 5895 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5896 if (timeSinceLast > interval) { 5897 doTrim = true; 5898 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5899 + "; running immediately"); 5900 } 5901 } 5902 } 5903 if (doTrim) { 5904 if (!isFirstBoot()) { 5905 try { 5906 ActivityManagerNative.getDefault().showBootMessage( 5907 mContext.getResources().getString( 5908 R.string.android_upgrading_fstrim), true); 5909 } catch (RemoteException e) { 5910 } 5911 } 5912 ms.runMaintenance(); 5913 } 5914 } else { 5915 Slog.e(TAG, "Mount service unavailable!"); 5916 } 5917 } catch (RemoteException e) { 5918 // Can't happen; MountService is local 5919 } 5920 5921 final ArraySet<PackageParser.Package> pkgs; 5922 synchronized (mPackages) { 5923 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5924 } 5925 5926 if (pkgs != null) { 5927 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5928 // in case the device runs out of space. 5929 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5930 // Give priority to core apps. 5931 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5932 PackageParser.Package pkg = it.next(); 5933 if (pkg.coreApp) { 5934 if (DEBUG_DEXOPT) { 5935 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5936 } 5937 sortedPkgs.add(pkg); 5938 it.remove(); 5939 } 5940 } 5941 // Give priority to system apps that listen for pre boot complete. 5942 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5943 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5944 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5945 PackageParser.Package pkg = it.next(); 5946 if (pkgNames.contains(pkg.packageName)) { 5947 if (DEBUG_DEXOPT) { 5948 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5949 } 5950 sortedPkgs.add(pkg); 5951 it.remove(); 5952 } 5953 } 5954 // Give priority to system apps. 5955 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5956 PackageParser.Package pkg = it.next(); 5957 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5958 if (DEBUG_DEXOPT) { 5959 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5960 } 5961 sortedPkgs.add(pkg); 5962 it.remove(); 5963 } 5964 } 5965 // Give priority to updated system apps. 5966 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5967 PackageParser.Package pkg = it.next(); 5968 if (pkg.isUpdatedSystemApp()) { 5969 if (DEBUG_DEXOPT) { 5970 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5971 } 5972 sortedPkgs.add(pkg); 5973 it.remove(); 5974 } 5975 } 5976 // Give priority to apps that listen for boot complete. 5977 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5978 pkgNames = getPackageNamesForIntent(intent); 5979 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5980 PackageParser.Package pkg = it.next(); 5981 if (pkgNames.contains(pkg.packageName)) { 5982 if (DEBUG_DEXOPT) { 5983 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5984 } 5985 sortedPkgs.add(pkg); 5986 it.remove(); 5987 } 5988 } 5989 // Filter out packages that aren't recently used. 5990 filterRecentlyUsedApps(pkgs); 5991 // Add all remaining apps. 5992 for (PackageParser.Package pkg : pkgs) { 5993 if (DEBUG_DEXOPT) { 5994 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5995 } 5996 sortedPkgs.add(pkg); 5997 } 5998 5999 // If we want to be lazy, filter everything that wasn't recently used. 6000 if (mLazyDexOpt) { 6001 filterRecentlyUsedApps(sortedPkgs); 6002 } 6003 6004 int i = 0; 6005 int total = sortedPkgs.size(); 6006 File dataDir = Environment.getDataDirectory(); 6007 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6008 if (lowThreshold == 0) { 6009 throw new IllegalStateException("Invalid low memory threshold"); 6010 } 6011 for (PackageParser.Package pkg : sortedPkgs) { 6012 long usableSpace = dataDir.getUsableSpace(); 6013 if (usableSpace < lowThreshold) { 6014 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6015 break; 6016 } 6017 performBootDexOpt(pkg, ++i, total); 6018 } 6019 } 6020 } 6021 6022 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6023 // Filter out packages that aren't recently used. 6024 // 6025 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6026 // should do a full dexopt. 6027 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6028 int total = pkgs.size(); 6029 int skipped = 0; 6030 long now = System.currentTimeMillis(); 6031 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6032 PackageParser.Package pkg = i.next(); 6033 long then = pkg.mLastPackageUsageTimeInMills; 6034 if (then + mDexOptLRUThresholdInMills < now) { 6035 if (DEBUG_DEXOPT) { 6036 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6037 ((then == 0) ? "never" : new Date(then))); 6038 } 6039 i.remove(); 6040 skipped++; 6041 } 6042 } 6043 if (DEBUG_DEXOPT) { 6044 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6045 } 6046 } 6047 } 6048 6049 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6050 List<ResolveInfo> ris = null; 6051 try { 6052 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6053 intent, null, 0, UserHandle.USER_OWNER); 6054 } catch (RemoteException e) { 6055 } 6056 ArraySet<String> pkgNames = new ArraySet<String>(); 6057 if (ris != null) { 6058 for (ResolveInfo ri : ris) { 6059 pkgNames.add(ri.activityInfo.packageName); 6060 } 6061 } 6062 return pkgNames; 6063 } 6064 6065 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6066 if (DEBUG_DEXOPT) { 6067 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6068 } 6069 if (!isFirstBoot()) { 6070 try { 6071 ActivityManagerNative.getDefault().showBootMessage( 6072 mContext.getResources().getString(R.string.android_upgrading_apk, 6073 curr, total), true); 6074 } catch (RemoteException e) { 6075 } 6076 } 6077 PackageParser.Package p = pkg; 6078 synchronized (mInstallLock) { 6079 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6080 false /* force dex */, false /* defer */, true /* include dependencies */); 6081 } 6082 } 6083 6084 @Override 6085 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6086 return performDexOpt(packageName, instructionSet, false); 6087 } 6088 6089 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6090 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6091 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6092 if (!dexopt && !updateUsage) { 6093 // We aren't going to dexopt or update usage, so bail early. 6094 return false; 6095 } 6096 PackageParser.Package p; 6097 final String targetInstructionSet; 6098 synchronized (mPackages) { 6099 p = mPackages.get(packageName); 6100 if (p == null) { 6101 return false; 6102 } 6103 if (updateUsage) { 6104 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6105 } 6106 mPackageUsage.write(false); 6107 if (!dexopt) { 6108 // We aren't going to dexopt, so bail early. 6109 return false; 6110 } 6111 6112 targetInstructionSet = instructionSet != null ? instructionSet : 6113 getPrimaryInstructionSet(p.applicationInfo); 6114 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6115 return false; 6116 } 6117 } 6118 6119 synchronized (mInstallLock) { 6120 final String[] instructionSets = new String[] { targetInstructionSet }; 6121 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6122 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6123 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6124 } 6125 } 6126 6127 public ArraySet<String> getPackagesThatNeedDexOpt() { 6128 ArraySet<String> pkgs = null; 6129 synchronized (mPackages) { 6130 for (PackageParser.Package p : mPackages.values()) { 6131 if (DEBUG_DEXOPT) { 6132 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6133 } 6134 if (!p.mDexOptPerformed.isEmpty()) { 6135 continue; 6136 } 6137 if (pkgs == null) { 6138 pkgs = new ArraySet<String>(); 6139 } 6140 pkgs.add(p.packageName); 6141 } 6142 } 6143 return pkgs; 6144 } 6145 6146 public void shutdown() { 6147 mPackageUsage.write(true); 6148 } 6149 6150 @Override 6151 public void forceDexOpt(String packageName) { 6152 enforceSystemOrRoot("forceDexOpt"); 6153 6154 PackageParser.Package pkg; 6155 synchronized (mPackages) { 6156 pkg = mPackages.get(packageName); 6157 if (pkg == null) { 6158 throw new IllegalArgumentException("Missing package: " + packageName); 6159 } 6160 } 6161 6162 synchronized (mInstallLock) { 6163 final String[] instructionSets = new String[] { 6164 getPrimaryInstructionSet(pkg.applicationInfo) }; 6165 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6166 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6167 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6168 throw new IllegalStateException("Failed to dexopt: " + res); 6169 } 6170 } 6171 } 6172 6173 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6174 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6175 Slog.w(TAG, "Unable to update from " + oldPkg.name 6176 + " to " + newPkg.packageName 6177 + ": old package not in system partition"); 6178 return false; 6179 } else if (mPackages.get(oldPkg.name) != null) { 6180 Slog.w(TAG, "Unable to update from " + oldPkg.name 6181 + " to " + newPkg.packageName 6182 + ": old package still exists"); 6183 return false; 6184 } 6185 return true; 6186 } 6187 6188 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6189 int[] users = sUserManager.getUserIds(); 6190 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6191 if (res < 0) { 6192 return res; 6193 } 6194 for (int user : users) { 6195 if (user != 0) { 6196 res = mInstaller.createUserData(volumeUuid, packageName, 6197 UserHandle.getUid(user, uid), user, seinfo); 6198 if (res < 0) { 6199 return res; 6200 } 6201 } 6202 } 6203 return res; 6204 } 6205 6206 private int removeDataDirsLI(String volumeUuid, String packageName) { 6207 int[] users = sUserManager.getUserIds(); 6208 int res = 0; 6209 for (int user : users) { 6210 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6211 if (resInner < 0) { 6212 res = resInner; 6213 } 6214 } 6215 6216 return res; 6217 } 6218 6219 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6220 int[] users = sUserManager.getUserIds(); 6221 int res = 0; 6222 for (int user : users) { 6223 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6224 if (resInner < 0) { 6225 res = resInner; 6226 } 6227 } 6228 return res; 6229 } 6230 6231 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6232 PackageParser.Package changingLib) { 6233 if (file.path != null) { 6234 usesLibraryFiles.add(file.path); 6235 return; 6236 } 6237 PackageParser.Package p = mPackages.get(file.apk); 6238 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6239 // If we are doing this while in the middle of updating a library apk, 6240 // then we need to make sure to use that new apk for determining the 6241 // dependencies here. (We haven't yet finished committing the new apk 6242 // to the package manager state.) 6243 if (p == null || p.packageName.equals(changingLib.packageName)) { 6244 p = changingLib; 6245 } 6246 } 6247 if (p != null) { 6248 usesLibraryFiles.addAll(p.getAllCodePaths()); 6249 } 6250 } 6251 6252 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6253 PackageParser.Package changingLib) throws PackageManagerException { 6254 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6255 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6256 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6257 for (int i=0; i<N; i++) { 6258 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6259 if (file == null) { 6260 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6261 "Package " + pkg.packageName + " requires unavailable shared library " 6262 + pkg.usesLibraries.get(i) + "; failing!"); 6263 } 6264 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6265 } 6266 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6267 for (int i=0; i<N; i++) { 6268 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6269 if (file == null) { 6270 Slog.w(TAG, "Package " + pkg.packageName 6271 + " desires unavailable shared library " 6272 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6273 } else { 6274 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6275 } 6276 } 6277 N = usesLibraryFiles.size(); 6278 if (N > 0) { 6279 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6280 } else { 6281 pkg.usesLibraryFiles = null; 6282 } 6283 } 6284 } 6285 6286 private static boolean hasString(List<String> list, List<String> which) { 6287 if (list == null) { 6288 return false; 6289 } 6290 for (int i=list.size()-1; i>=0; i--) { 6291 for (int j=which.size()-1; j>=0; j--) { 6292 if (which.get(j).equals(list.get(i))) { 6293 return true; 6294 } 6295 } 6296 } 6297 return false; 6298 } 6299 6300 private void updateAllSharedLibrariesLPw() { 6301 for (PackageParser.Package pkg : mPackages.values()) { 6302 try { 6303 updateSharedLibrariesLPw(pkg, null); 6304 } catch (PackageManagerException e) { 6305 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6306 } 6307 } 6308 } 6309 6310 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6311 PackageParser.Package changingPkg) { 6312 ArrayList<PackageParser.Package> res = null; 6313 for (PackageParser.Package pkg : mPackages.values()) { 6314 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6315 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6316 if (res == null) { 6317 res = new ArrayList<PackageParser.Package>(); 6318 } 6319 res.add(pkg); 6320 try { 6321 updateSharedLibrariesLPw(pkg, changingPkg); 6322 } catch (PackageManagerException e) { 6323 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6324 } 6325 } 6326 } 6327 return res; 6328 } 6329 6330 /** 6331 * Derive the value of the {@code cpuAbiOverride} based on the provided 6332 * value and an optional stored value from the package settings. 6333 */ 6334 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6335 String cpuAbiOverride = null; 6336 6337 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6338 cpuAbiOverride = null; 6339 } else if (abiOverride != null) { 6340 cpuAbiOverride = abiOverride; 6341 } else if (settings != null) { 6342 cpuAbiOverride = settings.cpuAbiOverrideString; 6343 } 6344 6345 return cpuAbiOverride; 6346 } 6347 6348 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6349 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6350 boolean success = false; 6351 try { 6352 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6353 currentTime, user); 6354 success = true; 6355 return res; 6356 } finally { 6357 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6358 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6359 } 6360 } 6361 } 6362 6363 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6364 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6365 final File scanFile = new File(pkg.codePath); 6366 if (pkg.applicationInfo.getCodePath() == null || 6367 pkg.applicationInfo.getResourcePath() == null) { 6368 // Bail out. The resource and code paths haven't been set. 6369 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6370 "Code and resource paths haven't been set correctly"); 6371 } 6372 6373 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6374 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6375 } else { 6376 // Only allow system apps to be flagged as core apps. 6377 pkg.coreApp = false; 6378 } 6379 6380 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6381 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6382 } 6383 6384 if (mCustomResolverComponentName != null && 6385 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6386 setUpCustomResolverActivity(pkg); 6387 } 6388 6389 if (pkg.packageName.equals("android")) { 6390 synchronized (mPackages) { 6391 if (mAndroidApplication != null) { 6392 Slog.w(TAG, "*************************************************"); 6393 Slog.w(TAG, "Core android package being redefined. Skipping."); 6394 Slog.w(TAG, " file=" + scanFile); 6395 Slog.w(TAG, "*************************************************"); 6396 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6397 "Core android package being redefined. Skipping."); 6398 } 6399 6400 // Set up information for our fall-back user intent resolution activity. 6401 mPlatformPackage = pkg; 6402 pkg.mVersionCode = mSdkVersion; 6403 mAndroidApplication = pkg.applicationInfo; 6404 6405 if (!mResolverReplaced) { 6406 mResolveActivity.applicationInfo = mAndroidApplication; 6407 mResolveActivity.name = ResolverActivity.class.getName(); 6408 mResolveActivity.packageName = mAndroidApplication.packageName; 6409 mResolveActivity.processName = "system:ui"; 6410 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6411 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6412 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6413 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6414 mResolveActivity.exported = true; 6415 mResolveActivity.enabled = true; 6416 mResolveInfo.activityInfo = mResolveActivity; 6417 mResolveInfo.priority = 0; 6418 mResolveInfo.preferredOrder = 0; 6419 mResolveInfo.match = 0; 6420 mResolveComponentName = new ComponentName( 6421 mAndroidApplication.packageName, mResolveActivity.name); 6422 } 6423 } 6424 } 6425 6426 if (DEBUG_PACKAGE_SCANNING) { 6427 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6428 Log.d(TAG, "Scanning package " + pkg.packageName); 6429 } 6430 6431 if (mPackages.containsKey(pkg.packageName) 6432 || mSharedLibraries.containsKey(pkg.packageName)) { 6433 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6434 "Application package " + pkg.packageName 6435 + " already installed. Skipping duplicate."); 6436 } 6437 6438 // If we're only installing presumed-existing packages, require that the 6439 // scanned APK is both already known and at the path previously established 6440 // for it. Previously unknown packages we pick up normally, but if we have an 6441 // a priori expectation about this package's install presence, enforce it. 6442 // With a singular exception for new system packages. When an OTA contains 6443 // a new system package, we allow the codepath to change from a system location 6444 // to the user-installed location. If we don't allow this change, any newer, 6445 // user-installed version of the application will be ignored. 6446 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6447 if (mExpectingBetter.containsKey(pkg.packageName)) { 6448 logCriticalInfo(Log.WARN, 6449 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6450 } else { 6451 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6452 if (known != null) { 6453 if (DEBUG_PACKAGE_SCANNING) { 6454 Log.d(TAG, "Examining " + pkg.codePath 6455 + " and requiring known paths " + known.codePathString 6456 + " & " + known.resourcePathString); 6457 } 6458 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6459 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6460 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6461 "Application package " + pkg.packageName 6462 + " found at " + pkg.applicationInfo.getCodePath() 6463 + " but expected at " + known.codePathString + "; ignoring."); 6464 } 6465 } 6466 } 6467 } 6468 6469 // Initialize package source and resource directories 6470 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6471 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6472 6473 SharedUserSetting suid = null; 6474 PackageSetting pkgSetting = null; 6475 6476 if (!isSystemApp(pkg)) { 6477 // Only system apps can use these features. 6478 pkg.mOriginalPackages = null; 6479 pkg.mRealPackage = null; 6480 pkg.mAdoptPermissions = null; 6481 } 6482 6483 // writer 6484 synchronized (mPackages) { 6485 if (pkg.mSharedUserId != null) { 6486 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6487 if (suid == null) { 6488 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6489 "Creating application package " + pkg.packageName 6490 + " for shared user failed"); 6491 } 6492 if (DEBUG_PACKAGE_SCANNING) { 6493 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6494 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6495 + "): packages=" + suid.packages); 6496 } 6497 } 6498 6499 // Check if we are renaming from an original package name. 6500 PackageSetting origPackage = null; 6501 String realName = null; 6502 if (pkg.mOriginalPackages != null) { 6503 // This package may need to be renamed to a previously 6504 // installed name. Let's check on that... 6505 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6506 if (pkg.mOriginalPackages.contains(renamed)) { 6507 // This package had originally been installed as the 6508 // original name, and we have already taken care of 6509 // transitioning to the new one. Just update the new 6510 // one to continue using the old name. 6511 realName = pkg.mRealPackage; 6512 if (!pkg.packageName.equals(renamed)) { 6513 // Callers into this function may have already taken 6514 // care of renaming the package; only do it here if 6515 // it is not already done. 6516 pkg.setPackageName(renamed); 6517 } 6518 6519 } else { 6520 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6521 if ((origPackage = mSettings.peekPackageLPr( 6522 pkg.mOriginalPackages.get(i))) != null) { 6523 // We do have the package already installed under its 6524 // original name... should we use it? 6525 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6526 // New package is not compatible with original. 6527 origPackage = null; 6528 continue; 6529 } else if (origPackage.sharedUser != null) { 6530 // Make sure uid is compatible between packages. 6531 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6532 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6533 + " to " + pkg.packageName + ": old uid " 6534 + origPackage.sharedUser.name 6535 + " differs from " + pkg.mSharedUserId); 6536 origPackage = null; 6537 continue; 6538 } 6539 } else { 6540 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6541 + pkg.packageName + " to old name " + origPackage.name); 6542 } 6543 break; 6544 } 6545 } 6546 } 6547 } 6548 6549 if (mTransferedPackages.contains(pkg.packageName)) { 6550 Slog.w(TAG, "Package " + pkg.packageName 6551 + " was transferred to another, but its .apk remains"); 6552 } 6553 6554 // Just create the setting, don't add it yet. For already existing packages 6555 // the PkgSetting exists already and doesn't have to be created. 6556 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6557 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6558 pkg.applicationInfo.primaryCpuAbi, 6559 pkg.applicationInfo.secondaryCpuAbi, 6560 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6561 user, false); 6562 if (pkgSetting == null) { 6563 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6564 "Creating application package " + pkg.packageName + " failed"); 6565 } 6566 6567 if (pkgSetting.origPackage != null) { 6568 // If we are first transitioning from an original package, 6569 // fix up the new package's name now. We need to do this after 6570 // looking up the package under its new name, so getPackageLP 6571 // can take care of fiddling things correctly. 6572 pkg.setPackageName(origPackage.name); 6573 6574 // File a report about this. 6575 String msg = "New package " + pkgSetting.realName 6576 + " renamed to replace old package " + pkgSetting.name; 6577 reportSettingsProblem(Log.WARN, msg); 6578 6579 // Make a note of it. 6580 mTransferedPackages.add(origPackage.name); 6581 6582 // No longer need to retain this. 6583 pkgSetting.origPackage = null; 6584 } 6585 6586 if (realName != null) { 6587 // Make a note of it. 6588 mTransferedPackages.add(pkg.packageName); 6589 } 6590 6591 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6592 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6593 } 6594 6595 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6596 // Check all shared libraries and map to their actual file path. 6597 // We only do this here for apps not on a system dir, because those 6598 // are the only ones that can fail an install due to this. We 6599 // will take care of the system apps by updating all of their 6600 // library paths after the scan is done. 6601 updateSharedLibrariesLPw(pkg, null); 6602 } 6603 6604 if (mFoundPolicyFile) { 6605 SELinuxMMAC.assignSeinfoValue(pkg); 6606 } 6607 6608 pkg.applicationInfo.uid = pkgSetting.appId; 6609 pkg.mExtras = pkgSetting; 6610 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6611 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6612 // We just determined the app is signed correctly, so bring 6613 // over the latest parsed certs. 6614 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6615 } else { 6616 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6617 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6618 "Package " + pkg.packageName + " upgrade keys do not match the " 6619 + "previously installed version"); 6620 } else { 6621 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6622 String msg = "System package " + pkg.packageName 6623 + " signature changed; retaining data."; 6624 reportSettingsProblem(Log.WARN, msg); 6625 } 6626 } 6627 } else { 6628 try { 6629 verifySignaturesLP(pkgSetting, pkg); 6630 // We just determined the app is signed correctly, so bring 6631 // over the latest parsed certs. 6632 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6633 } catch (PackageManagerException e) { 6634 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6635 throw e; 6636 } 6637 // The signature has changed, but this package is in the system 6638 // image... let's recover! 6639 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6640 // However... if this package is part of a shared user, but it 6641 // doesn't match the signature of the shared user, let's fail. 6642 // What this means is that you can't change the signatures 6643 // associated with an overall shared user, which doesn't seem all 6644 // that unreasonable. 6645 if (pkgSetting.sharedUser != null) { 6646 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6647 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6648 throw new PackageManagerException( 6649 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6650 "Signature mismatch for shared user : " 6651 + pkgSetting.sharedUser); 6652 } 6653 } 6654 // File a report about this. 6655 String msg = "System package " + pkg.packageName 6656 + " signature changed; retaining data."; 6657 reportSettingsProblem(Log.WARN, msg); 6658 } 6659 } 6660 // Verify that this new package doesn't have any content providers 6661 // that conflict with existing packages. Only do this if the 6662 // package isn't already installed, since we don't want to break 6663 // things that are installed. 6664 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6665 final int N = pkg.providers.size(); 6666 int i; 6667 for (i=0; i<N; i++) { 6668 PackageParser.Provider p = pkg.providers.get(i); 6669 if (p.info.authority != null) { 6670 String names[] = p.info.authority.split(";"); 6671 for (int j = 0; j < names.length; j++) { 6672 if (mProvidersByAuthority.containsKey(names[j])) { 6673 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6674 final String otherPackageName = 6675 ((other != null && other.getComponentName() != null) ? 6676 other.getComponentName().getPackageName() : "?"); 6677 throw new PackageManagerException( 6678 INSTALL_FAILED_CONFLICTING_PROVIDER, 6679 "Can't install because provider name " + names[j] 6680 + " (in package " + pkg.applicationInfo.packageName 6681 + ") is already used by " + otherPackageName); 6682 } 6683 } 6684 } 6685 } 6686 } 6687 6688 if (pkg.mAdoptPermissions != null) { 6689 // This package wants to adopt ownership of permissions from 6690 // another package. 6691 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6692 final String origName = pkg.mAdoptPermissions.get(i); 6693 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6694 if (orig != null) { 6695 if (verifyPackageUpdateLPr(orig, pkg)) { 6696 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6697 + pkg.packageName); 6698 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6699 } 6700 } 6701 } 6702 } 6703 } 6704 6705 final String pkgName = pkg.packageName; 6706 6707 final long scanFileTime = scanFile.lastModified(); 6708 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6709 pkg.applicationInfo.processName = fixProcessName( 6710 pkg.applicationInfo.packageName, 6711 pkg.applicationInfo.processName, 6712 pkg.applicationInfo.uid); 6713 6714 File dataPath; 6715 if (mPlatformPackage == pkg) { 6716 // The system package is special. 6717 dataPath = new File(Environment.getDataDirectory(), "system"); 6718 6719 pkg.applicationInfo.dataDir = dataPath.getPath(); 6720 6721 } else { 6722 // This is a normal package, need to make its data directory. 6723 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6724 UserHandle.USER_OWNER, pkg.packageName); 6725 6726 boolean uidError = false; 6727 if (dataPath.exists()) { 6728 int currentUid = 0; 6729 try { 6730 StructStat stat = Os.stat(dataPath.getPath()); 6731 currentUid = stat.st_uid; 6732 } catch (ErrnoException e) { 6733 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6734 } 6735 6736 // If we have mismatched owners for the data path, we have a problem. 6737 if (currentUid != pkg.applicationInfo.uid) { 6738 boolean recovered = false; 6739 if (currentUid == 0) { 6740 // The directory somehow became owned by root. Wow. 6741 // This is probably because the system was stopped while 6742 // installd was in the middle of messing with its libs 6743 // directory. Ask installd to fix that. 6744 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6745 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6746 if (ret >= 0) { 6747 recovered = true; 6748 String msg = "Package " + pkg.packageName 6749 + " unexpectedly changed to uid 0; recovered to " + 6750 + pkg.applicationInfo.uid; 6751 reportSettingsProblem(Log.WARN, msg); 6752 } 6753 } 6754 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6755 || (scanFlags&SCAN_BOOTING) != 0)) { 6756 // If this is a system app, we can at least delete its 6757 // current data so the application will still work. 6758 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6759 if (ret >= 0) { 6760 // TODO: Kill the processes first 6761 // Old data gone! 6762 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6763 ? "System package " : "Third party package "; 6764 String msg = prefix + pkg.packageName 6765 + " has changed from uid: " 6766 + currentUid + " to " 6767 + pkg.applicationInfo.uid + "; old data erased"; 6768 reportSettingsProblem(Log.WARN, msg); 6769 recovered = true; 6770 6771 // And now re-install the app. 6772 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6773 pkg.applicationInfo.seinfo); 6774 if (ret == -1) { 6775 // Ack should not happen! 6776 msg = prefix + pkg.packageName 6777 + " could not have data directory re-created after delete."; 6778 reportSettingsProblem(Log.WARN, msg); 6779 throw new PackageManagerException( 6780 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6781 } 6782 } 6783 if (!recovered) { 6784 mHasSystemUidErrors = true; 6785 } 6786 } else if (!recovered) { 6787 // If we allow this install to proceed, we will be broken. 6788 // Abort, abort! 6789 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6790 "scanPackageLI"); 6791 } 6792 if (!recovered) { 6793 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6794 + pkg.applicationInfo.uid + "/fs_" 6795 + currentUid; 6796 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6797 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6798 String msg = "Package " + pkg.packageName 6799 + " has mismatched uid: " 6800 + currentUid + " on disk, " 6801 + pkg.applicationInfo.uid + " in settings"; 6802 // writer 6803 synchronized (mPackages) { 6804 mSettings.mReadMessages.append(msg); 6805 mSettings.mReadMessages.append('\n'); 6806 uidError = true; 6807 if (!pkgSetting.uidError) { 6808 reportSettingsProblem(Log.ERROR, msg); 6809 } 6810 } 6811 } 6812 } 6813 pkg.applicationInfo.dataDir = dataPath.getPath(); 6814 if (mShouldRestoreconData) { 6815 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6816 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6817 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6818 } 6819 } else { 6820 if (DEBUG_PACKAGE_SCANNING) { 6821 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6822 Log.v(TAG, "Want this data dir: " + dataPath); 6823 } 6824 //invoke installer to do the actual installation 6825 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6826 pkg.applicationInfo.seinfo); 6827 if (ret < 0) { 6828 // Error from installer 6829 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6830 "Unable to create data dirs [errorCode=" + ret + "]"); 6831 } 6832 6833 if (dataPath.exists()) { 6834 pkg.applicationInfo.dataDir = dataPath.getPath(); 6835 } else { 6836 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6837 pkg.applicationInfo.dataDir = null; 6838 } 6839 } 6840 6841 pkgSetting.uidError = uidError; 6842 } 6843 6844 final String path = scanFile.getPath(); 6845 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6846 6847 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6848 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6849 6850 // Some system apps still use directory structure for native libraries 6851 // in which case we might end up not detecting abi solely based on apk 6852 // structure. Try to detect abi based on directory structure. 6853 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6854 pkg.applicationInfo.primaryCpuAbi == null) { 6855 setBundledAppAbisAndRoots(pkg, pkgSetting); 6856 setNativeLibraryPaths(pkg); 6857 } 6858 6859 } else { 6860 if ((scanFlags & SCAN_MOVE) != 0) { 6861 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6862 // but we already have this packages package info in the PackageSetting. We just 6863 // use that and derive the native library path based on the new codepath. 6864 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6865 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6866 } 6867 6868 // Set native library paths again. For moves, the path will be updated based on the 6869 // ABIs we've determined above. For non-moves, the path will be updated based on the 6870 // ABIs we determined during compilation, but the path will depend on the final 6871 // package path (after the rename away from the stage path). 6872 setNativeLibraryPaths(pkg); 6873 } 6874 6875 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6876 final int[] userIds = sUserManager.getUserIds(); 6877 synchronized (mInstallLock) { 6878 // Make sure all user data directories are ready to roll; we're okay 6879 // if they already exist 6880 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6881 for (int userId : userIds) { 6882 if (userId != 0) { 6883 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6884 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6885 pkg.applicationInfo.seinfo); 6886 } 6887 } 6888 } 6889 6890 // Create a native library symlink only if we have native libraries 6891 // and if the native libraries are 32 bit libraries. We do not provide 6892 // this symlink for 64 bit libraries. 6893 if (pkg.applicationInfo.primaryCpuAbi != null && 6894 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6895 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6896 for (int userId : userIds) { 6897 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6898 nativeLibPath, userId) < 0) { 6899 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6900 "Failed linking native library dir (user=" + userId + ")"); 6901 } 6902 } 6903 } 6904 } 6905 6906 // This is a special case for the "system" package, where the ABI is 6907 // dictated by the zygote configuration (and init.rc). We should keep track 6908 // of this ABI so that we can deal with "normal" applications that run under 6909 // the same UID correctly. 6910 if (mPlatformPackage == pkg) { 6911 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6912 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6913 } 6914 6915 // If there's a mismatch between the abi-override in the package setting 6916 // and the abiOverride specified for the install. Warn about this because we 6917 // would've already compiled the app without taking the package setting into 6918 // account. 6919 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6920 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6921 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6922 " for package: " + pkg.packageName); 6923 } 6924 } 6925 6926 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6927 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6928 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6929 6930 // Copy the derived override back to the parsed package, so that we can 6931 // update the package settings accordingly. 6932 pkg.cpuAbiOverride = cpuAbiOverride; 6933 6934 if (DEBUG_ABI_SELECTION) { 6935 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6936 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6937 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6938 } 6939 6940 // Push the derived path down into PackageSettings so we know what to 6941 // clean up at uninstall time. 6942 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6943 6944 if (DEBUG_ABI_SELECTION) { 6945 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6946 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6947 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6948 } 6949 6950 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6951 // We don't do this here during boot because we can do it all 6952 // at once after scanning all existing packages. 6953 // 6954 // We also do this *before* we perform dexopt on this package, so that 6955 // we can avoid redundant dexopts, and also to make sure we've got the 6956 // code and package path correct. 6957 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6958 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6959 } 6960 6961 if ((scanFlags & SCAN_NO_DEX) == 0) { 6962 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6963 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6964 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6965 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6966 } 6967 } 6968 if (mFactoryTest && pkg.requestedPermissions.contains( 6969 android.Manifest.permission.FACTORY_TEST)) { 6970 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6971 } 6972 6973 ArrayList<PackageParser.Package> clientLibPkgs = null; 6974 6975 // writer 6976 synchronized (mPackages) { 6977 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6978 // Only system apps can add new shared libraries. 6979 if (pkg.libraryNames != null) { 6980 for (int i=0; i<pkg.libraryNames.size(); i++) { 6981 String name = pkg.libraryNames.get(i); 6982 boolean allowed = false; 6983 if (pkg.isUpdatedSystemApp()) { 6984 // New library entries can only be added through the 6985 // system image. This is important to get rid of a lot 6986 // of nasty edge cases: for example if we allowed a non- 6987 // system update of the app to add a library, then uninstalling 6988 // the update would make the library go away, and assumptions 6989 // we made such as through app install filtering would now 6990 // have allowed apps on the device which aren't compatible 6991 // with it. Better to just have the restriction here, be 6992 // conservative, and create many fewer cases that can negatively 6993 // impact the user experience. 6994 final PackageSetting sysPs = mSettings 6995 .getDisabledSystemPkgLPr(pkg.packageName); 6996 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6997 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6998 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6999 allowed = true; 7000 allowed = true; 7001 break; 7002 } 7003 } 7004 } 7005 } else { 7006 allowed = true; 7007 } 7008 if (allowed) { 7009 if (!mSharedLibraries.containsKey(name)) { 7010 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7011 } else if (!name.equals(pkg.packageName)) { 7012 Slog.w(TAG, "Package " + pkg.packageName + " library " 7013 + name + " already exists; skipping"); 7014 } 7015 } else { 7016 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7017 + name + " that is not declared on system image; skipping"); 7018 } 7019 } 7020 if ((scanFlags&SCAN_BOOTING) == 0) { 7021 // If we are not booting, we need to update any applications 7022 // that are clients of our shared library. If we are booting, 7023 // this will all be done once the scan is complete. 7024 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7025 } 7026 } 7027 } 7028 } 7029 7030 // We also need to dexopt any apps that are dependent on this library. Note that 7031 // if these fail, we should abort the install since installing the library will 7032 // result in some apps being broken. 7033 if (clientLibPkgs != null) { 7034 if ((scanFlags & SCAN_NO_DEX) == 0) { 7035 for (int i = 0; i < clientLibPkgs.size(); i++) { 7036 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7037 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7038 null /* instruction sets */, forceDex, 7039 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7040 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7041 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7042 "scanPackageLI failed to dexopt clientLibPkgs"); 7043 } 7044 } 7045 } 7046 } 7047 7048 // Also need to kill any apps that are dependent on the library. 7049 if (clientLibPkgs != null) { 7050 for (int i=0; i<clientLibPkgs.size(); i++) { 7051 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7052 killApplication(clientPkg.applicationInfo.packageName, 7053 clientPkg.applicationInfo.uid, "update lib"); 7054 } 7055 } 7056 7057 // Make sure we're not adding any bogus keyset info 7058 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7059 ksms.assertScannedPackageValid(pkg); 7060 7061 // writer 7062 synchronized (mPackages) { 7063 // We don't expect installation to fail beyond this point 7064 7065 // Add the new setting to mSettings 7066 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7067 // Add the new setting to mPackages 7068 mPackages.put(pkg.applicationInfo.packageName, pkg); 7069 // Make sure we don't accidentally delete its data. 7070 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7071 while (iter.hasNext()) { 7072 PackageCleanItem item = iter.next(); 7073 if (pkgName.equals(item.packageName)) { 7074 iter.remove(); 7075 } 7076 } 7077 7078 // Take care of first install / last update times. 7079 if (currentTime != 0) { 7080 if (pkgSetting.firstInstallTime == 0) { 7081 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7082 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7083 pkgSetting.lastUpdateTime = currentTime; 7084 } 7085 } else if (pkgSetting.firstInstallTime == 0) { 7086 // We need *something*. Take time time stamp of the file. 7087 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7088 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7089 if (scanFileTime != pkgSetting.timeStamp) { 7090 // A package on the system image has changed; consider this 7091 // to be an update. 7092 pkgSetting.lastUpdateTime = scanFileTime; 7093 } 7094 } 7095 7096 // Add the package's KeySets to the global KeySetManagerService 7097 ksms.addScannedPackageLPw(pkg); 7098 7099 int N = pkg.providers.size(); 7100 StringBuilder r = null; 7101 int i; 7102 for (i=0; i<N; i++) { 7103 PackageParser.Provider p = pkg.providers.get(i); 7104 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7105 p.info.processName, pkg.applicationInfo.uid); 7106 mProviders.addProvider(p); 7107 p.syncable = p.info.isSyncable; 7108 if (p.info.authority != null) { 7109 String names[] = p.info.authority.split(";"); 7110 p.info.authority = null; 7111 for (int j = 0; j < names.length; j++) { 7112 if (j == 1 && p.syncable) { 7113 // We only want the first authority for a provider to possibly be 7114 // syncable, so if we already added this provider using a different 7115 // authority clear the syncable flag. We copy the provider before 7116 // changing it because the mProviders object contains a reference 7117 // to a provider that we don't want to change. 7118 // Only do this for the second authority since the resulting provider 7119 // object can be the same for all future authorities for this provider. 7120 p = new PackageParser.Provider(p); 7121 p.syncable = false; 7122 } 7123 if (!mProvidersByAuthority.containsKey(names[j])) { 7124 mProvidersByAuthority.put(names[j], p); 7125 if (p.info.authority == null) { 7126 p.info.authority = names[j]; 7127 } else { 7128 p.info.authority = p.info.authority + ";" + names[j]; 7129 } 7130 if (DEBUG_PACKAGE_SCANNING) { 7131 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7132 Log.d(TAG, "Registered content provider: " + names[j] 7133 + ", className = " + p.info.name + ", isSyncable = " 7134 + p.info.isSyncable); 7135 } 7136 } else { 7137 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7138 Slog.w(TAG, "Skipping provider name " + names[j] + 7139 " (in package " + pkg.applicationInfo.packageName + 7140 "): name already used by " 7141 + ((other != null && other.getComponentName() != null) 7142 ? other.getComponentName().getPackageName() : "?")); 7143 } 7144 } 7145 } 7146 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7147 if (r == null) { 7148 r = new StringBuilder(256); 7149 } else { 7150 r.append(' '); 7151 } 7152 r.append(p.info.name); 7153 } 7154 } 7155 if (r != null) { 7156 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7157 } 7158 7159 N = pkg.services.size(); 7160 r = null; 7161 for (i=0; i<N; i++) { 7162 PackageParser.Service s = pkg.services.get(i); 7163 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7164 s.info.processName, pkg.applicationInfo.uid); 7165 mServices.addService(s); 7166 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7167 if (r == null) { 7168 r = new StringBuilder(256); 7169 } else { 7170 r.append(' '); 7171 } 7172 r.append(s.info.name); 7173 } 7174 } 7175 if (r != null) { 7176 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7177 } 7178 7179 N = pkg.receivers.size(); 7180 r = null; 7181 for (i=0; i<N; i++) { 7182 PackageParser.Activity a = pkg.receivers.get(i); 7183 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7184 a.info.processName, pkg.applicationInfo.uid); 7185 mReceivers.addActivity(a, "receiver"); 7186 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7187 if (r == null) { 7188 r = new StringBuilder(256); 7189 } else { 7190 r.append(' '); 7191 } 7192 r.append(a.info.name); 7193 } 7194 } 7195 if (r != null) { 7196 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7197 } 7198 7199 N = pkg.activities.size(); 7200 r = null; 7201 for (i=0; i<N; i++) { 7202 PackageParser.Activity a = pkg.activities.get(i); 7203 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7204 a.info.processName, pkg.applicationInfo.uid); 7205 mActivities.addActivity(a, "activity"); 7206 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7207 if (r == null) { 7208 r = new StringBuilder(256); 7209 } else { 7210 r.append(' '); 7211 } 7212 r.append(a.info.name); 7213 } 7214 } 7215 if (r != null) { 7216 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7217 } 7218 7219 N = pkg.permissionGroups.size(); 7220 r = null; 7221 for (i=0; i<N; i++) { 7222 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7223 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7224 if (cur == null) { 7225 mPermissionGroups.put(pg.info.name, pg); 7226 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7227 if (r == null) { 7228 r = new StringBuilder(256); 7229 } else { 7230 r.append(' '); 7231 } 7232 r.append(pg.info.name); 7233 } 7234 } else { 7235 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7236 + pg.info.packageName + " ignored: original from " 7237 + cur.info.packageName); 7238 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7239 if (r == null) { 7240 r = new StringBuilder(256); 7241 } else { 7242 r.append(' '); 7243 } 7244 r.append("DUP:"); 7245 r.append(pg.info.name); 7246 } 7247 } 7248 } 7249 if (r != null) { 7250 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7251 } 7252 7253 N = pkg.permissions.size(); 7254 r = null; 7255 for (i=0; i<N; i++) { 7256 PackageParser.Permission p = pkg.permissions.get(i); 7257 7258 // Now that permission groups have a special meaning, we ignore permission 7259 // groups for legacy apps to prevent unexpected behavior. In particular, 7260 // permissions for one app being granted to someone just becuase they happen 7261 // to be in a group defined by another app (before this had no implications). 7262 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7263 p.group = mPermissionGroups.get(p.info.group); 7264 // Warn for a permission in an unknown group. 7265 if (p.info.group != null && p.group == null) { 7266 Slog.w(TAG, "Permission " + p.info.name + " from package " 7267 + p.info.packageName + " in an unknown group " + p.info.group); 7268 } 7269 } 7270 7271 ArrayMap<String, BasePermission> permissionMap = 7272 p.tree ? mSettings.mPermissionTrees 7273 : mSettings.mPermissions; 7274 BasePermission bp = permissionMap.get(p.info.name); 7275 7276 // Allow system apps to redefine non-system permissions 7277 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7278 final boolean currentOwnerIsSystem = (bp.perm != null 7279 && isSystemApp(bp.perm.owner)); 7280 if (isSystemApp(p.owner)) { 7281 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7282 // It's a built-in permission and no owner, take ownership now 7283 bp.packageSetting = pkgSetting; 7284 bp.perm = p; 7285 bp.uid = pkg.applicationInfo.uid; 7286 bp.sourcePackage = p.info.packageName; 7287 } else if (!currentOwnerIsSystem) { 7288 String msg = "New decl " + p.owner + " of permission " 7289 + p.info.name + " is system; overriding " + bp.sourcePackage; 7290 reportSettingsProblem(Log.WARN, msg); 7291 bp = null; 7292 } 7293 } 7294 } 7295 7296 if (bp == null) { 7297 bp = new BasePermission(p.info.name, p.info.packageName, 7298 BasePermission.TYPE_NORMAL); 7299 permissionMap.put(p.info.name, bp); 7300 } 7301 7302 if (bp.perm == null) { 7303 if (bp.sourcePackage == null 7304 || bp.sourcePackage.equals(p.info.packageName)) { 7305 BasePermission tree = findPermissionTreeLP(p.info.name); 7306 if (tree == null 7307 || tree.sourcePackage.equals(p.info.packageName)) { 7308 bp.packageSetting = pkgSetting; 7309 bp.perm = p; 7310 bp.uid = pkg.applicationInfo.uid; 7311 bp.sourcePackage = p.info.packageName; 7312 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7313 if (r == null) { 7314 r = new StringBuilder(256); 7315 } else { 7316 r.append(' '); 7317 } 7318 r.append(p.info.name); 7319 } 7320 } else { 7321 Slog.w(TAG, "Permission " + p.info.name + " from package " 7322 + p.info.packageName + " ignored: base tree " 7323 + tree.name + " is from package " 7324 + tree.sourcePackage); 7325 } 7326 } else { 7327 Slog.w(TAG, "Permission " + p.info.name + " from package " 7328 + p.info.packageName + " ignored: original from " 7329 + bp.sourcePackage); 7330 } 7331 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7332 if (r == null) { 7333 r = new StringBuilder(256); 7334 } else { 7335 r.append(' '); 7336 } 7337 r.append("DUP:"); 7338 r.append(p.info.name); 7339 } 7340 if (bp.perm == p) { 7341 bp.protectionLevel = p.info.protectionLevel; 7342 } 7343 } 7344 7345 if (r != null) { 7346 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7347 } 7348 7349 N = pkg.instrumentation.size(); 7350 r = null; 7351 for (i=0; i<N; i++) { 7352 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7353 a.info.packageName = pkg.applicationInfo.packageName; 7354 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7355 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7356 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7357 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7358 a.info.dataDir = pkg.applicationInfo.dataDir; 7359 7360 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7361 // need other information about the application, like the ABI and what not ? 7362 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7363 mInstrumentation.put(a.getComponentName(), a); 7364 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7365 if (r == null) { 7366 r = new StringBuilder(256); 7367 } else { 7368 r.append(' '); 7369 } 7370 r.append(a.info.name); 7371 } 7372 } 7373 if (r != null) { 7374 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7375 } 7376 7377 if (pkg.protectedBroadcasts != null) { 7378 N = pkg.protectedBroadcasts.size(); 7379 for (i=0; i<N; i++) { 7380 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7381 } 7382 } 7383 7384 pkgSetting.setTimeStamp(scanFileTime); 7385 7386 // Create idmap files for pairs of (packages, overlay packages). 7387 // Note: "android", ie framework-res.apk, is handled by native layers. 7388 if (pkg.mOverlayTarget != null) { 7389 // This is an overlay package. 7390 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7391 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7392 mOverlays.put(pkg.mOverlayTarget, 7393 new ArrayMap<String, PackageParser.Package>()); 7394 } 7395 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7396 map.put(pkg.packageName, pkg); 7397 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7398 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7399 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7400 "scanPackageLI failed to createIdmap"); 7401 } 7402 } 7403 } else if (mOverlays.containsKey(pkg.packageName) && 7404 !pkg.packageName.equals("android")) { 7405 // This is a regular package, with one or more known overlay packages. 7406 createIdmapsForPackageLI(pkg); 7407 } 7408 } 7409 7410 return pkg; 7411 } 7412 7413 /** 7414 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7415 * is derived purely on the basis of the contents of {@code scanFile} and 7416 * {@code cpuAbiOverride}. 7417 * 7418 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7419 */ 7420 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7421 String cpuAbiOverride, boolean extractLibs) 7422 throws PackageManagerException { 7423 // TODO: We can probably be smarter about this stuff. For installed apps, 7424 // we can calculate this information at install time once and for all. For 7425 // system apps, we can probably assume that this information doesn't change 7426 // after the first boot scan. As things stand, we do lots of unnecessary work. 7427 7428 // Give ourselves some initial paths; we'll come back for another 7429 // pass once we've determined ABI below. 7430 setNativeLibraryPaths(pkg); 7431 7432 // We would never need to extract libs for forward-locked and external packages, 7433 // since the container service will do it for us. We shouldn't attempt to 7434 // extract libs from system app when it was not updated. 7435 if (pkg.isForwardLocked() || isExternal(pkg) || 7436 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7437 extractLibs = false; 7438 } 7439 7440 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7441 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7442 7443 NativeLibraryHelper.Handle handle = null; 7444 try { 7445 handle = NativeLibraryHelper.Handle.create(scanFile); 7446 // TODO(multiArch): This can be null for apps that didn't go through the 7447 // usual installation process. We can calculate it again, like we 7448 // do during install time. 7449 // 7450 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7451 // unnecessary. 7452 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7453 7454 // Null out the abis so that they can be recalculated. 7455 pkg.applicationInfo.primaryCpuAbi = null; 7456 pkg.applicationInfo.secondaryCpuAbi = null; 7457 if (isMultiArch(pkg.applicationInfo)) { 7458 // Warn if we've set an abiOverride for multi-lib packages.. 7459 // By definition, we need to copy both 32 and 64 bit libraries for 7460 // such packages. 7461 if (pkg.cpuAbiOverride != null 7462 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7463 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7464 } 7465 7466 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7467 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7468 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7469 if (extractLibs) { 7470 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7471 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7472 useIsaSpecificSubdirs); 7473 } else { 7474 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7475 } 7476 } 7477 7478 maybeThrowExceptionForMultiArchCopy( 7479 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7480 7481 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7482 if (extractLibs) { 7483 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7484 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7485 useIsaSpecificSubdirs); 7486 } else { 7487 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7488 } 7489 } 7490 7491 maybeThrowExceptionForMultiArchCopy( 7492 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7493 7494 if (abi64 >= 0) { 7495 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7496 } 7497 7498 if (abi32 >= 0) { 7499 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7500 if (abi64 >= 0) { 7501 pkg.applicationInfo.secondaryCpuAbi = abi; 7502 } else { 7503 pkg.applicationInfo.primaryCpuAbi = abi; 7504 } 7505 } 7506 } else { 7507 String[] abiList = (cpuAbiOverride != null) ? 7508 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7509 7510 // Enable gross and lame hacks for apps that are built with old 7511 // SDK tools. We must scan their APKs for renderscript bitcode and 7512 // not launch them if it's present. Don't bother checking on devices 7513 // that don't have 64 bit support. 7514 boolean needsRenderScriptOverride = false; 7515 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7516 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7517 abiList = Build.SUPPORTED_32_BIT_ABIS; 7518 needsRenderScriptOverride = true; 7519 } 7520 7521 final int copyRet; 7522 if (extractLibs) { 7523 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7524 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7525 } else { 7526 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7527 } 7528 7529 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7530 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7531 "Error unpackaging native libs for app, errorCode=" + copyRet); 7532 } 7533 7534 if (copyRet >= 0) { 7535 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7536 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7537 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7538 } else if (needsRenderScriptOverride) { 7539 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7540 } 7541 } 7542 } catch (IOException ioe) { 7543 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7544 } finally { 7545 IoUtils.closeQuietly(handle); 7546 } 7547 7548 // Now that we've calculated the ABIs and determined if it's an internal app, 7549 // we will go ahead and populate the nativeLibraryPath. 7550 setNativeLibraryPaths(pkg); 7551 } 7552 7553 /** 7554 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7555 * i.e, so that all packages can be run inside a single process if required. 7556 * 7557 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7558 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7559 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7560 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7561 * updating a package that belongs to a shared user. 7562 * 7563 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7564 * adds unnecessary complexity. 7565 */ 7566 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7567 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7568 String requiredInstructionSet = null; 7569 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7570 requiredInstructionSet = VMRuntime.getInstructionSet( 7571 scannedPackage.applicationInfo.primaryCpuAbi); 7572 } 7573 7574 PackageSetting requirer = null; 7575 for (PackageSetting ps : packagesForUser) { 7576 // If packagesForUser contains scannedPackage, we skip it. This will happen 7577 // when scannedPackage is an update of an existing package. Without this check, 7578 // we will never be able to change the ABI of any package belonging to a shared 7579 // user, even if it's compatible with other packages. 7580 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7581 if (ps.primaryCpuAbiString == null) { 7582 continue; 7583 } 7584 7585 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7586 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7587 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7588 // this but there's not much we can do. 7589 String errorMessage = "Instruction set mismatch, " 7590 + ((requirer == null) ? "[caller]" : requirer) 7591 + " requires " + requiredInstructionSet + " whereas " + ps 7592 + " requires " + instructionSet; 7593 Slog.w(TAG, errorMessage); 7594 } 7595 7596 if (requiredInstructionSet == null) { 7597 requiredInstructionSet = instructionSet; 7598 requirer = ps; 7599 } 7600 } 7601 } 7602 7603 if (requiredInstructionSet != null) { 7604 String adjustedAbi; 7605 if (requirer != null) { 7606 // requirer != null implies that either scannedPackage was null or that scannedPackage 7607 // did not require an ABI, in which case we have to adjust scannedPackage to match 7608 // the ABI of the set (which is the same as requirer's ABI) 7609 adjustedAbi = requirer.primaryCpuAbiString; 7610 if (scannedPackage != null) { 7611 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7612 } 7613 } else { 7614 // requirer == null implies that we're updating all ABIs in the set to 7615 // match scannedPackage. 7616 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7617 } 7618 7619 for (PackageSetting ps : packagesForUser) { 7620 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7621 if (ps.primaryCpuAbiString != null) { 7622 continue; 7623 } 7624 7625 ps.primaryCpuAbiString = adjustedAbi; 7626 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7627 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7628 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7629 7630 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7631 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7632 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7633 ps.primaryCpuAbiString = null; 7634 ps.pkg.applicationInfo.primaryCpuAbi = null; 7635 return; 7636 } else { 7637 mInstaller.rmdex(ps.codePathString, 7638 getDexCodeInstructionSet(getPreferredInstructionSet())); 7639 } 7640 } 7641 } 7642 } 7643 } 7644 } 7645 7646 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7647 synchronized (mPackages) { 7648 mResolverReplaced = true; 7649 // Set up information for custom user intent resolution activity. 7650 mResolveActivity.applicationInfo = pkg.applicationInfo; 7651 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7652 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7653 mResolveActivity.processName = pkg.applicationInfo.packageName; 7654 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7655 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7656 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7657 mResolveActivity.theme = 0; 7658 mResolveActivity.exported = true; 7659 mResolveActivity.enabled = true; 7660 mResolveInfo.activityInfo = mResolveActivity; 7661 mResolveInfo.priority = 0; 7662 mResolveInfo.preferredOrder = 0; 7663 mResolveInfo.match = 0; 7664 mResolveComponentName = mCustomResolverComponentName; 7665 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7666 mResolveComponentName); 7667 } 7668 } 7669 7670 private static String calculateBundledApkRoot(final String codePathString) { 7671 final File codePath = new File(codePathString); 7672 final File codeRoot; 7673 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7674 codeRoot = Environment.getRootDirectory(); 7675 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7676 codeRoot = Environment.getOemDirectory(); 7677 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7678 codeRoot = Environment.getVendorDirectory(); 7679 } else { 7680 // Unrecognized code path; take its top real segment as the apk root: 7681 // e.g. /something/app/blah.apk => /something 7682 try { 7683 File f = codePath.getCanonicalFile(); 7684 File parent = f.getParentFile(); // non-null because codePath is a file 7685 File tmp; 7686 while ((tmp = parent.getParentFile()) != null) { 7687 f = parent; 7688 parent = tmp; 7689 } 7690 codeRoot = f; 7691 Slog.w(TAG, "Unrecognized code path " 7692 + codePath + " - using " + codeRoot); 7693 } catch (IOException e) { 7694 // Can't canonicalize the code path -- shenanigans? 7695 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7696 return Environment.getRootDirectory().getPath(); 7697 } 7698 } 7699 return codeRoot.getPath(); 7700 } 7701 7702 /** 7703 * Derive and set the location of native libraries for the given package, 7704 * which varies depending on where and how the package was installed. 7705 */ 7706 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7707 final ApplicationInfo info = pkg.applicationInfo; 7708 final String codePath = pkg.codePath; 7709 final File codeFile = new File(codePath); 7710 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7711 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7712 7713 info.nativeLibraryRootDir = null; 7714 info.nativeLibraryRootRequiresIsa = false; 7715 info.nativeLibraryDir = null; 7716 info.secondaryNativeLibraryDir = null; 7717 7718 if (isApkFile(codeFile)) { 7719 // Monolithic install 7720 if (bundledApp) { 7721 // If "/system/lib64/apkname" exists, assume that is the per-package 7722 // native library directory to use; otherwise use "/system/lib/apkname". 7723 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7724 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7725 getPrimaryInstructionSet(info)); 7726 7727 // This is a bundled system app so choose the path based on the ABI. 7728 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7729 // is just the default path. 7730 final String apkName = deriveCodePathName(codePath); 7731 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7732 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7733 apkName).getAbsolutePath(); 7734 7735 if (info.secondaryCpuAbi != null) { 7736 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7737 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7738 secondaryLibDir, apkName).getAbsolutePath(); 7739 } 7740 } else if (asecApp) { 7741 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7742 .getAbsolutePath(); 7743 } else { 7744 final String apkName = deriveCodePathName(codePath); 7745 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7746 .getAbsolutePath(); 7747 } 7748 7749 info.nativeLibraryRootRequiresIsa = false; 7750 info.nativeLibraryDir = info.nativeLibraryRootDir; 7751 } else { 7752 // Cluster install 7753 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7754 info.nativeLibraryRootRequiresIsa = true; 7755 7756 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7757 getPrimaryInstructionSet(info)).getAbsolutePath(); 7758 7759 if (info.secondaryCpuAbi != null) { 7760 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7761 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7762 } 7763 } 7764 } 7765 7766 /** 7767 * Calculate the abis and roots for a bundled app. These can uniquely 7768 * be determined from the contents of the system partition, i.e whether 7769 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7770 * of this information, and instead assume that the system was built 7771 * sensibly. 7772 */ 7773 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7774 PackageSetting pkgSetting) { 7775 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7776 7777 // If "/system/lib64/apkname" exists, assume that is the per-package 7778 // native library directory to use; otherwise use "/system/lib/apkname". 7779 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7780 setBundledAppAbi(pkg, apkRoot, apkName); 7781 // pkgSetting might be null during rescan following uninstall of updates 7782 // to a bundled app, so accommodate that possibility. The settings in 7783 // that case will be established later from the parsed package. 7784 // 7785 // If the settings aren't null, sync them up with what we've just derived. 7786 // note that apkRoot isn't stored in the package settings. 7787 if (pkgSetting != null) { 7788 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7789 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7790 } 7791 } 7792 7793 /** 7794 * Deduces the ABI of a bundled app and sets the relevant fields on the 7795 * parsed pkg object. 7796 * 7797 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7798 * under which system libraries are installed. 7799 * @param apkName the name of the installed package. 7800 */ 7801 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7802 final File codeFile = new File(pkg.codePath); 7803 7804 final boolean has64BitLibs; 7805 final boolean has32BitLibs; 7806 if (isApkFile(codeFile)) { 7807 // Monolithic install 7808 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7809 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7810 } else { 7811 // Cluster install 7812 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7813 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7814 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7815 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7816 has64BitLibs = (new File(rootDir, isa)).exists(); 7817 } else { 7818 has64BitLibs = false; 7819 } 7820 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7821 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7822 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7823 has32BitLibs = (new File(rootDir, isa)).exists(); 7824 } else { 7825 has32BitLibs = false; 7826 } 7827 } 7828 7829 if (has64BitLibs && !has32BitLibs) { 7830 // The package has 64 bit libs, but not 32 bit libs. Its primary 7831 // ABI should be 64 bit. We can safely assume here that the bundled 7832 // native libraries correspond to the most preferred ABI in the list. 7833 7834 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7835 pkg.applicationInfo.secondaryCpuAbi = null; 7836 } else if (has32BitLibs && !has64BitLibs) { 7837 // The package has 32 bit libs but not 64 bit libs. Its primary 7838 // ABI should be 32 bit. 7839 7840 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7841 pkg.applicationInfo.secondaryCpuAbi = null; 7842 } else if (has32BitLibs && has64BitLibs) { 7843 // The application has both 64 and 32 bit bundled libraries. We check 7844 // here that the app declares multiArch support, and warn if it doesn't. 7845 // 7846 // We will be lenient here and record both ABIs. The primary will be the 7847 // ABI that's higher on the list, i.e, a device that's configured to prefer 7848 // 64 bit apps will see a 64 bit primary ABI, 7849 7850 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7851 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7852 } 7853 7854 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7855 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7856 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7857 } else { 7858 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7859 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7860 } 7861 } else { 7862 pkg.applicationInfo.primaryCpuAbi = null; 7863 pkg.applicationInfo.secondaryCpuAbi = null; 7864 } 7865 } 7866 7867 private void killApplication(String pkgName, int appId, String reason) { 7868 // Request the ActivityManager to kill the process(only for existing packages) 7869 // so that we do not end up in a confused state while the user is still using the older 7870 // version of the application while the new one gets installed. 7871 IActivityManager am = ActivityManagerNative.getDefault(); 7872 if (am != null) { 7873 try { 7874 am.killApplicationWithAppId(pkgName, appId, reason); 7875 } catch (RemoteException e) { 7876 } 7877 } 7878 } 7879 7880 void removePackageLI(PackageSetting ps, boolean chatty) { 7881 if (DEBUG_INSTALL) { 7882 if (chatty) 7883 Log.d(TAG, "Removing package " + ps.name); 7884 } 7885 7886 // writer 7887 synchronized (mPackages) { 7888 mPackages.remove(ps.name); 7889 final PackageParser.Package pkg = ps.pkg; 7890 if (pkg != null) { 7891 cleanPackageDataStructuresLILPw(pkg, chatty); 7892 } 7893 } 7894 } 7895 7896 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7897 if (DEBUG_INSTALL) { 7898 if (chatty) 7899 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7900 } 7901 7902 // writer 7903 synchronized (mPackages) { 7904 mPackages.remove(pkg.applicationInfo.packageName); 7905 cleanPackageDataStructuresLILPw(pkg, chatty); 7906 } 7907 } 7908 7909 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7910 int N = pkg.providers.size(); 7911 StringBuilder r = null; 7912 int i; 7913 for (i=0; i<N; i++) { 7914 PackageParser.Provider p = pkg.providers.get(i); 7915 mProviders.removeProvider(p); 7916 if (p.info.authority == null) { 7917 7918 /* There was another ContentProvider with this authority when 7919 * this app was installed so this authority is null, 7920 * Ignore it as we don't have to unregister the provider. 7921 */ 7922 continue; 7923 } 7924 String names[] = p.info.authority.split(";"); 7925 for (int j = 0; j < names.length; j++) { 7926 if (mProvidersByAuthority.get(names[j]) == p) { 7927 mProvidersByAuthority.remove(names[j]); 7928 if (DEBUG_REMOVE) { 7929 if (chatty) 7930 Log.d(TAG, "Unregistered content provider: " + names[j] 7931 + ", className = " + p.info.name + ", isSyncable = " 7932 + p.info.isSyncable); 7933 } 7934 } 7935 } 7936 if (DEBUG_REMOVE && chatty) { 7937 if (r == null) { 7938 r = new StringBuilder(256); 7939 } else { 7940 r.append(' '); 7941 } 7942 r.append(p.info.name); 7943 } 7944 } 7945 if (r != null) { 7946 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7947 } 7948 7949 N = pkg.services.size(); 7950 r = null; 7951 for (i=0; i<N; i++) { 7952 PackageParser.Service s = pkg.services.get(i); 7953 mServices.removeService(s); 7954 if (chatty) { 7955 if (r == null) { 7956 r = new StringBuilder(256); 7957 } else { 7958 r.append(' '); 7959 } 7960 r.append(s.info.name); 7961 } 7962 } 7963 if (r != null) { 7964 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7965 } 7966 7967 N = pkg.receivers.size(); 7968 r = null; 7969 for (i=0; i<N; i++) { 7970 PackageParser.Activity a = pkg.receivers.get(i); 7971 mReceivers.removeActivity(a, "receiver"); 7972 if (DEBUG_REMOVE && chatty) { 7973 if (r == null) { 7974 r = new StringBuilder(256); 7975 } else { 7976 r.append(' '); 7977 } 7978 r.append(a.info.name); 7979 } 7980 } 7981 if (r != null) { 7982 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7983 } 7984 7985 N = pkg.activities.size(); 7986 r = null; 7987 for (i=0; i<N; i++) { 7988 PackageParser.Activity a = pkg.activities.get(i); 7989 mActivities.removeActivity(a, "activity"); 7990 if (DEBUG_REMOVE && chatty) { 7991 if (r == null) { 7992 r = new StringBuilder(256); 7993 } else { 7994 r.append(' '); 7995 } 7996 r.append(a.info.name); 7997 } 7998 } 7999 if (r != null) { 8000 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8001 } 8002 8003 N = pkg.permissions.size(); 8004 r = null; 8005 for (i=0; i<N; i++) { 8006 PackageParser.Permission p = pkg.permissions.get(i); 8007 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8008 if (bp == null) { 8009 bp = mSettings.mPermissionTrees.get(p.info.name); 8010 } 8011 if (bp != null && bp.perm == p) { 8012 bp.perm = null; 8013 if (DEBUG_REMOVE && chatty) { 8014 if (r == null) { 8015 r = new StringBuilder(256); 8016 } else { 8017 r.append(' '); 8018 } 8019 r.append(p.info.name); 8020 } 8021 } 8022 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8023 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8024 if (appOpPerms != null) { 8025 appOpPerms.remove(pkg.packageName); 8026 } 8027 } 8028 } 8029 if (r != null) { 8030 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8031 } 8032 8033 N = pkg.requestedPermissions.size(); 8034 r = null; 8035 for (i=0; i<N; i++) { 8036 String perm = pkg.requestedPermissions.get(i); 8037 BasePermission bp = mSettings.mPermissions.get(perm); 8038 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8039 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8040 if (appOpPerms != null) { 8041 appOpPerms.remove(pkg.packageName); 8042 if (appOpPerms.isEmpty()) { 8043 mAppOpPermissionPackages.remove(perm); 8044 } 8045 } 8046 } 8047 } 8048 if (r != null) { 8049 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8050 } 8051 8052 N = pkg.instrumentation.size(); 8053 r = null; 8054 for (i=0; i<N; i++) { 8055 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8056 mInstrumentation.remove(a.getComponentName()); 8057 if (DEBUG_REMOVE && chatty) { 8058 if (r == null) { 8059 r = new StringBuilder(256); 8060 } else { 8061 r.append(' '); 8062 } 8063 r.append(a.info.name); 8064 } 8065 } 8066 if (r != null) { 8067 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8068 } 8069 8070 r = null; 8071 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8072 // Only system apps can hold shared libraries. 8073 if (pkg.libraryNames != null) { 8074 for (i=0; i<pkg.libraryNames.size(); i++) { 8075 String name = pkg.libraryNames.get(i); 8076 SharedLibraryEntry cur = mSharedLibraries.get(name); 8077 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8078 mSharedLibraries.remove(name); 8079 if (DEBUG_REMOVE && chatty) { 8080 if (r == null) { 8081 r = new StringBuilder(256); 8082 } else { 8083 r.append(' '); 8084 } 8085 r.append(name); 8086 } 8087 } 8088 } 8089 } 8090 } 8091 if (r != null) { 8092 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8093 } 8094 } 8095 8096 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8097 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8098 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8099 return true; 8100 } 8101 } 8102 return false; 8103 } 8104 8105 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8106 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8107 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8108 8109 private void updatePermissionsLPw(String changingPkg, 8110 PackageParser.Package pkgInfo, int flags) { 8111 // Make sure there are no dangling permission trees. 8112 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8113 while (it.hasNext()) { 8114 final BasePermission bp = it.next(); 8115 if (bp.packageSetting == null) { 8116 // We may not yet have parsed the package, so just see if 8117 // we still know about its settings. 8118 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8119 } 8120 if (bp.packageSetting == null) { 8121 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8122 + " from package " + bp.sourcePackage); 8123 it.remove(); 8124 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8125 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8126 Slog.i(TAG, "Removing old permission tree: " + bp.name 8127 + " from package " + bp.sourcePackage); 8128 flags |= UPDATE_PERMISSIONS_ALL; 8129 it.remove(); 8130 } 8131 } 8132 } 8133 8134 // Make sure all dynamic permissions have been assigned to a package, 8135 // and make sure there are no dangling permissions. 8136 it = mSettings.mPermissions.values().iterator(); 8137 while (it.hasNext()) { 8138 final BasePermission bp = it.next(); 8139 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8140 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8141 + bp.name + " pkg=" + bp.sourcePackage 8142 + " info=" + bp.pendingInfo); 8143 if (bp.packageSetting == null && bp.pendingInfo != null) { 8144 final BasePermission tree = findPermissionTreeLP(bp.name); 8145 if (tree != null && tree.perm != null) { 8146 bp.packageSetting = tree.packageSetting; 8147 bp.perm = new PackageParser.Permission(tree.perm.owner, 8148 new PermissionInfo(bp.pendingInfo)); 8149 bp.perm.info.packageName = tree.perm.info.packageName; 8150 bp.perm.info.name = bp.name; 8151 bp.uid = tree.uid; 8152 } 8153 } 8154 } 8155 if (bp.packageSetting == null) { 8156 // We may not yet have parsed the package, so just see if 8157 // we still know about its settings. 8158 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8159 } 8160 if (bp.packageSetting == null) { 8161 Slog.w(TAG, "Removing dangling permission: " + bp.name 8162 + " from package " + bp.sourcePackage); 8163 it.remove(); 8164 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8165 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8166 Slog.i(TAG, "Removing old permission: " + bp.name 8167 + " from package " + bp.sourcePackage); 8168 flags |= UPDATE_PERMISSIONS_ALL; 8169 it.remove(); 8170 } 8171 } 8172 } 8173 8174 // Now update the permissions for all packages, in particular 8175 // replace the granted permissions of the system packages. 8176 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8177 for (PackageParser.Package pkg : mPackages.values()) { 8178 if (pkg != pkgInfo) { 8179 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8180 changingPkg); 8181 } 8182 } 8183 } 8184 8185 if (pkgInfo != null) { 8186 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8187 } 8188 } 8189 8190 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8191 String packageOfInterest) { 8192 // IMPORTANT: There are two types of permissions: install and runtime. 8193 // Install time permissions are granted when the app is installed to 8194 // all device users and users added in the future. Runtime permissions 8195 // are granted at runtime explicitly to specific users. Normal and signature 8196 // protected permissions are install time permissions. Dangerous permissions 8197 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8198 // otherwise they are runtime permissions. This function does not manage 8199 // runtime permissions except for the case an app targeting Lollipop MR1 8200 // being upgraded to target a newer SDK, in which case dangerous permissions 8201 // are transformed from install time to runtime ones. 8202 8203 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8204 if (ps == null) { 8205 return; 8206 } 8207 8208 PermissionsState permissionsState = ps.getPermissionsState(); 8209 PermissionsState origPermissions = permissionsState; 8210 8211 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8212 8213 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8214 8215 boolean changedInstallPermission = false; 8216 8217 if (replace) { 8218 ps.installPermissionsFixed = false; 8219 if (!ps.isSharedUser()) { 8220 origPermissions = new PermissionsState(permissionsState); 8221 permissionsState.reset(); 8222 } 8223 } 8224 8225 permissionsState.setGlobalGids(mGlobalGids); 8226 8227 final int N = pkg.requestedPermissions.size(); 8228 for (int i=0; i<N; i++) { 8229 final String name = pkg.requestedPermissions.get(i); 8230 final BasePermission bp = mSettings.mPermissions.get(name); 8231 8232 if (DEBUG_INSTALL) { 8233 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8234 } 8235 8236 if (bp == null || bp.packageSetting == null) { 8237 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8238 Slog.w(TAG, "Unknown permission " + name 8239 + " in package " + pkg.packageName); 8240 } 8241 continue; 8242 } 8243 8244 final String perm = bp.name; 8245 boolean allowedSig = false; 8246 int grant = GRANT_DENIED; 8247 8248 // Keep track of app op permissions. 8249 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8250 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8251 if (pkgs == null) { 8252 pkgs = new ArraySet<>(); 8253 mAppOpPermissionPackages.put(bp.name, pkgs); 8254 } 8255 pkgs.add(pkg.packageName); 8256 } 8257 8258 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8259 switch (level) { 8260 case PermissionInfo.PROTECTION_NORMAL: { 8261 // For all apps normal permissions are install time ones. 8262 grant = GRANT_INSTALL; 8263 } break; 8264 8265 case PermissionInfo.PROTECTION_DANGEROUS: { 8266 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8267 // For legacy apps dangerous permissions are install time ones. 8268 grant = GRANT_INSTALL_LEGACY; 8269 } else if (origPermissions.hasInstallPermission(bp.name)) { 8270 // For legacy apps that became modern, install becomes runtime. 8271 grant = GRANT_UPGRADE; 8272 } else { 8273 // For modern apps keep runtime permissions unchanged. 8274 grant = GRANT_RUNTIME; 8275 } 8276 } break; 8277 8278 case PermissionInfo.PROTECTION_SIGNATURE: { 8279 // For all apps signature permissions are install time ones. 8280 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8281 if (allowedSig) { 8282 grant = GRANT_INSTALL; 8283 } 8284 } break; 8285 } 8286 8287 if (DEBUG_INSTALL) { 8288 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8289 } 8290 8291 if (grant != GRANT_DENIED) { 8292 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8293 // If this is an existing, non-system package, then 8294 // we can't add any new permissions to it. 8295 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8296 // Except... if this is a permission that was added 8297 // to the platform (note: need to only do this when 8298 // updating the platform). 8299 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8300 grant = GRANT_DENIED; 8301 } 8302 } 8303 } 8304 8305 switch (grant) { 8306 case GRANT_INSTALL: { 8307 // Revoke this as runtime permission to handle the case of 8308 // a runtime permission being downgraded to an install one. 8309 for (int userId : UserManagerService.getInstance().getUserIds()) { 8310 if (origPermissions.getRuntimePermissionState( 8311 bp.name, userId) != null) { 8312 // Revoke the runtime permission and clear the flags. 8313 origPermissions.revokeRuntimePermission(bp, userId); 8314 origPermissions.updatePermissionFlags(bp, userId, 8315 PackageManager.MASK_PERMISSION_FLAGS, 0); 8316 // If we revoked a permission permission, we have to write. 8317 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8318 changedRuntimePermissionUserIds, userId); 8319 } 8320 } 8321 // Grant an install permission. 8322 if (permissionsState.grantInstallPermission(bp) != 8323 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8324 changedInstallPermission = true; 8325 } 8326 } break; 8327 8328 case GRANT_INSTALL_LEGACY: { 8329 // Grant an install permission. 8330 if (permissionsState.grantInstallPermission(bp) != 8331 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8332 changedInstallPermission = true; 8333 } 8334 } break; 8335 8336 case GRANT_RUNTIME: { 8337 // Grant previously granted runtime permissions. 8338 for (int userId : UserManagerService.getInstance().getUserIds()) { 8339 PermissionState permissionState = origPermissions 8340 .getRuntimePermissionState(bp.name, userId); 8341 final int flags = permissionState != null 8342 ? permissionState.getFlags() : 0; 8343 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8344 if (permissionsState.grantRuntimePermission(bp, userId) == 8345 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8346 // If we cannot put the permission as it was, we have to write. 8347 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8348 changedRuntimePermissionUserIds, userId); 8349 } 8350 } 8351 // Propagate the permission flags. 8352 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8353 } 8354 } break; 8355 8356 case GRANT_UPGRADE: { 8357 // Grant runtime permissions for a previously held install permission. 8358 PermissionState permissionState = origPermissions 8359 .getInstallPermissionState(bp.name); 8360 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8361 8362 if (origPermissions.revokeInstallPermission(bp) 8363 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8364 // We will be transferring the permission flags, so clear them. 8365 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8366 PackageManager.MASK_PERMISSION_FLAGS, 0); 8367 changedInstallPermission = true; 8368 } 8369 8370 // If the permission is not to be promoted to runtime we ignore it and 8371 // also its other flags as they are not applicable to install permissions. 8372 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8373 for (int userId : currentUserIds) { 8374 if (permissionsState.grantRuntimePermission(bp, userId) != 8375 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8376 // Transfer the permission flags. 8377 permissionsState.updatePermissionFlags(bp, userId, 8378 flags, flags); 8379 // If we granted the permission, we have to write. 8380 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8381 changedRuntimePermissionUserIds, userId); 8382 } 8383 } 8384 } 8385 } break; 8386 8387 default: { 8388 if (packageOfInterest == null 8389 || packageOfInterest.equals(pkg.packageName)) { 8390 Slog.w(TAG, "Not granting permission " + perm 8391 + " to package " + pkg.packageName 8392 + " because it was previously installed without"); 8393 } 8394 } break; 8395 } 8396 } else { 8397 if (permissionsState.revokeInstallPermission(bp) != 8398 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8399 // Also drop the permission flags. 8400 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8401 PackageManager.MASK_PERMISSION_FLAGS, 0); 8402 changedInstallPermission = true; 8403 Slog.i(TAG, "Un-granting permission " + perm 8404 + " from package " + pkg.packageName 8405 + " (protectionLevel=" + bp.protectionLevel 8406 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8407 + ")"); 8408 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8409 // Don't print warning for app op permissions, since it is fine for them 8410 // not to be granted, there is a UI for the user to decide. 8411 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8412 Slog.w(TAG, "Not granting permission " + perm 8413 + " to package " + pkg.packageName 8414 + " (protectionLevel=" + bp.protectionLevel 8415 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8416 + ")"); 8417 } 8418 } 8419 } 8420 } 8421 8422 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8423 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8424 // This is the first that we have heard about this package, so the 8425 // permissions we have now selected are fixed until explicitly 8426 // changed. 8427 ps.installPermissionsFixed = true; 8428 } 8429 8430 // Persist the runtime permissions state for users with changes. 8431 for (int userId : changedRuntimePermissionUserIds) { 8432 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8433 } 8434 } 8435 8436 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8437 boolean allowed = false; 8438 final int NP = PackageParser.NEW_PERMISSIONS.length; 8439 for (int ip=0; ip<NP; ip++) { 8440 final PackageParser.NewPermissionInfo npi 8441 = PackageParser.NEW_PERMISSIONS[ip]; 8442 if (npi.name.equals(perm) 8443 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8444 allowed = true; 8445 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8446 + pkg.packageName); 8447 break; 8448 } 8449 } 8450 return allowed; 8451 } 8452 8453 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8454 BasePermission bp, PermissionsState origPermissions) { 8455 boolean allowed; 8456 allowed = (compareSignatures( 8457 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8458 == PackageManager.SIGNATURE_MATCH) 8459 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8460 == PackageManager.SIGNATURE_MATCH); 8461 if (!allowed && (bp.protectionLevel 8462 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8463 if (isSystemApp(pkg)) { 8464 // For updated system applications, a system permission 8465 // is granted only if it had been defined by the original application. 8466 if (pkg.isUpdatedSystemApp()) { 8467 final PackageSetting sysPs = mSettings 8468 .getDisabledSystemPkgLPr(pkg.packageName); 8469 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8470 // If the original was granted this permission, we take 8471 // that grant decision as read and propagate it to the 8472 // update. 8473 if (sysPs.isPrivileged()) { 8474 allowed = true; 8475 } 8476 } else { 8477 // The system apk may have been updated with an older 8478 // version of the one on the data partition, but which 8479 // granted a new system permission that it didn't have 8480 // before. In this case we do want to allow the app to 8481 // now get the new permission if the ancestral apk is 8482 // privileged to get it. 8483 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8484 for (int j=0; 8485 j<sysPs.pkg.requestedPermissions.size(); j++) { 8486 if (perm.equals( 8487 sysPs.pkg.requestedPermissions.get(j))) { 8488 allowed = true; 8489 break; 8490 } 8491 } 8492 } 8493 } 8494 } else { 8495 allowed = isPrivilegedApp(pkg); 8496 } 8497 } 8498 } 8499 if (!allowed) { 8500 if (!allowed && (bp.protectionLevel 8501 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8502 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8503 // If this was a previously normal/dangerous permission that got moved 8504 // to a system permission as part of the runtime permission redesign, then 8505 // we still want to blindly grant it to old apps. 8506 allowed = true; 8507 } 8508 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8509 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8510 // If this permission is to be granted to the system installer and 8511 // this app is an installer, then it gets the permission. 8512 allowed = true; 8513 } 8514 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8515 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8516 // If this permission is to be granted to the system verifier and 8517 // this app is a verifier, then it gets the permission. 8518 allowed = true; 8519 } 8520 if (!allowed && (bp.protectionLevel 8521 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8522 && isSystemApp(pkg)) { 8523 // Any pre-installed system app is allowed to get this permission. 8524 allowed = true; 8525 } 8526 if (!allowed && (bp.protectionLevel 8527 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8528 // For development permissions, a development permission 8529 // is granted only if it was already granted. 8530 allowed = origPermissions.hasInstallPermission(perm); 8531 } 8532 } 8533 return allowed; 8534 } 8535 8536 final class ActivityIntentResolver 8537 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8538 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8539 boolean defaultOnly, int userId) { 8540 if (!sUserManager.exists(userId)) return null; 8541 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8542 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8543 } 8544 8545 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8546 int userId) { 8547 if (!sUserManager.exists(userId)) return null; 8548 mFlags = flags; 8549 return super.queryIntent(intent, resolvedType, 8550 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8551 } 8552 8553 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8554 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8555 if (!sUserManager.exists(userId)) return null; 8556 if (packageActivities == null) { 8557 return null; 8558 } 8559 mFlags = flags; 8560 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8561 final int N = packageActivities.size(); 8562 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8563 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8564 8565 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8566 for (int i = 0; i < N; ++i) { 8567 intentFilters = packageActivities.get(i).intents; 8568 if (intentFilters != null && intentFilters.size() > 0) { 8569 PackageParser.ActivityIntentInfo[] array = 8570 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8571 intentFilters.toArray(array); 8572 listCut.add(array); 8573 } 8574 } 8575 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8576 } 8577 8578 public final void addActivity(PackageParser.Activity a, String type) { 8579 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8580 mActivities.put(a.getComponentName(), a); 8581 if (DEBUG_SHOW_INFO) 8582 Log.v( 8583 TAG, " " + type + " " + 8584 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8585 if (DEBUG_SHOW_INFO) 8586 Log.v(TAG, " Class=" + a.info.name); 8587 final int NI = a.intents.size(); 8588 for (int j=0; j<NI; j++) { 8589 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8590 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8591 intent.setPriority(0); 8592 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8593 + a.className + " with priority > 0, forcing to 0"); 8594 } 8595 if (DEBUG_SHOW_INFO) { 8596 Log.v(TAG, " IntentFilter:"); 8597 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8598 } 8599 if (!intent.debugCheck()) { 8600 Log.w(TAG, "==> For Activity " + a.info.name); 8601 } 8602 addFilter(intent); 8603 } 8604 } 8605 8606 public final void removeActivity(PackageParser.Activity a, String type) { 8607 mActivities.remove(a.getComponentName()); 8608 if (DEBUG_SHOW_INFO) { 8609 Log.v(TAG, " " + type + " " 8610 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8611 : a.info.name) + ":"); 8612 Log.v(TAG, " Class=" + a.info.name); 8613 } 8614 final int NI = a.intents.size(); 8615 for (int j=0; j<NI; j++) { 8616 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8617 if (DEBUG_SHOW_INFO) { 8618 Log.v(TAG, " IntentFilter:"); 8619 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8620 } 8621 removeFilter(intent); 8622 } 8623 } 8624 8625 @Override 8626 protected boolean allowFilterResult( 8627 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8628 ActivityInfo filterAi = filter.activity.info; 8629 for (int i=dest.size()-1; i>=0; i--) { 8630 ActivityInfo destAi = dest.get(i).activityInfo; 8631 if (destAi.name == filterAi.name 8632 && destAi.packageName == filterAi.packageName) { 8633 return false; 8634 } 8635 } 8636 return true; 8637 } 8638 8639 @Override 8640 protected ActivityIntentInfo[] newArray(int size) { 8641 return new ActivityIntentInfo[size]; 8642 } 8643 8644 @Override 8645 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8646 if (!sUserManager.exists(userId)) return true; 8647 PackageParser.Package p = filter.activity.owner; 8648 if (p != null) { 8649 PackageSetting ps = (PackageSetting)p.mExtras; 8650 if (ps != null) { 8651 // System apps are never considered stopped for purposes of 8652 // filtering, because there may be no way for the user to 8653 // actually re-launch them. 8654 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8655 && ps.getStopped(userId); 8656 } 8657 } 8658 return false; 8659 } 8660 8661 @Override 8662 protected boolean isPackageForFilter(String packageName, 8663 PackageParser.ActivityIntentInfo info) { 8664 return packageName.equals(info.activity.owner.packageName); 8665 } 8666 8667 @Override 8668 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8669 int match, int userId) { 8670 if (!sUserManager.exists(userId)) return null; 8671 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8672 return null; 8673 } 8674 final PackageParser.Activity activity = info.activity; 8675 if (mSafeMode && (activity.info.applicationInfo.flags 8676 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8677 return null; 8678 } 8679 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8680 if (ps == null) { 8681 return null; 8682 } 8683 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8684 ps.readUserState(userId), userId); 8685 if (ai == null) { 8686 return null; 8687 } 8688 final ResolveInfo res = new ResolveInfo(); 8689 res.activityInfo = ai; 8690 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8691 res.filter = info; 8692 } 8693 if (info != null) { 8694 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8695 } 8696 res.priority = info.getPriority(); 8697 res.preferredOrder = activity.owner.mPreferredOrder; 8698 //System.out.println("Result: " + res.activityInfo.className + 8699 // " = " + res.priority); 8700 res.match = match; 8701 res.isDefault = info.hasDefault; 8702 res.labelRes = info.labelRes; 8703 res.nonLocalizedLabel = info.nonLocalizedLabel; 8704 if (userNeedsBadging(userId)) { 8705 res.noResourceId = true; 8706 } else { 8707 res.icon = info.icon; 8708 } 8709 res.iconResourceId = info.icon; 8710 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8711 return res; 8712 } 8713 8714 @Override 8715 protected void sortResults(List<ResolveInfo> results) { 8716 Collections.sort(results, mResolvePrioritySorter); 8717 } 8718 8719 @Override 8720 protected void dumpFilter(PrintWriter out, String prefix, 8721 PackageParser.ActivityIntentInfo filter) { 8722 out.print(prefix); out.print( 8723 Integer.toHexString(System.identityHashCode(filter.activity))); 8724 out.print(' '); 8725 filter.activity.printComponentShortName(out); 8726 out.print(" filter "); 8727 out.println(Integer.toHexString(System.identityHashCode(filter))); 8728 } 8729 8730 @Override 8731 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8732 return filter.activity; 8733 } 8734 8735 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8736 PackageParser.Activity activity = (PackageParser.Activity)label; 8737 out.print(prefix); out.print( 8738 Integer.toHexString(System.identityHashCode(activity))); 8739 out.print(' '); 8740 activity.printComponentShortName(out); 8741 if (count > 1) { 8742 out.print(" ("); out.print(count); out.print(" filters)"); 8743 } 8744 out.println(); 8745 } 8746 8747// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8748// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8749// final List<ResolveInfo> retList = Lists.newArrayList(); 8750// while (i.hasNext()) { 8751// final ResolveInfo resolveInfo = i.next(); 8752// if (isEnabledLP(resolveInfo.activityInfo)) { 8753// retList.add(resolveInfo); 8754// } 8755// } 8756// return retList; 8757// } 8758 8759 // Keys are String (activity class name), values are Activity. 8760 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8761 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8762 private int mFlags; 8763 } 8764 8765 private final class ServiceIntentResolver 8766 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8767 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8768 boolean defaultOnly, int userId) { 8769 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8770 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8771 } 8772 8773 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8774 int userId) { 8775 if (!sUserManager.exists(userId)) return null; 8776 mFlags = flags; 8777 return super.queryIntent(intent, resolvedType, 8778 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8779 } 8780 8781 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8782 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8783 if (!sUserManager.exists(userId)) return null; 8784 if (packageServices == null) { 8785 return null; 8786 } 8787 mFlags = flags; 8788 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8789 final int N = packageServices.size(); 8790 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8791 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8792 8793 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8794 for (int i = 0; i < N; ++i) { 8795 intentFilters = packageServices.get(i).intents; 8796 if (intentFilters != null && intentFilters.size() > 0) { 8797 PackageParser.ServiceIntentInfo[] array = 8798 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8799 intentFilters.toArray(array); 8800 listCut.add(array); 8801 } 8802 } 8803 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8804 } 8805 8806 public final void addService(PackageParser.Service s) { 8807 mServices.put(s.getComponentName(), s); 8808 if (DEBUG_SHOW_INFO) { 8809 Log.v(TAG, " " 8810 + (s.info.nonLocalizedLabel != null 8811 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8812 Log.v(TAG, " Class=" + s.info.name); 8813 } 8814 final int NI = s.intents.size(); 8815 int j; 8816 for (j=0; j<NI; j++) { 8817 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8818 if (DEBUG_SHOW_INFO) { 8819 Log.v(TAG, " IntentFilter:"); 8820 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8821 } 8822 if (!intent.debugCheck()) { 8823 Log.w(TAG, "==> For Service " + s.info.name); 8824 } 8825 addFilter(intent); 8826 } 8827 } 8828 8829 public final void removeService(PackageParser.Service s) { 8830 mServices.remove(s.getComponentName()); 8831 if (DEBUG_SHOW_INFO) { 8832 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8833 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8834 Log.v(TAG, " Class=" + s.info.name); 8835 } 8836 final int NI = s.intents.size(); 8837 int j; 8838 for (j=0; j<NI; j++) { 8839 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8840 if (DEBUG_SHOW_INFO) { 8841 Log.v(TAG, " IntentFilter:"); 8842 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8843 } 8844 removeFilter(intent); 8845 } 8846 } 8847 8848 @Override 8849 protected boolean allowFilterResult( 8850 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8851 ServiceInfo filterSi = filter.service.info; 8852 for (int i=dest.size()-1; i>=0; i--) { 8853 ServiceInfo destAi = dest.get(i).serviceInfo; 8854 if (destAi.name == filterSi.name 8855 && destAi.packageName == filterSi.packageName) { 8856 return false; 8857 } 8858 } 8859 return true; 8860 } 8861 8862 @Override 8863 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8864 return new PackageParser.ServiceIntentInfo[size]; 8865 } 8866 8867 @Override 8868 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8869 if (!sUserManager.exists(userId)) return true; 8870 PackageParser.Package p = filter.service.owner; 8871 if (p != null) { 8872 PackageSetting ps = (PackageSetting)p.mExtras; 8873 if (ps != null) { 8874 // System apps are never considered stopped for purposes of 8875 // filtering, because there may be no way for the user to 8876 // actually re-launch them. 8877 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8878 && ps.getStopped(userId); 8879 } 8880 } 8881 return false; 8882 } 8883 8884 @Override 8885 protected boolean isPackageForFilter(String packageName, 8886 PackageParser.ServiceIntentInfo info) { 8887 return packageName.equals(info.service.owner.packageName); 8888 } 8889 8890 @Override 8891 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8892 int match, int userId) { 8893 if (!sUserManager.exists(userId)) return null; 8894 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8895 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8896 return null; 8897 } 8898 final PackageParser.Service service = info.service; 8899 if (mSafeMode && (service.info.applicationInfo.flags 8900 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8901 return null; 8902 } 8903 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8904 if (ps == null) { 8905 return null; 8906 } 8907 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8908 ps.readUserState(userId), userId); 8909 if (si == null) { 8910 return null; 8911 } 8912 final ResolveInfo res = new ResolveInfo(); 8913 res.serviceInfo = si; 8914 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8915 res.filter = filter; 8916 } 8917 res.priority = info.getPriority(); 8918 res.preferredOrder = service.owner.mPreferredOrder; 8919 res.match = match; 8920 res.isDefault = info.hasDefault; 8921 res.labelRes = info.labelRes; 8922 res.nonLocalizedLabel = info.nonLocalizedLabel; 8923 res.icon = info.icon; 8924 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8925 return res; 8926 } 8927 8928 @Override 8929 protected void sortResults(List<ResolveInfo> results) { 8930 Collections.sort(results, mResolvePrioritySorter); 8931 } 8932 8933 @Override 8934 protected void dumpFilter(PrintWriter out, String prefix, 8935 PackageParser.ServiceIntentInfo filter) { 8936 out.print(prefix); out.print( 8937 Integer.toHexString(System.identityHashCode(filter.service))); 8938 out.print(' '); 8939 filter.service.printComponentShortName(out); 8940 out.print(" filter "); 8941 out.println(Integer.toHexString(System.identityHashCode(filter))); 8942 } 8943 8944 @Override 8945 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8946 return filter.service; 8947 } 8948 8949 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8950 PackageParser.Service service = (PackageParser.Service)label; 8951 out.print(prefix); out.print( 8952 Integer.toHexString(System.identityHashCode(service))); 8953 out.print(' '); 8954 service.printComponentShortName(out); 8955 if (count > 1) { 8956 out.print(" ("); out.print(count); out.print(" filters)"); 8957 } 8958 out.println(); 8959 } 8960 8961// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8962// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8963// final List<ResolveInfo> retList = Lists.newArrayList(); 8964// while (i.hasNext()) { 8965// final ResolveInfo resolveInfo = (ResolveInfo) i; 8966// if (isEnabledLP(resolveInfo.serviceInfo)) { 8967// retList.add(resolveInfo); 8968// } 8969// } 8970// return retList; 8971// } 8972 8973 // Keys are String (activity class name), values are Activity. 8974 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8975 = new ArrayMap<ComponentName, PackageParser.Service>(); 8976 private int mFlags; 8977 }; 8978 8979 private final class ProviderIntentResolver 8980 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8981 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8982 boolean defaultOnly, int userId) { 8983 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8984 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8985 } 8986 8987 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8988 int userId) { 8989 if (!sUserManager.exists(userId)) 8990 return null; 8991 mFlags = flags; 8992 return super.queryIntent(intent, resolvedType, 8993 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8994 } 8995 8996 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8997 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8998 if (!sUserManager.exists(userId)) 8999 return null; 9000 if (packageProviders == null) { 9001 return null; 9002 } 9003 mFlags = flags; 9004 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9005 final int N = packageProviders.size(); 9006 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9007 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9008 9009 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9010 for (int i = 0; i < N; ++i) { 9011 intentFilters = packageProviders.get(i).intents; 9012 if (intentFilters != null && intentFilters.size() > 0) { 9013 PackageParser.ProviderIntentInfo[] array = 9014 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9015 intentFilters.toArray(array); 9016 listCut.add(array); 9017 } 9018 } 9019 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9020 } 9021 9022 public final void addProvider(PackageParser.Provider p) { 9023 if (mProviders.containsKey(p.getComponentName())) { 9024 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9025 return; 9026 } 9027 9028 mProviders.put(p.getComponentName(), p); 9029 if (DEBUG_SHOW_INFO) { 9030 Log.v(TAG, " " 9031 + (p.info.nonLocalizedLabel != null 9032 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9033 Log.v(TAG, " Class=" + p.info.name); 9034 } 9035 final int NI = p.intents.size(); 9036 int j; 9037 for (j = 0; j < NI; j++) { 9038 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9039 if (DEBUG_SHOW_INFO) { 9040 Log.v(TAG, " IntentFilter:"); 9041 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9042 } 9043 if (!intent.debugCheck()) { 9044 Log.w(TAG, "==> For Provider " + p.info.name); 9045 } 9046 addFilter(intent); 9047 } 9048 } 9049 9050 public final void removeProvider(PackageParser.Provider p) { 9051 mProviders.remove(p.getComponentName()); 9052 if (DEBUG_SHOW_INFO) { 9053 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9054 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9055 Log.v(TAG, " Class=" + p.info.name); 9056 } 9057 final int NI = p.intents.size(); 9058 int j; 9059 for (j = 0; j < NI; j++) { 9060 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9061 if (DEBUG_SHOW_INFO) { 9062 Log.v(TAG, " IntentFilter:"); 9063 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9064 } 9065 removeFilter(intent); 9066 } 9067 } 9068 9069 @Override 9070 protected boolean allowFilterResult( 9071 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9072 ProviderInfo filterPi = filter.provider.info; 9073 for (int i = dest.size() - 1; i >= 0; i--) { 9074 ProviderInfo destPi = dest.get(i).providerInfo; 9075 if (destPi.name == filterPi.name 9076 && destPi.packageName == filterPi.packageName) { 9077 return false; 9078 } 9079 } 9080 return true; 9081 } 9082 9083 @Override 9084 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9085 return new PackageParser.ProviderIntentInfo[size]; 9086 } 9087 9088 @Override 9089 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9090 if (!sUserManager.exists(userId)) 9091 return true; 9092 PackageParser.Package p = filter.provider.owner; 9093 if (p != null) { 9094 PackageSetting ps = (PackageSetting) p.mExtras; 9095 if (ps != null) { 9096 // System apps are never considered stopped for purposes of 9097 // filtering, because there may be no way for the user to 9098 // actually re-launch them. 9099 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9100 && ps.getStopped(userId); 9101 } 9102 } 9103 return false; 9104 } 9105 9106 @Override 9107 protected boolean isPackageForFilter(String packageName, 9108 PackageParser.ProviderIntentInfo info) { 9109 return packageName.equals(info.provider.owner.packageName); 9110 } 9111 9112 @Override 9113 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9114 int match, int userId) { 9115 if (!sUserManager.exists(userId)) 9116 return null; 9117 final PackageParser.ProviderIntentInfo info = filter; 9118 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9119 return null; 9120 } 9121 final PackageParser.Provider provider = info.provider; 9122 if (mSafeMode && (provider.info.applicationInfo.flags 9123 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9124 return null; 9125 } 9126 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9127 if (ps == null) { 9128 return null; 9129 } 9130 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9131 ps.readUserState(userId), userId); 9132 if (pi == null) { 9133 return null; 9134 } 9135 final ResolveInfo res = new ResolveInfo(); 9136 res.providerInfo = pi; 9137 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9138 res.filter = filter; 9139 } 9140 res.priority = info.getPriority(); 9141 res.preferredOrder = provider.owner.mPreferredOrder; 9142 res.match = match; 9143 res.isDefault = info.hasDefault; 9144 res.labelRes = info.labelRes; 9145 res.nonLocalizedLabel = info.nonLocalizedLabel; 9146 res.icon = info.icon; 9147 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9148 return res; 9149 } 9150 9151 @Override 9152 protected void sortResults(List<ResolveInfo> results) { 9153 Collections.sort(results, mResolvePrioritySorter); 9154 } 9155 9156 @Override 9157 protected void dumpFilter(PrintWriter out, String prefix, 9158 PackageParser.ProviderIntentInfo filter) { 9159 out.print(prefix); 9160 out.print( 9161 Integer.toHexString(System.identityHashCode(filter.provider))); 9162 out.print(' '); 9163 filter.provider.printComponentShortName(out); 9164 out.print(" filter "); 9165 out.println(Integer.toHexString(System.identityHashCode(filter))); 9166 } 9167 9168 @Override 9169 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9170 return filter.provider; 9171 } 9172 9173 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9174 PackageParser.Provider provider = (PackageParser.Provider)label; 9175 out.print(prefix); out.print( 9176 Integer.toHexString(System.identityHashCode(provider))); 9177 out.print(' '); 9178 provider.printComponentShortName(out); 9179 if (count > 1) { 9180 out.print(" ("); out.print(count); out.print(" filters)"); 9181 } 9182 out.println(); 9183 } 9184 9185 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9186 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9187 private int mFlags; 9188 }; 9189 9190 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9191 new Comparator<ResolveInfo>() { 9192 public int compare(ResolveInfo r1, ResolveInfo r2) { 9193 int v1 = r1.priority; 9194 int v2 = r2.priority; 9195 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9196 if (v1 != v2) { 9197 return (v1 > v2) ? -1 : 1; 9198 } 9199 v1 = r1.preferredOrder; 9200 v2 = r2.preferredOrder; 9201 if (v1 != v2) { 9202 return (v1 > v2) ? -1 : 1; 9203 } 9204 if (r1.isDefault != r2.isDefault) { 9205 return r1.isDefault ? -1 : 1; 9206 } 9207 v1 = r1.match; 9208 v2 = r2.match; 9209 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9210 if (v1 != v2) { 9211 return (v1 > v2) ? -1 : 1; 9212 } 9213 if (r1.system != r2.system) { 9214 return r1.system ? -1 : 1; 9215 } 9216 return 0; 9217 } 9218 }; 9219 9220 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9221 new Comparator<ProviderInfo>() { 9222 public int compare(ProviderInfo p1, ProviderInfo p2) { 9223 final int v1 = p1.initOrder; 9224 final int v2 = p2.initOrder; 9225 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9226 } 9227 }; 9228 9229 final void sendPackageBroadcast(final String action, final String pkg, 9230 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9231 final int[] userIds) { 9232 mHandler.post(new Runnable() { 9233 @Override 9234 public void run() { 9235 try { 9236 final IActivityManager am = ActivityManagerNative.getDefault(); 9237 if (am == null) return; 9238 final int[] resolvedUserIds; 9239 if (userIds == null) { 9240 resolvedUserIds = am.getRunningUserIds(); 9241 } else { 9242 resolvedUserIds = userIds; 9243 } 9244 for (int id : resolvedUserIds) { 9245 final Intent intent = new Intent(action, 9246 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9247 if (extras != null) { 9248 intent.putExtras(extras); 9249 } 9250 if (targetPkg != null) { 9251 intent.setPackage(targetPkg); 9252 } 9253 // Modify the UID when posting to other users 9254 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9255 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9256 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9257 intent.putExtra(Intent.EXTRA_UID, uid); 9258 } 9259 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9260 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9261 if (DEBUG_BROADCASTS) { 9262 RuntimeException here = new RuntimeException("here"); 9263 here.fillInStackTrace(); 9264 Slog.d(TAG, "Sending to user " + id + ": " 9265 + intent.toShortString(false, true, false, false) 9266 + " " + intent.getExtras(), here); 9267 } 9268 am.broadcastIntent(null, intent, null, finishedReceiver, 9269 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9270 null, finishedReceiver != null, false, id); 9271 } 9272 } catch (RemoteException ex) { 9273 } 9274 } 9275 }); 9276 } 9277 9278 /** 9279 * Check if the external storage media is available. This is true if there 9280 * is a mounted external storage medium or if the external storage is 9281 * emulated. 9282 */ 9283 private boolean isExternalMediaAvailable() { 9284 return mMediaMounted || Environment.isExternalStorageEmulated(); 9285 } 9286 9287 @Override 9288 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9289 // writer 9290 synchronized (mPackages) { 9291 if (!isExternalMediaAvailable()) { 9292 // If the external storage is no longer mounted at this point, 9293 // the caller may not have been able to delete all of this 9294 // packages files and can not delete any more. Bail. 9295 return null; 9296 } 9297 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9298 if (lastPackage != null) { 9299 pkgs.remove(lastPackage); 9300 } 9301 if (pkgs.size() > 0) { 9302 return pkgs.get(0); 9303 } 9304 } 9305 return null; 9306 } 9307 9308 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9309 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9310 userId, andCode ? 1 : 0, packageName); 9311 if (mSystemReady) { 9312 msg.sendToTarget(); 9313 } else { 9314 if (mPostSystemReadyMessages == null) { 9315 mPostSystemReadyMessages = new ArrayList<>(); 9316 } 9317 mPostSystemReadyMessages.add(msg); 9318 } 9319 } 9320 9321 void startCleaningPackages() { 9322 // reader 9323 synchronized (mPackages) { 9324 if (!isExternalMediaAvailable()) { 9325 return; 9326 } 9327 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9328 return; 9329 } 9330 } 9331 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9332 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9333 IActivityManager am = ActivityManagerNative.getDefault(); 9334 if (am != null) { 9335 try { 9336 am.startService(null, intent, null, mContext.getOpPackageName(), 9337 UserHandle.USER_OWNER); 9338 } catch (RemoteException e) { 9339 } 9340 } 9341 } 9342 9343 @Override 9344 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9345 int installFlags, String installerPackageName, VerificationParams verificationParams, 9346 String packageAbiOverride) { 9347 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9348 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9349 } 9350 9351 @Override 9352 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9353 int installFlags, String installerPackageName, VerificationParams verificationParams, 9354 String packageAbiOverride, int userId) { 9355 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9356 9357 final int callingUid = Binder.getCallingUid(); 9358 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9359 9360 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9361 try { 9362 if (observer != null) { 9363 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9364 } 9365 } catch (RemoteException re) { 9366 } 9367 return; 9368 } 9369 9370 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9371 installFlags |= PackageManager.INSTALL_FROM_ADB; 9372 9373 } else { 9374 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9375 // about installerPackageName. 9376 9377 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9378 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9379 } 9380 9381 UserHandle user; 9382 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9383 user = UserHandle.ALL; 9384 } else { 9385 user = new UserHandle(userId); 9386 } 9387 9388 // Only system components can circumvent runtime permissions when installing. 9389 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9390 && mContext.checkCallingOrSelfPermission(Manifest.permission 9391 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9392 throw new SecurityException("You need the " 9393 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9394 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9395 } 9396 9397 verificationParams.setInstallerUid(callingUid); 9398 9399 final File originFile = new File(originPath); 9400 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9401 9402 final Message msg = mHandler.obtainMessage(INIT_COPY); 9403 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9404 null, verificationParams, user, packageAbiOverride); 9405 mHandler.sendMessage(msg); 9406 } 9407 9408 void installStage(String packageName, File stagedDir, String stagedCid, 9409 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9410 String installerPackageName, int installerUid, UserHandle user) { 9411 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9412 params.referrerUri, installerUid, null); 9413 verifParams.setInstallerUid(installerUid); 9414 9415 final OriginInfo origin; 9416 if (stagedDir != null) { 9417 origin = OriginInfo.fromStagedFile(stagedDir); 9418 } else { 9419 origin = OriginInfo.fromStagedContainer(stagedCid); 9420 } 9421 9422 final Message msg = mHandler.obtainMessage(INIT_COPY); 9423 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9424 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9425 mHandler.sendMessage(msg); 9426 } 9427 9428 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9429 Bundle extras = new Bundle(1); 9430 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9431 9432 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9433 packageName, extras, null, null, new int[] {userId}); 9434 try { 9435 IActivityManager am = ActivityManagerNative.getDefault(); 9436 final boolean isSystem = 9437 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9438 if (isSystem && am.isUserRunning(userId, false)) { 9439 // The just-installed/enabled app is bundled on the system, so presumed 9440 // to be able to run automatically without needing an explicit launch. 9441 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9442 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9443 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9444 .setPackage(packageName); 9445 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9446 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9447 } 9448 } catch (RemoteException e) { 9449 // shouldn't happen 9450 Slog.w(TAG, "Unable to bootstrap installed package", e); 9451 } 9452 } 9453 9454 @Override 9455 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9456 int userId) { 9457 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9458 PackageSetting pkgSetting; 9459 final int uid = Binder.getCallingUid(); 9460 enforceCrossUserPermission(uid, userId, true, true, 9461 "setApplicationHiddenSetting for user " + userId); 9462 9463 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9464 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9465 return false; 9466 } 9467 9468 long callingId = Binder.clearCallingIdentity(); 9469 try { 9470 boolean sendAdded = false; 9471 boolean sendRemoved = false; 9472 // writer 9473 synchronized (mPackages) { 9474 pkgSetting = mSettings.mPackages.get(packageName); 9475 if (pkgSetting == null) { 9476 return false; 9477 } 9478 if (pkgSetting.getHidden(userId) != hidden) { 9479 pkgSetting.setHidden(hidden, userId); 9480 mSettings.writePackageRestrictionsLPr(userId); 9481 if (hidden) { 9482 sendRemoved = true; 9483 } else { 9484 sendAdded = true; 9485 } 9486 } 9487 } 9488 if (sendAdded) { 9489 sendPackageAddedForUser(packageName, pkgSetting, userId); 9490 return true; 9491 } 9492 if (sendRemoved) { 9493 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9494 "hiding pkg"); 9495 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9496 } 9497 } finally { 9498 Binder.restoreCallingIdentity(callingId); 9499 } 9500 return false; 9501 } 9502 9503 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9504 int userId) { 9505 final PackageRemovedInfo info = new PackageRemovedInfo(); 9506 info.removedPackage = packageName; 9507 info.removedUsers = new int[] {userId}; 9508 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9509 info.sendBroadcast(false, false, false); 9510 } 9511 9512 /** 9513 * Returns true if application is not found or there was an error. Otherwise it returns 9514 * the hidden state of the package for the given user. 9515 */ 9516 @Override 9517 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9518 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9519 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9520 false, "getApplicationHidden for user " + userId); 9521 PackageSetting pkgSetting; 9522 long callingId = Binder.clearCallingIdentity(); 9523 try { 9524 // writer 9525 synchronized (mPackages) { 9526 pkgSetting = mSettings.mPackages.get(packageName); 9527 if (pkgSetting == null) { 9528 return true; 9529 } 9530 return pkgSetting.getHidden(userId); 9531 } 9532 } finally { 9533 Binder.restoreCallingIdentity(callingId); 9534 } 9535 } 9536 9537 /** 9538 * @hide 9539 */ 9540 @Override 9541 public int installExistingPackageAsUser(String packageName, int userId) { 9542 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9543 null); 9544 PackageSetting pkgSetting; 9545 final int uid = Binder.getCallingUid(); 9546 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9547 + userId); 9548 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9549 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9550 } 9551 9552 long callingId = Binder.clearCallingIdentity(); 9553 try { 9554 boolean sendAdded = false; 9555 9556 // writer 9557 synchronized (mPackages) { 9558 pkgSetting = mSettings.mPackages.get(packageName); 9559 if (pkgSetting == null) { 9560 return PackageManager.INSTALL_FAILED_INVALID_URI; 9561 } 9562 if (!pkgSetting.getInstalled(userId)) { 9563 pkgSetting.setInstalled(true, userId); 9564 pkgSetting.setHidden(false, userId); 9565 mSettings.writePackageRestrictionsLPr(userId); 9566 sendAdded = true; 9567 } 9568 } 9569 9570 if (sendAdded) { 9571 sendPackageAddedForUser(packageName, pkgSetting, userId); 9572 } 9573 } finally { 9574 Binder.restoreCallingIdentity(callingId); 9575 } 9576 9577 return PackageManager.INSTALL_SUCCEEDED; 9578 } 9579 9580 boolean isUserRestricted(int userId, String restrictionKey) { 9581 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9582 if (restrictions.getBoolean(restrictionKey, false)) { 9583 Log.w(TAG, "User is restricted: " + restrictionKey); 9584 return true; 9585 } 9586 return false; 9587 } 9588 9589 @Override 9590 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9591 mContext.enforceCallingOrSelfPermission( 9592 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9593 "Only package verification agents can verify applications"); 9594 9595 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9596 final PackageVerificationResponse response = new PackageVerificationResponse( 9597 verificationCode, Binder.getCallingUid()); 9598 msg.arg1 = id; 9599 msg.obj = response; 9600 mHandler.sendMessage(msg); 9601 } 9602 9603 @Override 9604 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9605 long millisecondsToDelay) { 9606 mContext.enforceCallingOrSelfPermission( 9607 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9608 "Only package verification agents can extend verification timeouts"); 9609 9610 final PackageVerificationState state = mPendingVerification.get(id); 9611 final PackageVerificationResponse response = new PackageVerificationResponse( 9612 verificationCodeAtTimeout, Binder.getCallingUid()); 9613 9614 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9615 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9616 } 9617 if (millisecondsToDelay < 0) { 9618 millisecondsToDelay = 0; 9619 } 9620 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9621 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9622 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9623 } 9624 9625 if ((state != null) && !state.timeoutExtended()) { 9626 state.extendTimeout(); 9627 9628 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9629 msg.arg1 = id; 9630 msg.obj = response; 9631 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9632 } 9633 } 9634 9635 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9636 int verificationCode, UserHandle user) { 9637 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9638 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9639 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9640 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9641 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9642 9643 mContext.sendBroadcastAsUser(intent, user, 9644 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9645 } 9646 9647 private ComponentName matchComponentForVerifier(String packageName, 9648 List<ResolveInfo> receivers) { 9649 ActivityInfo targetReceiver = null; 9650 9651 final int NR = receivers.size(); 9652 for (int i = 0; i < NR; i++) { 9653 final ResolveInfo info = receivers.get(i); 9654 if (info.activityInfo == null) { 9655 continue; 9656 } 9657 9658 if (packageName.equals(info.activityInfo.packageName)) { 9659 targetReceiver = info.activityInfo; 9660 break; 9661 } 9662 } 9663 9664 if (targetReceiver == null) { 9665 return null; 9666 } 9667 9668 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9669 } 9670 9671 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9672 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9673 if (pkgInfo.verifiers.length == 0) { 9674 return null; 9675 } 9676 9677 final int N = pkgInfo.verifiers.length; 9678 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9679 for (int i = 0; i < N; i++) { 9680 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9681 9682 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9683 receivers); 9684 if (comp == null) { 9685 continue; 9686 } 9687 9688 final int verifierUid = getUidForVerifier(verifierInfo); 9689 if (verifierUid == -1) { 9690 continue; 9691 } 9692 9693 if (DEBUG_VERIFY) { 9694 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9695 + " with the correct signature"); 9696 } 9697 sufficientVerifiers.add(comp); 9698 verificationState.addSufficientVerifier(verifierUid); 9699 } 9700 9701 return sufficientVerifiers; 9702 } 9703 9704 private int getUidForVerifier(VerifierInfo verifierInfo) { 9705 synchronized (mPackages) { 9706 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9707 if (pkg == null) { 9708 return -1; 9709 } else if (pkg.mSignatures.length != 1) { 9710 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9711 + " has more than one signature; ignoring"); 9712 return -1; 9713 } 9714 9715 /* 9716 * If the public key of the package's signature does not match 9717 * our expected public key, then this is a different package and 9718 * we should skip. 9719 */ 9720 9721 final byte[] expectedPublicKey; 9722 try { 9723 final Signature verifierSig = pkg.mSignatures[0]; 9724 final PublicKey publicKey = verifierSig.getPublicKey(); 9725 expectedPublicKey = publicKey.getEncoded(); 9726 } catch (CertificateException e) { 9727 return -1; 9728 } 9729 9730 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9731 9732 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9733 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9734 + " does not have the expected public key; ignoring"); 9735 return -1; 9736 } 9737 9738 return pkg.applicationInfo.uid; 9739 } 9740 } 9741 9742 @Override 9743 public void finishPackageInstall(int token) { 9744 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9745 9746 if (DEBUG_INSTALL) { 9747 Slog.v(TAG, "BM finishing package install for " + token); 9748 } 9749 9750 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9751 mHandler.sendMessage(msg); 9752 } 9753 9754 /** 9755 * Get the verification agent timeout. 9756 * 9757 * @return verification timeout in milliseconds 9758 */ 9759 private long getVerificationTimeout() { 9760 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9761 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9762 DEFAULT_VERIFICATION_TIMEOUT); 9763 } 9764 9765 /** 9766 * Get the default verification agent response code. 9767 * 9768 * @return default verification response code 9769 */ 9770 private int getDefaultVerificationResponse() { 9771 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9772 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9773 DEFAULT_VERIFICATION_RESPONSE); 9774 } 9775 9776 /** 9777 * Check whether or not package verification has been enabled. 9778 * 9779 * @return true if verification should be performed 9780 */ 9781 private boolean isVerificationEnabled(int userId, int installFlags) { 9782 if (!DEFAULT_VERIFY_ENABLE) { 9783 return false; 9784 } 9785 9786 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9787 9788 // Check if installing from ADB 9789 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9790 // Do not run verification in a test harness environment 9791 if (ActivityManager.isRunningInTestHarness()) { 9792 return false; 9793 } 9794 if (ensureVerifyAppsEnabled) { 9795 return true; 9796 } 9797 // Check if the developer does not want package verification for ADB installs 9798 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9799 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9800 return false; 9801 } 9802 } 9803 9804 if (ensureVerifyAppsEnabled) { 9805 return true; 9806 } 9807 9808 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9809 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9810 } 9811 9812 @Override 9813 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9814 throws RemoteException { 9815 mContext.enforceCallingOrSelfPermission( 9816 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9817 "Only intentfilter verification agents can verify applications"); 9818 9819 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9820 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9821 Binder.getCallingUid(), verificationCode, failedDomains); 9822 msg.arg1 = id; 9823 msg.obj = response; 9824 mHandler.sendMessage(msg); 9825 } 9826 9827 @Override 9828 public int getIntentVerificationStatus(String packageName, int userId) { 9829 synchronized (mPackages) { 9830 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9831 } 9832 } 9833 9834 @Override 9835 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9836 mContext.enforceCallingOrSelfPermission( 9837 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9838 9839 boolean result = false; 9840 synchronized (mPackages) { 9841 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9842 } 9843 if (result) { 9844 scheduleWritePackageRestrictionsLocked(userId); 9845 } 9846 return result; 9847 } 9848 9849 @Override 9850 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9851 synchronized (mPackages) { 9852 return mSettings.getIntentFilterVerificationsLPr(packageName); 9853 } 9854 } 9855 9856 @Override 9857 public List<IntentFilter> getAllIntentFilters(String packageName) { 9858 if (TextUtils.isEmpty(packageName)) { 9859 return Collections.<IntentFilter>emptyList(); 9860 } 9861 synchronized (mPackages) { 9862 PackageParser.Package pkg = mPackages.get(packageName); 9863 if (pkg == null || pkg.activities == null) { 9864 return Collections.<IntentFilter>emptyList(); 9865 } 9866 final int count = pkg.activities.size(); 9867 ArrayList<IntentFilter> result = new ArrayList<>(); 9868 for (int n=0; n<count; n++) { 9869 PackageParser.Activity activity = pkg.activities.get(n); 9870 if (activity.intents != null || activity.intents.size() > 0) { 9871 result.addAll(activity.intents); 9872 } 9873 } 9874 return result; 9875 } 9876 } 9877 9878 @Override 9879 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9880 mContext.enforceCallingOrSelfPermission( 9881 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9882 9883 synchronized (mPackages) { 9884 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9885 if (packageName != null) { 9886 result |= updateIntentVerificationStatus(packageName, 9887 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9888 UserHandle.myUserId()); 9889 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9890 packageName, userId); 9891 } 9892 return result; 9893 } 9894 } 9895 9896 @Override 9897 public String getDefaultBrowserPackageName(int userId) { 9898 synchronized (mPackages) { 9899 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9900 } 9901 } 9902 9903 /** 9904 * Get the "allow unknown sources" setting. 9905 * 9906 * @return the current "allow unknown sources" setting 9907 */ 9908 private int getUnknownSourcesSettings() { 9909 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9910 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9911 -1); 9912 } 9913 9914 @Override 9915 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9916 final int uid = Binder.getCallingUid(); 9917 // writer 9918 synchronized (mPackages) { 9919 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9920 if (targetPackageSetting == null) { 9921 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9922 } 9923 9924 PackageSetting installerPackageSetting; 9925 if (installerPackageName != null) { 9926 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9927 if (installerPackageSetting == null) { 9928 throw new IllegalArgumentException("Unknown installer package: " 9929 + installerPackageName); 9930 } 9931 } else { 9932 installerPackageSetting = null; 9933 } 9934 9935 Signature[] callerSignature; 9936 Object obj = mSettings.getUserIdLPr(uid); 9937 if (obj != null) { 9938 if (obj instanceof SharedUserSetting) { 9939 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9940 } else if (obj instanceof PackageSetting) { 9941 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9942 } else { 9943 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9944 } 9945 } else { 9946 throw new SecurityException("Unknown calling uid " + uid); 9947 } 9948 9949 // Verify: can't set installerPackageName to a package that is 9950 // not signed with the same cert as the caller. 9951 if (installerPackageSetting != null) { 9952 if (compareSignatures(callerSignature, 9953 installerPackageSetting.signatures.mSignatures) 9954 != PackageManager.SIGNATURE_MATCH) { 9955 throw new SecurityException( 9956 "Caller does not have same cert as new installer package " 9957 + installerPackageName); 9958 } 9959 } 9960 9961 // Verify: if target already has an installer package, it must 9962 // be signed with the same cert as the caller. 9963 if (targetPackageSetting.installerPackageName != null) { 9964 PackageSetting setting = mSettings.mPackages.get( 9965 targetPackageSetting.installerPackageName); 9966 // If the currently set package isn't valid, then it's always 9967 // okay to change it. 9968 if (setting != null) { 9969 if (compareSignatures(callerSignature, 9970 setting.signatures.mSignatures) 9971 != PackageManager.SIGNATURE_MATCH) { 9972 throw new SecurityException( 9973 "Caller does not have same cert as old installer package " 9974 + targetPackageSetting.installerPackageName); 9975 } 9976 } 9977 } 9978 9979 // Okay! 9980 targetPackageSetting.installerPackageName = installerPackageName; 9981 scheduleWriteSettingsLocked(); 9982 } 9983 } 9984 9985 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9986 // Queue up an async operation since the package installation may take a little while. 9987 mHandler.post(new Runnable() { 9988 public void run() { 9989 mHandler.removeCallbacks(this); 9990 // Result object to be returned 9991 PackageInstalledInfo res = new PackageInstalledInfo(); 9992 res.returnCode = currentStatus; 9993 res.uid = -1; 9994 res.pkg = null; 9995 res.removedInfo = new PackageRemovedInfo(); 9996 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9997 args.doPreInstall(res.returnCode); 9998 synchronized (mInstallLock) { 9999 installPackageLI(args, res); 10000 } 10001 args.doPostInstall(res.returnCode, res.uid); 10002 } 10003 10004 // A restore should be performed at this point if (a) the install 10005 // succeeded, (b) the operation is not an update, and (c) the new 10006 // package has not opted out of backup participation. 10007 final boolean update = res.removedInfo.removedPackage != null; 10008 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10009 boolean doRestore = !update 10010 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10011 10012 // Set up the post-install work request bookkeeping. This will be used 10013 // and cleaned up by the post-install event handling regardless of whether 10014 // there's a restore pass performed. Token values are >= 1. 10015 int token; 10016 if (mNextInstallToken < 0) mNextInstallToken = 1; 10017 token = mNextInstallToken++; 10018 10019 PostInstallData data = new PostInstallData(args, res); 10020 mRunningInstalls.put(token, data); 10021 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10022 10023 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10024 // Pass responsibility to the Backup Manager. It will perform a 10025 // restore if appropriate, then pass responsibility back to the 10026 // Package Manager to run the post-install observer callbacks 10027 // and broadcasts. 10028 IBackupManager bm = IBackupManager.Stub.asInterface( 10029 ServiceManager.getService(Context.BACKUP_SERVICE)); 10030 if (bm != null) { 10031 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10032 + " to BM for possible restore"); 10033 try { 10034 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10035 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10036 } else { 10037 doRestore = false; 10038 } 10039 } catch (RemoteException e) { 10040 // can't happen; the backup manager is local 10041 } catch (Exception e) { 10042 Slog.e(TAG, "Exception trying to enqueue restore", e); 10043 doRestore = false; 10044 } 10045 } else { 10046 Slog.e(TAG, "Backup Manager not found!"); 10047 doRestore = false; 10048 } 10049 } 10050 10051 if (!doRestore) { 10052 // No restore possible, or the Backup Manager was mysteriously not 10053 // available -- just fire the post-install work request directly. 10054 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10055 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10056 mHandler.sendMessage(msg); 10057 } 10058 } 10059 }); 10060 } 10061 10062 private abstract class HandlerParams { 10063 private static final int MAX_RETRIES = 4; 10064 10065 /** 10066 * Number of times startCopy() has been attempted and had a non-fatal 10067 * error. 10068 */ 10069 private int mRetries = 0; 10070 10071 /** User handle for the user requesting the information or installation. */ 10072 private final UserHandle mUser; 10073 10074 HandlerParams(UserHandle user) { 10075 mUser = user; 10076 } 10077 10078 UserHandle getUser() { 10079 return mUser; 10080 } 10081 10082 final boolean startCopy() { 10083 boolean res; 10084 try { 10085 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10086 10087 if (++mRetries > MAX_RETRIES) { 10088 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10089 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10090 handleServiceError(); 10091 return false; 10092 } else { 10093 handleStartCopy(); 10094 res = true; 10095 } 10096 } catch (RemoteException e) { 10097 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10098 mHandler.sendEmptyMessage(MCS_RECONNECT); 10099 res = false; 10100 } 10101 handleReturnCode(); 10102 return res; 10103 } 10104 10105 final void serviceError() { 10106 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10107 handleServiceError(); 10108 handleReturnCode(); 10109 } 10110 10111 abstract void handleStartCopy() throws RemoteException; 10112 abstract void handleServiceError(); 10113 abstract void handleReturnCode(); 10114 } 10115 10116 class MeasureParams extends HandlerParams { 10117 private final PackageStats mStats; 10118 private boolean mSuccess; 10119 10120 private final IPackageStatsObserver mObserver; 10121 10122 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10123 super(new UserHandle(stats.userHandle)); 10124 mObserver = observer; 10125 mStats = stats; 10126 } 10127 10128 @Override 10129 public String toString() { 10130 return "MeasureParams{" 10131 + Integer.toHexString(System.identityHashCode(this)) 10132 + " " + mStats.packageName + "}"; 10133 } 10134 10135 @Override 10136 void handleStartCopy() throws RemoteException { 10137 synchronized (mInstallLock) { 10138 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10139 } 10140 10141 if (mSuccess) { 10142 final boolean mounted; 10143 if (Environment.isExternalStorageEmulated()) { 10144 mounted = true; 10145 } else { 10146 final String status = Environment.getExternalStorageState(); 10147 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10148 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10149 } 10150 10151 if (mounted) { 10152 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10153 10154 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10155 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10156 10157 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10158 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10159 10160 // Always subtract cache size, since it's a subdirectory 10161 mStats.externalDataSize -= mStats.externalCacheSize; 10162 10163 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10164 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10165 10166 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10167 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10168 } 10169 } 10170 } 10171 10172 @Override 10173 void handleReturnCode() { 10174 if (mObserver != null) { 10175 try { 10176 mObserver.onGetStatsCompleted(mStats, mSuccess); 10177 } catch (RemoteException e) { 10178 Slog.i(TAG, "Observer no longer exists."); 10179 } 10180 } 10181 } 10182 10183 @Override 10184 void handleServiceError() { 10185 Slog.e(TAG, "Could not measure application " + mStats.packageName 10186 + " external storage"); 10187 } 10188 } 10189 10190 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10191 throws RemoteException { 10192 long result = 0; 10193 for (File path : paths) { 10194 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10195 } 10196 return result; 10197 } 10198 10199 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10200 for (File path : paths) { 10201 try { 10202 mcs.clearDirectory(path.getAbsolutePath()); 10203 } catch (RemoteException e) { 10204 } 10205 } 10206 } 10207 10208 static class OriginInfo { 10209 /** 10210 * Location where install is coming from, before it has been 10211 * copied/renamed into place. This could be a single monolithic APK 10212 * file, or a cluster directory. This location may be untrusted. 10213 */ 10214 final File file; 10215 final String cid; 10216 10217 /** 10218 * Flag indicating that {@link #file} or {@link #cid} has already been 10219 * staged, meaning downstream users don't need to defensively copy the 10220 * contents. 10221 */ 10222 final boolean staged; 10223 10224 /** 10225 * Flag indicating that {@link #file} or {@link #cid} is an already 10226 * installed app that is being moved. 10227 */ 10228 final boolean existing; 10229 10230 final String resolvedPath; 10231 final File resolvedFile; 10232 10233 static OriginInfo fromNothing() { 10234 return new OriginInfo(null, null, false, false); 10235 } 10236 10237 static OriginInfo fromUntrustedFile(File file) { 10238 return new OriginInfo(file, null, false, false); 10239 } 10240 10241 static OriginInfo fromExistingFile(File file) { 10242 return new OriginInfo(file, null, false, true); 10243 } 10244 10245 static OriginInfo fromStagedFile(File file) { 10246 return new OriginInfo(file, null, true, false); 10247 } 10248 10249 static OriginInfo fromStagedContainer(String cid) { 10250 return new OriginInfo(null, cid, true, false); 10251 } 10252 10253 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10254 this.file = file; 10255 this.cid = cid; 10256 this.staged = staged; 10257 this.existing = existing; 10258 10259 if (cid != null) { 10260 resolvedPath = PackageHelper.getSdDir(cid); 10261 resolvedFile = new File(resolvedPath); 10262 } else if (file != null) { 10263 resolvedPath = file.getAbsolutePath(); 10264 resolvedFile = file; 10265 } else { 10266 resolvedPath = null; 10267 resolvedFile = null; 10268 } 10269 } 10270 } 10271 10272 class MoveInfo { 10273 final int moveId; 10274 final String fromUuid; 10275 final String toUuid; 10276 final String packageName; 10277 final String dataAppName; 10278 final int appId; 10279 final String seinfo; 10280 10281 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10282 String dataAppName, int appId, String seinfo) { 10283 this.moveId = moveId; 10284 this.fromUuid = fromUuid; 10285 this.toUuid = toUuid; 10286 this.packageName = packageName; 10287 this.dataAppName = dataAppName; 10288 this.appId = appId; 10289 this.seinfo = seinfo; 10290 } 10291 } 10292 10293 class InstallParams extends HandlerParams { 10294 final OriginInfo origin; 10295 final MoveInfo move; 10296 final IPackageInstallObserver2 observer; 10297 int installFlags; 10298 final String installerPackageName; 10299 final String volumeUuid; 10300 final VerificationParams verificationParams; 10301 private InstallArgs mArgs; 10302 private int mRet; 10303 final String packageAbiOverride; 10304 10305 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10306 int installFlags, String installerPackageName, String volumeUuid, 10307 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10308 super(user); 10309 this.origin = origin; 10310 this.move = move; 10311 this.observer = observer; 10312 this.installFlags = installFlags; 10313 this.installerPackageName = installerPackageName; 10314 this.volumeUuid = volumeUuid; 10315 this.verificationParams = verificationParams; 10316 this.packageAbiOverride = packageAbiOverride; 10317 } 10318 10319 @Override 10320 public String toString() { 10321 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10322 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10323 } 10324 10325 public ManifestDigest getManifestDigest() { 10326 if (verificationParams == null) { 10327 return null; 10328 } 10329 return verificationParams.getManifestDigest(); 10330 } 10331 10332 private int installLocationPolicy(PackageInfoLite pkgLite) { 10333 String packageName = pkgLite.packageName; 10334 int installLocation = pkgLite.installLocation; 10335 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10336 // reader 10337 synchronized (mPackages) { 10338 PackageParser.Package pkg = mPackages.get(packageName); 10339 if (pkg != null) { 10340 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10341 // Check for downgrading. 10342 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10343 try { 10344 checkDowngrade(pkg, pkgLite); 10345 } catch (PackageManagerException e) { 10346 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10347 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10348 } 10349 } 10350 // Check for updated system application. 10351 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10352 if (onSd) { 10353 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10354 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10355 } 10356 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10357 } else { 10358 if (onSd) { 10359 // Install flag overrides everything. 10360 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10361 } 10362 // If current upgrade specifies particular preference 10363 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10364 // Application explicitly specified internal. 10365 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10366 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10367 // App explictly prefers external. Let policy decide 10368 } else { 10369 // Prefer previous location 10370 if (isExternal(pkg)) { 10371 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10372 } 10373 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10374 } 10375 } 10376 } else { 10377 // Invalid install. Return error code 10378 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10379 } 10380 } 10381 } 10382 // All the special cases have been taken care of. 10383 // Return result based on recommended install location. 10384 if (onSd) { 10385 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10386 } 10387 return pkgLite.recommendedInstallLocation; 10388 } 10389 10390 /* 10391 * Invoke remote method to get package information and install 10392 * location values. Override install location based on default 10393 * policy if needed and then create install arguments based 10394 * on the install location. 10395 */ 10396 public void handleStartCopy() throws RemoteException { 10397 int ret = PackageManager.INSTALL_SUCCEEDED; 10398 10399 // If we're already staged, we've firmly committed to an install location 10400 if (origin.staged) { 10401 if (origin.file != null) { 10402 installFlags |= PackageManager.INSTALL_INTERNAL; 10403 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10404 } else if (origin.cid != null) { 10405 installFlags |= PackageManager.INSTALL_EXTERNAL; 10406 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10407 } else { 10408 throw new IllegalStateException("Invalid stage location"); 10409 } 10410 } 10411 10412 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10413 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10414 10415 PackageInfoLite pkgLite = null; 10416 10417 if (onInt && onSd) { 10418 // Check if both bits are set. 10419 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10420 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10421 } else { 10422 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10423 packageAbiOverride); 10424 10425 /* 10426 * If we have too little free space, try to free cache 10427 * before giving up. 10428 */ 10429 if (!origin.staged && pkgLite.recommendedInstallLocation 10430 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10431 // TODO: focus freeing disk space on the target device 10432 final StorageManager storage = StorageManager.from(mContext); 10433 final long lowThreshold = storage.getStorageLowBytes( 10434 Environment.getDataDirectory()); 10435 10436 final long sizeBytes = mContainerService.calculateInstalledSize( 10437 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10438 10439 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10440 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10441 installFlags, packageAbiOverride); 10442 } 10443 10444 /* 10445 * The cache free must have deleted the file we 10446 * downloaded to install. 10447 * 10448 * TODO: fix the "freeCache" call to not delete 10449 * the file we care about. 10450 */ 10451 if (pkgLite.recommendedInstallLocation 10452 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10453 pkgLite.recommendedInstallLocation 10454 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10455 } 10456 } 10457 } 10458 10459 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10460 int loc = pkgLite.recommendedInstallLocation; 10461 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10462 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10463 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10464 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10465 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10466 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10467 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10468 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10469 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10470 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10471 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10472 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10473 } else { 10474 // Override with defaults if needed. 10475 loc = installLocationPolicy(pkgLite); 10476 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10477 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10478 } else if (!onSd && !onInt) { 10479 // Override install location with flags 10480 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10481 // Set the flag to install on external media. 10482 installFlags |= PackageManager.INSTALL_EXTERNAL; 10483 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10484 } else { 10485 // Make sure the flag for installing on external 10486 // media is unset 10487 installFlags |= PackageManager.INSTALL_INTERNAL; 10488 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10489 } 10490 } 10491 } 10492 } 10493 10494 final InstallArgs args = createInstallArgs(this); 10495 mArgs = args; 10496 10497 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10498 /* 10499 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10500 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10501 */ 10502 int userIdentifier = getUser().getIdentifier(); 10503 if (userIdentifier == UserHandle.USER_ALL 10504 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10505 userIdentifier = UserHandle.USER_OWNER; 10506 } 10507 10508 /* 10509 * Determine if we have any installed package verifiers. If we 10510 * do, then we'll defer to them to verify the packages. 10511 */ 10512 final int requiredUid = mRequiredVerifierPackage == null ? -1 10513 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10514 if (!origin.existing && requiredUid != -1 10515 && isVerificationEnabled(userIdentifier, installFlags)) { 10516 final Intent verification = new Intent( 10517 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10518 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10519 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10520 PACKAGE_MIME_TYPE); 10521 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10522 10523 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10524 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10525 0 /* TODO: Which userId? */); 10526 10527 if (DEBUG_VERIFY) { 10528 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10529 + verification.toString() + " with " + pkgLite.verifiers.length 10530 + " optional verifiers"); 10531 } 10532 10533 final int verificationId = mPendingVerificationToken++; 10534 10535 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10536 10537 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10538 installerPackageName); 10539 10540 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10541 installFlags); 10542 10543 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10544 pkgLite.packageName); 10545 10546 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10547 pkgLite.versionCode); 10548 10549 if (verificationParams != null) { 10550 if (verificationParams.getVerificationURI() != null) { 10551 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10552 verificationParams.getVerificationURI()); 10553 } 10554 if (verificationParams.getOriginatingURI() != null) { 10555 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10556 verificationParams.getOriginatingURI()); 10557 } 10558 if (verificationParams.getReferrer() != null) { 10559 verification.putExtra(Intent.EXTRA_REFERRER, 10560 verificationParams.getReferrer()); 10561 } 10562 if (verificationParams.getOriginatingUid() >= 0) { 10563 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10564 verificationParams.getOriginatingUid()); 10565 } 10566 if (verificationParams.getInstallerUid() >= 0) { 10567 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10568 verificationParams.getInstallerUid()); 10569 } 10570 } 10571 10572 final PackageVerificationState verificationState = new PackageVerificationState( 10573 requiredUid, args); 10574 10575 mPendingVerification.append(verificationId, verificationState); 10576 10577 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10578 receivers, verificationState); 10579 10580 /* 10581 * If any sufficient verifiers were listed in the package 10582 * manifest, attempt to ask them. 10583 */ 10584 if (sufficientVerifiers != null) { 10585 final int N = sufficientVerifiers.size(); 10586 if (N == 0) { 10587 Slog.i(TAG, "Additional verifiers required, but none installed."); 10588 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10589 } else { 10590 for (int i = 0; i < N; i++) { 10591 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10592 10593 final Intent sufficientIntent = new Intent(verification); 10594 sufficientIntent.setComponent(verifierComponent); 10595 10596 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10597 } 10598 } 10599 } 10600 10601 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10602 mRequiredVerifierPackage, receivers); 10603 if (ret == PackageManager.INSTALL_SUCCEEDED 10604 && mRequiredVerifierPackage != null) { 10605 /* 10606 * Send the intent to the required verification agent, 10607 * but only start the verification timeout after the 10608 * target BroadcastReceivers have run. 10609 */ 10610 verification.setComponent(requiredVerifierComponent); 10611 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10612 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10613 new BroadcastReceiver() { 10614 @Override 10615 public void onReceive(Context context, Intent intent) { 10616 final Message msg = mHandler 10617 .obtainMessage(CHECK_PENDING_VERIFICATION); 10618 msg.arg1 = verificationId; 10619 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10620 } 10621 }, null, 0, null, null); 10622 10623 /* 10624 * We don't want the copy to proceed until verification 10625 * succeeds, so null out this field. 10626 */ 10627 mArgs = null; 10628 } 10629 } else { 10630 /* 10631 * No package verification is enabled, so immediately start 10632 * the remote call to initiate copy using temporary file. 10633 */ 10634 ret = args.copyApk(mContainerService, true); 10635 } 10636 } 10637 10638 mRet = ret; 10639 } 10640 10641 @Override 10642 void handleReturnCode() { 10643 // If mArgs is null, then MCS couldn't be reached. When it 10644 // reconnects, it will try again to install. At that point, this 10645 // will succeed. 10646 if (mArgs != null) { 10647 processPendingInstall(mArgs, mRet); 10648 } 10649 } 10650 10651 @Override 10652 void handleServiceError() { 10653 mArgs = createInstallArgs(this); 10654 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10655 } 10656 10657 public boolean isForwardLocked() { 10658 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10659 } 10660 } 10661 10662 /** 10663 * Used during creation of InstallArgs 10664 * 10665 * @param installFlags package installation flags 10666 * @return true if should be installed on external storage 10667 */ 10668 private static boolean installOnExternalAsec(int installFlags) { 10669 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10670 return false; 10671 } 10672 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10673 return true; 10674 } 10675 return false; 10676 } 10677 10678 /** 10679 * Used during creation of InstallArgs 10680 * 10681 * @param installFlags package installation flags 10682 * @return true if should be installed as forward locked 10683 */ 10684 private static boolean installForwardLocked(int installFlags) { 10685 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10686 } 10687 10688 private InstallArgs createInstallArgs(InstallParams params) { 10689 if (params.move != null) { 10690 return new MoveInstallArgs(params); 10691 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10692 return new AsecInstallArgs(params); 10693 } else { 10694 return new FileInstallArgs(params); 10695 } 10696 } 10697 10698 /** 10699 * Create args that describe an existing installed package. Typically used 10700 * when cleaning up old installs, or used as a move source. 10701 */ 10702 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10703 String resourcePath, String[] instructionSets) { 10704 final boolean isInAsec; 10705 if (installOnExternalAsec(installFlags)) { 10706 /* Apps on SD card are always in ASEC containers. */ 10707 isInAsec = true; 10708 } else if (installForwardLocked(installFlags) 10709 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10710 /* 10711 * Forward-locked apps are only in ASEC containers if they're the 10712 * new style 10713 */ 10714 isInAsec = true; 10715 } else { 10716 isInAsec = false; 10717 } 10718 10719 if (isInAsec) { 10720 return new AsecInstallArgs(codePath, instructionSets, 10721 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10722 } else { 10723 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10724 } 10725 } 10726 10727 static abstract class InstallArgs { 10728 /** @see InstallParams#origin */ 10729 final OriginInfo origin; 10730 /** @see InstallParams#move */ 10731 final MoveInfo move; 10732 10733 final IPackageInstallObserver2 observer; 10734 // Always refers to PackageManager flags only 10735 final int installFlags; 10736 final String installerPackageName; 10737 final String volumeUuid; 10738 final ManifestDigest manifestDigest; 10739 final UserHandle user; 10740 final String abiOverride; 10741 10742 // The list of instruction sets supported by this app. This is currently 10743 // only used during the rmdex() phase to clean up resources. We can get rid of this 10744 // if we move dex files under the common app path. 10745 /* nullable */ String[] instructionSets; 10746 10747 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10748 int installFlags, String installerPackageName, String volumeUuid, 10749 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10750 String abiOverride) { 10751 this.origin = origin; 10752 this.move = move; 10753 this.installFlags = installFlags; 10754 this.observer = observer; 10755 this.installerPackageName = installerPackageName; 10756 this.volumeUuid = volumeUuid; 10757 this.manifestDigest = manifestDigest; 10758 this.user = user; 10759 this.instructionSets = instructionSets; 10760 this.abiOverride = abiOverride; 10761 } 10762 10763 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10764 abstract int doPreInstall(int status); 10765 10766 /** 10767 * Rename package into final resting place. All paths on the given 10768 * scanned package should be updated to reflect the rename. 10769 */ 10770 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10771 abstract int doPostInstall(int status, int uid); 10772 10773 /** @see PackageSettingBase#codePathString */ 10774 abstract String getCodePath(); 10775 /** @see PackageSettingBase#resourcePathString */ 10776 abstract String getResourcePath(); 10777 10778 // Need installer lock especially for dex file removal. 10779 abstract void cleanUpResourcesLI(); 10780 abstract boolean doPostDeleteLI(boolean delete); 10781 10782 /** 10783 * Called before the source arguments are copied. This is used mostly 10784 * for MoveParams when it needs to read the source file to put it in the 10785 * destination. 10786 */ 10787 int doPreCopy() { 10788 return PackageManager.INSTALL_SUCCEEDED; 10789 } 10790 10791 /** 10792 * Called after the source arguments are copied. This is used mostly for 10793 * MoveParams when it needs to read the source file to put it in the 10794 * destination. 10795 * 10796 * @return 10797 */ 10798 int doPostCopy(int uid) { 10799 return PackageManager.INSTALL_SUCCEEDED; 10800 } 10801 10802 protected boolean isFwdLocked() { 10803 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10804 } 10805 10806 protected boolean isExternalAsec() { 10807 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10808 } 10809 10810 UserHandle getUser() { 10811 return user; 10812 } 10813 } 10814 10815 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10816 if (!allCodePaths.isEmpty()) { 10817 if (instructionSets == null) { 10818 throw new IllegalStateException("instructionSet == null"); 10819 } 10820 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10821 for (String codePath : allCodePaths) { 10822 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10823 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10824 if (retCode < 0) { 10825 Slog.w(TAG, "Couldn't remove dex file for package: " 10826 + " at location " + codePath + ", retcode=" + retCode); 10827 // we don't consider this to be a failure of the core package deletion 10828 } 10829 } 10830 } 10831 } 10832 } 10833 10834 /** 10835 * Logic to handle installation of non-ASEC applications, including copying 10836 * and renaming logic. 10837 */ 10838 class FileInstallArgs extends InstallArgs { 10839 private File codeFile; 10840 private File resourceFile; 10841 10842 // Example topology: 10843 // /data/app/com.example/base.apk 10844 // /data/app/com.example/split_foo.apk 10845 // /data/app/com.example/lib/arm/libfoo.so 10846 // /data/app/com.example/lib/arm64/libfoo.so 10847 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10848 10849 /** New install */ 10850 FileInstallArgs(InstallParams params) { 10851 super(params.origin, params.move, params.observer, params.installFlags, 10852 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10853 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10854 if (isFwdLocked()) { 10855 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10856 } 10857 } 10858 10859 /** Existing install */ 10860 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10861 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10862 null); 10863 this.codeFile = (codePath != null) ? new File(codePath) : null; 10864 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10865 } 10866 10867 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10868 if (origin.staged) { 10869 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10870 codeFile = origin.file; 10871 resourceFile = origin.file; 10872 return PackageManager.INSTALL_SUCCEEDED; 10873 } 10874 10875 try { 10876 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10877 codeFile = tempDir; 10878 resourceFile = tempDir; 10879 } catch (IOException e) { 10880 Slog.w(TAG, "Failed to create copy file: " + e); 10881 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10882 } 10883 10884 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10885 @Override 10886 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10887 if (!FileUtils.isValidExtFilename(name)) { 10888 throw new IllegalArgumentException("Invalid filename: " + name); 10889 } 10890 try { 10891 final File file = new File(codeFile, name); 10892 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10893 O_RDWR | O_CREAT, 0644); 10894 Os.chmod(file.getAbsolutePath(), 0644); 10895 return new ParcelFileDescriptor(fd); 10896 } catch (ErrnoException e) { 10897 throw new RemoteException("Failed to open: " + e.getMessage()); 10898 } 10899 } 10900 }; 10901 10902 int ret = PackageManager.INSTALL_SUCCEEDED; 10903 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10904 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10905 Slog.e(TAG, "Failed to copy package"); 10906 return ret; 10907 } 10908 10909 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10910 NativeLibraryHelper.Handle handle = null; 10911 try { 10912 handle = NativeLibraryHelper.Handle.create(codeFile); 10913 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10914 abiOverride); 10915 } catch (IOException e) { 10916 Slog.e(TAG, "Copying native libraries failed", e); 10917 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10918 } finally { 10919 IoUtils.closeQuietly(handle); 10920 } 10921 10922 return ret; 10923 } 10924 10925 int doPreInstall(int status) { 10926 if (status != PackageManager.INSTALL_SUCCEEDED) { 10927 cleanUp(); 10928 } 10929 return status; 10930 } 10931 10932 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10933 if (status != PackageManager.INSTALL_SUCCEEDED) { 10934 cleanUp(); 10935 return false; 10936 } 10937 10938 final File targetDir = codeFile.getParentFile(); 10939 final File beforeCodeFile = codeFile; 10940 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10941 10942 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10943 try { 10944 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10945 } catch (ErrnoException e) { 10946 Slog.w(TAG, "Failed to rename", e); 10947 return false; 10948 } 10949 10950 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10951 Slog.w(TAG, "Failed to restorecon"); 10952 return false; 10953 } 10954 10955 // Reflect the rename internally 10956 codeFile = afterCodeFile; 10957 resourceFile = afterCodeFile; 10958 10959 // Reflect the rename in scanned details 10960 pkg.codePath = afterCodeFile.getAbsolutePath(); 10961 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10962 pkg.baseCodePath); 10963 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10964 pkg.splitCodePaths); 10965 10966 // Reflect the rename in app info 10967 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10968 pkg.applicationInfo.setCodePath(pkg.codePath); 10969 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10970 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10971 pkg.applicationInfo.setResourcePath(pkg.codePath); 10972 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10973 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10974 10975 return true; 10976 } 10977 10978 int doPostInstall(int status, int uid) { 10979 if (status != PackageManager.INSTALL_SUCCEEDED) { 10980 cleanUp(); 10981 } 10982 return status; 10983 } 10984 10985 @Override 10986 String getCodePath() { 10987 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10988 } 10989 10990 @Override 10991 String getResourcePath() { 10992 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10993 } 10994 10995 private boolean cleanUp() { 10996 if (codeFile == null || !codeFile.exists()) { 10997 return false; 10998 } 10999 11000 if (codeFile.isDirectory()) { 11001 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11002 } else { 11003 codeFile.delete(); 11004 } 11005 11006 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11007 resourceFile.delete(); 11008 } 11009 11010 return true; 11011 } 11012 11013 void cleanUpResourcesLI() { 11014 // Try enumerating all code paths before deleting 11015 List<String> allCodePaths = Collections.EMPTY_LIST; 11016 if (codeFile != null && codeFile.exists()) { 11017 try { 11018 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11019 allCodePaths = pkg.getAllCodePaths(); 11020 } catch (PackageParserException e) { 11021 // Ignored; we tried our best 11022 } 11023 } 11024 11025 cleanUp(); 11026 removeDexFiles(allCodePaths, instructionSets); 11027 } 11028 11029 boolean doPostDeleteLI(boolean delete) { 11030 // XXX err, shouldn't we respect the delete flag? 11031 cleanUpResourcesLI(); 11032 return true; 11033 } 11034 } 11035 11036 private boolean isAsecExternal(String cid) { 11037 final String asecPath = PackageHelper.getSdFilesystem(cid); 11038 return !asecPath.startsWith(mAsecInternalPath); 11039 } 11040 11041 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11042 PackageManagerException { 11043 if (copyRet < 0) { 11044 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11045 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11046 throw new PackageManagerException(copyRet, message); 11047 } 11048 } 11049 } 11050 11051 /** 11052 * Extract the MountService "container ID" from the full code path of an 11053 * .apk. 11054 */ 11055 static String cidFromCodePath(String fullCodePath) { 11056 int eidx = fullCodePath.lastIndexOf("/"); 11057 String subStr1 = fullCodePath.substring(0, eidx); 11058 int sidx = subStr1.lastIndexOf("/"); 11059 return subStr1.substring(sidx+1, eidx); 11060 } 11061 11062 /** 11063 * Logic to handle installation of ASEC applications, including copying and 11064 * renaming logic. 11065 */ 11066 class AsecInstallArgs extends InstallArgs { 11067 static final String RES_FILE_NAME = "pkg.apk"; 11068 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11069 11070 String cid; 11071 String packagePath; 11072 String resourcePath; 11073 11074 /** New install */ 11075 AsecInstallArgs(InstallParams params) { 11076 super(params.origin, params.move, params.observer, params.installFlags, 11077 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11078 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11079 } 11080 11081 /** Existing install */ 11082 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11083 boolean isExternal, boolean isForwardLocked) { 11084 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11085 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11086 instructionSets, null); 11087 // Hackily pretend we're still looking at a full code path 11088 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11089 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11090 } 11091 11092 // Extract cid from fullCodePath 11093 int eidx = fullCodePath.lastIndexOf("/"); 11094 String subStr1 = fullCodePath.substring(0, eidx); 11095 int sidx = subStr1.lastIndexOf("/"); 11096 cid = subStr1.substring(sidx+1, eidx); 11097 setMountPath(subStr1); 11098 } 11099 11100 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11101 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11102 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11103 instructionSets, null); 11104 this.cid = cid; 11105 setMountPath(PackageHelper.getSdDir(cid)); 11106 } 11107 11108 void createCopyFile() { 11109 cid = mInstallerService.allocateExternalStageCidLegacy(); 11110 } 11111 11112 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11113 if (origin.staged) { 11114 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11115 cid = origin.cid; 11116 setMountPath(PackageHelper.getSdDir(cid)); 11117 return PackageManager.INSTALL_SUCCEEDED; 11118 } 11119 11120 if (temp) { 11121 createCopyFile(); 11122 } else { 11123 /* 11124 * Pre-emptively destroy the container since it's destroyed if 11125 * copying fails due to it existing anyway. 11126 */ 11127 PackageHelper.destroySdDir(cid); 11128 } 11129 11130 final String newMountPath = imcs.copyPackageToContainer( 11131 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11132 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11133 11134 if (newMountPath != null) { 11135 setMountPath(newMountPath); 11136 return PackageManager.INSTALL_SUCCEEDED; 11137 } else { 11138 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11139 } 11140 } 11141 11142 @Override 11143 String getCodePath() { 11144 return packagePath; 11145 } 11146 11147 @Override 11148 String getResourcePath() { 11149 return resourcePath; 11150 } 11151 11152 int doPreInstall(int status) { 11153 if (status != PackageManager.INSTALL_SUCCEEDED) { 11154 // Destroy container 11155 PackageHelper.destroySdDir(cid); 11156 } else { 11157 boolean mounted = PackageHelper.isContainerMounted(cid); 11158 if (!mounted) { 11159 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11160 Process.SYSTEM_UID); 11161 if (newMountPath != null) { 11162 setMountPath(newMountPath); 11163 } else { 11164 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11165 } 11166 } 11167 } 11168 return status; 11169 } 11170 11171 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11172 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11173 String newMountPath = null; 11174 if (PackageHelper.isContainerMounted(cid)) { 11175 // Unmount the container 11176 if (!PackageHelper.unMountSdDir(cid)) { 11177 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11178 return false; 11179 } 11180 } 11181 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11182 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11183 " which might be stale. Will try to clean up."); 11184 // Clean up the stale container and proceed to recreate. 11185 if (!PackageHelper.destroySdDir(newCacheId)) { 11186 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11187 return false; 11188 } 11189 // Successfully cleaned up stale container. Try to rename again. 11190 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11191 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11192 + " inspite of cleaning it up."); 11193 return false; 11194 } 11195 } 11196 if (!PackageHelper.isContainerMounted(newCacheId)) { 11197 Slog.w(TAG, "Mounting container " + newCacheId); 11198 newMountPath = PackageHelper.mountSdDir(newCacheId, 11199 getEncryptKey(), Process.SYSTEM_UID); 11200 } else { 11201 newMountPath = PackageHelper.getSdDir(newCacheId); 11202 } 11203 if (newMountPath == null) { 11204 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11205 return false; 11206 } 11207 Log.i(TAG, "Succesfully renamed " + cid + 11208 " to " + newCacheId + 11209 " at new path: " + newMountPath); 11210 cid = newCacheId; 11211 11212 final File beforeCodeFile = new File(packagePath); 11213 setMountPath(newMountPath); 11214 final File afterCodeFile = new File(packagePath); 11215 11216 // Reflect the rename in scanned details 11217 pkg.codePath = afterCodeFile.getAbsolutePath(); 11218 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11219 pkg.baseCodePath); 11220 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11221 pkg.splitCodePaths); 11222 11223 // Reflect the rename in app info 11224 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11225 pkg.applicationInfo.setCodePath(pkg.codePath); 11226 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11227 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11228 pkg.applicationInfo.setResourcePath(pkg.codePath); 11229 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11230 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11231 11232 return true; 11233 } 11234 11235 private void setMountPath(String mountPath) { 11236 final File mountFile = new File(mountPath); 11237 11238 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11239 if (monolithicFile.exists()) { 11240 packagePath = monolithicFile.getAbsolutePath(); 11241 if (isFwdLocked()) { 11242 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11243 } else { 11244 resourcePath = packagePath; 11245 } 11246 } else { 11247 packagePath = mountFile.getAbsolutePath(); 11248 resourcePath = packagePath; 11249 } 11250 } 11251 11252 int doPostInstall(int status, int uid) { 11253 if (status != PackageManager.INSTALL_SUCCEEDED) { 11254 cleanUp(); 11255 } else { 11256 final int groupOwner; 11257 final String protectedFile; 11258 if (isFwdLocked()) { 11259 groupOwner = UserHandle.getSharedAppGid(uid); 11260 protectedFile = RES_FILE_NAME; 11261 } else { 11262 groupOwner = -1; 11263 protectedFile = null; 11264 } 11265 11266 if (uid < Process.FIRST_APPLICATION_UID 11267 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11268 Slog.e(TAG, "Failed to finalize " + cid); 11269 PackageHelper.destroySdDir(cid); 11270 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11271 } 11272 11273 boolean mounted = PackageHelper.isContainerMounted(cid); 11274 if (!mounted) { 11275 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11276 } 11277 } 11278 return status; 11279 } 11280 11281 private void cleanUp() { 11282 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11283 11284 // Destroy secure container 11285 PackageHelper.destroySdDir(cid); 11286 } 11287 11288 private List<String> getAllCodePaths() { 11289 final File codeFile = new File(getCodePath()); 11290 if (codeFile != null && codeFile.exists()) { 11291 try { 11292 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11293 return pkg.getAllCodePaths(); 11294 } catch (PackageParserException e) { 11295 // Ignored; we tried our best 11296 } 11297 } 11298 return Collections.EMPTY_LIST; 11299 } 11300 11301 void cleanUpResourcesLI() { 11302 // Enumerate all code paths before deleting 11303 cleanUpResourcesLI(getAllCodePaths()); 11304 } 11305 11306 private void cleanUpResourcesLI(List<String> allCodePaths) { 11307 cleanUp(); 11308 removeDexFiles(allCodePaths, instructionSets); 11309 } 11310 11311 String getPackageName() { 11312 return getAsecPackageName(cid); 11313 } 11314 11315 boolean doPostDeleteLI(boolean delete) { 11316 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11317 final List<String> allCodePaths = getAllCodePaths(); 11318 boolean mounted = PackageHelper.isContainerMounted(cid); 11319 if (mounted) { 11320 // Unmount first 11321 if (PackageHelper.unMountSdDir(cid)) { 11322 mounted = false; 11323 } 11324 } 11325 if (!mounted && delete) { 11326 cleanUpResourcesLI(allCodePaths); 11327 } 11328 return !mounted; 11329 } 11330 11331 @Override 11332 int doPreCopy() { 11333 if (isFwdLocked()) { 11334 if (!PackageHelper.fixSdPermissions(cid, 11335 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11336 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11337 } 11338 } 11339 11340 return PackageManager.INSTALL_SUCCEEDED; 11341 } 11342 11343 @Override 11344 int doPostCopy(int uid) { 11345 if (isFwdLocked()) { 11346 if (uid < Process.FIRST_APPLICATION_UID 11347 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11348 RES_FILE_NAME)) { 11349 Slog.e(TAG, "Failed to finalize " + cid); 11350 PackageHelper.destroySdDir(cid); 11351 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11352 } 11353 } 11354 11355 return PackageManager.INSTALL_SUCCEEDED; 11356 } 11357 } 11358 11359 /** 11360 * Logic to handle movement of existing installed applications. 11361 */ 11362 class MoveInstallArgs extends InstallArgs { 11363 private File codeFile; 11364 private File resourceFile; 11365 11366 /** New install */ 11367 MoveInstallArgs(InstallParams params) { 11368 super(params.origin, params.move, params.observer, params.installFlags, 11369 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11370 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11371 } 11372 11373 int copyApk(IMediaContainerService imcs, boolean temp) { 11374 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11375 + move.fromUuid + " to " + move.toUuid); 11376 synchronized (mInstaller) { 11377 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11378 move.dataAppName, move.appId, move.seinfo) != 0) { 11379 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11380 } 11381 } 11382 11383 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11384 resourceFile = codeFile; 11385 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11386 11387 return PackageManager.INSTALL_SUCCEEDED; 11388 } 11389 11390 int doPreInstall(int status) { 11391 if (status != PackageManager.INSTALL_SUCCEEDED) { 11392 cleanUp(move.toUuid); 11393 } 11394 return status; 11395 } 11396 11397 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11398 if (status != PackageManager.INSTALL_SUCCEEDED) { 11399 cleanUp(move.toUuid); 11400 return false; 11401 } 11402 11403 // Reflect the move in app info 11404 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11405 pkg.applicationInfo.setCodePath(pkg.codePath); 11406 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11407 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11408 pkg.applicationInfo.setResourcePath(pkg.codePath); 11409 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11410 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11411 11412 return true; 11413 } 11414 11415 int doPostInstall(int status, int uid) { 11416 if (status == PackageManager.INSTALL_SUCCEEDED) { 11417 cleanUp(move.fromUuid); 11418 } else { 11419 cleanUp(move.toUuid); 11420 } 11421 return status; 11422 } 11423 11424 @Override 11425 String getCodePath() { 11426 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11427 } 11428 11429 @Override 11430 String getResourcePath() { 11431 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11432 } 11433 11434 private boolean cleanUp(String volumeUuid) { 11435 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11436 move.dataAppName); 11437 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11438 synchronized (mInstallLock) { 11439 // Clean up both app data and code 11440 removeDataDirsLI(volumeUuid, move.packageName); 11441 if (codeFile.isDirectory()) { 11442 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11443 } else { 11444 codeFile.delete(); 11445 } 11446 } 11447 return true; 11448 } 11449 11450 void cleanUpResourcesLI() { 11451 throw new UnsupportedOperationException(); 11452 } 11453 11454 boolean doPostDeleteLI(boolean delete) { 11455 throw new UnsupportedOperationException(); 11456 } 11457 } 11458 11459 static String getAsecPackageName(String packageCid) { 11460 int idx = packageCid.lastIndexOf("-"); 11461 if (idx == -1) { 11462 return packageCid; 11463 } 11464 return packageCid.substring(0, idx); 11465 } 11466 11467 // Utility method used to create code paths based on package name and available index. 11468 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11469 String idxStr = ""; 11470 int idx = 1; 11471 // Fall back to default value of idx=1 if prefix is not 11472 // part of oldCodePath 11473 if (oldCodePath != null) { 11474 String subStr = oldCodePath; 11475 // Drop the suffix right away 11476 if (suffix != null && subStr.endsWith(suffix)) { 11477 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11478 } 11479 // If oldCodePath already contains prefix find out the 11480 // ending index to either increment or decrement. 11481 int sidx = subStr.lastIndexOf(prefix); 11482 if (sidx != -1) { 11483 subStr = subStr.substring(sidx + prefix.length()); 11484 if (subStr != null) { 11485 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11486 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11487 } 11488 try { 11489 idx = Integer.parseInt(subStr); 11490 if (idx <= 1) { 11491 idx++; 11492 } else { 11493 idx--; 11494 } 11495 } catch(NumberFormatException e) { 11496 } 11497 } 11498 } 11499 } 11500 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11501 return prefix + idxStr; 11502 } 11503 11504 private File getNextCodePath(File targetDir, String packageName) { 11505 int suffix = 1; 11506 File result; 11507 do { 11508 result = new File(targetDir, packageName + "-" + suffix); 11509 suffix++; 11510 } while (result.exists()); 11511 return result; 11512 } 11513 11514 // Utility method that returns the relative package path with respect 11515 // to the installation directory. Like say for /data/data/com.test-1.apk 11516 // string com.test-1 is returned. 11517 static String deriveCodePathName(String codePath) { 11518 if (codePath == null) { 11519 return null; 11520 } 11521 final File codeFile = new File(codePath); 11522 final String name = codeFile.getName(); 11523 if (codeFile.isDirectory()) { 11524 return name; 11525 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11526 final int lastDot = name.lastIndexOf('.'); 11527 return name.substring(0, lastDot); 11528 } else { 11529 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11530 return null; 11531 } 11532 } 11533 11534 class PackageInstalledInfo { 11535 String name; 11536 int uid; 11537 // The set of users that originally had this package installed. 11538 int[] origUsers; 11539 // The set of users that now have this package installed. 11540 int[] newUsers; 11541 PackageParser.Package pkg; 11542 int returnCode; 11543 String returnMsg; 11544 PackageRemovedInfo removedInfo; 11545 11546 public void setError(int code, String msg) { 11547 returnCode = code; 11548 returnMsg = msg; 11549 Slog.w(TAG, msg); 11550 } 11551 11552 public void setError(String msg, PackageParserException e) { 11553 returnCode = e.error; 11554 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11555 Slog.w(TAG, msg, e); 11556 } 11557 11558 public void setError(String msg, PackageManagerException e) { 11559 returnCode = e.error; 11560 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11561 Slog.w(TAG, msg, e); 11562 } 11563 11564 // In some error cases we want to convey more info back to the observer 11565 String origPackage; 11566 String origPermission; 11567 } 11568 11569 /* 11570 * Install a non-existing package. 11571 */ 11572 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11573 UserHandle user, String installerPackageName, String volumeUuid, 11574 PackageInstalledInfo res) { 11575 // Remember this for later, in case we need to rollback this install 11576 String pkgName = pkg.packageName; 11577 11578 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11579 final boolean dataDirExists = Environment 11580 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11581 synchronized(mPackages) { 11582 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11583 // A package with the same name is already installed, though 11584 // it has been renamed to an older name. The package we 11585 // are trying to install should be installed as an update to 11586 // the existing one, but that has not been requested, so bail. 11587 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11588 + " without first uninstalling package running as " 11589 + mSettings.mRenamedPackages.get(pkgName)); 11590 return; 11591 } 11592 if (mPackages.containsKey(pkgName)) { 11593 // Don't allow installation over an existing package with the same name. 11594 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11595 + " without first uninstalling."); 11596 return; 11597 } 11598 } 11599 11600 try { 11601 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11602 System.currentTimeMillis(), user); 11603 11604 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11605 // delete the partially installed application. the data directory will have to be 11606 // restored if it was already existing 11607 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11608 // remove package from internal structures. Note that we want deletePackageX to 11609 // delete the package data and cache directories that it created in 11610 // scanPackageLocked, unless those directories existed before we even tried to 11611 // install. 11612 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11613 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11614 res.removedInfo, true); 11615 } 11616 11617 } catch (PackageManagerException e) { 11618 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11619 } 11620 } 11621 11622 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11623 // Can't rotate keys during boot or if sharedUser. 11624 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11625 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11626 return false; 11627 } 11628 // app is using upgradeKeySets; make sure all are valid 11629 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11630 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11631 for (int i = 0; i < upgradeKeySets.length; i++) { 11632 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11633 Slog.wtf(TAG, "Package " 11634 + (oldPs.name != null ? oldPs.name : "<null>") 11635 + " contains upgrade-key-set reference to unknown key-set: " 11636 + upgradeKeySets[i] 11637 + " reverting to signatures check."); 11638 return false; 11639 } 11640 } 11641 return true; 11642 } 11643 11644 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11645 // Upgrade keysets are being used. Determine if new package has a superset of the 11646 // required keys. 11647 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11648 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11649 for (int i = 0; i < upgradeKeySets.length; i++) { 11650 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11651 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11652 return true; 11653 } 11654 } 11655 return false; 11656 } 11657 11658 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11659 UserHandle user, String installerPackageName, String volumeUuid, 11660 PackageInstalledInfo res) { 11661 final PackageParser.Package oldPackage; 11662 final String pkgName = pkg.packageName; 11663 final int[] allUsers; 11664 final boolean[] perUserInstalled; 11665 final boolean weFroze; 11666 11667 // First find the old package info and check signatures 11668 synchronized(mPackages) { 11669 oldPackage = mPackages.get(pkgName); 11670 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11671 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11672 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11673 if(!checkUpgradeKeySetLP(ps, pkg)) { 11674 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11675 "New package not signed by keys specified by upgrade-keysets: " 11676 + pkgName); 11677 return; 11678 } 11679 } else { 11680 // default to original signature matching 11681 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11682 != PackageManager.SIGNATURE_MATCH) { 11683 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11684 "New package has a different signature: " + pkgName); 11685 return; 11686 } 11687 } 11688 11689 // In case of rollback, remember per-user/profile install state 11690 allUsers = sUserManager.getUserIds(); 11691 perUserInstalled = new boolean[allUsers.length]; 11692 for (int i = 0; i < allUsers.length; i++) { 11693 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11694 } 11695 11696 // Mark the app as frozen to prevent launching during the upgrade 11697 // process, and then kill all running instances 11698 if (!ps.frozen) { 11699 ps.frozen = true; 11700 weFroze = true; 11701 } else { 11702 weFroze = false; 11703 } 11704 } 11705 11706 // Now that we're guarded by frozen state, kill app during upgrade 11707 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11708 11709 try { 11710 boolean sysPkg = (isSystemApp(oldPackage)); 11711 if (sysPkg) { 11712 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11713 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11714 } else { 11715 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11716 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11717 } 11718 } finally { 11719 // Regardless of success or failure of upgrade steps above, always 11720 // unfreeze the package if we froze it 11721 if (weFroze) { 11722 unfreezePackage(pkgName); 11723 } 11724 } 11725 } 11726 11727 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11728 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11729 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11730 String volumeUuid, PackageInstalledInfo res) { 11731 String pkgName = deletedPackage.packageName; 11732 boolean deletedPkg = true; 11733 boolean updatedSettings = false; 11734 11735 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11736 + deletedPackage); 11737 long origUpdateTime; 11738 if (pkg.mExtras != null) { 11739 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11740 } else { 11741 origUpdateTime = 0; 11742 } 11743 11744 // First delete the existing package while retaining the data directory 11745 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11746 res.removedInfo, true)) { 11747 // If the existing package wasn't successfully deleted 11748 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11749 deletedPkg = false; 11750 } else { 11751 // Successfully deleted the old package; proceed with replace. 11752 11753 // If deleted package lived in a container, give users a chance to 11754 // relinquish resources before killing. 11755 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11756 if (DEBUG_INSTALL) { 11757 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11758 } 11759 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11760 final ArrayList<String> pkgList = new ArrayList<String>(1); 11761 pkgList.add(deletedPackage.applicationInfo.packageName); 11762 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11763 } 11764 11765 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11766 try { 11767 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11768 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11769 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11770 perUserInstalled, res, user); 11771 updatedSettings = true; 11772 } catch (PackageManagerException e) { 11773 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11774 } 11775 } 11776 11777 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11778 // remove package from internal structures. Note that we want deletePackageX to 11779 // delete the package data and cache directories that it created in 11780 // scanPackageLocked, unless those directories existed before we even tried to 11781 // install. 11782 if(updatedSettings) { 11783 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11784 deletePackageLI( 11785 pkgName, null, true, allUsers, perUserInstalled, 11786 PackageManager.DELETE_KEEP_DATA, 11787 res.removedInfo, true); 11788 } 11789 // Since we failed to install the new package we need to restore the old 11790 // package that we deleted. 11791 if (deletedPkg) { 11792 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11793 File restoreFile = new File(deletedPackage.codePath); 11794 // Parse old package 11795 boolean oldExternal = isExternal(deletedPackage); 11796 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11797 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11798 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11799 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11800 try { 11801 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11802 } catch (PackageManagerException e) { 11803 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11804 + e.getMessage()); 11805 return; 11806 } 11807 // Restore of old package succeeded. Update permissions. 11808 // writer 11809 synchronized (mPackages) { 11810 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11811 UPDATE_PERMISSIONS_ALL); 11812 // can downgrade to reader 11813 mSettings.writeLPr(); 11814 } 11815 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11816 } 11817 } 11818 } 11819 11820 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11821 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11822 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11823 String volumeUuid, PackageInstalledInfo res) { 11824 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11825 + ", old=" + deletedPackage); 11826 boolean disabledSystem = false; 11827 boolean updatedSettings = false; 11828 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11829 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11830 != 0) { 11831 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11832 } 11833 String packageName = deletedPackage.packageName; 11834 if (packageName == null) { 11835 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11836 "Attempt to delete null packageName."); 11837 return; 11838 } 11839 PackageParser.Package oldPkg; 11840 PackageSetting oldPkgSetting; 11841 // reader 11842 synchronized (mPackages) { 11843 oldPkg = mPackages.get(packageName); 11844 oldPkgSetting = mSettings.mPackages.get(packageName); 11845 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11846 (oldPkgSetting == null)) { 11847 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11848 "Couldn't find package:" + packageName + " information"); 11849 return; 11850 } 11851 } 11852 11853 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11854 res.removedInfo.removedPackage = packageName; 11855 // Remove existing system package 11856 removePackageLI(oldPkgSetting, true); 11857 // writer 11858 synchronized (mPackages) { 11859 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11860 if (!disabledSystem && deletedPackage != null) { 11861 // We didn't need to disable the .apk as a current system package, 11862 // which means we are replacing another update that is already 11863 // installed. We need to make sure to delete the older one's .apk. 11864 res.removedInfo.args = createInstallArgsForExisting(0, 11865 deletedPackage.applicationInfo.getCodePath(), 11866 deletedPackage.applicationInfo.getResourcePath(), 11867 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11868 } else { 11869 res.removedInfo.args = null; 11870 } 11871 } 11872 11873 // Successfully disabled the old package. Now proceed with re-installation 11874 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11875 11876 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11877 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11878 11879 PackageParser.Package newPackage = null; 11880 try { 11881 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11882 if (newPackage.mExtras != null) { 11883 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11884 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11885 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11886 11887 // is the update attempting to change shared user? that isn't going to work... 11888 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11889 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11890 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11891 + " to " + newPkgSetting.sharedUser); 11892 updatedSettings = true; 11893 } 11894 } 11895 11896 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11897 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11898 perUserInstalled, res, user); 11899 updatedSettings = true; 11900 } 11901 11902 } catch (PackageManagerException e) { 11903 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11904 } 11905 11906 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11907 // Re installation failed. Restore old information 11908 // Remove new pkg information 11909 if (newPackage != null) { 11910 removeInstalledPackageLI(newPackage, true); 11911 } 11912 // Add back the old system package 11913 try { 11914 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11915 } catch (PackageManagerException e) { 11916 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11917 } 11918 // Restore the old system information in Settings 11919 synchronized (mPackages) { 11920 if (disabledSystem) { 11921 mSettings.enableSystemPackageLPw(packageName); 11922 } 11923 if (updatedSettings) { 11924 mSettings.setInstallerPackageName(packageName, 11925 oldPkgSetting.installerPackageName); 11926 } 11927 mSettings.writeLPr(); 11928 } 11929 } 11930 } 11931 11932 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11933 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11934 UserHandle user) { 11935 String pkgName = newPackage.packageName; 11936 synchronized (mPackages) { 11937 //write settings. the installStatus will be incomplete at this stage. 11938 //note that the new package setting would have already been 11939 //added to mPackages. It hasn't been persisted yet. 11940 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11941 mSettings.writeLPr(); 11942 } 11943 11944 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11945 11946 synchronized (mPackages) { 11947 updatePermissionsLPw(newPackage.packageName, newPackage, 11948 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11949 ? UPDATE_PERMISSIONS_ALL : 0)); 11950 // For system-bundled packages, we assume that installing an upgraded version 11951 // of the package implies that the user actually wants to run that new code, 11952 // so we enable the package. 11953 PackageSetting ps = mSettings.mPackages.get(pkgName); 11954 if (ps != null) { 11955 if (isSystemApp(newPackage)) { 11956 // NB: implicit assumption that system package upgrades apply to all users 11957 if (DEBUG_INSTALL) { 11958 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11959 } 11960 if (res.origUsers != null) { 11961 for (int userHandle : res.origUsers) { 11962 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11963 userHandle, installerPackageName); 11964 } 11965 } 11966 // Also convey the prior install/uninstall state 11967 if (allUsers != null && perUserInstalled != null) { 11968 for (int i = 0; i < allUsers.length; i++) { 11969 if (DEBUG_INSTALL) { 11970 Slog.d(TAG, " user " + allUsers[i] 11971 + " => " + perUserInstalled[i]); 11972 } 11973 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11974 } 11975 // these install state changes will be persisted in the 11976 // upcoming call to mSettings.writeLPr(). 11977 } 11978 } 11979 // It's implied that when a user requests installation, they want the app to be 11980 // installed and enabled. 11981 int userId = user.getIdentifier(); 11982 if (userId != UserHandle.USER_ALL) { 11983 ps.setInstalled(true, userId); 11984 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11985 } 11986 } 11987 res.name = pkgName; 11988 res.uid = newPackage.applicationInfo.uid; 11989 res.pkg = newPackage; 11990 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11991 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11992 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11993 //to update install status 11994 mSettings.writeLPr(); 11995 } 11996 } 11997 11998 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11999 final int installFlags = args.installFlags; 12000 final String installerPackageName = args.installerPackageName; 12001 final String volumeUuid = args.volumeUuid; 12002 final File tmpPackageFile = new File(args.getCodePath()); 12003 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12004 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12005 || (args.volumeUuid != null)); 12006 boolean replace = false; 12007 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12008 if (args.move != null) { 12009 // moving a complete application; perfom an initial scan on the new install location 12010 scanFlags |= SCAN_INITIAL; 12011 } 12012 // Result object to be returned 12013 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12014 12015 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12016 // Retrieve PackageSettings and parse package 12017 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12018 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12019 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12020 PackageParser pp = new PackageParser(); 12021 pp.setSeparateProcesses(mSeparateProcesses); 12022 pp.setDisplayMetrics(mMetrics); 12023 12024 final PackageParser.Package pkg; 12025 try { 12026 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12027 } catch (PackageParserException e) { 12028 res.setError("Failed parse during installPackageLI", e); 12029 return; 12030 } 12031 12032 // Mark that we have an install time CPU ABI override. 12033 pkg.cpuAbiOverride = args.abiOverride; 12034 12035 String pkgName = res.name = pkg.packageName; 12036 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12037 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12038 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12039 return; 12040 } 12041 } 12042 12043 try { 12044 pp.collectCertificates(pkg, parseFlags); 12045 pp.collectManifestDigest(pkg); 12046 } catch (PackageParserException e) { 12047 res.setError("Failed collect during installPackageLI", e); 12048 return; 12049 } 12050 12051 /* If the installer passed in a manifest digest, compare it now. */ 12052 if (args.manifestDigest != null) { 12053 if (DEBUG_INSTALL) { 12054 final String parsedManifest = pkg.manifestDigest == null ? "null" 12055 : pkg.manifestDigest.toString(); 12056 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12057 + parsedManifest); 12058 } 12059 12060 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12061 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12062 return; 12063 } 12064 } else if (DEBUG_INSTALL) { 12065 final String parsedManifest = pkg.manifestDigest == null 12066 ? "null" : pkg.manifestDigest.toString(); 12067 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12068 } 12069 12070 // Get rid of all references to package scan path via parser. 12071 pp = null; 12072 String oldCodePath = null; 12073 boolean systemApp = false; 12074 synchronized (mPackages) { 12075 // Check if installing already existing package 12076 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12077 String oldName = mSettings.mRenamedPackages.get(pkgName); 12078 if (pkg.mOriginalPackages != null 12079 && pkg.mOriginalPackages.contains(oldName) 12080 && mPackages.containsKey(oldName)) { 12081 // This package is derived from an original package, 12082 // and this device has been updating from that original 12083 // name. We must continue using the original name, so 12084 // rename the new package here. 12085 pkg.setPackageName(oldName); 12086 pkgName = pkg.packageName; 12087 replace = true; 12088 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12089 + oldName + " pkgName=" + pkgName); 12090 } else if (mPackages.containsKey(pkgName)) { 12091 // This package, under its official name, already exists 12092 // on the device; we should replace it. 12093 replace = true; 12094 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12095 } 12096 12097 // Prevent apps opting out from runtime permissions 12098 if (replace) { 12099 PackageParser.Package oldPackage = mPackages.get(pkgName); 12100 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12101 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12102 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12103 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12104 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12105 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12106 + " doesn't support runtime permissions but the old" 12107 + " target SDK " + oldTargetSdk + " does."); 12108 return; 12109 } 12110 } 12111 } 12112 12113 PackageSetting ps = mSettings.mPackages.get(pkgName); 12114 if (ps != null) { 12115 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12116 12117 // Quick sanity check that we're signed correctly if updating; 12118 // we'll check this again later when scanning, but we want to 12119 // bail early here before tripping over redefined permissions. 12120 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12121 if (!checkUpgradeKeySetLP(ps, pkg)) { 12122 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12123 + pkg.packageName + " upgrade keys do not match the " 12124 + "previously installed version"); 12125 return; 12126 } 12127 } else { 12128 try { 12129 verifySignaturesLP(ps, pkg); 12130 } catch (PackageManagerException e) { 12131 res.setError(e.error, e.getMessage()); 12132 return; 12133 } 12134 } 12135 12136 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12137 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12138 systemApp = (ps.pkg.applicationInfo.flags & 12139 ApplicationInfo.FLAG_SYSTEM) != 0; 12140 } 12141 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12142 } 12143 12144 // Check whether the newly-scanned package wants to define an already-defined perm 12145 int N = pkg.permissions.size(); 12146 for (int i = N-1; i >= 0; i--) { 12147 PackageParser.Permission perm = pkg.permissions.get(i); 12148 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12149 if (bp != null) { 12150 // If the defining package is signed with our cert, it's okay. This 12151 // also includes the "updating the same package" case, of course. 12152 // "updating same package" could also involve key-rotation. 12153 final boolean sigsOk; 12154 if (bp.sourcePackage.equals(pkg.packageName) 12155 && (bp.packageSetting instanceof PackageSetting) 12156 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12157 scanFlags))) { 12158 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12159 } else { 12160 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12161 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12162 } 12163 if (!sigsOk) { 12164 // If the owning package is the system itself, we log but allow 12165 // install to proceed; we fail the install on all other permission 12166 // redefinitions. 12167 if (!bp.sourcePackage.equals("android")) { 12168 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12169 + pkg.packageName + " attempting to redeclare permission " 12170 + perm.info.name + " already owned by " + bp.sourcePackage); 12171 res.origPermission = perm.info.name; 12172 res.origPackage = bp.sourcePackage; 12173 return; 12174 } else { 12175 Slog.w(TAG, "Package " + pkg.packageName 12176 + " attempting to redeclare system permission " 12177 + perm.info.name + "; ignoring new declaration"); 12178 pkg.permissions.remove(i); 12179 } 12180 } 12181 } 12182 } 12183 12184 } 12185 12186 if (systemApp && onExternal) { 12187 // Disable updates to system apps on sdcard 12188 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12189 "Cannot install updates to system apps on sdcard"); 12190 return; 12191 } 12192 12193 if (args.move != null) { 12194 // We did an in-place move, so dex is ready to roll 12195 scanFlags |= SCAN_NO_DEX; 12196 scanFlags |= SCAN_MOVE; 12197 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12198 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12199 scanFlags |= SCAN_NO_DEX; 12200 12201 try { 12202 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12203 true /* extract libs */); 12204 } catch (PackageManagerException pme) { 12205 Slog.e(TAG, "Error deriving application ABI", pme); 12206 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12207 return; 12208 } 12209 12210 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12211 int result = mPackageDexOptimizer 12212 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12213 false /* defer */, false /* inclDependencies */); 12214 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12215 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12216 return; 12217 } 12218 } 12219 12220 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12221 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12222 return; 12223 } 12224 12225 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12226 12227 if (replace) { 12228 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12229 installerPackageName, volumeUuid, res); 12230 } else { 12231 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12232 args.user, installerPackageName, volumeUuid, res); 12233 } 12234 synchronized (mPackages) { 12235 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12236 if (ps != null) { 12237 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12238 } 12239 } 12240 } 12241 12242 private void startIntentFilterVerifications(int userId, boolean replacing, 12243 PackageParser.Package pkg) { 12244 if (mIntentFilterVerifierComponent == null) { 12245 Slog.w(TAG, "No IntentFilter verification will not be done as " 12246 + "there is no IntentFilterVerifier available!"); 12247 return; 12248 } 12249 12250 final int verifierUid = getPackageUid( 12251 mIntentFilterVerifierComponent.getPackageName(), 12252 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12253 12254 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12255 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12256 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12257 mHandler.sendMessage(msg); 12258 } 12259 12260 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12261 PackageParser.Package pkg) { 12262 int size = pkg.activities.size(); 12263 if (size == 0) { 12264 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12265 "No activity, so no need to verify any IntentFilter!"); 12266 return; 12267 } 12268 12269 final boolean hasDomainURLs = hasDomainURLs(pkg); 12270 if (!hasDomainURLs) { 12271 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12272 "No domain URLs, so no need to verify any IntentFilter!"); 12273 return; 12274 } 12275 12276 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12277 + " if any IntentFilter from the " + size 12278 + " Activities needs verification ..."); 12279 12280 int count = 0; 12281 final String packageName = pkg.packageName; 12282 12283 synchronized (mPackages) { 12284 // If this is a new install and we see that we've already run verification for this 12285 // package, we have nothing to do: it means the state was restored from backup. 12286 if (!replacing) { 12287 IntentFilterVerificationInfo ivi = 12288 mSettings.getIntentFilterVerificationLPr(packageName); 12289 if (ivi != null) { 12290 if (DEBUG_DOMAIN_VERIFICATION) { 12291 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12292 + ivi.getStatusString()); 12293 } 12294 return; 12295 } 12296 } 12297 12298 // If any filters need to be verified, then all need to be. 12299 boolean needToVerify = false; 12300 for (PackageParser.Activity a : pkg.activities) { 12301 for (ActivityIntentInfo filter : a.intents) { 12302 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12303 if (DEBUG_DOMAIN_VERIFICATION) { 12304 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12305 } 12306 needToVerify = true; 12307 break; 12308 } 12309 } 12310 } 12311 12312 if (needToVerify) { 12313 final int verificationId = mIntentFilterVerificationToken++; 12314 for (PackageParser.Activity a : pkg.activities) { 12315 for (ActivityIntentInfo filter : a.intents) { 12316 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12317 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12318 "Verification needed for IntentFilter:" + filter.toString()); 12319 mIntentFilterVerifier.addOneIntentFilterVerification( 12320 verifierUid, userId, verificationId, filter, packageName); 12321 count++; 12322 } 12323 } 12324 } 12325 } 12326 } 12327 12328 if (count > 0) { 12329 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12330 + " IntentFilter verification" + (count > 1 ? "s" : "") 12331 + " for userId:" + userId); 12332 mIntentFilterVerifier.startVerifications(userId); 12333 } else { 12334 if (DEBUG_DOMAIN_VERIFICATION) { 12335 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12336 } 12337 } 12338 } 12339 12340 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12341 final ComponentName cn = filter.activity.getComponentName(); 12342 final String packageName = cn.getPackageName(); 12343 12344 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12345 packageName); 12346 if (ivi == null) { 12347 return true; 12348 } 12349 int status = ivi.getStatus(); 12350 switch (status) { 12351 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12352 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12353 return true; 12354 12355 default: 12356 // Nothing to do 12357 return false; 12358 } 12359 } 12360 12361 private static boolean isMultiArch(PackageSetting ps) { 12362 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12363 } 12364 12365 private static boolean isMultiArch(ApplicationInfo info) { 12366 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12367 } 12368 12369 private static boolean isExternal(PackageParser.Package pkg) { 12370 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12371 } 12372 12373 private static boolean isExternal(PackageSetting ps) { 12374 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12375 } 12376 12377 private static boolean isExternal(ApplicationInfo info) { 12378 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12379 } 12380 12381 private static boolean isSystemApp(PackageParser.Package pkg) { 12382 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12383 } 12384 12385 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12386 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12387 } 12388 12389 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12390 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12391 } 12392 12393 private static boolean isSystemApp(PackageSetting ps) { 12394 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12395 } 12396 12397 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12398 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12399 } 12400 12401 private int packageFlagsToInstallFlags(PackageSetting ps) { 12402 int installFlags = 0; 12403 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12404 // This existing package was an external ASEC install when we have 12405 // the external flag without a UUID 12406 installFlags |= PackageManager.INSTALL_EXTERNAL; 12407 } 12408 if (ps.isForwardLocked()) { 12409 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12410 } 12411 return installFlags; 12412 } 12413 12414 private void deleteTempPackageFiles() { 12415 final FilenameFilter filter = new FilenameFilter() { 12416 public boolean accept(File dir, String name) { 12417 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12418 } 12419 }; 12420 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12421 file.delete(); 12422 } 12423 } 12424 12425 @Override 12426 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12427 int flags) { 12428 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12429 flags); 12430 } 12431 12432 @Override 12433 public void deletePackage(final String packageName, 12434 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12435 mContext.enforceCallingOrSelfPermission( 12436 android.Manifest.permission.DELETE_PACKAGES, null); 12437 Preconditions.checkNotNull(packageName); 12438 Preconditions.checkNotNull(observer); 12439 final int uid = Binder.getCallingUid(); 12440 if (UserHandle.getUserId(uid) != userId) { 12441 mContext.enforceCallingPermission( 12442 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12443 "deletePackage for user " + userId); 12444 } 12445 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12446 try { 12447 observer.onPackageDeleted(packageName, 12448 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12449 } catch (RemoteException re) { 12450 } 12451 return; 12452 } 12453 12454 boolean uninstallBlocked = false; 12455 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12456 int[] users = sUserManager.getUserIds(); 12457 for (int i = 0; i < users.length; ++i) { 12458 if (getBlockUninstallForUser(packageName, users[i])) { 12459 uninstallBlocked = true; 12460 break; 12461 } 12462 } 12463 } else { 12464 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12465 } 12466 if (uninstallBlocked) { 12467 try { 12468 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12469 null); 12470 } catch (RemoteException re) { 12471 } 12472 return; 12473 } 12474 12475 if (DEBUG_REMOVE) { 12476 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12477 } 12478 // Queue up an async operation since the package deletion may take a little while. 12479 mHandler.post(new Runnable() { 12480 public void run() { 12481 mHandler.removeCallbacks(this); 12482 final int returnCode = deletePackageX(packageName, userId, flags); 12483 if (observer != null) { 12484 try { 12485 observer.onPackageDeleted(packageName, returnCode, null); 12486 } catch (RemoteException e) { 12487 Log.i(TAG, "Observer no longer exists."); 12488 } //end catch 12489 } //end if 12490 } //end run 12491 }); 12492 } 12493 12494 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12495 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12496 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12497 try { 12498 if (dpm != null) { 12499 if (dpm.isDeviceOwner(packageName)) { 12500 return true; 12501 } 12502 int[] users; 12503 if (userId == UserHandle.USER_ALL) { 12504 users = sUserManager.getUserIds(); 12505 } else { 12506 users = new int[]{userId}; 12507 } 12508 for (int i = 0; i < users.length; ++i) { 12509 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12510 return true; 12511 } 12512 } 12513 } 12514 } catch (RemoteException e) { 12515 } 12516 return false; 12517 } 12518 12519 /** 12520 * This method is an internal method that could be get invoked either 12521 * to delete an installed package or to clean up a failed installation. 12522 * After deleting an installed package, a broadcast is sent to notify any 12523 * listeners that the package has been installed. For cleaning up a failed 12524 * installation, the broadcast is not necessary since the package's 12525 * installation wouldn't have sent the initial broadcast either 12526 * The key steps in deleting a package are 12527 * deleting the package information in internal structures like mPackages, 12528 * deleting the packages base directories through installd 12529 * updating mSettings to reflect current status 12530 * persisting settings for later use 12531 * sending a broadcast if necessary 12532 */ 12533 private int deletePackageX(String packageName, int userId, int flags) { 12534 final PackageRemovedInfo info = new PackageRemovedInfo(); 12535 final boolean res; 12536 12537 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12538 ? UserHandle.ALL : new UserHandle(userId); 12539 12540 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12541 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12542 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12543 } 12544 12545 boolean removedForAllUsers = false; 12546 boolean systemUpdate = false; 12547 12548 // for the uninstall-updates case and restricted profiles, remember the per- 12549 // userhandle installed state 12550 int[] allUsers; 12551 boolean[] perUserInstalled; 12552 synchronized (mPackages) { 12553 PackageSetting ps = mSettings.mPackages.get(packageName); 12554 allUsers = sUserManager.getUserIds(); 12555 perUserInstalled = new boolean[allUsers.length]; 12556 for (int i = 0; i < allUsers.length; i++) { 12557 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12558 } 12559 } 12560 12561 synchronized (mInstallLock) { 12562 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12563 res = deletePackageLI(packageName, removeForUser, 12564 true, allUsers, perUserInstalled, 12565 flags | REMOVE_CHATTY, info, true); 12566 systemUpdate = info.isRemovedPackageSystemUpdate; 12567 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12568 removedForAllUsers = true; 12569 } 12570 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12571 + " removedForAllUsers=" + removedForAllUsers); 12572 } 12573 12574 if (res) { 12575 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12576 12577 // If the removed package was a system update, the old system package 12578 // was re-enabled; we need to broadcast this information 12579 if (systemUpdate) { 12580 Bundle extras = new Bundle(1); 12581 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12582 ? info.removedAppId : info.uid); 12583 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12584 12585 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12586 extras, null, null, null); 12587 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12588 extras, null, null, null); 12589 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12590 null, packageName, null, null); 12591 } 12592 } 12593 // Force a gc here. 12594 Runtime.getRuntime().gc(); 12595 // Delete the resources here after sending the broadcast to let 12596 // other processes clean up before deleting resources. 12597 if (info.args != null) { 12598 synchronized (mInstallLock) { 12599 info.args.doPostDeleteLI(true); 12600 } 12601 } 12602 12603 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12604 } 12605 12606 class PackageRemovedInfo { 12607 String removedPackage; 12608 int uid = -1; 12609 int removedAppId = -1; 12610 int[] removedUsers = null; 12611 boolean isRemovedPackageSystemUpdate = false; 12612 // Clean up resources deleted packages. 12613 InstallArgs args = null; 12614 12615 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12616 Bundle extras = new Bundle(1); 12617 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12618 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12619 if (replacing) { 12620 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12621 } 12622 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12623 if (removedPackage != null) { 12624 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12625 extras, null, null, removedUsers); 12626 if (fullRemove && !replacing) { 12627 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12628 extras, null, null, removedUsers); 12629 } 12630 } 12631 if (removedAppId >= 0) { 12632 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12633 removedUsers); 12634 } 12635 } 12636 } 12637 12638 /* 12639 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12640 * flag is not set, the data directory is removed as well. 12641 * make sure this flag is set for partially installed apps. If not its meaningless to 12642 * delete a partially installed application. 12643 */ 12644 private void removePackageDataLI(PackageSetting ps, 12645 int[] allUserHandles, boolean[] perUserInstalled, 12646 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12647 String packageName = ps.name; 12648 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12649 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12650 // Retrieve object to delete permissions for shared user later on 12651 final PackageSetting deletedPs; 12652 // reader 12653 synchronized (mPackages) { 12654 deletedPs = mSettings.mPackages.get(packageName); 12655 if (outInfo != null) { 12656 outInfo.removedPackage = packageName; 12657 outInfo.removedUsers = deletedPs != null 12658 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12659 : null; 12660 } 12661 } 12662 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12663 removeDataDirsLI(ps.volumeUuid, packageName); 12664 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12665 } 12666 // writer 12667 synchronized (mPackages) { 12668 if (deletedPs != null) { 12669 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12670 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12671 clearDefaultBrowserIfNeeded(packageName); 12672 if (outInfo != null) { 12673 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12674 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12675 } 12676 updatePermissionsLPw(deletedPs.name, null, 0); 12677 if (deletedPs.sharedUser != null) { 12678 // Remove permissions associated with package. Since runtime 12679 // permissions are per user we have to kill the removed package 12680 // or packages running under the shared user of the removed 12681 // package if revoking the permissions requested only by the removed 12682 // package is successful and this causes a change in gids. 12683 for (int userId : UserManagerService.getInstance().getUserIds()) { 12684 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12685 userId); 12686 if (userIdToKill == UserHandle.USER_ALL 12687 || userIdToKill >= UserHandle.USER_OWNER) { 12688 // If gids changed for this user, kill all affected packages. 12689 mHandler.post(new Runnable() { 12690 @Override 12691 public void run() { 12692 // This has to happen with no lock held. 12693 killSettingPackagesForUser(deletedPs, userIdToKill, 12694 KILL_APP_REASON_GIDS_CHANGED); 12695 } 12696 }); 12697 break; 12698 } 12699 } 12700 } 12701 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12702 } 12703 // make sure to preserve per-user disabled state if this removal was just 12704 // a downgrade of a system app to the factory package 12705 if (allUserHandles != null && perUserInstalled != null) { 12706 if (DEBUG_REMOVE) { 12707 Slog.d(TAG, "Propagating install state across downgrade"); 12708 } 12709 for (int i = 0; i < allUserHandles.length; i++) { 12710 if (DEBUG_REMOVE) { 12711 Slog.d(TAG, " user " + allUserHandles[i] 12712 + " => " + perUserInstalled[i]); 12713 } 12714 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12715 } 12716 } 12717 } 12718 // can downgrade to reader 12719 if (writeSettings) { 12720 // Save settings now 12721 mSettings.writeLPr(); 12722 } 12723 } 12724 if (outInfo != null) { 12725 // A user ID was deleted here. Go through all users and remove it 12726 // from KeyStore. 12727 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12728 } 12729 } 12730 12731 static boolean locationIsPrivileged(File path) { 12732 try { 12733 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12734 .getCanonicalPath(); 12735 return path.getCanonicalPath().startsWith(privilegedAppDir); 12736 } catch (IOException e) { 12737 Slog.e(TAG, "Unable to access code path " + path); 12738 } 12739 return false; 12740 } 12741 12742 /* 12743 * Tries to delete system package. 12744 */ 12745 private boolean deleteSystemPackageLI(PackageSetting newPs, 12746 int[] allUserHandles, boolean[] perUserInstalled, 12747 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12748 final boolean applyUserRestrictions 12749 = (allUserHandles != null) && (perUserInstalled != null); 12750 PackageSetting disabledPs = null; 12751 // Confirm if the system package has been updated 12752 // An updated system app can be deleted. This will also have to restore 12753 // the system pkg from system partition 12754 // reader 12755 synchronized (mPackages) { 12756 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12757 } 12758 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12759 + " disabledPs=" + disabledPs); 12760 if (disabledPs == null) { 12761 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12762 return false; 12763 } else if (DEBUG_REMOVE) { 12764 Slog.d(TAG, "Deleting system pkg from data partition"); 12765 } 12766 if (DEBUG_REMOVE) { 12767 if (applyUserRestrictions) { 12768 Slog.d(TAG, "Remembering install states:"); 12769 for (int i = 0; i < allUserHandles.length; i++) { 12770 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12771 } 12772 } 12773 } 12774 // Delete the updated package 12775 outInfo.isRemovedPackageSystemUpdate = true; 12776 if (disabledPs.versionCode < newPs.versionCode) { 12777 // Delete data for downgrades 12778 flags &= ~PackageManager.DELETE_KEEP_DATA; 12779 } else { 12780 // Preserve data by setting flag 12781 flags |= PackageManager.DELETE_KEEP_DATA; 12782 } 12783 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12784 allUserHandles, perUserInstalled, outInfo, writeSettings); 12785 if (!ret) { 12786 return false; 12787 } 12788 // writer 12789 synchronized (mPackages) { 12790 // Reinstate the old system package 12791 mSettings.enableSystemPackageLPw(newPs.name); 12792 // Remove any native libraries from the upgraded package. 12793 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12794 } 12795 // Install the system package 12796 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12797 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12798 if (locationIsPrivileged(disabledPs.codePath)) { 12799 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12800 } 12801 12802 final PackageParser.Package newPkg; 12803 try { 12804 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12805 } catch (PackageManagerException e) { 12806 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12807 return false; 12808 } 12809 12810 // writer 12811 synchronized (mPackages) { 12812 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12813 12814 // Propagate the permissions state as we do want to drop on the floor 12815 // runtime permissions. The update permissions method below will take 12816 // care of removing obsolete permissions and grant install permissions. 12817 ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState()); 12818 updatePermissionsLPw(newPkg.packageName, newPkg, 12819 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12820 12821 if (applyUserRestrictions) { 12822 if (DEBUG_REMOVE) { 12823 Slog.d(TAG, "Propagating install state across reinstall"); 12824 } 12825 for (int i = 0; i < allUserHandles.length; i++) { 12826 if (DEBUG_REMOVE) { 12827 Slog.d(TAG, " user " + allUserHandles[i] 12828 + " => " + perUserInstalled[i]); 12829 } 12830 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12831 } 12832 // Regardless of writeSettings we need to ensure that this restriction 12833 // state propagation is persisted 12834 mSettings.writeAllUsersPackageRestrictionsLPr(); 12835 } 12836 // can downgrade to reader here 12837 if (writeSettings) { 12838 mSettings.writeLPr(); 12839 } 12840 } 12841 return true; 12842 } 12843 12844 private boolean deleteInstalledPackageLI(PackageSetting ps, 12845 boolean deleteCodeAndResources, int flags, 12846 int[] allUserHandles, boolean[] perUserInstalled, 12847 PackageRemovedInfo outInfo, boolean writeSettings) { 12848 if (outInfo != null) { 12849 outInfo.uid = ps.appId; 12850 } 12851 12852 // Delete package data from internal structures and also remove data if flag is set 12853 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12854 12855 // Delete application code and resources 12856 if (deleteCodeAndResources && (outInfo != null)) { 12857 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12858 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12859 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12860 } 12861 return true; 12862 } 12863 12864 @Override 12865 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12866 int userId) { 12867 mContext.enforceCallingOrSelfPermission( 12868 android.Manifest.permission.DELETE_PACKAGES, null); 12869 synchronized (mPackages) { 12870 PackageSetting ps = mSettings.mPackages.get(packageName); 12871 if (ps == null) { 12872 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12873 return false; 12874 } 12875 if (!ps.getInstalled(userId)) { 12876 // Can't block uninstall for an app that is not installed or enabled. 12877 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12878 return false; 12879 } 12880 ps.setBlockUninstall(blockUninstall, userId); 12881 mSettings.writePackageRestrictionsLPr(userId); 12882 } 12883 return true; 12884 } 12885 12886 @Override 12887 public boolean getBlockUninstallForUser(String packageName, int userId) { 12888 synchronized (mPackages) { 12889 PackageSetting ps = mSettings.mPackages.get(packageName); 12890 if (ps == null) { 12891 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12892 return false; 12893 } 12894 return ps.getBlockUninstall(userId); 12895 } 12896 } 12897 12898 /* 12899 * This method handles package deletion in general 12900 */ 12901 private boolean deletePackageLI(String packageName, UserHandle user, 12902 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12903 int flags, PackageRemovedInfo outInfo, 12904 boolean writeSettings) { 12905 if (packageName == null) { 12906 Slog.w(TAG, "Attempt to delete null packageName."); 12907 return false; 12908 } 12909 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12910 PackageSetting ps; 12911 boolean dataOnly = false; 12912 int removeUser = -1; 12913 int appId = -1; 12914 synchronized (mPackages) { 12915 ps = mSettings.mPackages.get(packageName); 12916 if (ps == null) { 12917 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12918 return false; 12919 } 12920 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12921 && user.getIdentifier() != UserHandle.USER_ALL) { 12922 // The caller is asking that the package only be deleted for a single 12923 // user. To do this, we just mark its uninstalled state and delete 12924 // its data. If this is a system app, we only allow this to happen if 12925 // they have set the special DELETE_SYSTEM_APP which requests different 12926 // semantics than normal for uninstalling system apps. 12927 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12928 ps.setUserState(user.getIdentifier(), 12929 COMPONENT_ENABLED_STATE_DEFAULT, 12930 false, //installed 12931 true, //stopped 12932 true, //notLaunched 12933 false, //hidden 12934 null, null, null, 12935 false, // blockUninstall 12936 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12937 if (!isSystemApp(ps)) { 12938 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12939 // Other user still have this package installed, so all 12940 // we need to do is clear this user's data and save that 12941 // it is uninstalled. 12942 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12943 removeUser = user.getIdentifier(); 12944 appId = ps.appId; 12945 scheduleWritePackageRestrictionsLocked(removeUser); 12946 } else { 12947 // We need to set it back to 'installed' so the uninstall 12948 // broadcasts will be sent correctly. 12949 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12950 ps.setInstalled(true, user.getIdentifier()); 12951 } 12952 } else { 12953 // This is a system app, so we assume that the 12954 // other users still have this package installed, so all 12955 // we need to do is clear this user's data and save that 12956 // it is uninstalled. 12957 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12958 removeUser = user.getIdentifier(); 12959 appId = ps.appId; 12960 scheduleWritePackageRestrictionsLocked(removeUser); 12961 } 12962 } 12963 } 12964 12965 if (removeUser >= 0) { 12966 // From above, we determined that we are deleting this only 12967 // for a single user. Continue the work here. 12968 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12969 if (outInfo != null) { 12970 outInfo.removedPackage = packageName; 12971 outInfo.removedAppId = appId; 12972 outInfo.removedUsers = new int[] {removeUser}; 12973 } 12974 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12975 removeKeystoreDataIfNeeded(removeUser, appId); 12976 schedulePackageCleaning(packageName, removeUser, false); 12977 synchronized (mPackages) { 12978 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12979 scheduleWritePackageRestrictionsLocked(removeUser); 12980 } 12981 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser); 12982 } 12983 return true; 12984 } 12985 12986 if (dataOnly) { 12987 // Delete application data first 12988 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12989 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12990 return true; 12991 } 12992 12993 boolean ret = false; 12994 if (isSystemApp(ps)) { 12995 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12996 // When an updated system application is deleted we delete the existing resources as well and 12997 // fall back to existing code in system partition 12998 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12999 flags, outInfo, writeSettings); 13000 } else { 13001 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13002 // Kill application pre-emptively especially for apps on sd. 13003 killApplication(packageName, ps.appId, "uninstall pkg"); 13004 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13005 allUserHandles, perUserInstalled, 13006 outInfo, writeSettings); 13007 } 13008 13009 return ret; 13010 } 13011 13012 private final class ClearStorageConnection implements ServiceConnection { 13013 IMediaContainerService mContainerService; 13014 13015 @Override 13016 public void onServiceConnected(ComponentName name, IBinder service) { 13017 synchronized (this) { 13018 mContainerService = IMediaContainerService.Stub.asInterface(service); 13019 notifyAll(); 13020 } 13021 } 13022 13023 @Override 13024 public void onServiceDisconnected(ComponentName name) { 13025 } 13026 } 13027 13028 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13029 final boolean mounted; 13030 if (Environment.isExternalStorageEmulated()) { 13031 mounted = true; 13032 } else { 13033 final String status = Environment.getExternalStorageState(); 13034 13035 mounted = status.equals(Environment.MEDIA_MOUNTED) 13036 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13037 } 13038 13039 if (!mounted) { 13040 return; 13041 } 13042 13043 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13044 int[] users; 13045 if (userId == UserHandle.USER_ALL) { 13046 users = sUserManager.getUserIds(); 13047 } else { 13048 users = new int[] { userId }; 13049 } 13050 final ClearStorageConnection conn = new ClearStorageConnection(); 13051 if (mContext.bindServiceAsUser( 13052 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13053 try { 13054 for (int curUser : users) { 13055 long timeout = SystemClock.uptimeMillis() + 5000; 13056 synchronized (conn) { 13057 long now = SystemClock.uptimeMillis(); 13058 while (conn.mContainerService == null && now < timeout) { 13059 try { 13060 conn.wait(timeout - now); 13061 } catch (InterruptedException e) { 13062 } 13063 } 13064 } 13065 if (conn.mContainerService == null) { 13066 return; 13067 } 13068 13069 final UserEnvironment userEnv = new UserEnvironment(curUser); 13070 clearDirectory(conn.mContainerService, 13071 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13072 if (allData) { 13073 clearDirectory(conn.mContainerService, 13074 userEnv.buildExternalStorageAppDataDirs(packageName)); 13075 clearDirectory(conn.mContainerService, 13076 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13077 } 13078 } 13079 } finally { 13080 mContext.unbindService(conn); 13081 } 13082 } 13083 } 13084 13085 @Override 13086 public void clearApplicationUserData(final String packageName, 13087 final IPackageDataObserver observer, final int userId) { 13088 mContext.enforceCallingOrSelfPermission( 13089 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13090 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13091 // Queue up an async operation since the package deletion may take a little while. 13092 mHandler.post(new Runnable() { 13093 public void run() { 13094 mHandler.removeCallbacks(this); 13095 final boolean succeeded; 13096 synchronized (mInstallLock) { 13097 succeeded = clearApplicationUserDataLI(packageName, userId); 13098 } 13099 clearExternalStorageDataSync(packageName, userId, true); 13100 if (succeeded) { 13101 // invoke DeviceStorageMonitor's update method to clear any notifications 13102 DeviceStorageMonitorInternal 13103 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13104 if (dsm != null) { 13105 dsm.checkMemory(); 13106 } 13107 } 13108 if(observer != null) { 13109 try { 13110 observer.onRemoveCompleted(packageName, succeeded); 13111 } catch (RemoteException e) { 13112 Log.i(TAG, "Observer no longer exists."); 13113 } 13114 } //end if observer 13115 } //end run 13116 }); 13117 } 13118 13119 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13120 if (packageName == null) { 13121 Slog.w(TAG, "Attempt to delete null packageName."); 13122 return false; 13123 } 13124 13125 // Try finding details about the requested package 13126 PackageParser.Package pkg; 13127 synchronized (mPackages) { 13128 pkg = mPackages.get(packageName); 13129 if (pkg == null) { 13130 final PackageSetting ps = mSettings.mPackages.get(packageName); 13131 if (ps != null) { 13132 pkg = ps.pkg; 13133 } 13134 } 13135 13136 if (pkg == null) { 13137 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13138 return false; 13139 } 13140 13141 PackageSetting ps = (PackageSetting) pkg.mExtras; 13142 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 13143 } 13144 13145 // Always delete data directories for package, even if we found no other 13146 // record of app. This helps users recover from UID mismatches without 13147 // resorting to a full data wipe. 13148 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13149 if (retCode < 0) { 13150 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13151 return false; 13152 } 13153 13154 final int appId = pkg.applicationInfo.uid; 13155 removeKeystoreDataIfNeeded(userId, appId); 13156 13157 // Create a native library symlink only if we have native libraries 13158 // and if the native libraries are 32 bit libraries. We do not provide 13159 // this symlink for 64 bit libraries. 13160 if (pkg.applicationInfo.primaryCpuAbi != null && 13161 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13162 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13163 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13164 nativeLibPath, userId) < 0) { 13165 Slog.w(TAG, "Failed linking native library dir"); 13166 return false; 13167 } 13168 } 13169 13170 return true; 13171 } 13172 13173 /** 13174 * Reverts user permission state changes (permissions and flags). 13175 * 13176 * @param ps The package for which to reset. 13177 * @param userId The device user for which to do a reset. 13178 */ 13179 private void resetUserChangesToRuntimePermissionsAndFlagsLocked( 13180 final PackageSetting ps, final int userId) { 13181 if (ps.pkg == null) { 13182 return; 13183 } 13184 13185 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13186 | FLAG_PERMISSION_USER_FIXED 13187 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13188 13189 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13190 | FLAG_PERMISSION_POLICY_FIXED; 13191 13192 boolean writeInstallPermissions = false; 13193 boolean writeRuntimePermissions = false; 13194 13195 final int permissionCount = ps.pkg.requestedPermissions.size(); 13196 for (int i = 0; i < permissionCount; i++) { 13197 String permission = ps.pkg.requestedPermissions.get(i); 13198 13199 BasePermission bp = mSettings.mPermissions.get(permission); 13200 if (bp == null) { 13201 continue; 13202 } 13203 13204 // If shared user we just reset the state to which only this app contributed. 13205 if (ps.sharedUser != null) { 13206 boolean used = false; 13207 final int packageCount = ps.sharedUser.packages.size(); 13208 for (int j = 0; j < packageCount; j++) { 13209 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13210 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13211 && pkg.pkg.requestedPermissions.contains(permission)) { 13212 used = true; 13213 break; 13214 } 13215 } 13216 if (used) { 13217 continue; 13218 } 13219 } 13220 13221 PermissionsState permissionsState = ps.getPermissionsState(); 13222 13223 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13224 13225 // Always clear the user settable flags. 13226 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13227 bp.name) != null; 13228 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13229 if (hasInstallState) { 13230 writeInstallPermissions = true; 13231 } else { 13232 writeRuntimePermissions = true; 13233 } 13234 } 13235 13236 // Below is only runtime permission handling. 13237 if (!bp.isRuntime()) { 13238 continue; 13239 } 13240 13241 // Never clobber system or policy. 13242 if ((oldFlags & policyOrSystemFlags) != 0) { 13243 continue; 13244 } 13245 13246 // If this permission was granted by default, make sure it is. 13247 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13248 if (permissionsState.grantRuntimePermission(bp, userId) 13249 != PERMISSION_OPERATION_FAILURE) { 13250 writeRuntimePermissions = true; 13251 } 13252 } else { 13253 // Otherwise, reset the permission. 13254 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13255 switch (revokeResult) { 13256 case PERMISSION_OPERATION_SUCCESS: { 13257 writeRuntimePermissions = true; 13258 } break; 13259 13260 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13261 writeRuntimePermissions = true; 13262 // If gids changed for this user, kill all affected packages. 13263 mHandler.post(new Runnable() { 13264 @Override 13265 public void run() { 13266 // This has to happen with no lock held. 13267 killSettingPackagesForUser(ps, userId, 13268 KILL_APP_REASON_GIDS_CHANGED); 13269 } 13270 }); 13271 } break; 13272 } 13273 } 13274 } 13275 13276 // Synchronously write as we are taking permissions away. 13277 if (writeRuntimePermissions) { 13278 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13279 } 13280 13281 // Synchronously write as we are taking permissions away. 13282 if (writeInstallPermissions) { 13283 mSettings.writeLPr(); 13284 } 13285 } 13286 13287 /** 13288 * Remove entries from the keystore daemon. Will only remove it if the 13289 * {@code appId} is valid. 13290 */ 13291 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13292 if (appId < 0) { 13293 return; 13294 } 13295 13296 final KeyStore keyStore = KeyStore.getInstance(); 13297 if (keyStore != null) { 13298 if (userId == UserHandle.USER_ALL) { 13299 for (final int individual : sUserManager.getUserIds()) { 13300 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13301 } 13302 } else { 13303 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13304 } 13305 } else { 13306 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13307 } 13308 } 13309 13310 @Override 13311 public void deleteApplicationCacheFiles(final String packageName, 13312 final IPackageDataObserver observer) { 13313 mContext.enforceCallingOrSelfPermission( 13314 android.Manifest.permission.DELETE_CACHE_FILES, null); 13315 // Queue up an async operation since the package deletion may take a little while. 13316 final int userId = UserHandle.getCallingUserId(); 13317 mHandler.post(new Runnable() { 13318 public void run() { 13319 mHandler.removeCallbacks(this); 13320 final boolean succeded; 13321 synchronized (mInstallLock) { 13322 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13323 } 13324 clearExternalStorageDataSync(packageName, userId, false); 13325 if (observer != null) { 13326 try { 13327 observer.onRemoveCompleted(packageName, succeded); 13328 } catch (RemoteException e) { 13329 Log.i(TAG, "Observer no longer exists."); 13330 } 13331 } //end if observer 13332 } //end run 13333 }); 13334 } 13335 13336 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13337 if (packageName == null) { 13338 Slog.w(TAG, "Attempt to delete null packageName."); 13339 return false; 13340 } 13341 PackageParser.Package p; 13342 synchronized (mPackages) { 13343 p = mPackages.get(packageName); 13344 } 13345 if (p == null) { 13346 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13347 return false; 13348 } 13349 final ApplicationInfo applicationInfo = p.applicationInfo; 13350 if (applicationInfo == null) { 13351 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13352 return false; 13353 } 13354 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13355 if (retCode < 0) { 13356 Slog.w(TAG, "Couldn't remove cache files for package: " 13357 + packageName + " u" + userId); 13358 return false; 13359 } 13360 return true; 13361 } 13362 13363 @Override 13364 public void getPackageSizeInfo(final String packageName, int userHandle, 13365 final IPackageStatsObserver observer) { 13366 mContext.enforceCallingOrSelfPermission( 13367 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13368 if (packageName == null) { 13369 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13370 } 13371 13372 PackageStats stats = new PackageStats(packageName, userHandle); 13373 13374 /* 13375 * Queue up an async operation since the package measurement may take a 13376 * little while. 13377 */ 13378 Message msg = mHandler.obtainMessage(INIT_COPY); 13379 msg.obj = new MeasureParams(stats, observer); 13380 mHandler.sendMessage(msg); 13381 } 13382 13383 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13384 PackageStats pStats) { 13385 if (packageName == null) { 13386 Slog.w(TAG, "Attempt to get size of null packageName."); 13387 return false; 13388 } 13389 PackageParser.Package p; 13390 boolean dataOnly = false; 13391 String libDirRoot = null; 13392 String asecPath = null; 13393 PackageSetting ps = null; 13394 synchronized (mPackages) { 13395 p = mPackages.get(packageName); 13396 ps = mSettings.mPackages.get(packageName); 13397 if(p == null) { 13398 dataOnly = true; 13399 if((ps == null) || (ps.pkg == null)) { 13400 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13401 return false; 13402 } 13403 p = ps.pkg; 13404 } 13405 if (ps != null) { 13406 libDirRoot = ps.legacyNativeLibraryPathString; 13407 } 13408 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13409 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13410 if (secureContainerId != null) { 13411 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13412 } 13413 } 13414 } 13415 String publicSrcDir = null; 13416 if(!dataOnly) { 13417 final ApplicationInfo applicationInfo = p.applicationInfo; 13418 if (applicationInfo == null) { 13419 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13420 return false; 13421 } 13422 if (p.isForwardLocked()) { 13423 publicSrcDir = applicationInfo.getBaseResourcePath(); 13424 } 13425 } 13426 // TODO: extend to measure size of split APKs 13427 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13428 // not just the first level. 13429 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13430 // just the primary. 13431 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13432 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13433 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13434 if (res < 0) { 13435 return false; 13436 } 13437 13438 // Fix-up for forward-locked applications in ASEC containers. 13439 if (!isExternal(p)) { 13440 pStats.codeSize += pStats.externalCodeSize; 13441 pStats.externalCodeSize = 0L; 13442 } 13443 13444 return true; 13445 } 13446 13447 13448 @Override 13449 public void addPackageToPreferred(String packageName) { 13450 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13451 } 13452 13453 @Override 13454 public void removePackageFromPreferred(String packageName) { 13455 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13456 } 13457 13458 @Override 13459 public List<PackageInfo> getPreferredPackages(int flags) { 13460 return new ArrayList<PackageInfo>(); 13461 } 13462 13463 private int getUidTargetSdkVersionLockedLPr(int uid) { 13464 Object obj = mSettings.getUserIdLPr(uid); 13465 if (obj instanceof SharedUserSetting) { 13466 final SharedUserSetting sus = (SharedUserSetting) obj; 13467 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13468 final Iterator<PackageSetting> it = sus.packages.iterator(); 13469 while (it.hasNext()) { 13470 final PackageSetting ps = it.next(); 13471 if (ps.pkg != null) { 13472 int v = ps.pkg.applicationInfo.targetSdkVersion; 13473 if (v < vers) vers = v; 13474 } 13475 } 13476 return vers; 13477 } else if (obj instanceof PackageSetting) { 13478 final PackageSetting ps = (PackageSetting) obj; 13479 if (ps.pkg != null) { 13480 return ps.pkg.applicationInfo.targetSdkVersion; 13481 } 13482 } 13483 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13484 } 13485 13486 @Override 13487 public void addPreferredActivity(IntentFilter filter, int match, 13488 ComponentName[] set, ComponentName activity, int userId) { 13489 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13490 "Adding preferred"); 13491 } 13492 13493 private void addPreferredActivityInternal(IntentFilter filter, int match, 13494 ComponentName[] set, ComponentName activity, boolean always, int userId, 13495 String opname) { 13496 // writer 13497 int callingUid = Binder.getCallingUid(); 13498 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13499 if (filter.countActions() == 0) { 13500 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13501 return; 13502 } 13503 synchronized (mPackages) { 13504 if (mContext.checkCallingOrSelfPermission( 13505 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13506 != PackageManager.PERMISSION_GRANTED) { 13507 if (getUidTargetSdkVersionLockedLPr(callingUid) 13508 < Build.VERSION_CODES.FROYO) { 13509 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13510 + callingUid); 13511 return; 13512 } 13513 mContext.enforceCallingOrSelfPermission( 13514 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13515 } 13516 13517 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13518 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13519 + userId + ":"); 13520 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13521 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13522 scheduleWritePackageRestrictionsLocked(userId); 13523 } 13524 } 13525 13526 @Override 13527 public void replacePreferredActivity(IntentFilter filter, int match, 13528 ComponentName[] set, ComponentName activity, int userId) { 13529 if (filter.countActions() != 1) { 13530 throw new IllegalArgumentException( 13531 "replacePreferredActivity expects filter to have only 1 action."); 13532 } 13533 if (filter.countDataAuthorities() != 0 13534 || filter.countDataPaths() != 0 13535 || filter.countDataSchemes() > 1 13536 || filter.countDataTypes() != 0) { 13537 throw new IllegalArgumentException( 13538 "replacePreferredActivity expects filter to have no data authorities, " + 13539 "paths, or types; and at most one scheme."); 13540 } 13541 13542 final int callingUid = Binder.getCallingUid(); 13543 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13544 synchronized (mPackages) { 13545 if (mContext.checkCallingOrSelfPermission( 13546 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13547 != PackageManager.PERMISSION_GRANTED) { 13548 if (getUidTargetSdkVersionLockedLPr(callingUid) 13549 < Build.VERSION_CODES.FROYO) { 13550 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13551 + Binder.getCallingUid()); 13552 return; 13553 } 13554 mContext.enforceCallingOrSelfPermission( 13555 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13556 } 13557 13558 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13559 if (pir != null) { 13560 // Get all of the existing entries that exactly match this filter. 13561 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13562 if (existing != null && existing.size() == 1) { 13563 PreferredActivity cur = existing.get(0); 13564 if (DEBUG_PREFERRED) { 13565 Slog.i(TAG, "Checking replace of preferred:"); 13566 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13567 if (!cur.mPref.mAlways) { 13568 Slog.i(TAG, " -- CUR; not mAlways!"); 13569 } else { 13570 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13571 Slog.i(TAG, " -- CUR: mSet=" 13572 + Arrays.toString(cur.mPref.mSetComponents)); 13573 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13574 Slog.i(TAG, " -- NEW: mMatch=" 13575 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13576 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13577 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13578 } 13579 } 13580 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13581 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13582 && cur.mPref.sameSet(set)) { 13583 // Setting the preferred activity to what it happens to be already 13584 if (DEBUG_PREFERRED) { 13585 Slog.i(TAG, "Replacing with same preferred activity " 13586 + cur.mPref.mShortComponent + " for user " 13587 + userId + ":"); 13588 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13589 } 13590 return; 13591 } 13592 } 13593 13594 if (existing != null) { 13595 if (DEBUG_PREFERRED) { 13596 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13597 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13598 } 13599 for (int i = 0; i < existing.size(); i++) { 13600 PreferredActivity pa = existing.get(i); 13601 if (DEBUG_PREFERRED) { 13602 Slog.i(TAG, "Removing existing preferred activity " 13603 + pa.mPref.mComponent + ":"); 13604 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13605 } 13606 pir.removeFilter(pa); 13607 } 13608 } 13609 } 13610 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13611 "Replacing preferred"); 13612 } 13613 } 13614 13615 @Override 13616 public void clearPackagePreferredActivities(String packageName) { 13617 final int uid = Binder.getCallingUid(); 13618 // writer 13619 synchronized (mPackages) { 13620 PackageParser.Package pkg = mPackages.get(packageName); 13621 if (pkg == null || pkg.applicationInfo.uid != uid) { 13622 if (mContext.checkCallingOrSelfPermission( 13623 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13624 != PackageManager.PERMISSION_GRANTED) { 13625 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13626 < Build.VERSION_CODES.FROYO) { 13627 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13628 + Binder.getCallingUid()); 13629 return; 13630 } 13631 mContext.enforceCallingOrSelfPermission( 13632 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13633 } 13634 } 13635 13636 int user = UserHandle.getCallingUserId(); 13637 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13638 scheduleWritePackageRestrictionsLocked(user); 13639 } 13640 } 13641 } 13642 13643 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13644 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13645 ArrayList<PreferredActivity> removed = null; 13646 boolean changed = false; 13647 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13648 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13649 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13650 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13651 continue; 13652 } 13653 Iterator<PreferredActivity> it = pir.filterIterator(); 13654 while (it.hasNext()) { 13655 PreferredActivity pa = it.next(); 13656 // Mark entry for removal only if it matches the package name 13657 // and the entry is of type "always". 13658 if (packageName == null || 13659 (pa.mPref.mComponent.getPackageName().equals(packageName) 13660 && pa.mPref.mAlways)) { 13661 if (removed == null) { 13662 removed = new ArrayList<PreferredActivity>(); 13663 } 13664 removed.add(pa); 13665 } 13666 } 13667 if (removed != null) { 13668 for (int j=0; j<removed.size(); j++) { 13669 PreferredActivity pa = removed.get(j); 13670 pir.removeFilter(pa); 13671 } 13672 changed = true; 13673 } 13674 } 13675 return changed; 13676 } 13677 13678 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13679 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13680 if (userId == UserHandle.USER_ALL) { 13681 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13682 sUserManager.getUserIds())) { 13683 for (int oneUserId : sUserManager.getUserIds()) { 13684 scheduleWritePackageRestrictionsLocked(oneUserId); 13685 } 13686 } 13687 } else { 13688 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13689 scheduleWritePackageRestrictionsLocked(userId); 13690 } 13691 } 13692 } 13693 13694 13695 void clearDefaultBrowserIfNeeded(String packageName) { 13696 for (int oneUserId : sUserManager.getUserIds()) { 13697 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13698 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13699 if (packageName.equals(defaultBrowserPackageName)) { 13700 setDefaultBrowserPackageName(null, oneUserId); 13701 } 13702 } 13703 } 13704 13705 @Override 13706 public void resetPreferredActivities(int userId) { 13707 mContext.enforceCallingOrSelfPermission( 13708 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13709 // writer 13710 synchronized (mPackages) { 13711 clearPackagePreferredActivitiesLPw(null, userId); 13712 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13713 applyFactoryDefaultBrowserLPw(userId); 13714 primeDomainVerificationsLPw(userId); 13715 13716 scheduleWritePackageRestrictionsLocked(userId); 13717 } 13718 } 13719 13720 @Override 13721 public int getPreferredActivities(List<IntentFilter> outFilters, 13722 List<ComponentName> outActivities, String packageName) { 13723 13724 int num = 0; 13725 final int userId = UserHandle.getCallingUserId(); 13726 // reader 13727 synchronized (mPackages) { 13728 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13729 if (pir != null) { 13730 final Iterator<PreferredActivity> it = pir.filterIterator(); 13731 while (it.hasNext()) { 13732 final PreferredActivity pa = it.next(); 13733 if (packageName == null 13734 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13735 && pa.mPref.mAlways)) { 13736 if (outFilters != null) { 13737 outFilters.add(new IntentFilter(pa)); 13738 } 13739 if (outActivities != null) { 13740 outActivities.add(pa.mPref.mComponent); 13741 } 13742 } 13743 } 13744 } 13745 } 13746 13747 return num; 13748 } 13749 13750 @Override 13751 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13752 int userId) { 13753 int callingUid = Binder.getCallingUid(); 13754 if (callingUid != Process.SYSTEM_UID) { 13755 throw new SecurityException( 13756 "addPersistentPreferredActivity can only be run by the system"); 13757 } 13758 if (filter.countActions() == 0) { 13759 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13760 return; 13761 } 13762 synchronized (mPackages) { 13763 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13764 " :"); 13765 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13766 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13767 new PersistentPreferredActivity(filter, activity)); 13768 scheduleWritePackageRestrictionsLocked(userId); 13769 } 13770 } 13771 13772 @Override 13773 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13774 int callingUid = Binder.getCallingUid(); 13775 if (callingUid != Process.SYSTEM_UID) { 13776 throw new SecurityException( 13777 "clearPackagePersistentPreferredActivities can only be run by the system"); 13778 } 13779 ArrayList<PersistentPreferredActivity> removed = null; 13780 boolean changed = false; 13781 synchronized (mPackages) { 13782 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13783 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13784 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13785 .valueAt(i); 13786 if (userId != thisUserId) { 13787 continue; 13788 } 13789 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13790 while (it.hasNext()) { 13791 PersistentPreferredActivity ppa = it.next(); 13792 // Mark entry for removal only if it matches the package name. 13793 if (ppa.mComponent.getPackageName().equals(packageName)) { 13794 if (removed == null) { 13795 removed = new ArrayList<PersistentPreferredActivity>(); 13796 } 13797 removed.add(ppa); 13798 } 13799 } 13800 if (removed != null) { 13801 for (int j=0; j<removed.size(); j++) { 13802 PersistentPreferredActivity ppa = removed.get(j); 13803 ppir.removeFilter(ppa); 13804 } 13805 changed = true; 13806 } 13807 } 13808 13809 if (changed) { 13810 scheduleWritePackageRestrictionsLocked(userId); 13811 } 13812 } 13813 } 13814 13815 /** 13816 * Common machinery for picking apart a restored XML blob and passing 13817 * it to a caller-supplied functor to be applied to the running system. 13818 */ 13819 private void restoreFromXml(XmlPullParser parser, int userId, 13820 String expectedStartTag, BlobXmlRestorer functor) 13821 throws IOException, XmlPullParserException { 13822 int type; 13823 while ((type = parser.next()) != XmlPullParser.START_TAG 13824 && type != XmlPullParser.END_DOCUMENT) { 13825 } 13826 if (type != XmlPullParser.START_TAG) { 13827 // oops didn't find a start tag?! 13828 if (DEBUG_BACKUP) { 13829 Slog.e(TAG, "Didn't find start tag during restore"); 13830 } 13831 return; 13832 } 13833 13834 // this is supposed to be TAG_PREFERRED_BACKUP 13835 if (!expectedStartTag.equals(parser.getName())) { 13836 if (DEBUG_BACKUP) { 13837 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13838 } 13839 return; 13840 } 13841 13842 // skip interfering stuff, then we're aligned with the backing implementation 13843 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13844 functor.apply(parser, userId); 13845 } 13846 13847 private interface BlobXmlRestorer { 13848 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13849 } 13850 13851 /** 13852 * Non-Binder method, support for the backup/restore mechanism: write the 13853 * full set of preferred activities in its canonical XML format. Returns the 13854 * XML output as a byte array, or null if there is none. 13855 */ 13856 @Override 13857 public byte[] getPreferredActivityBackup(int userId) { 13858 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13859 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13860 } 13861 13862 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13863 try { 13864 final XmlSerializer serializer = new FastXmlSerializer(); 13865 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13866 serializer.startDocument(null, true); 13867 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13868 13869 synchronized (mPackages) { 13870 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13871 } 13872 13873 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13874 serializer.endDocument(); 13875 serializer.flush(); 13876 } catch (Exception e) { 13877 if (DEBUG_BACKUP) { 13878 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13879 } 13880 return null; 13881 } 13882 13883 return dataStream.toByteArray(); 13884 } 13885 13886 @Override 13887 public void restorePreferredActivities(byte[] backup, int userId) { 13888 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13889 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13890 } 13891 13892 try { 13893 final XmlPullParser parser = Xml.newPullParser(); 13894 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13895 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13896 new BlobXmlRestorer() { 13897 @Override 13898 public void apply(XmlPullParser parser, int userId) 13899 throws XmlPullParserException, IOException { 13900 synchronized (mPackages) { 13901 mSettings.readPreferredActivitiesLPw(parser, userId); 13902 } 13903 } 13904 } ); 13905 } catch (Exception e) { 13906 if (DEBUG_BACKUP) { 13907 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13908 } 13909 } 13910 } 13911 13912 /** 13913 * Non-Binder method, support for the backup/restore mechanism: write the 13914 * default browser (etc) settings in its canonical XML format. Returns the default 13915 * browser XML representation as a byte array, or null if there is none. 13916 */ 13917 @Override 13918 public byte[] getDefaultAppsBackup(int userId) { 13919 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13920 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13921 } 13922 13923 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13924 try { 13925 final XmlSerializer serializer = new FastXmlSerializer(); 13926 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13927 serializer.startDocument(null, true); 13928 serializer.startTag(null, TAG_DEFAULT_APPS); 13929 13930 synchronized (mPackages) { 13931 mSettings.writeDefaultAppsLPr(serializer, userId); 13932 } 13933 13934 serializer.endTag(null, TAG_DEFAULT_APPS); 13935 serializer.endDocument(); 13936 serializer.flush(); 13937 } catch (Exception e) { 13938 if (DEBUG_BACKUP) { 13939 Slog.e(TAG, "Unable to write default apps for backup", e); 13940 } 13941 return null; 13942 } 13943 13944 return dataStream.toByteArray(); 13945 } 13946 13947 @Override 13948 public void restoreDefaultApps(byte[] backup, int userId) { 13949 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13950 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13951 } 13952 13953 try { 13954 final XmlPullParser parser = Xml.newPullParser(); 13955 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13956 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13957 new BlobXmlRestorer() { 13958 @Override 13959 public void apply(XmlPullParser parser, int userId) 13960 throws XmlPullParserException, IOException { 13961 synchronized (mPackages) { 13962 mSettings.readDefaultAppsLPw(parser, userId); 13963 } 13964 } 13965 } ); 13966 } catch (Exception e) { 13967 if (DEBUG_BACKUP) { 13968 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13969 } 13970 } 13971 } 13972 13973 @Override 13974 public byte[] getIntentFilterVerificationBackup(int userId) { 13975 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13976 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13977 } 13978 13979 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13980 try { 13981 final XmlSerializer serializer = new FastXmlSerializer(); 13982 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13983 serializer.startDocument(null, true); 13984 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13985 13986 synchronized (mPackages) { 13987 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13988 } 13989 13990 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13991 serializer.endDocument(); 13992 serializer.flush(); 13993 } catch (Exception e) { 13994 if (DEBUG_BACKUP) { 13995 Slog.e(TAG, "Unable to write default apps for backup", e); 13996 } 13997 return null; 13998 } 13999 14000 return dataStream.toByteArray(); 14001 } 14002 14003 @Override 14004 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14005 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14006 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14007 } 14008 14009 try { 14010 final XmlPullParser parser = Xml.newPullParser(); 14011 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14012 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14013 new BlobXmlRestorer() { 14014 @Override 14015 public void apply(XmlPullParser parser, int userId) 14016 throws XmlPullParserException, IOException { 14017 synchronized (mPackages) { 14018 mSettings.readAllDomainVerificationsLPr(parser, userId); 14019 mSettings.writeLPr(); 14020 } 14021 } 14022 } ); 14023 } catch (Exception e) { 14024 if (DEBUG_BACKUP) { 14025 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14026 } 14027 } 14028 } 14029 14030 @Override 14031 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14032 int sourceUserId, int targetUserId, int flags) { 14033 mContext.enforceCallingOrSelfPermission( 14034 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14035 int callingUid = Binder.getCallingUid(); 14036 enforceOwnerRights(ownerPackage, callingUid); 14037 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14038 if (intentFilter.countActions() == 0) { 14039 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14040 return; 14041 } 14042 synchronized (mPackages) { 14043 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14044 ownerPackage, targetUserId, flags); 14045 CrossProfileIntentResolver resolver = 14046 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14047 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14048 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14049 if (existing != null) { 14050 int size = existing.size(); 14051 for (int i = 0; i < size; i++) { 14052 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14053 return; 14054 } 14055 } 14056 } 14057 resolver.addFilter(newFilter); 14058 scheduleWritePackageRestrictionsLocked(sourceUserId); 14059 } 14060 } 14061 14062 @Override 14063 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14064 mContext.enforceCallingOrSelfPermission( 14065 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14066 int callingUid = Binder.getCallingUid(); 14067 enforceOwnerRights(ownerPackage, callingUid); 14068 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14069 synchronized (mPackages) { 14070 CrossProfileIntentResolver resolver = 14071 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14072 ArraySet<CrossProfileIntentFilter> set = 14073 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14074 for (CrossProfileIntentFilter filter : set) { 14075 if (filter.getOwnerPackage().equals(ownerPackage)) { 14076 resolver.removeFilter(filter); 14077 } 14078 } 14079 scheduleWritePackageRestrictionsLocked(sourceUserId); 14080 } 14081 } 14082 14083 // Enforcing that callingUid is owning pkg on userId 14084 private void enforceOwnerRights(String pkg, int callingUid) { 14085 // The system owns everything. 14086 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14087 return; 14088 } 14089 int callingUserId = UserHandle.getUserId(callingUid); 14090 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14091 if (pi == null) { 14092 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14093 + callingUserId); 14094 } 14095 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14096 throw new SecurityException("Calling uid " + callingUid 14097 + " does not own package " + pkg); 14098 } 14099 } 14100 14101 @Override 14102 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14103 Intent intent = new Intent(Intent.ACTION_MAIN); 14104 intent.addCategory(Intent.CATEGORY_HOME); 14105 14106 final int callingUserId = UserHandle.getCallingUserId(); 14107 List<ResolveInfo> list = queryIntentActivities(intent, null, 14108 PackageManager.GET_META_DATA, callingUserId); 14109 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14110 true, false, false, callingUserId); 14111 14112 allHomeCandidates.clear(); 14113 if (list != null) { 14114 for (ResolveInfo ri : list) { 14115 allHomeCandidates.add(ri); 14116 } 14117 } 14118 return (preferred == null || preferred.activityInfo == null) 14119 ? null 14120 : new ComponentName(preferred.activityInfo.packageName, 14121 preferred.activityInfo.name); 14122 } 14123 14124 @Override 14125 public void setApplicationEnabledSetting(String appPackageName, 14126 int newState, int flags, int userId, String callingPackage) { 14127 if (!sUserManager.exists(userId)) return; 14128 if (callingPackage == null) { 14129 callingPackage = Integer.toString(Binder.getCallingUid()); 14130 } 14131 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14132 } 14133 14134 @Override 14135 public void setComponentEnabledSetting(ComponentName componentName, 14136 int newState, int flags, int userId) { 14137 if (!sUserManager.exists(userId)) return; 14138 setEnabledSetting(componentName.getPackageName(), 14139 componentName.getClassName(), newState, flags, userId, null); 14140 } 14141 14142 private void setEnabledSetting(final String packageName, String className, int newState, 14143 final int flags, int userId, String callingPackage) { 14144 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14145 || newState == COMPONENT_ENABLED_STATE_ENABLED 14146 || newState == COMPONENT_ENABLED_STATE_DISABLED 14147 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14148 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14149 throw new IllegalArgumentException("Invalid new component state: " 14150 + newState); 14151 } 14152 PackageSetting pkgSetting; 14153 final int uid = Binder.getCallingUid(); 14154 final int permission = mContext.checkCallingOrSelfPermission( 14155 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14156 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14157 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14158 boolean sendNow = false; 14159 boolean isApp = (className == null); 14160 String componentName = isApp ? packageName : className; 14161 int packageUid = -1; 14162 ArrayList<String> components; 14163 14164 // writer 14165 synchronized (mPackages) { 14166 pkgSetting = mSettings.mPackages.get(packageName); 14167 if (pkgSetting == null) { 14168 if (className == null) { 14169 throw new IllegalArgumentException( 14170 "Unknown package: " + packageName); 14171 } 14172 throw new IllegalArgumentException( 14173 "Unknown component: " + packageName 14174 + "/" + className); 14175 } 14176 // Allow root and verify that userId is not being specified by a different user 14177 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14178 throw new SecurityException( 14179 "Permission Denial: attempt to change component state from pid=" 14180 + Binder.getCallingPid() 14181 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14182 } 14183 if (className == null) { 14184 // We're dealing with an application/package level state change 14185 if (pkgSetting.getEnabled(userId) == newState) { 14186 // Nothing to do 14187 return; 14188 } 14189 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14190 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14191 // Don't care about who enables an app. 14192 callingPackage = null; 14193 } 14194 pkgSetting.setEnabled(newState, userId, callingPackage); 14195 // pkgSetting.pkg.mSetEnabled = newState; 14196 } else { 14197 // We're dealing with a component level state change 14198 // First, verify that this is a valid class name. 14199 PackageParser.Package pkg = pkgSetting.pkg; 14200 if (pkg == null || !pkg.hasComponentClassName(className)) { 14201 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14202 throw new IllegalArgumentException("Component class " + className 14203 + " does not exist in " + packageName); 14204 } else { 14205 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14206 + className + " does not exist in " + packageName); 14207 } 14208 } 14209 switch (newState) { 14210 case COMPONENT_ENABLED_STATE_ENABLED: 14211 if (!pkgSetting.enableComponentLPw(className, userId)) { 14212 return; 14213 } 14214 break; 14215 case COMPONENT_ENABLED_STATE_DISABLED: 14216 if (!pkgSetting.disableComponentLPw(className, userId)) { 14217 return; 14218 } 14219 break; 14220 case COMPONENT_ENABLED_STATE_DEFAULT: 14221 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14222 return; 14223 } 14224 break; 14225 default: 14226 Slog.e(TAG, "Invalid new component state: " + newState); 14227 return; 14228 } 14229 } 14230 scheduleWritePackageRestrictionsLocked(userId); 14231 components = mPendingBroadcasts.get(userId, packageName); 14232 final boolean newPackage = components == null; 14233 if (newPackage) { 14234 components = new ArrayList<String>(); 14235 } 14236 if (!components.contains(componentName)) { 14237 components.add(componentName); 14238 } 14239 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14240 sendNow = true; 14241 // Purge entry from pending broadcast list if another one exists already 14242 // since we are sending one right away. 14243 mPendingBroadcasts.remove(userId, packageName); 14244 } else { 14245 if (newPackage) { 14246 mPendingBroadcasts.put(userId, packageName, components); 14247 } 14248 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14249 // Schedule a message 14250 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14251 } 14252 } 14253 } 14254 14255 long callingId = Binder.clearCallingIdentity(); 14256 try { 14257 if (sendNow) { 14258 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14259 sendPackageChangedBroadcast(packageName, 14260 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14261 } 14262 } finally { 14263 Binder.restoreCallingIdentity(callingId); 14264 } 14265 } 14266 14267 private void sendPackageChangedBroadcast(String packageName, 14268 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14269 if (DEBUG_INSTALL) 14270 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14271 + componentNames); 14272 Bundle extras = new Bundle(4); 14273 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14274 String nameList[] = new String[componentNames.size()]; 14275 componentNames.toArray(nameList); 14276 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14277 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14278 extras.putInt(Intent.EXTRA_UID, packageUid); 14279 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14280 new int[] {UserHandle.getUserId(packageUid)}); 14281 } 14282 14283 @Override 14284 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14285 if (!sUserManager.exists(userId)) return; 14286 final int uid = Binder.getCallingUid(); 14287 final int permission = mContext.checkCallingOrSelfPermission( 14288 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14289 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14290 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14291 // writer 14292 synchronized (mPackages) { 14293 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14294 allowedByPermission, uid, userId)) { 14295 scheduleWritePackageRestrictionsLocked(userId); 14296 } 14297 } 14298 } 14299 14300 @Override 14301 public String getInstallerPackageName(String packageName) { 14302 // reader 14303 synchronized (mPackages) { 14304 return mSettings.getInstallerPackageNameLPr(packageName); 14305 } 14306 } 14307 14308 @Override 14309 public int getApplicationEnabledSetting(String packageName, int userId) { 14310 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14311 int uid = Binder.getCallingUid(); 14312 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14313 // reader 14314 synchronized (mPackages) { 14315 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14316 } 14317 } 14318 14319 @Override 14320 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14321 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14322 int uid = Binder.getCallingUid(); 14323 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14324 // reader 14325 synchronized (mPackages) { 14326 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14327 } 14328 } 14329 14330 @Override 14331 public void enterSafeMode() { 14332 enforceSystemOrRoot("Only the system can request entering safe mode"); 14333 14334 if (!mSystemReady) { 14335 mSafeMode = true; 14336 } 14337 } 14338 14339 @Override 14340 public void systemReady() { 14341 mSystemReady = true; 14342 14343 // Read the compatibilty setting when the system is ready. 14344 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14345 mContext.getContentResolver(), 14346 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14347 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14348 if (DEBUG_SETTINGS) { 14349 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14350 } 14351 14352 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14353 14354 synchronized (mPackages) { 14355 // Verify that all of the preferred activity components actually 14356 // exist. It is possible for applications to be updated and at 14357 // that point remove a previously declared activity component that 14358 // had been set as a preferred activity. We try to clean this up 14359 // the next time we encounter that preferred activity, but it is 14360 // possible for the user flow to never be able to return to that 14361 // situation so here we do a sanity check to make sure we haven't 14362 // left any junk around. 14363 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14364 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14365 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14366 removed.clear(); 14367 for (PreferredActivity pa : pir.filterSet()) { 14368 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14369 removed.add(pa); 14370 } 14371 } 14372 if (removed.size() > 0) { 14373 for (int r=0; r<removed.size(); r++) { 14374 PreferredActivity pa = removed.get(r); 14375 Slog.w(TAG, "Removing dangling preferred activity: " 14376 + pa.mPref.mComponent); 14377 pir.removeFilter(pa); 14378 } 14379 mSettings.writePackageRestrictionsLPr( 14380 mSettings.mPreferredActivities.keyAt(i)); 14381 } 14382 } 14383 14384 for (int userId : UserManagerService.getInstance().getUserIds()) { 14385 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14386 grantPermissionsUserIds = ArrayUtils.appendInt( 14387 grantPermissionsUserIds, userId); 14388 } 14389 } 14390 } 14391 sUserManager.systemReady(); 14392 14393 // If we upgraded grant all default permissions before kicking off. 14394 for (int userId : grantPermissionsUserIds) { 14395 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14396 } 14397 14398 // Kick off any messages waiting for system ready 14399 if (mPostSystemReadyMessages != null) { 14400 for (Message msg : mPostSystemReadyMessages) { 14401 msg.sendToTarget(); 14402 } 14403 mPostSystemReadyMessages = null; 14404 } 14405 14406 // Watch for external volumes that come and go over time 14407 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14408 storage.registerListener(mStorageListener); 14409 14410 mInstallerService.systemReady(); 14411 mPackageDexOptimizer.systemReady(); 14412 } 14413 14414 @Override 14415 public boolean isSafeMode() { 14416 return mSafeMode; 14417 } 14418 14419 @Override 14420 public boolean hasSystemUidErrors() { 14421 return mHasSystemUidErrors; 14422 } 14423 14424 static String arrayToString(int[] array) { 14425 StringBuffer buf = new StringBuffer(128); 14426 buf.append('['); 14427 if (array != null) { 14428 for (int i=0; i<array.length; i++) { 14429 if (i > 0) buf.append(", "); 14430 buf.append(array[i]); 14431 } 14432 } 14433 buf.append(']'); 14434 return buf.toString(); 14435 } 14436 14437 static class DumpState { 14438 public static final int DUMP_LIBS = 1 << 0; 14439 public static final int DUMP_FEATURES = 1 << 1; 14440 public static final int DUMP_RESOLVERS = 1 << 2; 14441 public static final int DUMP_PERMISSIONS = 1 << 3; 14442 public static final int DUMP_PACKAGES = 1 << 4; 14443 public static final int DUMP_SHARED_USERS = 1 << 5; 14444 public static final int DUMP_MESSAGES = 1 << 6; 14445 public static final int DUMP_PROVIDERS = 1 << 7; 14446 public static final int DUMP_VERIFIERS = 1 << 8; 14447 public static final int DUMP_PREFERRED = 1 << 9; 14448 public static final int DUMP_PREFERRED_XML = 1 << 10; 14449 public static final int DUMP_KEYSETS = 1 << 11; 14450 public static final int DUMP_VERSION = 1 << 12; 14451 public static final int DUMP_INSTALLS = 1 << 13; 14452 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14453 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14454 14455 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14456 14457 private int mTypes; 14458 14459 private int mOptions; 14460 14461 private boolean mTitlePrinted; 14462 14463 private SharedUserSetting mSharedUser; 14464 14465 public boolean isDumping(int type) { 14466 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14467 return true; 14468 } 14469 14470 return (mTypes & type) != 0; 14471 } 14472 14473 public void setDump(int type) { 14474 mTypes |= type; 14475 } 14476 14477 public boolean isOptionEnabled(int option) { 14478 return (mOptions & option) != 0; 14479 } 14480 14481 public void setOptionEnabled(int option) { 14482 mOptions |= option; 14483 } 14484 14485 public boolean onTitlePrinted() { 14486 final boolean printed = mTitlePrinted; 14487 mTitlePrinted = true; 14488 return printed; 14489 } 14490 14491 public boolean getTitlePrinted() { 14492 return mTitlePrinted; 14493 } 14494 14495 public void setTitlePrinted(boolean enabled) { 14496 mTitlePrinted = enabled; 14497 } 14498 14499 public SharedUserSetting getSharedUser() { 14500 return mSharedUser; 14501 } 14502 14503 public void setSharedUser(SharedUserSetting user) { 14504 mSharedUser = user; 14505 } 14506 } 14507 14508 @Override 14509 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14510 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14511 != PackageManager.PERMISSION_GRANTED) { 14512 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14513 + Binder.getCallingPid() 14514 + ", uid=" + Binder.getCallingUid() 14515 + " without permission " 14516 + android.Manifest.permission.DUMP); 14517 return; 14518 } 14519 14520 DumpState dumpState = new DumpState(); 14521 boolean fullPreferred = false; 14522 boolean checkin = false; 14523 14524 String packageName = null; 14525 ArraySet<String> permissionNames = null; 14526 14527 int opti = 0; 14528 while (opti < args.length) { 14529 String opt = args[opti]; 14530 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14531 break; 14532 } 14533 opti++; 14534 14535 if ("-a".equals(opt)) { 14536 // Right now we only know how to print all. 14537 } else if ("-h".equals(opt)) { 14538 pw.println("Package manager dump options:"); 14539 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14540 pw.println(" --checkin: dump for a checkin"); 14541 pw.println(" -f: print details of intent filters"); 14542 pw.println(" -h: print this help"); 14543 pw.println(" cmd may be one of:"); 14544 pw.println(" l[ibraries]: list known shared libraries"); 14545 pw.println(" f[ibraries]: list device features"); 14546 pw.println(" k[eysets]: print known keysets"); 14547 pw.println(" r[esolvers]: dump intent resolvers"); 14548 pw.println(" perm[issions]: dump permissions"); 14549 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14550 pw.println(" pref[erred]: print preferred package settings"); 14551 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14552 pw.println(" prov[iders]: dump content providers"); 14553 pw.println(" p[ackages]: dump installed packages"); 14554 pw.println(" s[hared-users]: dump shared user IDs"); 14555 pw.println(" m[essages]: print collected runtime messages"); 14556 pw.println(" v[erifiers]: print package verifier info"); 14557 pw.println(" version: print database version info"); 14558 pw.println(" write: write current settings now"); 14559 pw.println(" <package.name>: info about given package"); 14560 pw.println(" installs: details about install sessions"); 14561 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14562 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14563 return; 14564 } else if ("--checkin".equals(opt)) { 14565 checkin = true; 14566 } else if ("-f".equals(opt)) { 14567 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14568 } else { 14569 pw.println("Unknown argument: " + opt + "; use -h for help"); 14570 } 14571 } 14572 14573 // Is the caller requesting to dump a particular piece of data? 14574 if (opti < args.length) { 14575 String cmd = args[opti]; 14576 opti++; 14577 // Is this a package name? 14578 if ("android".equals(cmd) || cmd.contains(".")) { 14579 packageName = cmd; 14580 // When dumping a single package, we always dump all of its 14581 // filter information since the amount of data will be reasonable. 14582 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14583 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14584 dumpState.setDump(DumpState.DUMP_LIBS); 14585 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14586 dumpState.setDump(DumpState.DUMP_FEATURES); 14587 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14588 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14589 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14590 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14591 } else if ("permission".equals(cmd)) { 14592 if (opti >= args.length) { 14593 pw.println("Error: permission requires permission name"); 14594 return; 14595 } 14596 permissionNames = new ArraySet<>(); 14597 while (opti < args.length) { 14598 permissionNames.add(args[opti]); 14599 opti++; 14600 } 14601 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14602 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14603 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14604 dumpState.setDump(DumpState.DUMP_PREFERRED); 14605 } else if ("preferred-xml".equals(cmd)) { 14606 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14607 if (opti < args.length && "--full".equals(args[opti])) { 14608 fullPreferred = true; 14609 opti++; 14610 } 14611 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14612 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14613 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14614 dumpState.setDump(DumpState.DUMP_PACKAGES); 14615 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14616 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14617 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14618 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14619 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14620 dumpState.setDump(DumpState.DUMP_MESSAGES); 14621 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14622 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14623 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14624 || "intent-filter-verifiers".equals(cmd)) { 14625 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14626 } else if ("version".equals(cmd)) { 14627 dumpState.setDump(DumpState.DUMP_VERSION); 14628 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14629 dumpState.setDump(DumpState.DUMP_KEYSETS); 14630 } else if ("installs".equals(cmd)) { 14631 dumpState.setDump(DumpState.DUMP_INSTALLS); 14632 } else if ("write".equals(cmd)) { 14633 synchronized (mPackages) { 14634 mSettings.writeLPr(); 14635 pw.println("Settings written."); 14636 return; 14637 } 14638 } 14639 } 14640 14641 if (checkin) { 14642 pw.println("vers,1"); 14643 } 14644 14645 // reader 14646 synchronized (mPackages) { 14647 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14648 if (!checkin) { 14649 if (dumpState.onTitlePrinted()) 14650 pw.println(); 14651 pw.println("Database versions:"); 14652 pw.print(" SDK Version:"); 14653 pw.print(" internal="); 14654 pw.print(mSettings.mInternalSdkPlatform); 14655 pw.print(" external="); 14656 pw.println(mSettings.mExternalSdkPlatform); 14657 pw.print(" DB Version:"); 14658 pw.print(" internal="); 14659 pw.print(mSettings.mInternalDatabaseVersion); 14660 pw.print(" external="); 14661 pw.println(mSettings.mExternalDatabaseVersion); 14662 } 14663 } 14664 14665 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14666 if (!checkin) { 14667 if (dumpState.onTitlePrinted()) 14668 pw.println(); 14669 pw.println("Verifiers:"); 14670 pw.print(" Required: "); 14671 pw.print(mRequiredVerifierPackage); 14672 pw.print(" (uid="); 14673 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14674 pw.println(")"); 14675 } else if (mRequiredVerifierPackage != null) { 14676 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14677 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14678 } 14679 } 14680 14681 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14682 packageName == null) { 14683 if (mIntentFilterVerifierComponent != null) { 14684 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14685 if (!checkin) { 14686 if (dumpState.onTitlePrinted()) 14687 pw.println(); 14688 pw.println("Intent Filter Verifier:"); 14689 pw.print(" Using: "); 14690 pw.print(verifierPackageName); 14691 pw.print(" (uid="); 14692 pw.print(getPackageUid(verifierPackageName, 0)); 14693 pw.println(")"); 14694 } else if (verifierPackageName != null) { 14695 pw.print("ifv,"); pw.print(verifierPackageName); 14696 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14697 } 14698 } else { 14699 pw.println(); 14700 pw.println("No Intent Filter Verifier available!"); 14701 } 14702 } 14703 14704 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14705 boolean printedHeader = false; 14706 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14707 while (it.hasNext()) { 14708 String name = it.next(); 14709 SharedLibraryEntry ent = mSharedLibraries.get(name); 14710 if (!checkin) { 14711 if (!printedHeader) { 14712 if (dumpState.onTitlePrinted()) 14713 pw.println(); 14714 pw.println("Libraries:"); 14715 printedHeader = true; 14716 } 14717 pw.print(" "); 14718 } else { 14719 pw.print("lib,"); 14720 } 14721 pw.print(name); 14722 if (!checkin) { 14723 pw.print(" -> "); 14724 } 14725 if (ent.path != null) { 14726 if (!checkin) { 14727 pw.print("(jar) "); 14728 pw.print(ent.path); 14729 } else { 14730 pw.print(",jar,"); 14731 pw.print(ent.path); 14732 } 14733 } else { 14734 if (!checkin) { 14735 pw.print("(apk) "); 14736 pw.print(ent.apk); 14737 } else { 14738 pw.print(",apk,"); 14739 pw.print(ent.apk); 14740 } 14741 } 14742 pw.println(); 14743 } 14744 } 14745 14746 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14747 if (dumpState.onTitlePrinted()) 14748 pw.println(); 14749 if (!checkin) { 14750 pw.println("Features:"); 14751 } 14752 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14753 while (it.hasNext()) { 14754 String name = it.next(); 14755 if (!checkin) { 14756 pw.print(" "); 14757 } else { 14758 pw.print("feat,"); 14759 } 14760 pw.println(name); 14761 } 14762 } 14763 14764 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14765 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14766 : "Activity Resolver Table:", " ", packageName, 14767 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14768 dumpState.setTitlePrinted(true); 14769 } 14770 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14771 : "Receiver Resolver Table:", " ", packageName, 14772 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14773 dumpState.setTitlePrinted(true); 14774 } 14775 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14776 : "Service Resolver Table:", " ", packageName, 14777 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14778 dumpState.setTitlePrinted(true); 14779 } 14780 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14781 : "Provider Resolver Table:", " ", packageName, 14782 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14783 dumpState.setTitlePrinted(true); 14784 } 14785 } 14786 14787 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14788 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14789 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14790 int user = mSettings.mPreferredActivities.keyAt(i); 14791 if (pir.dump(pw, 14792 dumpState.getTitlePrinted() 14793 ? "\nPreferred Activities User " + user + ":" 14794 : "Preferred Activities User " + user + ":", " ", 14795 packageName, true, false)) { 14796 dumpState.setTitlePrinted(true); 14797 } 14798 } 14799 } 14800 14801 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14802 pw.flush(); 14803 FileOutputStream fout = new FileOutputStream(fd); 14804 BufferedOutputStream str = new BufferedOutputStream(fout); 14805 XmlSerializer serializer = new FastXmlSerializer(); 14806 try { 14807 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14808 serializer.startDocument(null, true); 14809 serializer.setFeature( 14810 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14811 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14812 serializer.endDocument(); 14813 serializer.flush(); 14814 } catch (IllegalArgumentException e) { 14815 pw.println("Failed writing: " + e); 14816 } catch (IllegalStateException e) { 14817 pw.println("Failed writing: " + e); 14818 } catch (IOException e) { 14819 pw.println("Failed writing: " + e); 14820 } 14821 } 14822 14823 if (!checkin 14824 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14825 && packageName == null) { 14826 pw.println(); 14827 int count = mSettings.mPackages.size(); 14828 if (count == 0) { 14829 pw.println("No applications!"); 14830 pw.println(); 14831 } else { 14832 final String prefix = " "; 14833 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14834 if (allPackageSettings.size() == 0) { 14835 pw.println("No domain preferred apps!"); 14836 pw.println(); 14837 } else { 14838 pw.println("App verification status:"); 14839 pw.println(); 14840 count = 0; 14841 for (PackageSetting ps : allPackageSettings) { 14842 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14843 if (ivi == null || ivi.getPackageName() == null) continue; 14844 pw.println(prefix + "Package: " + ivi.getPackageName()); 14845 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14846 pw.println(prefix + "Status: " + ivi.getStatusString()); 14847 pw.println(); 14848 count++; 14849 } 14850 if (count == 0) { 14851 pw.println(prefix + "No app verification established."); 14852 pw.println(); 14853 } 14854 for (int userId : sUserManager.getUserIds()) { 14855 pw.println("App linkages for user " + userId + ":"); 14856 pw.println(); 14857 count = 0; 14858 for (PackageSetting ps : allPackageSettings) { 14859 final int status = ps.getDomainVerificationStatusForUser(userId); 14860 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14861 continue; 14862 } 14863 pw.println(prefix + "Package: " + ps.name); 14864 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 14865 String statusStr = IntentFilterVerificationInfo. 14866 getStatusStringFromValue(status); 14867 pw.println(prefix + "Status: " + statusStr); 14868 pw.println(); 14869 count++; 14870 } 14871 if (count == 0) { 14872 pw.println(prefix + "No configured app linkages."); 14873 pw.println(); 14874 } 14875 } 14876 } 14877 } 14878 } 14879 14880 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14881 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14882 if (packageName == null && permissionNames == null) { 14883 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14884 if (iperm == 0) { 14885 if (dumpState.onTitlePrinted()) 14886 pw.println(); 14887 pw.println("AppOp Permissions:"); 14888 } 14889 pw.print(" AppOp Permission "); 14890 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14891 pw.println(":"); 14892 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14893 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14894 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14895 } 14896 } 14897 } 14898 } 14899 14900 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14901 boolean printedSomething = false; 14902 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14903 if (packageName != null && !packageName.equals(p.info.packageName)) { 14904 continue; 14905 } 14906 if (!printedSomething) { 14907 if (dumpState.onTitlePrinted()) 14908 pw.println(); 14909 pw.println("Registered ContentProviders:"); 14910 printedSomething = true; 14911 } 14912 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14913 pw.print(" "); pw.println(p.toString()); 14914 } 14915 printedSomething = false; 14916 for (Map.Entry<String, PackageParser.Provider> entry : 14917 mProvidersByAuthority.entrySet()) { 14918 PackageParser.Provider p = entry.getValue(); 14919 if (packageName != null && !packageName.equals(p.info.packageName)) { 14920 continue; 14921 } 14922 if (!printedSomething) { 14923 if (dumpState.onTitlePrinted()) 14924 pw.println(); 14925 pw.println("ContentProvider Authorities:"); 14926 printedSomething = true; 14927 } 14928 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14929 pw.print(" "); pw.println(p.toString()); 14930 if (p.info != null && p.info.applicationInfo != null) { 14931 final String appInfo = p.info.applicationInfo.toString(); 14932 pw.print(" applicationInfo="); pw.println(appInfo); 14933 } 14934 } 14935 } 14936 14937 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14938 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14939 } 14940 14941 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14942 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14943 } 14944 14945 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14946 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14947 } 14948 14949 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14950 // XXX should handle packageName != null by dumping only install data that 14951 // the given package is involved with. 14952 if (dumpState.onTitlePrinted()) pw.println(); 14953 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14954 } 14955 14956 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14957 if (dumpState.onTitlePrinted()) pw.println(); 14958 mSettings.dumpReadMessagesLPr(pw, dumpState); 14959 14960 pw.println(); 14961 pw.println("Package warning messages:"); 14962 BufferedReader in = null; 14963 String line = null; 14964 try { 14965 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14966 while ((line = in.readLine()) != null) { 14967 if (line.contains("ignored: updated version")) continue; 14968 pw.println(line); 14969 } 14970 } catch (IOException ignored) { 14971 } finally { 14972 IoUtils.closeQuietly(in); 14973 } 14974 } 14975 14976 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14977 BufferedReader in = null; 14978 String line = null; 14979 try { 14980 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14981 while ((line = in.readLine()) != null) { 14982 if (line.contains("ignored: updated version")) continue; 14983 pw.print("msg,"); 14984 pw.println(line); 14985 } 14986 } catch (IOException ignored) { 14987 } finally { 14988 IoUtils.closeQuietly(in); 14989 } 14990 } 14991 } 14992 } 14993 14994 private String dumpDomainString(String packageName) { 14995 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 14996 List<IntentFilter> filters = getAllIntentFilters(packageName); 14997 14998 ArraySet<String> result = new ArraySet<>(); 14999 if (iviList.size() > 0) { 15000 for (IntentFilterVerificationInfo ivi : iviList) { 15001 for (String host : ivi.getDomains()) { 15002 result.add(host); 15003 } 15004 } 15005 } 15006 if (filters != null && filters.size() > 0) { 15007 for (IntentFilter filter : filters) { 15008 if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15009 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) { 15010 result.addAll(filter.getHostsList()); 15011 } 15012 } 15013 } 15014 15015 StringBuilder sb = new StringBuilder(result.size() * 16); 15016 for (String domain : result) { 15017 if (sb.length() > 0) sb.append(" "); 15018 sb.append(domain); 15019 } 15020 return sb.toString(); 15021 } 15022 15023 // ------- apps on sdcard specific code ------- 15024 static final boolean DEBUG_SD_INSTALL = false; 15025 15026 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15027 15028 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15029 15030 private boolean mMediaMounted = false; 15031 15032 static String getEncryptKey() { 15033 try { 15034 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15035 SD_ENCRYPTION_KEYSTORE_NAME); 15036 if (sdEncKey == null) { 15037 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15038 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15039 if (sdEncKey == null) { 15040 Slog.e(TAG, "Failed to create encryption keys"); 15041 return null; 15042 } 15043 } 15044 return sdEncKey; 15045 } catch (NoSuchAlgorithmException nsae) { 15046 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15047 return null; 15048 } catch (IOException ioe) { 15049 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15050 return null; 15051 } 15052 } 15053 15054 /* 15055 * Update media status on PackageManager. 15056 */ 15057 @Override 15058 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15059 int callingUid = Binder.getCallingUid(); 15060 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15061 throw new SecurityException("Media status can only be updated by the system"); 15062 } 15063 // reader; this apparently protects mMediaMounted, but should probably 15064 // be a different lock in that case. 15065 synchronized (mPackages) { 15066 Log.i(TAG, "Updating external media status from " 15067 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15068 + (mediaStatus ? "mounted" : "unmounted")); 15069 if (DEBUG_SD_INSTALL) 15070 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15071 + ", mMediaMounted=" + mMediaMounted); 15072 if (mediaStatus == mMediaMounted) { 15073 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15074 : 0, -1); 15075 mHandler.sendMessage(msg); 15076 return; 15077 } 15078 mMediaMounted = mediaStatus; 15079 } 15080 // Queue up an async operation since the package installation may take a 15081 // little while. 15082 mHandler.post(new Runnable() { 15083 public void run() { 15084 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15085 } 15086 }); 15087 } 15088 15089 /** 15090 * Called by MountService when the initial ASECs to scan are available. 15091 * Should block until all the ASEC containers are finished being scanned. 15092 */ 15093 public void scanAvailableAsecs() { 15094 updateExternalMediaStatusInner(true, false, false); 15095 if (mShouldRestoreconData) { 15096 SELinuxMMAC.setRestoreconDone(); 15097 mShouldRestoreconData = false; 15098 } 15099 } 15100 15101 /* 15102 * Collect information of applications on external media, map them against 15103 * existing containers and update information based on current mount status. 15104 * Please note that we always have to report status if reportStatus has been 15105 * set to true especially when unloading packages. 15106 */ 15107 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15108 boolean externalStorage) { 15109 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15110 int[] uidArr = EmptyArray.INT; 15111 15112 final String[] list = PackageHelper.getSecureContainerList(); 15113 if (ArrayUtils.isEmpty(list)) { 15114 Log.i(TAG, "No secure containers found"); 15115 } else { 15116 // Process list of secure containers and categorize them 15117 // as active or stale based on their package internal state. 15118 15119 // reader 15120 synchronized (mPackages) { 15121 for (String cid : list) { 15122 // Leave stages untouched for now; installer service owns them 15123 if (PackageInstallerService.isStageName(cid)) continue; 15124 15125 if (DEBUG_SD_INSTALL) 15126 Log.i(TAG, "Processing container " + cid); 15127 String pkgName = getAsecPackageName(cid); 15128 if (pkgName == null) { 15129 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15130 continue; 15131 } 15132 if (DEBUG_SD_INSTALL) 15133 Log.i(TAG, "Looking for pkg : " + pkgName); 15134 15135 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15136 if (ps == null) { 15137 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15138 continue; 15139 } 15140 15141 /* 15142 * Skip packages that are not external if we're unmounting 15143 * external storage. 15144 */ 15145 if (externalStorage && !isMounted && !isExternal(ps)) { 15146 continue; 15147 } 15148 15149 final AsecInstallArgs args = new AsecInstallArgs(cid, 15150 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15151 // The package status is changed only if the code path 15152 // matches between settings and the container id. 15153 if (ps.codePathString != null 15154 && ps.codePathString.startsWith(args.getCodePath())) { 15155 if (DEBUG_SD_INSTALL) { 15156 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15157 + " at code path: " + ps.codePathString); 15158 } 15159 15160 // We do have a valid package installed on sdcard 15161 processCids.put(args, ps.codePathString); 15162 final int uid = ps.appId; 15163 if (uid != -1) { 15164 uidArr = ArrayUtils.appendInt(uidArr, uid); 15165 } 15166 } else { 15167 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15168 + ps.codePathString); 15169 } 15170 } 15171 } 15172 15173 Arrays.sort(uidArr); 15174 } 15175 15176 // Process packages with valid entries. 15177 if (isMounted) { 15178 if (DEBUG_SD_INSTALL) 15179 Log.i(TAG, "Loading packages"); 15180 loadMediaPackages(processCids, uidArr); 15181 startCleaningPackages(); 15182 mInstallerService.onSecureContainersAvailable(); 15183 } else { 15184 if (DEBUG_SD_INSTALL) 15185 Log.i(TAG, "Unloading packages"); 15186 unloadMediaPackages(processCids, uidArr, reportStatus); 15187 } 15188 } 15189 15190 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15191 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15192 final int size = infos.size(); 15193 final String[] packageNames = new String[size]; 15194 final int[] packageUids = new int[size]; 15195 for (int i = 0; i < size; i++) { 15196 final ApplicationInfo info = infos.get(i); 15197 packageNames[i] = info.packageName; 15198 packageUids[i] = info.uid; 15199 } 15200 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15201 finishedReceiver); 15202 } 15203 15204 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15205 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15206 sendResourcesChangedBroadcast(mediaStatus, replacing, 15207 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15208 } 15209 15210 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15211 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15212 int size = pkgList.length; 15213 if (size > 0) { 15214 // Send broadcasts here 15215 Bundle extras = new Bundle(); 15216 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15217 if (uidArr != null) { 15218 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15219 } 15220 if (replacing) { 15221 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15222 } 15223 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15224 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15225 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15226 } 15227 } 15228 15229 /* 15230 * Look at potentially valid container ids from processCids If package 15231 * information doesn't match the one on record or package scanning fails, 15232 * the cid is added to list of removeCids. We currently don't delete stale 15233 * containers. 15234 */ 15235 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15236 ArrayList<String> pkgList = new ArrayList<String>(); 15237 Set<AsecInstallArgs> keys = processCids.keySet(); 15238 15239 for (AsecInstallArgs args : keys) { 15240 String codePath = processCids.get(args); 15241 if (DEBUG_SD_INSTALL) 15242 Log.i(TAG, "Loading container : " + args.cid); 15243 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15244 try { 15245 // Make sure there are no container errors first. 15246 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15247 Slog.e(TAG, "Failed to mount cid : " + args.cid 15248 + " when installing from sdcard"); 15249 continue; 15250 } 15251 // Check code path here. 15252 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15253 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15254 + " does not match one in settings " + codePath); 15255 continue; 15256 } 15257 // Parse package 15258 int parseFlags = mDefParseFlags; 15259 if (args.isExternalAsec()) { 15260 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15261 } 15262 if (args.isFwdLocked()) { 15263 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15264 } 15265 15266 synchronized (mInstallLock) { 15267 PackageParser.Package pkg = null; 15268 try { 15269 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15270 } catch (PackageManagerException e) { 15271 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15272 } 15273 // Scan the package 15274 if (pkg != null) { 15275 /* 15276 * TODO why is the lock being held? doPostInstall is 15277 * called in other places without the lock. This needs 15278 * to be straightened out. 15279 */ 15280 // writer 15281 synchronized (mPackages) { 15282 retCode = PackageManager.INSTALL_SUCCEEDED; 15283 pkgList.add(pkg.packageName); 15284 // Post process args 15285 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15286 pkg.applicationInfo.uid); 15287 } 15288 } else { 15289 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15290 } 15291 } 15292 15293 } finally { 15294 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15295 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15296 } 15297 } 15298 } 15299 // writer 15300 synchronized (mPackages) { 15301 // If the platform SDK has changed since the last time we booted, 15302 // we need to re-grant app permission to catch any new ones that 15303 // appear. This is really a hack, and means that apps can in some 15304 // cases get permissions that the user didn't initially explicitly 15305 // allow... it would be nice to have some better way to handle 15306 // this situation. 15307 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15308 if (regrantPermissions) 15309 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15310 + mSdkVersion + "; regranting permissions for external storage"); 15311 mSettings.mExternalSdkPlatform = mSdkVersion; 15312 15313 // Make sure group IDs have been assigned, and any permission 15314 // changes in other apps are accounted for 15315 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15316 | (regrantPermissions 15317 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15318 : 0)); 15319 15320 mSettings.updateExternalDatabaseVersion(); 15321 15322 // can downgrade to reader 15323 // Persist settings 15324 mSettings.writeLPr(); 15325 } 15326 // Send a broadcast to let everyone know we are done processing 15327 if (pkgList.size() > 0) { 15328 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15329 } 15330 } 15331 15332 /* 15333 * Utility method to unload a list of specified containers 15334 */ 15335 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15336 // Just unmount all valid containers. 15337 for (AsecInstallArgs arg : cidArgs) { 15338 synchronized (mInstallLock) { 15339 arg.doPostDeleteLI(false); 15340 } 15341 } 15342 } 15343 15344 /* 15345 * Unload packages mounted on external media. This involves deleting package 15346 * data from internal structures, sending broadcasts about diabled packages, 15347 * gc'ing to free up references, unmounting all secure containers 15348 * corresponding to packages on external media, and posting a 15349 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15350 * that we always have to post this message if status has been requested no 15351 * matter what. 15352 */ 15353 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15354 final boolean reportStatus) { 15355 if (DEBUG_SD_INSTALL) 15356 Log.i(TAG, "unloading media packages"); 15357 ArrayList<String> pkgList = new ArrayList<String>(); 15358 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15359 final Set<AsecInstallArgs> keys = processCids.keySet(); 15360 for (AsecInstallArgs args : keys) { 15361 String pkgName = args.getPackageName(); 15362 if (DEBUG_SD_INSTALL) 15363 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15364 // Delete package internally 15365 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15366 synchronized (mInstallLock) { 15367 boolean res = deletePackageLI(pkgName, null, false, null, null, 15368 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15369 if (res) { 15370 pkgList.add(pkgName); 15371 } else { 15372 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15373 failedList.add(args); 15374 } 15375 } 15376 } 15377 15378 // reader 15379 synchronized (mPackages) { 15380 // We didn't update the settings after removing each package; 15381 // write them now for all packages. 15382 mSettings.writeLPr(); 15383 } 15384 15385 // We have to absolutely send UPDATED_MEDIA_STATUS only 15386 // after confirming that all the receivers processed the ordered 15387 // broadcast when packages get disabled, force a gc to clean things up. 15388 // and unload all the containers. 15389 if (pkgList.size() > 0) { 15390 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15391 new IIntentReceiver.Stub() { 15392 public void performReceive(Intent intent, int resultCode, String data, 15393 Bundle extras, boolean ordered, boolean sticky, 15394 int sendingUser) throws RemoteException { 15395 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15396 reportStatus ? 1 : 0, 1, keys); 15397 mHandler.sendMessage(msg); 15398 } 15399 }); 15400 } else { 15401 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15402 keys); 15403 mHandler.sendMessage(msg); 15404 } 15405 } 15406 15407 private void loadPrivatePackages(VolumeInfo vol) { 15408 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15409 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15410 synchronized (mInstallLock) { 15411 synchronized (mPackages) { 15412 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15413 for (PackageSetting ps : packages) { 15414 final PackageParser.Package pkg; 15415 try { 15416 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15417 loaded.add(pkg.applicationInfo); 15418 } catch (PackageManagerException e) { 15419 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15420 } 15421 } 15422 15423 // TODO: regrant any permissions that changed based since original install 15424 15425 mSettings.writeLPr(); 15426 } 15427 } 15428 15429 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15430 sendResourcesChangedBroadcast(true, false, loaded, null); 15431 } 15432 15433 private void unloadPrivatePackages(VolumeInfo vol) { 15434 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15435 synchronized (mInstallLock) { 15436 synchronized (mPackages) { 15437 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15438 for (PackageSetting ps : packages) { 15439 if (ps.pkg == null) continue; 15440 15441 final ApplicationInfo info = ps.pkg.applicationInfo; 15442 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15443 if (deletePackageLI(ps.name, null, false, null, null, 15444 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15445 unloaded.add(info); 15446 } else { 15447 Slog.w(TAG, "Failed to unload " + ps.codePath); 15448 } 15449 } 15450 15451 mSettings.writeLPr(); 15452 } 15453 } 15454 15455 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15456 sendResourcesChangedBroadcast(false, false, unloaded, null); 15457 } 15458 15459 /** 15460 * Examine all users present on given mounted volume, and destroy data 15461 * belonging to users that are no longer valid, or whose user ID has been 15462 * recycled. 15463 */ 15464 private void reconcileUsers(String volumeUuid) { 15465 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15466 if (ArrayUtils.isEmpty(files)) { 15467 Slog.d(TAG, "No users found on " + volumeUuid); 15468 return; 15469 } 15470 15471 for (File file : files) { 15472 if (!file.isDirectory()) continue; 15473 15474 final int userId; 15475 final UserInfo info; 15476 try { 15477 userId = Integer.parseInt(file.getName()); 15478 info = sUserManager.getUserInfo(userId); 15479 } catch (NumberFormatException e) { 15480 Slog.w(TAG, "Invalid user directory " + file); 15481 continue; 15482 } 15483 15484 boolean destroyUser = false; 15485 if (info == null) { 15486 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15487 + " because no matching user was found"); 15488 destroyUser = true; 15489 } else { 15490 try { 15491 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15492 } catch (IOException e) { 15493 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15494 + " because we failed to enforce serial number: " + e); 15495 destroyUser = true; 15496 } 15497 } 15498 15499 if (destroyUser) { 15500 synchronized (mInstallLock) { 15501 mInstaller.removeUserDataDirs(volumeUuid, userId); 15502 } 15503 } 15504 } 15505 15506 final UserManager um = mContext.getSystemService(UserManager.class); 15507 for (UserInfo user : um.getUsers()) { 15508 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15509 if (userDir.exists()) continue; 15510 15511 try { 15512 UserManagerService.prepareUserDirectory(userDir); 15513 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15514 } catch (IOException e) { 15515 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15516 } 15517 } 15518 } 15519 15520 /** 15521 * Examine all apps present on given mounted volume, and destroy apps that 15522 * aren't expected, either due to uninstallation or reinstallation on 15523 * another volume. 15524 */ 15525 private void reconcileApps(String volumeUuid) { 15526 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15527 if (ArrayUtils.isEmpty(files)) { 15528 Slog.d(TAG, "No apps found on " + volumeUuid); 15529 return; 15530 } 15531 15532 for (File file : files) { 15533 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15534 && !PackageInstallerService.isStageName(file.getName()); 15535 if (!isPackage) { 15536 // Ignore entries which are not packages 15537 continue; 15538 } 15539 15540 boolean destroyApp = false; 15541 String packageName = null; 15542 try { 15543 final PackageLite pkg = PackageParser.parsePackageLite(file, 15544 PackageParser.PARSE_MUST_BE_APK); 15545 packageName = pkg.packageName; 15546 15547 synchronized (mPackages) { 15548 final PackageSetting ps = mSettings.mPackages.get(packageName); 15549 if (ps == null) { 15550 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15551 + volumeUuid + " because we found no install record"); 15552 destroyApp = true; 15553 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15554 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15555 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15556 destroyApp = true; 15557 } 15558 } 15559 15560 } catch (PackageParserException e) { 15561 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15562 destroyApp = true; 15563 } 15564 15565 if (destroyApp) { 15566 synchronized (mInstallLock) { 15567 if (packageName != null) { 15568 removeDataDirsLI(volumeUuid, packageName); 15569 } 15570 if (file.isDirectory()) { 15571 mInstaller.rmPackageDir(file.getAbsolutePath()); 15572 } else { 15573 file.delete(); 15574 } 15575 } 15576 } 15577 } 15578 } 15579 15580 private void unfreezePackage(String packageName) { 15581 synchronized (mPackages) { 15582 final PackageSetting ps = mSettings.mPackages.get(packageName); 15583 if (ps != null) { 15584 ps.frozen = false; 15585 } 15586 } 15587 } 15588 15589 @Override 15590 public int movePackage(final String packageName, final String volumeUuid) { 15591 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15592 15593 final int moveId = mNextMoveId.getAndIncrement(); 15594 try { 15595 movePackageInternal(packageName, volumeUuid, moveId); 15596 } catch (PackageManagerException e) { 15597 Slog.w(TAG, "Failed to move " + packageName, e); 15598 mMoveCallbacks.notifyStatusChanged(moveId, 15599 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15600 } 15601 return moveId; 15602 } 15603 15604 private void movePackageInternal(final String packageName, final String volumeUuid, 15605 final int moveId) throws PackageManagerException { 15606 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15607 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15608 final PackageManager pm = mContext.getPackageManager(); 15609 15610 final boolean currentAsec; 15611 final String currentVolumeUuid; 15612 final File codeFile; 15613 final String installerPackageName; 15614 final String packageAbiOverride; 15615 final int appId; 15616 final String seinfo; 15617 final String label; 15618 15619 // reader 15620 synchronized (mPackages) { 15621 final PackageParser.Package pkg = mPackages.get(packageName); 15622 final PackageSetting ps = mSettings.mPackages.get(packageName); 15623 if (pkg == null || ps == null) { 15624 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15625 } 15626 15627 if (pkg.applicationInfo.isSystemApp()) { 15628 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15629 "Cannot move system application"); 15630 } 15631 15632 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15633 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15634 "Package already moved to " + volumeUuid); 15635 } 15636 15637 final File probe = new File(pkg.codePath); 15638 final File probeOat = new File(probe, "oat"); 15639 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15640 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15641 "Move only supported for modern cluster style installs"); 15642 } 15643 15644 if (ps.frozen) { 15645 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15646 "Failed to move already frozen package"); 15647 } 15648 ps.frozen = true; 15649 15650 currentAsec = pkg.applicationInfo.isForwardLocked() 15651 || pkg.applicationInfo.isExternalAsec(); 15652 currentVolumeUuid = ps.volumeUuid; 15653 codeFile = new File(pkg.codePath); 15654 installerPackageName = ps.installerPackageName; 15655 packageAbiOverride = ps.cpuAbiOverrideString; 15656 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15657 seinfo = pkg.applicationInfo.seinfo; 15658 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15659 } 15660 15661 // Now that we're guarded by frozen state, kill app during move 15662 killApplication(packageName, appId, "move pkg"); 15663 15664 final Bundle extras = new Bundle(); 15665 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15666 extras.putString(Intent.EXTRA_TITLE, label); 15667 mMoveCallbacks.notifyCreated(moveId, extras); 15668 15669 int installFlags; 15670 final boolean moveCompleteApp; 15671 final File measurePath; 15672 15673 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15674 installFlags = INSTALL_INTERNAL; 15675 moveCompleteApp = !currentAsec; 15676 measurePath = Environment.getDataAppDirectory(volumeUuid); 15677 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15678 installFlags = INSTALL_EXTERNAL; 15679 moveCompleteApp = false; 15680 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15681 } else { 15682 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15683 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15684 || !volume.isMountedWritable()) { 15685 unfreezePackage(packageName); 15686 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15687 "Move location not mounted private volume"); 15688 } 15689 15690 Preconditions.checkState(!currentAsec); 15691 15692 installFlags = INSTALL_INTERNAL; 15693 moveCompleteApp = true; 15694 measurePath = Environment.getDataAppDirectory(volumeUuid); 15695 } 15696 15697 final PackageStats stats = new PackageStats(null, -1); 15698 synchronized (mInstaller) { 15699 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15700 unfreezePackage(packageName); 15701 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15702 "Failed to measure package size"); 15703 } 15704 } 15705 15706 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15707 + stats.dataSize); 15708 15709 final long startFreeBytes = measurePath.getFreeSpace(); 15710 final long sizeBytes; 15711 if (moveCompleteApp) { 15712 sizeBytes = stats.codeSize + stats.dataSize; 15713 } else { 15714 sizeBytes = stats.codeSize; 15715 } 15716 15717 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15718 unfreezePackage(packageName); 15719 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15720 "Not enough free space to move"); 15721 } 15722 15723 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15724 15725 final CountDownLatch installedLatch = new CountDownLatch(1); 15726 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15727 @Override 15728 public void onUserActionRequired(Intent intent) throws RemoteException { 15729 throw new IllegalStateException(); 15730 } 15731 15732 @Override 15733 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15734 Bundle extras) throws RemoteException { 15735 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15736 + PackageManager.installStatusToString(returnCode, msg)); 15737 15738 installedLatch.countDown(); 15739 15740 // Regardless of success or failure of the move operation, 15741 // always unfreeze the package 15742 unfreezePackage(packageName); 15743 15744 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15745 switch (status) { 15746 case PackageInstaller.STATUS_SUCCESS: 15747 mMoveCallbacks.notifyStatusChanged(moveId, 15748 PackageManager.MOVE_SUCCEEDED); 15749 break; 15750 case PackageInstaller.STATUS_FAILURE_STORAGE: 15751 mMoveCallbacks.notifyStatusChanged(moveId, 15752 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15753 break; 15754 default: 15755 mMoveCallbacks.notifyStatusChanged(moveId, 15756 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15757 break; 15758 } 15759 } 15760 }; 15761 15762 final MoveInfo move; 15763 if (moveCompleteApp) { 15764 // Kick off a thread to report progress estimates 15765 new Thread() { 15766 @Override 15767 public void run() { 15768 while (true) { 15769 try { 15770 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15771 break; 15772 } 15773 } catch (InterruptedException ignored) { 15774 } 15775 15776 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15777 final int progress = 10 + (int) MathUtils.constrain( 15778 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15779 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15780 } 15781 } 15782 }.start(); 15783 15784 final String dataAppName = codeFile.getName(); 15785 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15786 dataAppName, appId, seinfo); 15787 } else { 15788 move = null; 15789 } 15790 15791 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15792 15793 final Message msg = mHandler.obtainMessage(INIT_COPY); 15794 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15795 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15796 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15797 mHandler.sendMessage(msg); 15798 } 15799 15800 @Override 15801 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15802 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15803 15804 final int realMoveId = mNextMoveId.getAndIncrement(); 15805 final Bundle extras = new Bundle(); 15806 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15807 mMoveCallbacks.notifyCreated(realMoveId, extras); 15808 15809 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15810 @Override 15811 public void onCreated(int moveId, Bundle extras) { 15812 // Ignored 15813 } 15814 15815 @Override 15816 public void onStatusChanged(int moveId, int status, long estMillis) { 15817 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15818 } 15819 }; 15820 15821 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15822 storage.setPrimaryStorageUuid(volumeUuid, callback); 15823 return realMoveId; 15824 } 15825 15826 @Override 15827 public int getMoveStatus(int moveId) { 15828 mContext.enforceCallingOrSelfPermission( 15829 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15830 return mMoveCallbacks.mLastStatus.get(moveId); 15831 } 15832 15833 @Override 15834 public void registerMoveCallback(IPackageMoveObserver callback) { 15835 mContext.enforceCallingOrSelfPermission( 15836 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15837 mMoveCallbacks.register(callback); 15838 } 15839 15840 @Override 15841 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15842 mContext.enforceCallingOrSelfPermission( 15843 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15844 mMoveCallbacks.unregister(callback); 15845 } 15846 15847 @Override 15848 public boolean setInstallLocation(int loc) { 15849 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15850 null); 15851 if (getInstallLocation() == loc) { 15852 return true; 15853 } 15854 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15855 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15856 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15857 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15858 return true; 15859 } 15860 return false; 15861 } 15862 15863 @Override 15864 public int getInstallLocation() { 15865 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15866 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15867 PackageHelper.APP_INSTALL_AUTO); 15868 } 15869 15870 /** Called by UserManagerService */ 15871 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15872 mDirtyUsers.remove(userHandle); 15873 mSettings.removeUserLPw(userHandle); 15874 mPendingBroadcasts.remove(userHandle); 15875 if (mInstaller != null) { 15876 // Technically, we shouldn't be doing this with the package lock 15877 // held. However, this is very rare, and there is already so much 15878 // other disk I/O going on, that we'll let it slide for now. 15879 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15880 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15881 final String volumeUuid = vol.getFsUuid(); 15882 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15883 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15884 } 15885 } 15886 mUserNeedsBadging.delete(userHandle); 15887 removeUnusedPackagesLILPw(userManager, userHandle); 15888 } 15889 15890 /** 15891 * We're removing userHandle and would like to remove any downloaded packages 15892 * that are no longer in use by any other user. 15893 * @param userHandle the user being removed 15894 */ 15895 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15896 final boolean DEBUG_CLEAN_APKS = false; 15897 int [] users = userManager.getUserIdsLPr(); 15898 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15899 while (psit.hasNext()) { 15900 PackageSetting ps = psit.next(); 15901 if (ps.pkg == null) { 15902 continue; 15903 } 15904 final String packageName = ps.pkg.packageName; 15905 // Skip over if system app 15906 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15907 continue; 15908 } 15909 if (DEBUG_CLEAN_APKS) { 15910 Slog.i(TAG, "Checking package " + packageName); 15911 } 15912 boolean keep = false; 15913 for (int i = 0; i < users.length; i++) { 15914 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15915 keep = true; 15916 if (DEBUG_CLEAN_APKS) { 15917 Slog.i(TAG, " Keeping package " + packageName + " for user " 15918 + users[i]); 15919 } 15920 break; 15921 } 15922 } 15923 if (!keep) { 15924 if (DEBUG_CLEAN_APKS) { 15925 Slog.i(TAG, " Removing package " + packageName); 15926 } 15927 mHandler.post(new Runnable() { 15928 public void run() { 15929 deletePackageX(packageName, userHandle, 0); 15930 } //end run 15931 }); 15932 } 15933 } 15934 } 15935 15936 /** Called by UserManagerService */ 15937 void createNewUserLILPw(int userHandle) { 15938 if (mInstaller != null) { 15939 mInstaller.createUserConfig(userHandle); 15940 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 15941 applyFactoryDefaultBrowserLPw(userHandle); 15942 primeDomainVerificationsLPw(userHandle); 15943 } 15944 } 15945 15946 void newUserCreatedLILPw(final int userHandle) { 15947 // We cannot grant the default permissions with a lock held as 15948 // we query providers from other components for default handlers 15949 // such as enabled IMEs, etc. 15950 mHandler.post(new Runnable() { 15951 @Override 15952 public void run() { 15953 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15954 } 15955 }); 15956 } 15957 15958 @Override 15959 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15960 mContext.enforceCallingOrSelfPermission( 15961 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15962 "Only package verification agents can read the verifier device identity"); 15963 15964 synchronized (mPackages) { 15965 return mSettings.getVerifierDeviceIdentityLPw(); 15966 } 15967 } 15968 15969 @Override 15970 public void setPermissionEnforced(String permission, boolean enforced) { 15971 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15972 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15973 synchronized (mPackages) { 15974 if (mSettings.mReadExternalStorageEnforced == null 15975 || mSettings.mReadExternalStorageEnforced != enforced) { 15976 mSettings.mReadExternalStorageEnforced = enforced; 15977 mSettings.writeLPr(); 15978 } 15979 } 15980 // kill any non-foreground processes so we restart them and 15981 // grant/revoke the GID. 15982 final IActivityManager am = ActivityManagerNative.getDefault(); 15983 if (am != null) { 15984 final long token = Binder.clearCallingIdentity(); 15985 try { 15986 am.killProcessesBelowForeground("setPermissionEnforcement"); 15987 } catch (RemoteException e) { 15988 } finally { 15989 Binder.restoreCallingIdentity(token); 15990 } 15991 } 15992 } else { 15993 throw new IllegalArgumentException("No selective enforcement for " + permission); 15994 } 15995 } 15996 15997 @Override 15998 @Deprecated 15999 public boolean isPermissionEnforced(String permission) { 16000 return true; 16001 } 16002 16003 @Override 16004 public boolean isStorageLow() { 16005 final long token = Binder.clearCallingIdentity(); 16006 try { 16007 final DeviceStorageMonitorInternal 16008 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16009 if (dsm != null) { 16010 return dsm.isMemoryLow(); 16011 } else { 16012 return false; 16013 } 16014 } finally { 16015 Binder.restoreCallingIdentity(token); 16016 } 16017 } 16018 16019 @Override 16020 public IPackageInstaller getPackageInstaller() { 16021 return mInstallerService; 16022 } 16023 16024 private boolean userNeedsBadging(int userId) { 16025 int index = mUserNeedsBadging.indexOfKey(userId); 16026 if (index < 0) { 16027 final UserInfo userInfo; 16028 final long token = Binder.clearCallingIdentity(); 16029 try { 16030 userInfo = sUserManager.getUserInfo(userId); 16031 } finally { 16032 Binder.restoreCallingIdentity(token); 16033 } 16034 final boolean b; 16035 if (userInfo != null && userInfo.isManagedProfile()) { 16036 b = true; 16037 } else { 16038 b = false; 16039 } 16040 mUserNeedsBadging.put(userId, b); 16041 return b; 16042 } 16043 return mUserNeedsBadging.valueAt(index); 16044 } 16045 16046 @Override 16047 public KeySet getKeySetByAlias(String packageName, String alias) { 16048 if (packageName == null || alias == null) { 16049 return null; 16050 } 16051 synchronized(mPackages) { 16052 final PackageParser.Package pkg = mPackages.get(packageName); 16053 if (pkg == null) { 16054 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16055 throw new IllegalArgumentException("Unknown package: " + packageName); 16056 } 16057 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16058 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16059 } 16060 } 16061 16062 @Override 16063 public KeySet getSigningKeySet(String packageName) { 16064 if (packageName == null) { 16065 return null; 16066 } 16067 synchronized(mPackages) { 16068 final PackageParser.Package pkg = mPackages.get(packageName); 16069 if (pkg == null) { 16070 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16071 throw new IllegalArgumentException("Unknown package: " + packageName); 16072 } 16073 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16074 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16075 throw new SecurityException("May not access signing KeySet of other apps."); 16076 } 16077 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16078 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16079 } 16080 } 16081 16082 @Override 16083 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16084 if (packageName == null || ks == null) { 16085 return false; 16086 } 16087 synchronized(mPackages) { 16088 final PackageParser.Package pkg = mPackages.get(packageName); 16089 if (pkg == null) { 16090 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16091 throw new IllegalArgumentException("Unknown package: " + packageName); 16092 } 16093 IBinder ksh = ks.getToken(); 16094 if (ksh instanceof KeySetHandle) { 16095 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16096 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16097 } 16098 return false; 16099 } 16100 } 16101 16102 @Override 16103 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16104 if (packageName == null || ks == null) { 16105 return false; 16106 } 16107 synchronized(mPackages) { 16108 final PackageParser.Package pkg = mPackages.get(packageName); 16109 if (pkg == null) { 16110 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16111 throw new IllegalArgumentException("Unknown package: " + packageName); 16112 } 16113 IBinder ksh = ks.getToken(); 16114 if (ksh instanceof KeySetHandle) { 16115 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16116 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16117 } 16118 return false; 16119 } 16120 } 16121 16122 public void getUsageStatsIfNoPackageUsageInfo() { 16123 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16124 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16125 if (usm == null) { 16126 throw new IllegalStateException("UsageStatsManager must be initialized"); 16127 } 16128 long now = System.currentTimeMillis(); 16129 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16130 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16131 String packageName = entry.getKey(); 16132 PackageParser.Package pkg = mPackages.get(packageName); 16133 if (pkg == null) { 16134 continue; 16135 } 16136 UsageStats usage = entry.getValue(); 16137 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16138 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16139 } 16140 } 16141 } 16142 16143 /** 16144 * Check and throw if the given before/after packages would be considered a 16145 * downgrade. 16146 */ 16147 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16148 throws PackageManagerException { 16149 if (after.versionCode < before.mVersionCode) { 16150 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16151 "Update version code " + after.versionCode + " is older than current " 16152 + before.mVersionCode); 16153 } else if (after.versionCode == before.mVersionCode) { 16154 if (after.baseRevisionCode < before.baseRevisionCode) { 16155 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16156 "Update base revision code " + after.baseRevisionCode 16157 + " is older than current " + before.baseRevisionCode); 16158 } 16159 16160 if (!ArrayUtils.isEmpty(after.splitNames)) { 16161 for (int i = 0; i < after.splitNames.length; i++) { 16162 final String splitName = after.splitNames[i]; 16163 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16164 if (j != -1) { 16165 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16166 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16167 "Update split " + splitName + " revision code " 16168 + after.splitRevisionCodes[i] + " is older than current " 16169 + before.splitRevisionCodes[j]); 16170 } 16171 } 16172 } 16173 } 16174 } 16175 } 16176 16177 private static class MoveCallbacks extends Handler { 16178 private static final int MSG_CREATED = 1; 16179 private static final int MSG_STATUS_CHANGED = 2; 16180 16181 private final RemoteCallbackList<IPackageMoveObserver> 16182 mCallbacks = new RemoteCallbackList<>(); 16183 16184 private final SparseIntArray mLastStatus = new SparseIntArray(); 16185 16186 public MoveCallbacks(Looper looper) { 16187 super(looper); 16188 } 16189 16190 public void register(IPackageMoveObserver callback) { 16191 mCallbacks.register(callback); 16192 } 16193 16194 public void unregister(IPackageMoveObserver callback) { 16195 mCallbacks.unregister(callback); 16196 } 16197 16198 @Override 16199 public void handleMessage(Message msg) { 16200 final SomeArgs args = (SomeArgs) msg.obj; 16201 final int n = mCallbacks.beginBroadcast(); 16202 for (int i = 0; i < n; i++) { 16203 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16204 try { 16205 invokeCallback(callback, msg.what, args); 16206 } catch (RemoteException ignored) { 16207 } 16208 } 16209 mCallbacks.finishBroadcast(); 16210 args.recycle(); 16211 } 16212 16213 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16214 throws RemoteException { 16215 switch (what) { 16216 case MSG_CREATED: { 16217 callback.onCreated(args.argi1, (Bundle) args.arg2); 16218 break; 16219 } 16220 case MSG_STATUS_CHANGED: { 16221 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16222 break; 16223 } 16224 } 16225 } 16226 16227 private void notifyCreated(int moveId, Bundle extras) { 16228 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16229 16230 final SomeArgs args = SomeArgs.obtain(); 16231 args.argi1 = moveId; 16232 args.arg2 = extras; 16233 obtainMessage(MSG_CREATED, args).sendToTarget(); 16234 } 16235 16236 private void notifyStatusChanged(int moveId, int status) { 16237 notifyStatusChanged(moveId, status, -1); 16238 } 16239 16240 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16241 Slog.v(TAG, "Move " + moveId + " status " + status); 16242 16243 final SomeArgs args = SomeArgs.obtain(); 16244 args.argi1 = moveId; 16245 args.argi2 = status; 16246 args.arg3 = estMillis; 16247 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16248 16249 synchronized (mLastStatus) { 16250 mLastStatus.put(moveId, status); 16251 } 16252 } 16253 } 16254 16255 private final class OnPermissionChangeListeners extends Handler { 16256 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16257 16258 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16259 new RemoteCallbackList<>(); 16260 16261 public OnPermissionChangeListeners(Looper looper) { 16262 super(looper); 16263 } 16264 16265 @Override 16266 public void handleMessage(Message msg) { 16267 switch (msg.what) { 16268 case MSG_ON_PERMISSIONS_CHANGED: { 16269 final int uid = msg.arg1; 16270 handleOnPermissionsChanged(uid); 16271 } break; 16272 } 16273 } 16274 16275 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16276 mPermissionListeners.register(listener); 16277 16278 } 16279 16280 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16281 mPermissionListeners.unregister(listener); 16282 } 16283 16284 public void onPermissionsChanged(int uid) { 16285 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16286 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16287 } 16288 } 16289 16290 private void handleOnPermissionsChanged(int uid) { 16291 final int count = mPermissionListeners.beginBroadcast(); 16292 try { 16293 for (int i = 0; i < count; i++) { 16294 IOnPermissionsChangeListener callback = mPermissionListeners 16295 .getBroadcastItem(i); 16296 try { 16297 callback.onPermissionsChanged(uid); 16298 } catch (RemoteException e) { 16299 Log.e(TAG, "Permission listener is dead", e); 16300 } 16301 } 16302 } finally { 16303 mPermissionListeners.finishBroadcast(); 16304 } 16305 } 16306 } 16307 16308 private class PackageManagerInternalImpl extends PackageManagerInternal { 16309 @Override 16310 public void setLocationPackagesProvider(PackagesProvider provider) { 16311 synchronized (mPackages) { 16312 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16313 } 16314 } 16315 16316 @Override 16317 public void setImePackagesProvider(PackagesProvider provider) { 16318 synchronized (mPackages) { 16319 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16320 } 16321 } 16322 16323 @Override 16324 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16325 synchronized (mPackages) { 16326 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16327 } 16328 } 16329 16330 @Override 16331 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16332 synchronized (mPackages) { 16333 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16334 } 16335 } 16336 16337 @Override 16338 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16339 synchronized (mPackages) { 16340 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16341 } 16342 } 16343 16344 @Override 16345 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16346 synchronized (mPackages) { 16347 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 16348 } 16349 } 16350 16351 @Override 16352 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16353 synchronized (mPackages) { 16354 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16355 packageName, userId); 16356 } 16357 } 16358 16359 @Override 16360 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16361 synchronized (mPackages) { 16362 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16363 packageName, userId); 16364 } 16365 } 16366 } 16367 16368 @Override 16369 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16370 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16371 synchronized (mPackages) { 16372 final long identity = Binder.clearCallingIdentity(); 16373 try { 16374 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16375 packageNames, userId); 16376 } finally { 16377 Binder.restoreCallingIdentity(identity); 16378 } 16379 } 16380 } 16381 16382 private static void enforceSystemOrPhoneCaller(String tag) { 16383 int callingUid = Binder.getCallingUid(); 16384 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16385 throw new SecurityException( 16386 "Cannot call " + tag + " from UID " + callingUid); 16387 } 16388 } 16389} 16390