PackageManagerService.java revision 6672c8ba3b9e52a384cddb7fe77bd8d97fbfd128
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.MATCH_ALL; 60import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 61import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 62import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 63import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 64import static android.content.pm.PackageManager.PERMISSION_DENIED; 65import static android.content.pm.PackageManager.PERMISSION_GRANTED; 66import static android.content.pm.PackageParser.isApkFile; 67import static android.os.Process.PACKAGE_INFO_GID; 68import static android.os.Process.SYSTEM_UID; 69import static android.system.OsConstants.O_CREAT; 70import static android.system.OsConstants.O_RDWR; 71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 75import static com.android.internal.util.ArrayUtils.appendInt; 76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 84 85import android.Manifest; 86import android.app.ActivityManager; 87import android.app.ActivityManagerNative; 88import android.app.AppGlobals; 89import android.app.IActivityManager; 90import android.app.admin.IDevicePolicyManager; 91import android.app.backup.IBackupManager; 92import android.app.usage.UsageStats; 93import android.app.usage.UsageStatsManager; 94import android.content.BroadcastReceiver; 95import android.content.ComponentName; 96import android.content.Context; 97import android.content.IIntentReceiver; 98import android.content.Intent; 99import android.content.IntentFilter; 100import android.content.IntentSender; 101import android.content.IntentSender.SendIntentException; 102import android.content.ServiceConnection; 103import android.content.pm.ActivityInfo; 104import android.content.pm.ApplicationInfo; 105import android.content.pm.FeatureInfo; 106import android.content.pm.IOnPermissionsChangeListener; 107import android.content.pm.IPackageDataObserver; 108import android.content.pm.IPackageDeleteObserver; 109import android.content.pm.IPackageDeleteObserver2; 110import android.content.pm.IPackageInstallObserver2; 111import android.content.pm.IPackageInstaller; 112import android.content.pm.IPackageManager; 113import android.content.pm.IPackageMoveObserver; 114import android.content.pm.IPackageStatsObserver; 115import android.content.pm.InstrumentationInfo; 116import android.content.pm.IntentFilterVerificationInfo; 117import android.content.pm.KeySet; 118import android.content.pm.ManifestDigest; 119import android.content.pm.PackageCleanItem; 120import android.content.pm.PackageInfo; 121import android.content.pm.PackageInfoLite; 122import android.content.pm.PackageInstaller; 123import android.content.pm.PackageManager; 124import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 125import android.content.pm.PackageManagerInternal; 126import android.content.pm.PackageParser; 127import android.content.pm.PackageParser.ActivityIntentInfo; 128import android.content.pm.PackageParser.PackageLite; 129import android.content.pm.PackageParser.PackageParserException; 130import android.content.pm.PackageStats; 131import android.content.pm.PackageUserState; 132import android.content.pm.ParceledListSlice; 133import android.content.pm.PermissionGroupInfo; 134import android.content.pm.PermissionInfo; 135import android.content.pm.ProviderInfo; 136import android.content.pm.ResolveInfo; 137import android.content.pm.ServiceInfo; 138import android.content.pm.Signature; 139import android.content.pm.UserInfo; 140import android.content.pm.VerificationParams; 141import android.content.pm.VerifierDeviceIdentity; 142import android.content.pm.VerifierInfo; 143import android.content.res.Resources; 144import android.hardware.display.DisplayManager; 145import android.net.Uri; 146import android.os.Debug; 147import android.os.Binder; 148import android.os.Build; 149import android.os.Bundle; 150import android.os.Environment; 151import android.os.Environment.UserEnvironment; 152import android.os.FileUtils; 153import android.os.Handler; 154import android.os.IBinder; 155import android.os.Looper; 156import android.os.Message; 157import android.os.Parcel; 158import android.os.ParcelFileDescriptor; 159import android.os.Process; 160import android.os.RemoteCallbackList; 161import android.os.RemoteException; 162import android.os.SELinux; 163import android.os.ServiceManager; 164import android.os.SystemClock; 165import android.os.SystemProperties; 166import android.os.UserHandle; 167import android.os.UserManager; 168import android.os.storage.IMountService; 169import android.os.storage.MountServiceInternal; 170import android.os.storage.StorageEventListener; 171import android.os.storage.StorageManager; 172import android.os.storage.VolumeInfo; 173import android.os.storage.VolumeRecord; 174import android.security.KeyStore; 175import android.security.SystemKeyStore; 176import android.system.ErrnoException; 177import android.system.Os; 178import android.system.StructStat; 179import android.text.TextUtils; 180import android.text.format.DateUtils; 181import android.util.ArrayMap; 182import android.util.ArraySet; 183import android.util.AtomicFile; 184import android.util.DisplayMetrics; 185import android.util.EventLog; 186import android.util.ExceptionUtils; 187import android.util.Log; 188import android.util.LogPrinter; 189import android.util.MathUtils; 190import android.util.PrintStreamPrinter; 191import android.util.Slog; 192import android.util.SparseArray; 193import android.util.SparseBooleanArray; 194import android.util.SparseIntArray; 195import android.util.Xml; 196import android.view.Display; 197 198import dalvik.system.DexFile; 199import dalvik.system.VMRuntime; 200 201import libcore.io.IoUtils; 202import libcore.util.EmptyArray; 203 204import com.android.internal.R; 205import com.android.internal.annotations.GuardedBy; 206import com.android.internal.app.IMediaContainerService; 207import com.android.internal.app.ResolverActivity; 208import com.android.internal.content.NativeLibraryHelper; 209import com.android.internal.content.PackageHelper; 210import com.android.internal.os.IParcelFileDescriptorFactory; 211import com.android.internal.os.SomeArgs; 212import com.android.internal.os.Zygote; 213import com.android.internal.util.ArrayUtils; 214import com.android.internal.util.FastPrintWriter; 215import com.android.internal.util.FastXmlSerializer; 216import com.android.internal.util.IndentingPrintWriter; 217import com.android.internal.util.Preconditions; 218import com.android.server.EventLogTags; 219import com.android.server.FgThread; 220import com.android.server.IntentResolver; 221import com.android.server.LocalServices; 222import com.android.server.ServiceThread; 223import com.android.server.SystemConfig; 224import com.android.server.Watchdog; 225import com.android.server.pm.PermissionsState.PermissionState; 226import com.android.server.pm.Settings.DatabaseVersion; 227import com.android.server.pm.Settings.VersionInfo; 228import com.android.server.storage.DeviceStorageMonitorInternal; 229 230import org.xmlpull.v1.XmlPullParser; 231import org.xmlpull.v1.XmlPullParserException; 232import org.xmlpull.v1.XmlSerializer; 233 234import java.io.BufferedInputStream; 235import java.io.BufferedOutputStream; 236import java.io.BufferedReader; 237import java.io.ByteArrayInputStream; 238import java.io.ByteArrayOutputStream; 239import java.io.File; 240import java.io.FileDescriptor; 241import java.io.FileNotFoundException; 242import java.io.FileOutputStream; 243import java.io.FileReader; 244import java.io.FilenameFilter; 245import java.io.IOException; 246import java.io.InputStream; 247import java.io.PrintWriter; 248import java.nio.charset.StandardCharsets; 249import java.security.NoSuchAlgorithmException; 250import java.security.PublicKey; 251import java.security.cert.CertificateEncodingException; 252import java.security.cert.CertificateException; 253import java.text.SimpleDateFormat; 254import java.util.ArrayList; 255import java.util.Arrays; 256import java.util.Collection; 257import java.util.Collections; 258import java.util.Comparator; 259import java.util.Date; 260import java.util.Iterator; 261import java.util.List; 262import java.util.Map; 263import java.util.Objects; 264import java.util.Set; 265import java.util.concurrent.CountDownLatch; 266import java.util.concurrent.TimeUnit; 267import java.util.concurrent.atomic.AtomicBoolean; 268import java.util.concurrent.atomic.AtomicInteger; 269import java.util.concurrent.atomic.AtomicLong; 270 271/** 272 * Keep track of all those .apks everywhere. 273 * 274 * This is very central to the platform's security; please run the unit 275 * tests whenever making modifications here: 276 * 277runtest -c android.content.pm.PackageManagerTests frameworks-core 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 = false; 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 = false; 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_REPLACING = 1<<11; 325 static final int SCAN_REQUIRE_KNOWN = 1<<12; 326 static final int SCAN_MOVE = 1<<13; 327 static final int SCAN_INITIAL = 1<<14; 328 329 static final int REMOVE_CHATTY = 1<<16; 330 331 private static final int[] EMPTY_INT_ARRAY = new int[0]; 332 333 /** 334 * Timeout (in milliseconds) after which the watchdog should declare that 335 * our handler thread is wedged. The usual default for such things is one 336 * minute but we sometimes do very lengthy I/O operations on this thread, 337 * such as installing multi-gigabyte applications, so ours needs to be longer. 338 */ 339 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 340 341 /** 342 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 343 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 344 * settings entry if available, otherwise we use the hardcoded default. If it's been 345 * more than this long since the last fstrim, we force one during the boot sequence. 346 * 347 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 348 * one gets run at the next available charging+idle time. This final mandatory 349 * no-fstrim check kicks in only of the other scheduling criteria is never met. 350 */ 351 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 352 353 /** 354 * Whether verification is enabled by default. 355 */ 356 private static final boolean DEFAULT_VERIFY_ENABLE = true; 357 358 /** 359 * The default maximum time to wait for the verification agent to return in 360 * milliseconds. 361 */ 362 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 363 364 /** 365 * The default response for package verification timeout. 366 * 367 * This can be either PackageManager.VERIFICATION_ALLOW or 368 * PackageManager.VERIFICATION_REJECT. 369 */ 370 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 371 372 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 373 374 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 375 DEFAULT_CONTAINER_PACKAGE, 376 "com.android.defcontainer.DefaultContainerService"); 377 378 private static final String KILL_APP_REASON_GIDS_CHANGED = 379 "permission grant or revoke changed gids"; 380 381 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 382 "permissions revoked"; 383 384 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 385 386 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 387 388 /** Permission grant: not grant the permission. */ 389 private static final int GRANT_DENIED = 1; 390 391 /** Permission grant: grant the permission as an install permission. */ 392 private static final int GRANT_INSTALL = 2; 393 394 /** Permission grant: grant the permission as an install permission for a legacy app. */ 395 private static final int GRANT_INSTALL_LEGACY = 3; 396 397 /** Permission grant: grant the permission as a runtime one. */ 398 private static final int GRANT_RUNTIME = 4; 399 400 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 401 private static final int GRANT_UPGRADE = 5; 402 403 /** Canonical intent used to identify what counts as a "web browser" app */ 404 private static final Intent sBrowserIntent; 405 static { 406 sBrowserIntent = new Intent(); 407 sBrowserIntent.setAction(Intent.ACTION_VIEW); 408 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 409 sBrowserIntent.setData(Uri.parse("http:")); 410 } 411 412 final ServiceThread mHandlerThread; 413 414 final PackageHandler mHandler; 415 416 /** 417 * Messages for {@link #mHandler} that need to wait for system ready before 418 * being dispatched. 419 */ 420 private ArrayList<Message> mPostSystemReadyMessages; 421 422 final int mSdkVersion = Build.VERSION.SDK_INT; 423 424 final Context mContext; 425 final boolean mFactoryTest; 426 final boolean mOnlyCore; 427 final boolean mLazyDexOpt; 428 final long mDexOptLRUThresholdInMills; 429 final DisplayMetrics mMetrics; 430 final int mDefParseFlags; 431 final String[] mSeparateProcesses; 432 final boolean mIsUpgrade; 433 434 // This is where all application persistent data goes. 435 final File mAppDataDir; 436 437 // This is where all application persistent data goes for secondary users. 438 final File mUserAppDataDir; 439 440 /** The location for ASEC container files on internal storage. */ 441 final String mAsecInternalPath; 442 443 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 444 // LOCK HELD. Can be called with mInstallLock held. 445 @GuardedBy("mInstallLock") 446 final Installer mInstaller; 447 448 /** Directory where installed third-party apps stored */ 449 final File mAppInstallDir; 450 451 /** 452 * Directory to which applications installed internally have their 453 * 32 bit native libraries copied. 454 */ 455 private File mAppLib32InstallDir; 456 457 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 458 // apps. 459 final File mDrmAppPrivateInstallDir; 460 461 // ---------------------------------------------------------------- 462 463 // Lock for state used when installing and doing other long running 464 // operations. Methods that must be called with this lock held have 465 // the suffix "LI". 466 final Object mInstallLock = new Object(); 467 468 // ---------------------------------------------------------------- 469 470 // Keys are String (package name), values are Package. This also serves 471 // as the lock for the global state. Methods that must be called with 472 // this lock held have the prefix "LP". 473 @GuardedBy("mPackages") 474 final ArrayMap<String, PackageParser.Package> mPackages = 475 new ArrayMap<String, PackageParser.Package>(); 476 477 // Tracks available target package names -> overlay package paths. 478 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 479 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 480 481 /** 482 * Tracks new system packages [receiving in an OTA] that we expect to 483 * find updated user-installed versions. Keys are package name, values 484 * are package location. 485 */ 486 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 487 488 final Settings mSettings; 489 boolean mRestoredSettings; 490 491 // System configuration read by SystemConfig. 492 final int[] mGlobalGids; 493 final SparseArray<ArraySet<String>> mSystemPermissions; 494 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 495 496 // If mac_permissions.xml was found for seinfo labeling. 497 boolean mFoundPolicyFile; 498 499 // If a recursive restorecon of /data/data/<pkg> is needed. 500 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 501 502 public static final class SharedLibraryEntry { 503 public final String path; 504 public final String apk; 505 506 SharedLibraryEntry(String _path, String _apk) { 507 path = _path; 508 apk = _apk; 509 } 510 } 511 512 // Currently known shared libraries. 513 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 514 new ArrayMap<String, SharedLibraryEntry>(); 515 516 // All available activities, for your resolving pleasure. 517 final ActivityIntentResolver mActivities = 518 new ActivityIntentResolver(); 519 520 // All available receivers, for your resolving pleasure. 521 final ActivityIntentResolver mReceivers = 522 new ActivityIntentResolver(); 523 524 // All available services, for your resolving pleasure. 525 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 526 527 // All available providers, for your resolving pleasure. 528 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 529 530 // Mapping from provider base names (first directory in content URI codePath) 531 // to the provider information. 532 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 533 new ArrayMap<String, PackageParser.Provider>(); 534 535 // Mapping from instrumentation class names to info about them. 536 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 537 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 538 539 // Mapping from permission names to info about them. 540 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 541 new ArrayMap<String, PackageParser.PermissionGroup>(); 542 543 // Packages whose data we have transfered into another package, thus 544 // should no longer exist. 545 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 546 547 // Broadcast actions that are only available to the system. 548 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 549 550 /** List of packages waiting for verification. */ 551 final SparseArray<PackageVerificationState> mPendingVerification 552 = new SparseArray<PackageVerificationState>(); 553 554 /** Set of packages associated with each app op permission. */ 555 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 556 557 final PackageInstallerService mInstallerService; 558 559 private final PackageDexOptimizer mPackageDexOptimizer; 560 561 private AtomicInteger mNextMoveId = new AtomicInteger(); 562 private final MoveCallbacks mMoveCallbacks; 563 564 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 565 566 // Cache of users who need badging. 567 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 568 569 /** Token for keys in mPendingVerification. */ 570 private int mPendingVerificationToken = 0; 571 572 volatile boolean mSystemReady; 573 volatile boolean mSafeMode; 574 volatile boolean mHasSystemUidErrors; 575 576 ApplicationInfo mAndroidApplication; 577 final ActivityInfo mResolveActivity = new ActivityInfo(); 578 final ResolveInfo mResolveInfo = new ResolveInfo(); 579 ComponentName mResolveComponentName; 580 PackageParser.Package mPlatformPackage; 581 ComponentName mCustomResolverComponentName; 582 583 boolean mResolverReplaced = false; 584 585 private final ComponentName mIntentFilterVerifierComponent; 586 private int mIntentFilterVerificationToken = 0; 587 588 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 589 = new SparseArray<IntentFilterVerificationState>(); 590 591 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 592 new DefaultPermissionGrantPolicy(this); 593 594 private static class IFVerificationParams { 595 PackageParser.Package pkg; 596 boolean replacing; 597 int userId; 598 int verifierUid; 599 600 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 601 int _userId, int _verifierUid) { 602 pkg = _pkg; 603 replacing = _replacing; 604 userId = _userId; 605 replacing = _replacing; 606 verifierUid = _verifierUid; 607 } 608 } 609 610 private interface IntentFilterVerifier<T extends IntentFilter> { 611 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 612 T filter, String packageName); 613 void startVerifications(int userId); 614 void receiveVerificationResponse(int verificationId); 615 } 616 617 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 618 private Context mContext; 619 private ComponentName mIntentFilterVerifierComponent; 620 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 621 622 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 623 mContext = context; 624 mIntentFilterVerifierComponent = verifierComponent; 625 } 626 627 private String getDefaultScheme() { 628 return IntentFilter.SCHEME_HTTPS; 629 } 630 631 @Override 632 public void startVerifications(int userId) { 633 // Launch verifications requests 634 int count = mCurrentIntentFilterVerifications.size(); 635 for (int n=0; n<count; n++) { 636 int verificationId = mCurrentIntentFilterVerifications.get(n); 637 final IntentFilterVerificationState ivs = 638 mIntentFilterVerificationStates.get(verificationId); 639 640 String packageName = ivs.getPackageName(); 641 642 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 643 final int filterCount = filters.size(); 644 ArraySet<String> domainsSet = new ArraySet<>(); 645 for (int m=0; m<filterCount; m++) { 646 PackageParser.ActivityIntentInfo filter = filters.get(m); 647 domainsSet.addAll(filter.getHostsList()); 648 } 649 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 650 synchronized (mPackages) { 651 if (mSettings.createIntentFilterVerificationIfNeededLPw( 652 packageName, domainsList) != null) { 653 scheduleWriteSettingsLocked(); 654 } 655 } 656 sendVerificationRequest(userId, verificationId, ivs); 657 } 658 mCurrentIntentFilterVerifications.clear(); 659 } 660 661 private void sendVerificationRequest(int userId, int verificationId, 662 IntentFilterVerificationState ivs) { 663 664 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 665 verificationIntent.putExtra( 666 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 667 verificationId); 668 verificationIntent.putExtra( 669 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 670 getDefaultScheme()); 671 verificationIntent.putExtra( 672 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 673 ivs.getHostsString()); 674 verificationIntent.putExtra( 675 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 676 ivs.getPackageName()); 677 verificationIntent.setComponent(mIntentFilterVerifierComponent); 678 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 679 680 UserHandle user = new UserHandle(userId); 681 mContext.sendBroadcastAsUser(verificationIntent, user); 682 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 683 "Sending IntentFilter verification broadcast"); 684 } 685 686 public void receiveVerificationResponse(int verificationId) { 687 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 688 689 final boolean verified = ivs.isVerified(); 690 691 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 692 final int count = filters.size(); 693 if (DEBUG_DOMAIN_VERIFICATION) { 694 Slog.i(TAG, "Received verification response " + verificationId 695 + " for " + count + " filters, verified=" + verified); 696 } 697 for (int n=0; n<count; n++) { 698 PackageParser.ActivityIntentInfo filter = filters.get(n); 699 filter.setVerified(verified); 700 701 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 702 + " verified with result:" + verified + " and hosts:" 703 + ivs.getHostsString()); 704 } 705 706 mIntentFilterVerificationStates.remove(verificationId); 707 708 final String packageName = ivs.getPackageName(); 709 IntentFilterVerificationInfo ivi = null; 710 711 synchronized (mPackages) { 712 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 713 } 714 if (ivi == null) { 715 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 716 + verificationId + " packageName:" + packageName); 717 return; 718 } 719 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 720 "Updating IntentFilterVerificationInfo for package " + packageName 721 +" verificationId:" + verificationId); 722 723 synchronized (mPackages) { 724 if (verified) { 725 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 726 } else { 727 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 728 } 729 scheduleWriteSettingsLocked(); 730 731 final int userId = ivs.getUserId(); 732 if (userId != UserHandle.USER_ALL) { 733 final int userStatus = 734 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 735 736 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 737 boolean needUpdate = false; 738 739 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 740 // already been set by the User thru the Disambiguation dialog 741 switch (userStatus) { 742 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 743 if (verified) { 744 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 745 } else { 746 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 747 } 748 needUpdate = true; 749 break; 750 751 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 752 if (verified) { 753 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 754 needUpdate = true; 755 } 756 break; 757 758 default: 759 // Nothing to do 760 } 761 762 if (needUpdate) { 763 mSettings.updateIntentFilterVerificationStatusLPw( 764 packageName, updatedStatus, userId); 765 scheduleWritePackageRestrictionsLocked(userId); 766 } 767 } 768 } 769 } 770 771 @Override 772 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 773 ActivityIntentInfo filter, String packageName) { 774 if (!hasValidDomains(filter)) { 775 return false; 776 } 777 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 778 if (ivs == null) { 779 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 780 packageName); 781 } 782 if (DEBUG_DOMAIN_VERIFICATION) { 783 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 784 } 785 ivs.addFilter(filter); 786 return true; 787 } 788 789 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 790 int userId, int verificationId, String packageName) { 791 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 792 verifierUid, userId, packageName); 793 ivs.setPendingState(); 794 synchronized (mPackages) { 795 mIntentFilterVerificationStates.append(verificationId, ivs); 796 mCurrentIntentFilterVerifications.add(verificationId); 797 } 798 return ivs; 799 } 800 } 801 802 private static boolean hasValidDomains(ActivityIntentInfo filter) { 803 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 804 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 805 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 806 } 807 808 private IntentFilterVerifier mIntentFilterVerifier; 809 810 // Set of pending broadcasts for aggregating enable/disable of components. 811 static class PendingPackageBroadcasts { 812 // for each user id, a map of <package name -> components within that package> 813 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 814 815 public PendingPackageBroadcasts() { 816 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 817 } 818 819 public ArrayList<String> get(int userId, String packageName) { 820 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 821 return packages.get(packageName); 822 } 823 824 public void put(int userId, String packageName, ArrayList<String> components) { 825 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 826 packages.put(packageName, components); 827 } 828 829 public void remove(int userId, String packageName) { 830 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 831 if (packages != null) { 832 packages.remove(packageName); 833 } 834 } 835 836 public void remove(int userId) { 837 mUidMap.remove(userId); 838 } 839 840 public int userIdCount() { 841 return mUidMap.size(); 842 } 843 844 public int userIdAt(int n) { 845 return mUidMap.keyAt(n); 846 } 847 848 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 849 return mUidMap.get(userId); 850 } 851 852 public int size() { 853 // total number of pending broadcast entries across all userIds 854 int num = 0; 855 for (int i = 0; i< mUidMap.size(); i++) { 856 num += mUidMap.valueAt(i).size(); 857 } 858 return num; 859 } 860 861 public void clear() { 862 mUidMap.clear(); 863 } 864 865 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 866 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 867 if (map == null) { 868 map = new ArrayMap<String, ArrayList<String>>(); 869 mUidMap.put(userId, map); 870 } 871 return map; 872 } 873 } 874 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 875 876 // Service Connection to remote media container service to copy 877 // package uri's from external media onto secure containers 878 // or internal storage. 879 private IMediaContainerService mContainerService = null; 880 881 static final int SEND_PENDING_BROADCAST = 1; 882 static final int MCS_BOUND = 3; 883 static final int END_COPY = 4; 884 static final int INIT_COPY = 5; 885 static final int MCS_UNBIND = 6; 886 static final int START_CLEANING_PACKAGE = 7; 887 static final int FIND_INSTALL_LOC = 8; 888 static final int POST_INSTALL = 9; 889 static final int MCS_RECONNECT = 10; 890 static final int MCS_GIVE_UP = 11; 891 static final int UPDATED_MEDIA_STATUS = 12; 892 static final int WRITE_SETTINGS = 13; 893 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 894 static final int PACKAGE_VERIFIED = 15; 895 static final int CHECK_PENDING_VERIFICATION = 16; 896 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 897 static final int INTENT_FILTER_VERIFIED = 18; 898 899 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 900 901 // Delay time in millisecs 902 static final int BROADCAST_DELAY = 10 * 1000; 903 904 static UserManagerService sUserManager; 905 906 // Stores a list of users whose package restrictions file needs to be updated 907 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 908 909 final private DefaultContainerConnection mDefContainerConn = 910 new DefaultContainerConnection(); 911 class DefaultContainerConnection implements ServiceConnection { 912 public void onServiceConnected(ComponentName name, IBinder service) { 913 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 914 IMediaContainerService imcs = 915 IMediaContainerService.Stub.asInterface(service); 916 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 917 } 918 919 public void onServiceDisconnected(ComponentName name) { 920 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 921 } 922 } 923 924 // Recordkeeping of restore-after-install operations that are currently in flight 925 // between the Package Manager and the Backup Manager 926 class PostInstallData { 927 public InstallArgs args; 928 public PackageInstalledInfo res; 929 930 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 931 args = _a; 932 res = _r; 933 } 934 } 935 936 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 937 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 938 939 // XML tags for backup/restore of various bits of state 940 private static final String TAG_PREFERRED_BACKUP = "pa"; 941 private static final String TAG_DEFAULT_APPS = "da"; 942 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 943 944 final String mRequiredVerifierPackage; 945 final String mRequiredInstallerPackage; 946 947 private final PackageUsage mPackageUsage = new PackageUsage(); 948 949 private class PackageUsage { 950 private static final int WRITE_INTERVAL 951 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 952 953 private final Object mFileLock = new Object(); 954 private final AtomicLong mLastWritten = new AtomicLong(0); 955 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 956 957 private boolean mIsHistoricalPackageUsageAvailable = true; 958 959 boolean isHistoricalPackageUsageAvailable() { 960 return mIsHistoricalPackageUsageAvailable; 961 } 962 963 void write(boolean force) { 964 if (force) { 965 writeInternal(); 966 return; 967 } 968 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 969 && !DEBUG_DEXOPT) { 970 return; 971 } 972 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 973 new Thread("PackageUsage_DiskWriter") { 974 @Override 975 public void run() { 976 try { 977 writeInternal(); 978 } finally { 979 mBackgroundWriteRunning.set(false); 980 } 981 } 982 }.start(); 983 } 984 } 985 986 private void writeInternal() { 987 synchronized (mPackages) { 988 synchronized (mFileLock) { 989 AtomicFile file = getFile(); 990 FileOutputStream f = null; 991 try { 992 f = file.startWrite(); 993 BufferedOutputStream out = new BufferedOutputStream(f); 994 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 995 StringBuilder sb = new StringBuilder(); 996 for (PackageParser.Package pkg : mPackages.values()) { 997 if (pkg.mLastPackageUsageTimeInMills == 0) { 998 continue; 999 } 1000 sb.setLength(0); 1001 sb.append(pkg.packageName); 1002 sb.append(' '); 1003 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1004 sb.append('\n'); 1005 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1006 } 1007 out.flush(); 1008 file.finishWrite(f); 1009 } catch (IOException e) { 1010 if (f != null) { 1011 file.failWrite(f); 1012 } 1013 Log.e(TAG, "Failed to write package usage times", e); 1014 } 1015 } 1016 } 1017 mLastWritten.set(SystemClock.elapsedRealtime()); 1018 } 1019 1020 void readLP() { 1021 synchronized (mFileLock) { 1022 AtomicFile file = getFile(); 1023 BufferedInputStream in = null; 1024 try { 1025 in = new BufferedInputStream(file.openRead()); 1026 StringBuffer sb = new StringBuffer(); 1027 while (true) { 1028 String packageName = readToken(in, sb, ' '); 1029 if (packageName == null) { 1030 break; 1031 } 1032 String timeInMillisString = readToken(in, sb, '\n'); 1033 if (timeInMillisString == null) { 1034 throw new IOException("Failed to find last usage time for package " 1035 + packageName); 1036 } 1037 PackageParser.Package pkg = mPackages.get(packageName); 1038 if (pkg == null) { 1039 continue; 1040 } 1041 long timeInMillis; 1042 try { 1043 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1044 } catch (NumberFormatException e) { 1045 throw new IOException("Failed to parse " + timeInMillisString 1046 + " as a long.", e); 1047 } 1048 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1049 } 1050 } catch (FileNotFoundException expected) { 1051 mIsHistoricalPackageUsageAvailable = false; 1052 } catch (IOException e) { 1053 Log.w(TAG, "Failed to read package usage times", e); 1054 } finally { 1055 IoUtils.closeQuietly(in); 1056 } 1057 } 1058 mLastWritten.set(SystemClock.elapsedRealtime()); 1059 } 1060 1061 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1062 throws IOException { 1063 sb.setLength(0); 1064 while (true) { 1065 int ch = in.read(); 1066 if (ch == -1) { 1067 if (sb.length() == 0) { 1068 return null; 1069 } 1070 throw new IOException("Unexpected EOF"); 1071 } 1072 if (ch == endOfToken) { 1073 return sb.toString(); 1074 } 1075 sb.append((char)ch); 1076 } 1077 } 1078 1079 private AtomicFile getFile() { 1080 File dataDir = Environment.getDataDirectory(); 1081 File systemDir = new File(dataDir, "system"); 1082 File fname = new File(systemDir, "package-usage.list"); 1083 return new AtomicFile(fname); 1084 } 1085 } 1086 1087 class PackageHandler extends Handler { 1088 private boolean mBound = false; 1089 final ArrayList<HandlerParams> mPendingInstalls = 1090 new ArrayList<HandlerParams>(); 1091 1092 private boolean connectToService() { 1093 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1094 " DefaultContainerService"); 1095 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1096 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1097 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1098 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1099 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1100 mBound = true; 1101 return true; 1102 } 1103 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1104 return false; 1105 } 1106 1107 private void disconnectService() { 1108 mContainerService = null; 1109 mBound = false; 1110 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1111 mContext.unbindService(mDefContainerConn); 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1113 } 1114 1115 PackageHandler(Looper looper) { 1116 super(looper); 1117 } 1118 1119 public void handleMessage(Message msg) { 1120 try { 1121 doHandleMessage(msg); 1122 } finally { 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1124 } 1125 } 1126 1127 void doHandleMessage(Message msg) { 1128 switch (msg.what) { 1129 case INIT_COPY: { 1130 HandlerParams params = (HandlerParams) msg.obj; 1131 int idx = mPendingInstalls.size(); 1132 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1133 // If a bind was already initiated we dont really 1134 // need to do anything. The pending install 1135 // will be processed later on. 1136 if (!mBound) { 1137 // If this is the only one pending we might 1138 // have to bind to the service again. 1139 if (!connectToService()) { 1140 Slog.e(TAG, "Failed to bind to media container service"); 1141 params.serviceError(); 1142 return; 1143 } else { 1144 // Once we bind to the service, the first 1145 // pending request will be processed. 1146 mPendingInstalls.add(idx, params); 1147 } 1148 } else { 1149 mPendingInstalls.add(idx, params); 1150 // Already bound to the service. Just make 1151 // sure we trigger off processing the first request. 1152 if (idx == 0) { 1153 mHandler.sendEmptyMessage(MCS_BOUND); 1154 } 1155 } 1156 break; 1157 } 1158 case MCS_BOUND: { 1159 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1160 if (msg.obj != null) { 1161 mContainerService = (IMediaContainerService) msg.obj; 1162 } 1163 if (mContainerService == null) { 1164 if (!mBound) { 1165 // Something seriously wrong since we are not bound and we are not 1166 // waiting for connection. Bail out. 1167 Slog.e(TAG, "Cannot bind to media container service"); 1168 for (HandlerParams params : mPendingInstalls) { 1169 // Indicate service bind error 1170 params.serviceError(); 1171 } 1172 mPendingInstalls.clear(); 1173 } else { 1174 Slog.w(TAG, "Waiting to connect to media container service"); 1175 } 1176 } else if (mPendingInstalls.size() > 0) { 1177 HandlerParams params = mPendingInstalls.get(0); 1178 if (params != null) { 1179 if (params.startCopy()) { 1180 // We are done... look for more work or to 1181 // go idle. 1182 if (DEBUG_SD_INSTALL) Log.i(TAG, 1183 "Checking for more work or unbind..."); 1184 // Delete pending install 1185 if (mPendingInstalls.size() > 0) { 1186 mPendingInstalls.remove(0); 1187 } 1188 if (mPendingInstalls.size() == 0) { 1189 if (mBound) { 1190 if (DEBUG_SD_INSTALL) Log.i(TAG, 1191 "Posting delayed MCS_UNBIND"); 1192 removeMessages(MCS_UNBIND); 1193 Message ubmsg = obtainMessage(MCS_UNBIND); 1194 // Unbind after a little delay, to avoid 1195 // continual thrashing. 1196 sendMessageDelayed(ubmsg, 10000); 1197 } 1198 } else { 1199 // There are more pending requests in queue. 1200 // Just post MCS_BOUND message to trigger processing 1201 // of next pending install. 1202 if (DEBUG_SD_INSTALL) Log.i(TAG, 1203 "Posting MCS_BOUND for next work"); 1204 mHandler.sendEmptyMessage(MCS_BOUND); 1205 } 1206 } 1207 } 1208 } else { 1209 // Should never happen ideally. 1210 Slog.w(TAG, "Empty queue"); 1211 } 1212 break; 1213 } 1214 case MCS_RECONNECT: { 1215 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1216 if (mPendingInstalls.size() > 0) { 1217 if (mBound) { 1218 disconnectService(); 1219 } 1220 if (!connectToService()) { 1221 Slog.e(TAG, "Failed to bind to media container service"); 1222 for (HandlerParams params : mPendingInstalls) { 1223 // Indicate service bind error 1224 params.serviceError(); 1225 } 1226 mPendingInstalls.clear(); 1227 } 1228 } 1229 break; 1230 } 1231 case MCS_UNBIND: { 1232 // If there is no actual work left, then time to unbind. 1233 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1234 1235 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1236 if (mBound) { 1237 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1238 1239 disconnectService(); 1240 } 1241 } else if (mPendingInstalls.size() > 0) { 1242 // There are more pending requests in queue. 1243 // Just post MCS_BOUND message to trigger processing 1244 // of next pending install. 1245 mHandler.sendEmptyMessage(MCS_BOUND); 1246 } 1247 1248 break; 1249 } 1250 case MCS_GIVE_UP: { 1251 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1252 mPendingInstalls.remove(0); 1253 break; 1254 } 1255 case SEND_PENDING_BROADCAST: { 1256 String packages[]; 1257 ArrayList<String> components[]; 1258 int size = 0; 1259 int uids[]; 1260 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1261 synchronized (mPackages) { 1262 if (mPendingBroadcasts == null) { 1263 return; 1264 } 1265 size = mPendingBroadcasts.size(); 1266 if (size <= 0) { 1267 // Nothing to be done. Just return 1268 return; 1269 } 1270 packages = new String[size]; 1271 components = new ArrayList[size]; 1272 uids = new int[size]; 1273 int i = 0; // filling out the above arrays 1274 1275 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1276 int packageUserId = mPendingBroadcasts.userIdAt(n); 1277 Iterator<Map.Entry<String, ArrayList<String>>> it 1278 = mPendingBroadcasts.packagesForUserId(packageUserId) 1279 .entrySet().iterator(); 1280 while (it.hasNext() && i < size) { 1281 Map.Entry<String, ArrayList<String>> ent = it.next(); 1282 packages[i] = ent.getKey(); 1283 components[i] = ent.getValue(); 1284 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1285 uids[i] = (ps != null) 1286 ? UserHandle.getUid(packageUserId, ps.appId) 1287 : -1; 1288 i++; 1289 } 1290 } 1291 size = i; 1292 mPendingBroadcasts.clear(); 1293 } 1294 // Send broadcasts 1295 for (int i = 0; i < size; i++) { 1296 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1297 } 1298 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1299 break; 1300 } 1301 case START_CLEANING_PACKAGE: { 1302 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1303 final String packageName = (String)msg.obj; 1304 final int userId = msg.arg1; 1305 final boolean andCode = msg.arg2 != 0; 1306 synchronized (mPackages) { 1307 if (userId == UserHandle.USER_ALL) { 1308 int[] users = sUserManager.getUserIds(); 1309 for (int user : users) { 1310 mSettings.addPackageToCleanLPw( 1311 new PackageCleanItem(user, packageName, andCode)); 1312 } 1313 } else { 1314 mSettings.addPackageToCleanLPw( 1315 new PackageCleanItem(userId, packageName, andCode)); 1316 } 1317 } 1318 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1319 startCleaningPackages(); 1320 } break; 1321 case POST_INSTALL: { 1322 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1323 PostInstallData data = mRunningInstalls.get(msg.arg1); 1324 mRunningInstalls.delete(msg.arg1); 1325 boolean deleteOld = false; 1326 1327 if (data != null) { 1328 InstallArgs args = data.args; 1329 PackageInstalledInfo res = data.res; 1330 1331 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1332 final String packageName = res.pkg.applicationInfo.packageName; 1333 res.removedInfo.sendBroadcast(false, true, false); 1334 Bundle extras = new Bundle(1); 1335 extras.putInt(Intent.EXTRA_UID, res.uid); 1336 1337 // Now that we successfully installed the package, grant runtime 1338 // permissions if requested before broadcasting the install. 1339 if ((args.installFlags 1340 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1341 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1342 args.installGrantPermissions); 1343 } 1344 1345 // Determine the set of users who are adding this 1346 // package for the first time vs. those who are seeing 1347 // an update. 1348 int[] firstUsers; 1349 int[] updateUsers = new int[0]; 1350 if (res.origUsers == null || res.origUsers.length == 0) { 1351 firstUsers = res.newUsers; 1352 } else { 1353 firstUsers = new int[0]; 1354 for (int i=0; i<res.newUsers.length; i++) { 1355 int user = res.newUsers[i]; 1356 boolean isNew = true; 1357 for (int j=0; j<res.origUsers.length; j++) { 1358 if (res.origUsers[j] == user) { 1359 isNew = false; 1360 break; 1361 } 1362 } 1363 if (isNew) { 1364 int[] newFirst = new int[firstUsers.length+1]; 1365 System.arraycopy(firstUsers, 0, newFirst, 0, 1366 firstUsers.length); 1367 newFirst[firstUsers.length] = user; 1368 firstUsers = newFirst; 1369 } else { 1370 int[] newUpdate = new int[updateUsers.length+1]; 1371 System.arraycopy(updateUsers, 0, newUpdate, 0, 1372 updateUsers.length); 1373 newUpdate[updateUsers.length] = user; 1374 updateUsers = newUpdate; 1375 } 1376 } 1377 } 1378 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1379 packageName, extras, null, null, firstUsers); 1380 final boolean update = res.removedInfo.removedPackage != null; 1381 if (update) { 1382 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1383 } 1384 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1385 packageName, extras, null, null, updateUsers); 1386 if (update) { 1387 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1388 packageName, extras, null, null, updateUsers); 1389 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1390 null, null, packageName, null, updateUsers); 1391 1392 // treat asec-hosted packages like removable media on upgrade 1393 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1394 if (DEBUG_INSTALL) { 1395 Slog.i(TAG, "upgrading pkg " + res.pkg 1396 + " is ASEC-hosted -> AVAILABLE"); 1397 } 1398 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1399 ArrayList<String> pkgList = new ArrayList<String>(1); 1400 pkgList.add(packageName); 1401 sendResourcesChangedBroadcast(true, true, 1402 pkgList,uidArray, null); 1403 } 1404 } 1405 if (res.removedInfo.args != null) { 1406 // Remove the replaced package's older resources safely now 1407 deleteOld = true; 1408 } 1409 1410 // If this app is a browser and it's newly-installed for some 1411 // users, clear any default-browser state in those users 1412 if (firstUsers.length > 0) { 1413 // the app's nature doesn't depend on the user, so we can just 1414 // check its browser nature in any user and generalize. 1415 if (packageIsBrowser(packageName, firstUsers[0])) { 1416 synchronized (mPackages) { 1417 for (int userId : firstUsers) { 1418 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1419 } 1420 } 1421 } 1422 } 1423 // Log current value of "unknown sources" setting 1424 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1425 getUnknownSourcesSettings()); 1426 } 1427 // Force a gc to clear up things 1428 Runtime.getRuntime().gc(); 1429 // We delete after a gc for applications on sdcard. 1430 if (deleteOld) { 1431 synchronized (mInstallLock) { 1432 res.removedInfo.args.doPostDeleteLI(true); 1433 } 1434 } 1435 if (args.observer != null) { 1436 try { 1437 Bundle extras = extrasForInstallResult(res); 1438 args.observer.onPackageInstalled(res.name, res.returnCode, 1439 res.returnMsg, extras); 1440 } catch (RemoteException e) { 1441 Slog.i(TAG, "Observer no longer exists."); 1442 } 1443 } 1444 } else { 1445 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1446 } 1447 } break; 1448 case UPDATED_MEDIA_STATUS: { 1449 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1450 boolean reportStatus = msg.arg1 == 1; 1451 boolean doGc = msg.arg2 == 1; 1452 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1453 if (doGc) { 1454 // Force a gc to clear up stale containers. 1455 Runtime.getRuntime().gc(); 1456 } 1457 if (msg.obj != null) { 1458 @SuppressWarnings("unchecked") 1459 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1460 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1461 // Unload containers 1462 unloadAllContainers(args); 1463 } 1464 if (reportStatus) { 1465 try { 1466 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1467 PackageHelper.getMountService().finishMediaUpdate(); 1468 } catch (RemoteException e) { 1469 Log.e(TAG, "MountService not running?"); 1470 } 1471 } 1472 } break; 1473 case WRITE_SETTINGS: { 1474 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1475 synchronized (mPackages) { 1476 removeMessages(WRITE_SETTINGS); 1477 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1478 mSettings.writeLPr(); 1479 mDirtyUsers.clear(); 1480 } 1481 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1482 } break; 1483 case WRITE_PACKAGE_RESTRICTIONS: { 1484 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1485 synchronized (mPackages) { 1486 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1487 for (int userId : mDirtyUsers) { 1488 mSettings.writePackageRestrictionsLPr(userId); 1489 } 1490 mDirtyUsers.clear(); 1491 } 1492 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1493 } break; 1494 case CHECK_PENDING_VERIFICATION: { 1495 final int verificationId = msg.arg1; 1496 final PackageVerificationState state = mPendingVerification.get(verificationId); 1497 1498 if ((state != null) && !state.timeoutExtended()) { 1499 final InstallArgs args = state.getInstallArgs(); 1500 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1501 1502 Slog.i(TAG, "Verification timed out for " + originUri); 1503 mPendingVerification.remove(verificationId); 1504 1505 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1506 1507 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1508 Slog.i(TAG, "Continuing with installation of " + originUri); 1509 state.setVerifierResponse(Binder.getCallingUid(), 1510 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1511 broadcastPackageVerified(verificationId, originUri, 1512 PackageManager.VERIFICATION_ALLOW, 1513 state.getInstallArgs().getUser()); 1514 try { 1515 ret = args.copyApk(mContainerService, true); 1516 } catch (RemoteException e) { 1517 Slog.e(TAG, "Could not contact the ContainerService"); 1518 } 1519 } else { 1520 broadcastPackageVerified(verificationId, originUri, 1521 PackageManager.VERIFICATION_REJECT, 1522 state.getInstallArgs().getUser()); 1523 } 1524 1525 processPendingInstall(args, ret); 1526 mHandler.sendEmptyMessage(MCS_UNBIND); 1527 } 1528 break; 1529 } 1530 case PACKAGE_VERIFIED: { 1531 final int verificationId = msg.arg1; 1532 1533 final PackageVerificationState state = mPendingVerification.get(verificationId); 1534 if (state == null) { 1535 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1536 break; 1537 } 1538 1539 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1540 1541 state.setVerifierResponse(response.callerUid, response.code); 1542 1543 if (state.isVerificationComplete()) { 1544 mPendingVerification.remove(verificationId); 1545 1546 final InstallArgs args = state.getInstallArgs(); 1547 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1548 1549 int ret; 1550 if (state.isInstallAllowed()) { 1551 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1552 broadcastPackageVerified(verificationId, originUri, 1553 response.code, state.getInstallArgs().getUser()); 1554 try { 1555 ret = args.copyApk(mContainerService, true); 1556 } catch (RemoteException e) { 1557 Slog.e(TAG, "Could not contact the ContainerService"); 1558 } 1559 } else { 1560 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1561 } 1562 1563 processPendingInstall(args, ret); 1564 1565 mHandler.sendEmptyMessage(MCS_UNBIND); 1566 } 1567 1568 break; 1569 } 1570 case START_INTENT_FILTER_VERIFICATIONS: { 1571 IFVerificationParams params = (IFVerificationParams) msg.obj; 1572 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1573 params.replacing, params.pkg); 1574 break; 1575 } 1576 case INTENT_FILTER_VERIFIED: { 1577 final int verificationId = msg.arg1; 1578 1579 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1580 verificationId); 1581 if (state == null) { 1582 Slog.w(TAG, "Invalid IntentFilter verification token " 1583 + verificationId + " received"); 1584 break; 1585 } 1586 1587 final int userId = state.getUserId(); 1588 1589 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1590 "Processing IntentFilter verification with token:" 1591 + verificationId + " and userId:" + userId); 1592 1593 final IntentFilterVerificationResponse response = 1594 (IntentFilterVerificationResponse) msg.obj; 1595 1596 state.setVerifierResponse(response.callerUid, response.code); 1597 1598 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1599 "IntentFilter verification with token:" + verificationId 1600 + " and userId:" + userId 1601 + " is settings verifier response with response code:" 1602 + response.code); 1603 1604 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1605 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1606 + response.getFailedDomainsString()); 1607 } 1608 1609 if (state.isVerificationComplete()) { 1610 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1611 } else { 1612 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1613 "IntentFilter verification with token:" + verificationId 1614 + " was not said to be complete"); 1615 } 1616 1617 break; 1618 } 1619 } 1620 } 1621 } 1622 1623 private StorageEventListener mStorageListener = new StorageEventListener() { 1624 @Override 1625 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1626 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1627 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1628 final String volumeUuid = vol.getFsUuid(); 1629 1630 // Clean up any users or apps that were removed or recreated 1631 // while this volume was missing 1632 reconcileUsers(volumeUuid); 1633 reconcileApps(volumeUuid); 1634 1635 // Clean up any install sessions that expired or were 1636 // cancelled while this volume was missing 1637 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1638 1639 loadPrivatePackages(vol); 1640 1641 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1642 unloadPrivatePackages(vol); 1643 } 1644 } 1645 1646 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1647 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1648 updateExternalMediaStatus(true, false); 1649 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1650 updateExternalMediaStatus(false, false); 1651 } 1652 } 1653 } 1654 1655 @Override 1656 public void onVolumeForgotten(String fsUuid) { 1657 if (TextUtils.isEmpty(fsUuid)) { 1658 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1659 return; 1660 } 1661 1662 // Remove any apps installed on the forgotten volume 1663 synchronized (mPackages) { 1664 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1665 for (PackageSetting ps : packages) { 1666 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1667 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1668 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1669 } 1670 1671 mSettings.onVolumeForgotten(fsUuid); 1672 mSettings.writeLPr(); 1673 } 1674 } 1675 }; 1676 1677 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1678 String[] grantedPermissions) { 1679 if (userId >= UserHandle.USER_OWNER) { 1680 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1681 } else if (userId == UserHandle.USER_ALL) { 1682 final int[] userIds; 1683 synchronized (mPackages) { 1684 userIds = UserManagerService.getInstance().getUserIds(); 1685 } 1686 for (int someUserId : userIds) { 1687 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1688 } 1689 } 1690 1691 // We could have touched GID membership, so flush out packages.list 1692 synchronized (mPackages) { 1693 mSettings.writePackageListLPr(); 1694 } 1695 } 1696 1697 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1698 String[] grantedPermissions) { 1699 SettingBase sb = (SettingBase) pkg.mExtras; 1700 if (sb == null) { 1701 return; 1702 } 1703 1704 PermissionsState permissionsState = sb.getPermissionsState(); 1705 1706 for (String permission : pkg.requestedPermissions) { 1707 BasePermission bp = mSettings.mPermissions.get(permission); 1708 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1709 || ArrayUtils.contains(grantedPermissions, permission))) { 1710 permissionsState.grantRuntimePermission(bp, userId); 1711 } 1712 } 1713 } 1714 1715 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1716 Bundle extras = null; 1717 switch (res.returnCode) { 1718 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1719 extras = new Bundle(); 1720 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1721 res.origPermission); 1722 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1723 res.origPackage); 1724 break; 1725 } 1726 case PackageManager.INSTALL_SUCCEEDED: { 1727 extras = new Bundle(); 1728 extras.putBoolean(Intent.EXTRA_REPLACING, 1729 res.removedInfo != null && res.removedInfo.removedPackage != null); 1730 break; 1731 } 1732 } 1733 return extras; 1734 } 1735 1736 void scheduleWriteSettingsLocked() { 1737 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1738 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1739 } 1740 } 1741 1742 void scheduleWritePackageRestrictionsLocked(int userId) { 1743 if (!sUserManager.exists(userId)) return; 1744 mDirtyUsers.add(userId); 1745 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1746 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1747 } 1748 } 1749 1750 public static PackageManagerService main(Context context, Installer installer, 1751 boolean factoryTest, boolean onlyCore) { 1752 PackageManagerService m = new PackageManagerService(context, installer, 1753 factoryTest, onlyCore); 1754 ServiceManager.addService("package", m); 1755 return m; 1756 } 1757 1758 static String[] splitString(String str, char sep) { 1759 int count = 1; 1760 int i = 0; 1761 while ((i=str.indexOf(sep, i)) >= 0) { 1762 count++; 1763 i++; 1764 } 1765 1766 String[] res = new String[count]; 1767 i=0; 1768 count = 0; 1769 int lastI=0; 1770 while ((i=str.indexOf(sep, i)) >= 0) { 1771 res[count] = str.substring(lastI, i); 1772 count++; 1773 i++; 1774 lastI = i; 1775 } 1776 res[count] = str.substring(lastI, str.length()); 1777 return res; 1778 } 1779 1780 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1781 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1782 Context.DISPLAY_SERVICE); 1783 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1784 } 1785 1786 public PackageManagerService(Context context, Installer installer, 1787 boolean factoryTest, boolean onlyCore) { 1788 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1789 SystemClock.uptimeMillis()); 1790 1791 if (mSdkVersion <= 0) { 1792 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1793 } 1794 1795 mContext = context; 1796 mFactoryTest = factoryTest; 1797 mOnlyCore = onlyCore; 1798 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1799 mMetrics = new DisplayMetrics(); 1800 mSettings = new Settings(mPackages); 1801 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1802 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1803 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1804 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1805 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1806 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1807 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1808 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1809 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1810 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1811 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1812 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1813 1814 // TODO: add a property to control this? 1815 long dexOptLRUThresholdInMinutes; 1816 if (mLazyDexOpt) { 1817 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1818 } else { 1819 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1820 } 1821 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1822 1823 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1824 if (separateProcesses != null && separateProcesses.length() > 0) { 1825 if ("*".equals(separateProcesses)) { 1826 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1827 mSeparateProcesses = null; 1828 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1829 } else { 1830 mDefParseFlags = 0; 1831 mSeparateProcesses = separateProcesses.split(","); 1832 Slog.w(TAG, "Running with debug.separate_processes: " 1833 + separateProcesses); 1834 } 1835 } else { 1836 mDefParseFlags = 0; 1837 mSeparateProcesses = null; 1838 } 1839 1840 mInstaller = installer; 1841 mPackageDexOptimizer = new PackageDexOptimizer(this); 1842 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1843 1844 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1845 FgThread.get().getLooper()); 1846 1847 getDefaultDisplayMetrics(context, mMetrics); 1848 1849 SystemConfig systemConfig = SystemConfig.getInstance(); 1850 mGlobalGids = systemConfig.getGlobalGids(); 1851 mSystemPermissions = systemConfig.getSystemPermissions(); 1852 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1853 1854 synchronized (mInstallLock) { 1855 // writer 1856 synchronized (mPackages) { 1857 mHandlerThread = new ServiceThread(TAG, 1858 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1859 mHandlerThread.start(); 1860 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1861 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1862 1863 File dataDir = Environment.getDataDirectory(); 1864 mAppDataDir = new File(dataDir, "data"); 1865 mAppInstallDir = new File(dataDir, "app"); 1866 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1867 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1868 mUserAppDataDir = new File(dataDir, "user"); 1869 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1870 1871 sUserManager = new UserManagerService(context, this, 1872 mInstallLock, mPackages); 1873 1874 // Propagate permission configuration in to package manager. 1875 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1876 = systemConfig.getPermissions(); 1877 for (int i=0; i<permConfig.size(); i++) { 1878 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1879 BasePermission bp = mSettings.mPermissions.get(perm.name); 1880 if (bp == null) { 1881 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1882 mSettings.mPermissions.put(perm.name, bp); 1883 } 1884 if (perm.gids != null) { 1885 bp.setGids(perm.gids, perm.perUser); 1886 } 1887 } 1888 1889 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1890 for (int i=0; i<libConfig.size(); i++) { 1891 mSharedLibraries.put(libConfig.keyAt(i), 1892 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1893 } 1894 1895 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1896 1897 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1898 mSdkVersion, mOnlyCore); 1899 1900 String customResolverActivity = Resources.getSystem().getString( 1901 R.string.config_customResolverActivity); 1902 if (TextUtils.isEmpty(customResolverActivity)) { 1903 customResolverActivity = null; 1904 } else { 1905 mCustomResolverComponentName = ComponentName.unflattenFromString( 1906 customResolverActivity); 1907 } 1908 1909 long startTime = SystemClock.uptimeMillis(); 1910 1911 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1912 startTime); 1913 1914 // Set flag to monitor and not change apk file paths when 1915 // scanning install directories. 1916 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1917 1918 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1919 1920 /** 1921 * Add everything in the in the boot class path to the 1922 * list of process files because dexopt will have been run 1923 * if necessary during zygote startup. 1924 */ 1925 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1926 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1927 1928 if (bootClassPath != null) { 1929 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1930 for (String element : bootClassPathElements) { 1931 alreadyDexOpted.add(element); 1932 } 1933 } else { 1934 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1935 } 1936 1937 if (systemServerClassPath != null) { 1938 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1939 for (String element : systemServerClassPathElements) { 1940 alreadyDexOpted.add(element); 1941 } 1942 } else { 1943 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1944 } 1945 1946 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1947 final String[] dexCodeInstructionSets = 1948 getDexCodeInstructionSets( 1949 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1950 1951 /** 1952 * Ensure all external libraries have had dexopt run on them. 1953 */ 1954 if (mSharedLibraries.size() > 0) { 1955 // NOTE: For now, we're compiling these system "shared libraries" 1956 // (and framework jars) into all available architectures. It's possible 1957 // to compile them only when we come across an app that uses them (there's 1958 // already logic for that in scanPackageLI) but that adds some complexity. 1959 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1960 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1961 final String lib = libEntry.path; 1962 if (lib == null) { 1963 continue; 1964 } 1965 1966 try { 1967 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1968 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1969 alreadyDexOpted.add(lib); 1970 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1971 } 1972 } catch (FileNotFoundException e) { 1973 Slog.w(TAG, "Library not found: " + lib); 1974 } catch (IOException e) { 1975 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1976 + e.getMessage()); 1977 } 1978 } 1979 } 1980 } 1981 1982 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1983 1984 // Gross hack for now: we know this file doesn't contain any 1985 // code, so don't dexopt it to avoid the resulting log spew. 1986 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1987 1988 // Gross hack for now: we know this file is only part of 1989 // the boot class path for art, so don't dexopt it to 1990 // avoid the resulting log spew. 1991 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1992 1993 /** 1994 * There are a number of commands implemented in Java, which 1995 * we currently need to do the dexopt on so that they can be 1996 * run from a non-root shell. 1997 */ 1998 String[] frameworkFiles = frameworkDir.list(); 1999 if (frameworkFiles != null) { 2000 // TODO: We could compile these only for the most preferred ABI. We should 2001 // first double check that the dex files for these commands are not referenced 2002 // by other system apps. 2003 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2004 for (int i=0; i<frameworkFiles.length; i++) { 2005 File libPath = new File(frameworkDir, frameworkFiles[i]); 2006 String path = libPath.getPath(); 2007 // Skip the file if we already did it. 2008 if (alreadyDexOpted.contains(path)) { 2009 continue; 2010 } 2011 // Skip the file if it is not a type we want to dexopt. 2012 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2013 continue; 2014 } 2015 try { 2016 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2017 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2018 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2019 } 2020 } catch (FileNotFoundException e) { 2021 Slog.w(TAG, "Jar not found: " + path); 2022 } catch (IOException e) { 2023 Slog.w(TAG, "Exception reading jar: " + path, e); 2024 } 2025 } 2026 } 2027 } 2028 2029 // Collect vendor overlay packages. 2030 // (Do this before scanning any apps.) 2031 // For security and version matching reason, only consider 2032 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2033 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2034 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2035 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2036 2037 // Find base frameworks (resource packages without code). 2038 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2039 | PackageParser.PARSE_IS_SYSTEM_DIR 2040 | PackageParser.PARSE_IS_PRIVILEGED, 2041 scanFlags | SCAN_NO_DEX, 0); 2042 2043 // Collected privileged system packages. 2044 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2045 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2046 | PackageParser.PARSE_IS_SYSTEM_DIR 2047 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2048 2049 // Collect ordinary system packages. 2050 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2051 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2052 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2053 2054 // Collect all vendor packages. 2055 File vendorAppDir = new File("/vendor/app"); 2056 try { 2057 vendorAppDir = vendorAppDir.getCanonicalFile(); 2058 } catch (IOException e) { 2059 // failed to look up canonical path, continue with original one 2060 } 2061 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2062 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2063 2064 // Collect all OEM packages. 2065 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2066 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2067 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2068 2069 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2070 mInstaller.moveFiles(); 2071 2072 // Prune any system packages that no longer exist. 2073 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2074 if (!mOnlyCore) { 2075 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2076 while (psit.hasNext()) { 2077 PackageSetting ps = psit.next(); 2078 2079 /* 2080 * If this is not a system app, it can't be a 2081 * disable system app. 2082 */ 2083 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2084 continue; 2085 } 2086 2087 /* 2088 * If the package is scanned, it's not erased. 2089 */ 2090 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2091 if (scannedPkg != null) { 2092 /* 2093 * If the system app is both scanned and in the 2094 * disabled packages list, then it must have been 2095 * added via OTA. Remove it from the currently 2096 * scanned package so the previously user-installed 2097 * application can be scanned. 2098 */ 2099 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2100 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2101 + ps.name + "; removing system app. Last known codePath=" 2102 + ps.codePathString + ", installStatus=" + ps.installStatus 2103 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2104 + scannedPkg.mVersionCode); 2105 removePackageLI(ps, true); 2106 mExpectingBetter.put(ps.name, ps.codePath); 2107 } 2108 2109 continue; 2110 } 2111 2112 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2113 psit.remove(); 2114 logCriticalInfo(Log.WARN, "System package " + ps.name 2115 + " no longer exists; wiping its data"); 2116 removeDataDirsLI(null, ps.name); 2117 } else { 2118 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2119 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2120 possiblyDeletedUpdatedSystemApps.add(ps.name); 2121 } 2122 } 2123 } 2124 } 2125 2126 //look for any incomplete package installations 2127 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2128 //clean up list 2129 for(int i = 0; i < deletePkgsList.size(); i++) { 2130 //clean up here 2131 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2132 } 2133 //delete tmp files 2134 deleteTempPackageFiles(); 2135 2136 // Remove any shared userIDs that have no associated packages 2137 mSettings.pruneSharedUsersLPw(); 2138 2139 if (!mOnlyCore) { 2140 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2141 SystemClock.uptimeMillis()); 2142 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2143 2144 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2145 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2146 2147 /** 2148 * Remove disable package settings for any updated system 2149 * apps that were removed via an OTA. If they're not a 2150 * previously-updated app, remove them completely. 2151 * Otherwise, just revoke their system-level permissions. 2152 */ 2153 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2154 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2155 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2156 2157 String msg; 2158 if (deletedPkg == null) { 2159 msg = "Updated system package " + deletedAppName 2160 + " no longer exists; wiping its data"; 2161 removeDataDirsLI(null, deletedAppName); 2162 } else { 2163 msg = "Updated system app + " + deletedAppName 2164 + " no longer present; removing system privileges for " 2165 + deletedAppName; 2166 2167 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2168 2169 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2170 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2171 } 2172 logCriticalInfo(Log.WARN, msg); 2173 } 2174 2175 /** 2176 * Make sure all system apps that we expected to appear on 2177 * the userdata partition actually showed up. If they never 2178 * appeared, crawl back and revive the system version. 2179 */ 2180 for (int i = 0; i < mExpectingBetter.size(); i++) { 2181 final String packageName = mExpectingBetter.keyAt(i); 2182 if (!mPackages.containsKey(packageName)) { 2183 final File scanFile = mExpectingBetter.valueAt(i); 2184 2185 logCriticalInfo(Log.WARN, "Expected better " + packageName 2186 + " but never showed up; reverting to system"); 2187 2188 final int reparseFlags; 2189 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2190 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2191 | PackageParser.PARSE_IS_SYSTEM_DIR 2192 | PackageParser.PARSE_IS_PRIVILEGED; 2193 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2194 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2195 | PackageParser.PARSE_IS_SYSTEM_DIR; 2196 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2197 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2198 | PackageParser.PARSE_IS_SYSTEM_DIR; 2199 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2200 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2201 | PackageParser.PARSE_IS_SYSTEM_DIR; 2202 } else { 2203 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2204 continue; 2205 } 2206 2207 mSettings.enableSystemPackageLPw(packageName); 2208 2209 try { 2210 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2211 } catch (PackageManagerException e) { 2212 Slog.e(TAG, "Failed to parse original system package: " 2213 + e.getMessage()); 2214 } 2215 } 2216 } 2217 } 2218 mExpectingBetter.clear(); 2219 2220 // Now that we know all of the shared libraries, update all clients to have 2221 // the correct library paths. 2222 updateAllSharedLibrariesLPw(); 2223 2224 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2225 // NOTE: We ignore potential failures here during a system scan (like 2226 // the rest of the commands above) because there's precious little we 2227 // can do about it. A settings error is reported, though. 2228 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2229 false /* force dexopt */, false /* defer dexopt */); 2230 } 2231 2232 // Now that we know all the packages we are keeping, 2233 // read and update their last usage times. 2234 mPackageUsage.readLP(); 2235 2236 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2237 SystemClock.uptimeMillis()); 2238 Slog.i(TAG, "Time to scan packages: " 2239 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2240 + " seconds"); 2241 2242 // If the platform SDK has changed since the last time we booted, 2243 // we need to re-grant app permission to catch any new ones that 2244 // appear. This is really a hack, and means that apps can in some 2245 // cases get permissions that the user didn't initially explicitly 2246 // allow... it would be nice to have some better way to handle 2247 // this situation. 2248 final VersionInfo ver = mSettings.getInternalVersion(); 2249 2250 int updateFlags = UPDATE_PERMISSIONS_ALL; 2251 if (ver.sdkVersion != mSdkVersion) { 2252 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2253 + mSdkVersion + "; regranting permissions for internal storage"); 2254 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2255 } 2256 updatePermissionsLPw(null, null, updateFlags); 2257 ver.sdkVersion = mSdkVersion; 2258 2259 // If this is the first boot, and it is a normal boot, then 2260 // we need to initialize the default preferred apps. 2261 if (!mRestoredSettings && !onlyCore) { 2262 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2263 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2264 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2265 } 2266 2267 // If this is first boot after an OTA, and a normal boot, then 2268 // we need to clear code cache directories. 2269 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2270 if (mIsUpgrade && !onlyCore) { 2271 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2272 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2273 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2274 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2275 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2276 } 2277 } 2278 ver.fingerprint = Build.FINGERPRINT; 2279 } 2280 2281 checkDefaultBrowser(); 2282 2283 // All the changes are done during package scanning. 2284 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2285 2286 // can downgrade to reader 2287 mSettings.writeLPr(); 2288 2289 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2290 SystemClock.uptimeMillis()); 2291 2292 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2293 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2294 2295 mInstallerService = new PackageInstallerService(context, this); 2296 2297 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2298 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2299 mIntentFilterVerifierComponent); 2300 2301 } // synchronized (mPackages) 2302 } // synchronized (mInstallLock) 2303 2304 // Now after opening every single application zip, make sure they 2305 // are all flushed. Not really needed, but keeps things nice and 2306 // tidy. 2307 Runtime.getRuntime().gc(); 2308 2309 // Expose private service for system components to use. 2310 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2311 } 2312 2313 @Override 2314 public boolean isFirstBoot() { 2315 return !mRestoredSettings; 2316 } 2317 2318 @Override 2319 public boolean isOnlyCoreApps() { 2320 return mOnlyCore; 2321 } 2322 2323 @Override 2324 public boolean isUpgrade() { 2325 return mIsUpgrade; 2326 } 2327 2328 private String getRequiredVerifierLPr() { 2329 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2330 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2331 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2332 2333 String requiredVerifier = null; 2334 2335 final int N = receivers.size(); 2336 for (int i = 0; i < N; i++) { 2337 final ResolveInfo info = receivers.get(i); 2338 2339 if (info.activityInfo == null) { 2340 continue; 2341 } 2342 2343 final String packageName = info.activityInfo.packageName; 2344 2345 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2346 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2347 continue; 2348 } 2349 2350 if (requiredVerifier != null) { 2351 throw new RuntimeException("There can be only one required verifier"); 2352 } 2353 2354 requiredVerifier = packageName; 2355 } 2356 2357 return requiredVerifier; 2358 } 2359 2360 private String getRequiredInstallerLPr() { 2361 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2362 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2363 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2364 2365 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2366 PACKAGE_MIME_TYPE, 0, 0); 2367 2368 String requiredInstaller = null; 2369 2370 final int N = installers.size(); 2371 for (int i = 0; i < N; i++) { 2372 final ResolveInfo info = installers.get(i); 2373 final String packageName = info.activityInfo.packageName; 2374 2375 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2376 continue; 2377 } 2378 2379 if (requiredInstaller != null) { 2380 throw new RuntimeException("There must be one required installer"); 2381 } 2382 2383 requiredInstaller = packageName; 2384 } 2385 2386 if (requiredInstaller == null) { 2387 throw new RuntimeException("There must be one required installer"); 2388 } 2389 2390 return requiredInstaller; 2391 } 2392 2393 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2394 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2395 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2396 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2397 2398 ComponentName verifierComponentName = null; 2399 2400 int priority = -1000; 2401 final int N = receivers.size(); 2402 for (int i = 0; i < N; i++) { 2403 final ResolveInfo info = receivers.get(i); 2404 2405 if (info.activityInfo == null) { 2406 continue; 2407 } 2408 2409 final String packageName = info.activityInfo.packageName; 2410 2411 final PackageSetting ps = mSettings.mPackages.get(packageName); 2412 if (ps == null) { 2413 continue; 2414 } 2415 2416 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2417 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2418 continue; 2419 } 2420 2421 // Select the IntentFilterVerifier with the highest priority 2422 if (priority < info.priority) { 2423 priority = info.priority; 2424 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2425 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2426 + verifierComponentName + " with priority: " + info.priority); 2427 } 2428 } 2429 2430 return verifierComponentName; 2431 } 2432 2433 private void primeDomainVerificationsLPw(int userId) { 2434 if (DEBUG_DOMAIN_VERIFICATION) { 2435 Slog.d(TAG, "Priming domain verifications in user " + userId); 2436 } 2437 2438 SystemConfig systemConfig = SystemConfig.getInstance(); 2439 ArraySet<String> packages = systemConfig.getLinkedApps(); 2440 ArraySet<String> domains = new ArraySet<String>(); 2441 2442 for (String packageName : packages) { 2443 PackageParser.Package pkg = mPackages.get(packageName); 2444 if (pkg != null) { 2445 if (!pkg.isSystemApp()) { 2446 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2447 continue; 2448 } 2449 2450 domains.clear(); 2451 for (PackageParser.Activity a : pkg.activities) { 2452 for (ActivityIntentInfo filter : a.intents) { 2453 if (hasValidDomains(filter)) { 2454 domains.addAll(filter.getHostsList()); 2455 } 2456 } 2457 } 2458 2459 if (domains.size() > 0) { 2460 if (DEBUG_DOMAIN_VERIFICATION) { 2461 Slog.v(TAG, " + " + packageName); 2462 } 2463 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2464 // state w.r.t. the formal app-linkage "no verification attempted" state; 2465 // and then 'always' in the per-user state actually used for intent resolution. 2466 final IntentFilterVerificationInfo ivi; 2467 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2468 new ArrayList<String>(domains)); 2469 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2470 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2471 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2472 } else { 2473 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2474 + "' does not handle web links"); 2475 } 2476 } else { 2477 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2478 } 2479 } 2480 2481 scheduleWritePackageRestrictionsLocked(userId); 2482 scheduleWriteSettingsLocked(); 2483 } 2484 2485 private void applyFactoryDefaultBrowserLPw(int userId) { 2486 // The default browser app's package name is stored in a string resource, 2487 // with a product-specific overlay used for vendor customization. 2488 String browserPkg = mContext.getResources().getString( 2489 com.android.internal.R.string.default_browser); 2490 if (!TextUtils.isEmpty(browserPkg)) { 2491 // non-empty string => required to be a known package 2492 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2493 if (ps == null) { 2494 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2495 browserPkg = null; 2496 } else { 2497 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2498 } 2499 } 2500 2501 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2502 // default. If there's more than one, just leave everything alone. 2503 if (browserPkg == null) { 2504 calculateDefaultBrowserLPw(userId); 2505 } 2506 } 2507 2508 private void calculateDefaultBrowserLPw(int userId) { 2509 List<String> allBrowsers = resolveAllBrowserApps(userId); 2510 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2511 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2512 } 2513 2514 private List<String> resolveAllBrowserApps(int userId) { 2515 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2516 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2517 PackageManager.MATCH_ALL, userId); 2518 2519 final int count = list.size(); 2520 List<String> result = new ArrayList<String>(count); 2521 for (int i=0; i<count; i++) { 2522 ResolveInfo info = list.get(i); 2523 if (info.activityInfo == null 2524 || !info.handleAllWebDataURI 2525 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2526 || result.contains(info.activityInfo.packageName)) { 2527 continue; 2528 } 2529 result.add(info.activityInfo.packageName); 2530 } 2531 2532 return result; 2533 } 2534 2535 private boolean packageIsBrowser(String packageName, int userId) { 2536 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2537 PackageManager.MATCH_ALL, userId); 2538 final int N = list.size(); 2539 for (int i = 0; i < N; i++) { 2540 ResolveInfo info = list.get(i); 2541 if (packageName.equals(info.activityInfo.packageName)) { 2542 return true; 2543 } 2544 } 2545 return false; 2546 } 2547 2548 private void checkDefaultBrowser() { 2549 final int myUserId = UserHandle.myUserId(); 2550 final String packageName = getDefaultBrowserPackageName(myUserId); 2551 if (packageName != null) { 2552 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2553 if (info == null) { 2554 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2555 synchronized (mPackages) { 2556 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2557 } 2558 } 2559 } 2560 } 2561 2562 @Override 2563 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2564 throws RemoteException { 2565 try { 2566 return super.onTransact(code, data, reply, flags); 2567 } catch (RuntimeException e) { 2568 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2569 Slog.wtf(TAG, "Package Manager Crash", e); 2570 } 2571 throw e; 2572 } 2573 } 2574 2575 void cleanupInstallFailedPackage(PackageSetting ps) { 2576 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2577 2578 removeDataDirsLI(ps.volumeUuid, ps.name); 2579 if (ps.codePath != null) { 2580 if (ps.codePath.isDirectory()) { 2581 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2582 } else { 2583 ps.codePath.delete(); 2584 } 2585 } 2586 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2587 if (ps.resourcePath.isDirectory()) { 2588 FileUtils.deleteContents(ps.resourcePath); 2589 } 2590 ps.resourcePath.delete(); 2591 } 2592 mSettings.removePackageLPw(ps.name); 2593 } 2594 2595 static int[] appendInts(int[] cur, int[] add) { 2596 if (add == null) return cur; 2597 if (cur == null) return add; 2598 final int N = add.length; 2599 for (int i=0; i<N; i++) { 2600 cur = appendInt(cur, add[i]); 2601 } 2602 return cur; 2603 } 2604 2605 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2606 if (!sUserManager.exists(userId)) return null; 2607 final PackageSetting ps = (PackageSetting) p.mExtras; 2608 if (ps == null) { 2609 return null; 2610 } 2611 2612 final PermissionsState permissionsState = ps.getPermissionsState(); 2613 2614 final int[] gids = permissionsState.computeGids(userId); 2615 final Set<String> permissions = permissionsState.getPermissions(userId); 2616 final PackageUserState state = ps.readUserState(userId); 2617 2618 return PackageParser.generatePackageInfo(p, gids, flags, 2619 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2620 } 2621 2622 @Override 2623 public boolean isPackageFrozen(String packageName) { 2624 synchronized (mPackages) { 2625 final PackageSetting ps = mSettings.mPackages.get(packageName); 2626 if (ps != null) { 2627 return ps.frozen; 2628 } 2629 } 2630 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2631 return true; 2632 } 2633 2634 @Override 2635 public boolean isPackageAvailable(String packageName, int userId) { 2636 if (!sUserManager.exists(userId)) return false; 2637 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2638 synchronized (mPackages) { 2639 PackageParser.Package p = mPackages.get(packageName); 2640 if (p != null) { 2641 final PackageSetting ps = (PackageSetting) p.mExtras; 2642 if (ps != null) { 2643 final PackageUserState state = ps.readUserState(userId); 2644 if (state != null) { 2645 return PackageParser.isAvailable(state); 2646 } 2647 } 2648 } 2649 } 2650 return false; 2651 } 2652 2653 @Override 2654 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2655 if (!sUserManager.exists(userId)) return null; 2656 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2657 // reader 2658 synchronized (mPackages) { 2659 PackageParser.Package p = mPackages.get(packageName); 2660 if (DEBUG_PACKAGE_INFO) 2661 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2662 if (p != null) { 2663 return generatePackageInfo(p, flags, userId); 2664 } 2665 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2666 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2667 } 2668 } 2669 return null; 2670 } 2671 2672 @Override 2673 public String[] currentToCanonicalPackageNames(String[] names) { 2674 String[] out = new String[names.length]; 2675 // reader 2676 synchronized (mPackages) { 2677 for (int i=names.length-1; i>=0; i--) { 2678 PackageSetting ps = mSettings.mPackages.get(names[i]); 2679 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2680 } 2681 } 2682 return out; 2683 } 2684 2685 @Override 2686 public String[] canonicalToCurrentPackageNames(String[] names) { 2687 String[] out = new String[names.length]; 2688 // reader 2689 synchronized (mPackages) { 2690 for (int i=names.length-1; i>=0; i--) { 2691 String cur = mSettings.mRenamedPackages.get(names[i]); 2692 out[i] = cur != null ? cur : names[i]; 2693 } 2694 } 2695 return out; 2696 } 2697 2698 @Override 2699 public int getPackageUid(String packageName, int userId) { 2700 if (!sUserManager.exists(userId)) return -1; 2701 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2702 2703 // reader 2704 synchronized (mPackages) { 2705 PackageParser.Package p = mPackages.get(packageName); 2706 if(p != null) { 2707 return UserHandle.getUid(userId, p.applicationInfo.uid); 2708 } 2709 PackageSetting ps = mSettings.mPackages.get(packageName); 2710 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2711 return -1; 2712 } 2713 p = ps.pkg; 2714 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2715 } 2716 } 2717 2718 @Override 2719 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2720 if (!sUserManager.exists(userId)) { 2721 return null; 2722 } 2723 2724 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2725 "getPackageGids"); 2726 2727 // reader 2728 synchronized (mPackages) { 2729 PackageParser.Package p = mPackages.get(packageName); 2730 if (DEBUG_PACKAGE_INFO) { 2731 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2732 } 2733 if (p != null) { 2734 PackageSetting ps = (PackageSetting) p.mExtras; 2735 return ps.getPermissionsState().computeGids(userId); 2736 } 2737 } 2738 2739 return null; 2740 } 2741 2742 static PermissionInfo generatePermissionInfo( 2743 BasePermission bp, int flags) { 2744 if (bp.perm != null) { 2745 return PackageParser.generatePermissionInfo(bp.perm, flags); 2746 } 2747 PermissionInfo pi = new PermissionInfo(); 2748 pi.name = bp.name; 2749 pi.packageName = bp.sourcePackage; 2750 pi.nonLocalizedLabel = bp.name; 2751 pi.protectionLevel = bp.protectionLevel; 2752 return pi; 2753 } 2754 2755 @Override 2756 public PermissionInfo getPermissionInfo(String name, int flags) { 2757 // reader 2758 synchronized (mPackages) { 2759 final BasePermission p = mSettings.mPermissions.get(name); 2760 if (p != null) { 2761 return generatePermissionInfo(p, flags); 2762 } 2763 return null; 2764 } 2765 } 2766 2767 @Override 2768 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2769 // reader 2770 synchronized (mPackages) { 2771 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2772 for (BasePermission p : mSettings.mPermissions.values()) { 2773 if (group == null) { 2774 if (p.perm == null || p.perm.info.group == null) { 2775 out.add(generatePermissionInfo(p, flags)); 2776 } 2777 } else { 2778 if (p.perm != null && group.equals(p.perm.info.group)) { 2779 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2780 } 2781 } 2782 } 2783 2784 if (out.size() > 0) { 2785 return out; 2786 } 2787 return mPermissionGroups.containsKey(group) ? out : null; 2788 } 2789 } 2790 2791 @Override 2792 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2793 // reader 2794 synchronized (mPackages) { 2795 return PackageParser.generatePermissionGroupInfo( 2796 mPermissionGroups.get(name), flags); 2797 } 2798 } 2799 2800 @Override 2801 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2802 // reader 2803 synchronized (mPackages) { 2804 final int N = mPermissionGroups.size(); 2805 ArrayList<PermissionGroupInfo> out 2806 = new ArrayList<PermissionGroupInfo>(N); 2807 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2808 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2809 } 2810 return out; 2811 } 2812 } 2813 2814 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2815 int userId) { 2816 if (!sUserManager.exists(userId)) return null; 2817 PackageSetting ps = mSettings.mPackages.get(packageName); 2818 if (ps != null) { 2819 if (ps.pkg == null) { 2820 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2821 flags, userId); 2822 if (pInfo != null) { 2823 return pInfo.applicationInfo; 2824 } 2825 return null; 2826 } 2827 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2828 ps.readUserState(userId), userId); 2829 } 2830 return null; 2831 } 2832 2833 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2834 int userId) { 2835 if (!sUserManager.exists(userId)) return null; 2836 PackageSetting ps = mSettings.mPackages.get(packageName); 2837 if (ps != null) { 2838 PackageParser.Package pkg = ps.pkg; 2839 if (pkg == null) { 2840 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2841 return null; 2842 } 2843 // Only data remains, so we aren't worried about code paths 2844 pkg = new PackageParser.Package(packageName); 2845 pkg.applicationInfo.packageName = packageName; 2846 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2847 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2848 pkg.applicationInfo.dataDir = Environment 2849 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2850 .getAbsolutePath(); 2851 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2852 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2853 } 2854 return generatePackageInfo(pkg, flags, userId); 2855 } 2856 return null; 2857 } 2858 2859 @Override 2860 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2861 if (!sUserManager.exists(userId)) return null; 2862 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2863 // writer 2864 synchronized (mPackages) { 2865 PackageParser.Package p = mPackages.get(packageName); 2866 if (DEBUG_PACKAGE_INFO) Log.v( 2867 TAG, "getApplicationInfo " + packageName 2868 + ": " + p); 2869 if (p != null) { 2870 PackageSetting ps = mSettings.mPackages.get(packageName); 2871 if (ps == null) return null; 2872 // Note: isEnabledLP() does not apply here - always return info 2873 return PackageParser.generateApplicationInfo( 2874 p, flags, ps.readUserState(userId), userId); 2875 } 2876 if ("android".equals(packageName)||"system".equals(packageName)) { 2877 return mAndroidApplication; 2878 } 2879 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2880 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2881 } 2882 } 2883 return null; 2884 } 2885 2886 @Override 2887 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2888 final IPackageDataObserver observer) { 2889 mContext.enforceCallingOrSelfPermission( 2890 android.Manifest.permission.CLEAR_APP_CACHE, null); 2891 // Queue up an async operation since clearing cache may take a little while. 2892 mHandler.post(new Runnable() { 2893 public void run() { 2894 mHandler.removeCallbacks(this); 2895 int retCode = -1; 2896 synchronized (mInstallLock) { 2897 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2898 if (retCode < 0) { 2899 Slog.w(TAG, "Couldn't clear application caches"); 2900 } 2901 } 2902 if (observer != null) { 2903 try { 2904 observer.onRemoveCompleted(null, (retCode >= 0)); 2905 } catch (RemoteException e) { 2906 Slog.w(TAG, "RemoveException when invoking call back"); 2907 } 2908 } 2909 } 2910 }); 2911 } 2912 2913 @Override 2914 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2915 final IntentSender pi) { 2916 mContext.enforceCallingOrSelfPermission( 2917 android.Manifest.permission.CLEAR_APP_CACHE, null); 2918 // Queue up an async operation since clearing cache may take a little while. 2919 mHandler.post(new Runnable() { 2920 public void run() { 2921 mHandler.removeCallbacks(this); 2922 int retCode = -1; 2923 synchronized (mInstallLock) { 2924 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2925 if (retCode < 0) { 2926 Slog.w(TAG, "Couldn't clear application caches"); 2927 } 2928 } 2929 if(pi != null) { 2930 try { 2931 // Callback via pending intent 2932 int code = (retCode >= 0) ? 1 : 0; 2933 pi.sendIntent(null, code, null, 2934 null, null); 2935 } catch (SendIntentException e1) { 2936 Slog.i(TAG, "Failed to send pending intent"); 2937 } 2938 } 2939 } 2940 }); 2941 } 2942 2943 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2944 synchronized (mInstallLock) { 2945 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2946 throw new IOException("Failed to free enough space"); 2947 } 2948 } 2949 } 2950 2951 @Override 2952 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2953 if (!sUserManager.exists(userId)) return null; 2954 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2955 synchronized (mPackages) { 2956 PackageParser.Activity a = mActivities.mActivities.get(component); 2957 2958 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2959 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2960 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2961 if (ps == null) return null; 2962 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2963 userId); 2964 } 2965 if (mResolveComponentName.equals(component)) { 2966 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2967 new PackageUserState(), userId); 2968 } 2969 } 2970 return null; 2971 } 2972 2973 @Override 2974 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2975 String resolvedType) { 2976 synchronized (mPackages) { 2977 if (component.equals(mResolveComponentName)) { 2978 // The resolver supports EVERYTHING! 2979 return true; 2980 } 2981 PackageParser.Activity a = mActivities.mActivities.get(component); 2982 if (a == null) { 2983 return false; 2984 } 2985 for (int i=0; i<a.intents.size(); i++) { 2986 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2987 intent.getData(), intent.getCategories(), TAG) >= 0) { 2988 return true; 2989 } 2990 } 2991 return false; 2992 } 2993 } 2994 2995 @Override 2996 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2997 if (!sUserManager.exists(userId)) return null; 2998 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2999 synchronized (mPackages) { 3000 PackageParser.Activity a = mReceivers.mActivities.get(component); 3001 if (DEBUG_PACKAGE_INFO) Log.v( 3002 TAG, "getReceiverInfo " + component + ": " + a); 3003 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3004 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3005 if (ps == null) return null; 3006 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3007 userId); 3008 } 3009 } 3010 return null; 3011 } 3012 3013 @Override 3014 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3015 if (!sUserManager.exists(userId)) return null; 3016 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3017 synchronized (mPackages) { 3018 PackageParser.Service s = mServices.mServices.get(component); 3019 if (DEBUG_PACKAGE_INFO) Log.v( 3020 TAG, "getServiceInfo " + component + ": " + s); 3021 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3022 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3023 if (ps == null) return null; 3024 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3025 userId); 3026 } 3027 } 3028 return null; 3029 } 3030 3031 @Override 3032 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3033 if (!sUserManager.exists(userId)) return null; 3034 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3035 synchronized (mPackages) { 3036 PackageParser.Provider p = mProviders.mProviders.get(component); 3037 if (DEBUG_PACKAGE_INFO) Log.v( 3038 TAG, "getProviderInfo " + component + ": " + p); 3039 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3040 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3041 if (ps == null) return null; 3042 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3043 userId); 3044 } 3045 } 3046 return null; 3047 } 3048 3049 @Override 3050 public String[] getSystemSharedLibraryNames() { 3051 Set<String> libSet; 3052 synchronized (mPackages) { 3053 libSet = mSharedLibraries.keySet(); 3054 int size = libSet.size(); 3055 if (size > 0) { 3056 String[] libs = new String[size]; 3057 libSet.toArray(libs); 3058 return libs; 3059 } 3060 } 3061 return null; 3062 } 3063 3064 /** 3065 * @hide 3066 */ 3067 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3068 synchronized (mPackages) { 3069 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3070 if (lib != null && lib.apk != null) { 3071 return mPackages.get(lib.apk); 3072 } 3073 } 3074 return null; 3075 } 3076 3077 @Override 3078 public FeatureInfo[] getSystemAvailableFeatures() { 3079 Collection<FeatureInfo> featSet; 3080 synchronized (mPackages) { 3081 featSet = mAvailableFeatures.values(); 3082 int size = featSet.size(); 3083 if (size > 0) { 3084 FeatureInfo[] features = new FeatureInfo[size+1]; 3085 featSet.toArray(features); 3086 FeatureInfo fi = new FeatureInfo(); 3087 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3088 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3089 features[size] = fi; 3090 return features; 3091 } 3092 } 3093 return null; 3094 } 3095 3096 @Override 3097 public boolean hasSystemFeature(String name) { 3098 synchronized (mPackages) { 3099 return mAvailableFeatures.containsKey(name); 3100 } 3101 } 3102 3103 private void checkValidCaller(int uid, int userId) { 3104 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3105 return; 3106 3107 throw new SecurityException("Caller uid=" + uid 3108 + " is not privileged to communicate with user=" + userId); 3109 } 3110 3111 @Override 3112 public int checkPermission(String permName, String pkgName, int userId) { 3113 if (!sUserManager.exists(userId)) { 3114 return PackageManager.PERMISSION_DENIED; 3115 } 3116 3117 synchronized (mPackages) { 3118 final PackageParser.Package p = mPackages.get(pkgName); 3119 if (p != null && p.mExtras != null) { 3120 final PackageSetting ps = (PackageSetting) p.mExtras; 3121 final PermissionsState permissionsState = ps.getPermissionsState(); 3122 if (permissionsState.hasPermission(permName, userId)) { 3123 return PackageManager.PERMISSION_GRANTED; 3124 } 3125 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3126 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3127 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3128 return PackageManager.PERMISSION_GRANTED; 3129 } 3130 } 3131 } 3132 3133 return PackageManager.PERMISSION_DENIED; 3134 } 3135 3136 @Override 3137 public int checkUidPermission(String permName, int uid) { 3138 final int userId = UserHandle.getUserId(uid); 3139 3140 if (!sUserManager.exists(userId)) { 3141 return PackageManager.PERMISSION_DENIED; 3142 } 3143 3144 synchronized (mPackages) { 3145 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3146 if (obj != null) { 3147 final SettingBase ps = (SettingBase) obj; 3148 final PermissionsState permissionsState = ps.getPermissionsState(); 3149 if (permissionsState.hasPermission(permName, userId)) { 3150 return PackageManager.PERMISSION_GRANTED; 3151 } 3152 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3153 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3154 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3155 return PackageManager.PERMISSION_GRANTED; 3156 } 3157 } else { 3158 ArraySet<String> perms = mSystemPermissions.get(uid); 3159 if (perms != null) { 3160 if (perms.contains(permName)) { 3161 return PackageManager.PERMISSION_GRANTED; 3162 } 3163 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3164 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3165 return PackageManager.PERMISSION_GRANTED; 3166 } 3167 } 3168 } 3169 } 3170 3171 return PackageManager.PERMISSION_DENIED; 3172 } 3173 3174 @Override 3175 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3176 if (UserHandle.getCallingUserId() != userId) { 3177 mContext.enforceCallingPermission( 3178 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3179 "isPermissionRevokedByPolicy for user " + userId); 3180 } 3181 3182 if (checkPermission(permission, packageName, userId) 3183 == PackageManager.PERMISSION_GRANTED) { 3184 return false; 3185 } 3186 3187 final long identity = Binder.clearCallingIdentity(); 3188 try { 3189 final int flags = getPermissionFlags(permission, packageName, userId); 3190 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3191 } finally { 3192 Binder.restoreCallingIdentity(identity); 3193 } 3194 } 3195 3196 /** 3197 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3198 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3199 * @param checkShell TODO(yamasani): 3200 * @param message the message to log on security exception 3201 */ 3202 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3203 boolean checkShell, String message) { 3204 if (userId < 0) { 3205 throw new IllegalArgumentException("Invalid userId " + userId); 3206 } 3207 if (checkShell) { 3208 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3209 } 3210 if (userId == UserHandle.getUserId(callingUid)) return; 3211 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3212 if (requireFullPermission) { 3213 mContext.enforceCallingOrSelfPermission( 3214 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3215 } else { 3216 try { 3217 mContext.enforceCallingOrSelfPermission( 3218 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3219 } catch (SecurityException se) { 3220 mContext.enforceCallingOrSelfPermission( 3221 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3222 } 3223 } 3224 } 3225 } 3226 3227 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3228 if (callingUid == Process.SHELL_UID) { 3229 if (userHandle >= 0 3230 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3231 throw new SecurityException("Shell does not have permission to access user " 3232 + userHandle); 3233 } else if (userHandle < 0) { 3234 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3235 + Debug.getCallers(3)); 3236 } 3237 } 3238 } 3239 3240 private BasePermission findPermissionTreeLP(String permName) { 3241 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3242 if (permName.startsWith(bp.name) && 3243 permName.length() > bp.name.length() && 3244 permName.charAt(bp.name.length()) == '.') { 3245 return bp; 3246 } 3247 } 3248 return null; 3249 } 3250 3251 private BasePermission checkPermissionTreeLP(String permName) { 3252 if (permName != null) { 3253 BasePermission bp = findPermissionTreeLP(permName); 3254 if (bp != null) { 3255 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3256 return bp; 3257 } 3258 throw new SecurityException("Calling uid " 3259 + Binder.getCallingUid() 3260 + " is not allowed to add to permission tree " 3261 + bp.name + " owned by uid " + bp.uid); 3262 } 3263 } 3264 throw new SecurityException("No permission tree found for " + permName); 3265 } 3266 3267 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3268 if (s1 == null) { 3269 return s2 == null; 3270 } 3271 if (s2 == null) { 3272 return false; 3273 } 3274 if (s1.getClass() != s2.getClass()) { 3275 return false; 3276 } 3277 return s1.equals(s2); 3278 } 3279 3280 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3281 if (pi1.icon != pi2.icon) return false; 3282 if (pi1.logo != pi2.logo) return false; 3283 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3284 if (!compareStrings(pi1.name, pi2.name)) return false; 3285 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3286 // We'll take care of setting this one. 3287 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3288 // These are not currently stored in settings. 3289 //if (!compareStrings(pi1.group, pi2.group)) return false; 3290 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3291 //if (pi1.labelRes != pi2.labelRes) return false; 3292 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3293 return true; 3294 } 3295 3296 int permissionInfoFootprint(PermissionInfo info) { 3297 int size = info.name.length(); 3298 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3299 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3300 return size; 3301 } 3302 3303 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3304 int size = 0; 3305 for (BasePermission perm : mSettings.mPermissions.values()) { 3306 if (perm.uid == tree.uid) { 3307 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3308 } 3309 } 3310 return size; 3311 } 3312 3313 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3314 // We calculate the max size of permissions defined by this uid and throw 3315 // if that plus the size of 'info' would exceed our stated maximum. 3316 if (tree.uid != Process.SYSTEM_UID) { 3317 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3318 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3319 throw new SecurityException("Permission tree size cap exceeded"); 3320 } 3321 } 3322 } 3323 3324 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3325 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3326 throw new SecurityException("Label must be specified in permission"); 3327 } 3328 BasePermission tree = checkPermissionTreeLP(info.name); 3329 BasePermission bp = mSettings.mPermissions.get(info.name); 3330 boolean added = bp == null; 3331 boolean changed = true; 3332 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3333 if (added) { 3334 enforcePermissionCapLocked(info, tree); 3335 bp = new BasePermission(info.name, tree.sourcePackage, 3336 BasePermission.TYPE_DYNAMIC); 3337 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3338 throw new SecurityException( 3339 "Not allowed to modify non-dynamic permission " 3340 + info.name); 3341 } else { 3342 if (bp.protectionLevel == fixedLevel 3343 && bp.perm.owner.equals(tree.perm.owner) 3344 && bp.uid == tree.uid 3345 && comparePermissionInfos(bp.perm.info, info)) { 3346 changed = false; 3347 } 3348 } 3349 bp.protectionLevel = fixedLevel; 3350 info = new PermissionInfo(info); 3351 info.protectionLevel = fixedLevel; 3352 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3353 bp.perm.info.packageName = tree.perm.info.packageName; 3354 bp.uid = tree.uid; 3355 if (added) { 3356 mSettings.mPermissions.put(info.name, bp); 3357 } 3358 if (changed) { 3359 if (!async) { 3360 mSettings.writeLPr(); 3361 } else { 3362 scheduleWriteSettingsLocked(); 3363 } 3364 } 3365 return added; 3366 } 3367 3368 @Override 3369 public boolean addPermission(PermissionInfo info) { 3370 synchronized (mPackages) { 3371 return addPermissionLocked(info, false); 3372 } 3373 } 3374 3375 @Override 3376 public boolean addPermissionAsync(PermissionInfo info) { 3377 synchronized (mPackages) { 3378 return addPermissionLocked(info, true); 3379 } 3380 } 3381 3382 @Override 3383 public void removePermission(String name) { 3384 synchronized (mPackages) { 3385 checkPermissionTreeLP(name); 3386 BasePermission bp = mSettings.mPermissions.get(name); 3387 if (bp != null) { 3388 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3389 throw new SecurityException( 3390 "Not allowed to modify non-dynamic permission " 3391 + name); 3392 } 3393 mSettings.mPermissions.remove(name); 3394 mSettings.writeLPr(); 3395 } 3396 } 3397 } 3398 3399 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3400 BasePermission bp) { 3401 int index = pkg.requestedPermissions.indexOf(bp.name); 3402 if (index == -1) { 3403 throw new SecurityException("Package " + pkg.packageName 3404 + " has not requested permission " + bp.name); 3405 } 3406 if (!bp.isRuntime()) { 3407 throw new SecurityException("Permission " + bp.name 3408 + " is not a changeable permission type"); 3409 } 3410 } 3411 3412 @Override 3413 public void grantRuntimePermission(String packageName, String name, final int userId) { 3414 if (!sUserManager.exists(userId)) { 3415 Log.e(TAG, "No such user:" + userId); 3416 return; 3417 } 3418 3419 mContext.enforceCallingOrSelfPermission( 3420 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3421 "grantRuntimePermission"); 3422 3423 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3424 "grantRuntimePermission"); 3425 3426 final int uid; 3427 final SettingBase sb; 3428 3429 synchronized (mPackages) { 3430 final PackageParser.Package pkg = mPackages.get(packageName); 3431 if (pkg == null) { 3432 throw new IllegalArgumentException("Unknown package: " + packageName); 3433 } 3434 3435 final BasePermission bp = mSettings.mPermissions.get(name); 3436 if (bp == null) { 3437 throw new IllegalArgumentException("Unknown permission: " + name); 3438 } 3439 3440 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3441 3442 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3443 sb = (SettingBase) pkg.mExtras; 3444 if (sb == null) { 3445 throw new IllegalArgumentException("Unknown package: " + packageName); 3446 } 3447 3448 final PermissionsState permissionsState = sb.getPermissionsState(); 3449 3450 final int flags = permissionsState.getPermissionFlags(name, userId); 3451 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3452 throw new SecurityException("Cannot grant system fixed permission: " 3453 + name + " for package: " + packageName); 3454 } 3455 3456 final int result = permissionsState.grantRuntimePermission(bp, userId); 3457 switch (result) { 3458 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3459 return; 3460 } 3461 3462 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3463 mHandler.post(new Runnable() { 3464 @Override 3465 public void run() { 3466 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3467 } 3468 }); 3469 } break; 3470 } 3471 3472 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3473 3474 // Not critical if that is lost - app has to request again. 3475 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3476 } 3477 3478 // Only need to do this if user is initialized. Otherwise it's a new user 3479 // and there are no processes running as the user yet and there's no need 3480 // to make an expensive call to remount processes for the changed permissions. 3481 if (READ_EXTERNAL_STORAGE.equals(name) 3482 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3483 final long token = Binder.clearCallingIdentity(); 3484 try { 3485 if (sUserManager.isInitialized(userId)) { 3486 MountServiceInternal mountServiceInternal = LocalServices.getService( 3487 MountServiceInternal.class); 3488 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3489 } 3490 } finally { 3491 Binder.restoreCallingIdentity(token); 3492 } 3493 } 3494 } 3495 3496 @Override 3497 public void revokeRuntimePermission(String packageName, String name, int userId) { 3498 if (!sUserManager.exists(userId)) { 3499 Log.e(TAG, "No such user:" + userId); 3500 return; 3501 } 3502 3503 mContext.enforceCallingOrSelfPermission( 3504 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3505 "revokeRuntimePermission"); 3506 3507 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3508 "revokeRuntimePermission"); 3509 3510 final SettingBase sb; 3511 3512 synchronized (mPackages) { 3513 final PackageParser.Package pkg = mPackages.get(packageName); 3514 if (pkg == null) { 3515 throw new IllegalArgumentException("Unknown package: " + packageName); 3516 } 3517 3518 final BasePermission bp = mSettings.mPermissions.get(name); 3519 if (bp == null) { 3520 throw new IllegalArgumentException("Unknown permission: " + name); 3521 } 3522 3523 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3524 3525 sb = (SettingBase) pkg.mExtras; 3526 if (sb == null) { 3527 throw new IllegalArgumentException("Unknown package: " + packageName); 3528 } 3529 3530 final PermissionsState permissionsState = sb.getPermissionsState(); 3531 3532 final int flags = permissionsState.getPermissionFlags(name, userId); 3533 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3534 throw new SecurityException("Cannot revoke system fixed permission: " 3535 + name + " for package: " + packageName); 3536 } 3537 3538 if (permissionsState.revokeRuntimePermission(bp, userId) == 3539 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3540 return; 3541 } 3542 3543 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3544 3545 // Critical, after this call app should never have the permission. 3546 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3547 } 3548 3549 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3550 } 3551 3552 @Override 3553 public void resetRuntimePermissions() { 3554 mContext.enforceCallingOrSelfPermission( 3555 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3556 "revokeRuntimePermission"); 3557 3558 int callingUid = Binder.getCallingUid(); 3559 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3560 mContext.enforceCallingOrSelfPermission( 3561 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3562 "resetRuntimePermissions"); 3563 } 3564 3565 synchronized (mPackages) { 3566 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3567 for (int userId : UserManagerService.getInstance().getUserIds()) { 3568 final int packageCount = mPackages.size(); 3569 for (int i = 0; i < packageCount; i++) { 3570 PackageParser.Package pkg = mPackages.valueAt(i); 3571 if (!(pkg.mExtras instanceof PackageSetting)) { 3572 continue; 3573 } 3574 PackageSetting ps = (PackageSetting) pkg.mExtras; 3575 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3576 } 3577 } 3578 } 3579 } 3580 3581 @Override 3582 public int getPermissionFlags(String name, String packageName, int userId) { 3583 if (!sUserManager.exists(userId)) { 3584 return 0; 3585 } 3586 3587 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3588 3589 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3590 "getPermissionFlags"); 3591 3592 synchronized (mPackages) { 3593 final PackageParser.Package pkg = mPackages.get(packageName); 3594 if (pkg == null) { 3595 throw new IllegalArgumentException("Unknown package: " + packageName); 3596 } 3597 3598 final BasePermission bp = mSettings.mPermissions.get(name); 3599 if (bp == null) { 3600 throw new IllegalArgumentException("Unknown permission: " + name); 3601 } 3602 3603 SettingBase sb = (SettingBase) pkg.mExtras; 3604 if (sb == null) { 3605 throw new IllegalArgumentException("Unknown package: " + packageName); 3606 } 3607 3608 PermissionsState permissionsState = sb.getPermissionsState(); 3609 return permissionsState.getPermissionFlags(name, userId); 3610 } 3611 } 3612 3613 @Override 3614 public void updatePermissionFlags(String name, String packageName, int flagMask, 3615 int flagValues, int userId) { 3616 if (!sUserManager.exists(userId)) { 3617 return; 3618 } 3619 3620 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3621 3622 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3623 "updatePermissionFlags"); 3624 3625 // Only the system can change these flags and nothing else. 3626 if (getCallingUid() != Process.SYSTEM_UID) { 3627 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3628 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3629 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3630 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3631 } 3632 3633 synchronized (mPackages) { 3634 final PackageParser.Package pkg = mPackages.get(packageName); 3635 if (pkg == null) { 3636 throw new IllegalArgumentException("Unknown package: " + packageName); 3637 } 3638 3639 final BasePermission bp = mSettings.mPermissions.get(name); 3640 if (bp == null) { 3641 throw new IllegalArgumentException("Unknown permission: " + name); 3642 } 3643 3644 SettingBase sb = (SettingBase) pkg.mExtras; 3645 if (sb == null) { 3646 throw new IllegalArgumentException("Unknown package: " + packageName); 3647 } 3648 3649 PermissionsState permissionsState = sb.getPermissionsState(); 3650 3651 // Only the package manager can change flags for system component permissions. 3652 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3653 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3654 return; 3655 } 3656 3657 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3658 3659 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3660 // Install and runtime permissions are stored in different places, 3661 // so figure out what permission changed and persist the change. 3662 if (permissionsState.getInstallPermissionState(name) != null) { 3663 scheduleWriteSettingsLocked(); 3664 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3665 || hadState) { 3666 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3667 } 3668 } 3669 } 3670 } 3671 3672 /** 3673 * Update the permission flags for all packages and runtime permissions of a user in order 3674 * to allow device or profile owner to remove POLICY_FIXED. 3675 */ 3676 @Override 3677 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3678 if (!sUserManager.exists(userId)) { 3679 return; 3680 } 3681 3682 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3683 3684 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3685 "updatePermissionFlagsForAllApps"); 3686 3687 // Only the system can change system fixed flags. 3688 if (getCallingUid() != Process.SYSTEM_UID) { 3689 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3690 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3691 } 3692 3693 synchronized (mPackages) { 3694 boolean changed = false; 3695 final int packageCount = mPackages.size(); 3696 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3697 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3698 SettingBase sb = (SettingBase) pkg.mExtras; 3699 if (sb == null) { 3700 continue; 3701 } 3702 PermissionsState permissionsState = sb.getPermissionsState(); 3703 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3704 userId, flagMask, flagValues); 3705 } 3706 if (changed) { 3707 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3708 } 3709 } 3710 } 3711 3712 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3713 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3714 != PackageManager.PERMISSION_GRANTED 3715 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3716 != PackageManager.PERMISSION_GRANTED) { 3717 throw new SecurityException(message + " requires " 3718 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3719 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3720 } 3721 } 3722 3723 @Override 3724 public boolean shouldShowRequestPermissionRationale(String permissionName, 3725 String packageName, int userId) { 3726 if (UserHandle.getCallingUserId() != userId) { 3727 mContext.enforceCallingPermission( 3728 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3729 "canShowRequestPermissionRationale for user " + userId); 3730 } 3731 3732 final int uid = getPackageUid(packageName, userId); 3733 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3734 return false; 3735 } 3736 3737 if (checkPermission(permissionName, packageName, userId) 3738 == PackageManager.PERMISSION_GRANTED) { 3739 return false; 3740 } 3741 3742 final int flags; 3743 3744 final long identity = Binder.clearCallingIdentity(); 3745 try { 3746 flags = getPermissionFlags(permissionName, 3747 packageName, userId); 3748 } finally { 3749 Binder.restoreCallingIdentity(identity); 3750 } 3751 3752 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3753 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3754 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3755 3756 if ((flags & fixedFlags) != 0) { 3757 return false; 3758 } 3759 3760 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3761 } 3762 3763 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3764 BasePermission bp = mSettings.mPermissions.get(permission); 3765 if (bp == null) { 3766 throw new SecurityException("Missing " + permission + " permission"); 3767 } 3768 3769 SettingBase sb = (SettingBase) pkg.mExtras; 3770 PermissionsState permissionsState = sb.getPermissionsState(); 3771 3772 if (permissionsState.grantInstallPermission(bp) != 3773 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3774 scheduleWriteSettingsLocked(); 3775 } 3776 } 3777 3778 @Override 3779 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3780 mContext.enforceCallingOrSelfPermission( 3781 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3782 "addOnPermissionsChangeListener"); 3783 3784 synchronized (mPackages) { 3785 mOnPermissionChangeListeners.addListenerLocked(listener); 3786 } 3787 } 3788 3789 @Override 3790 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3791 synchronized (mPackages) { 3792 mOnPermissionChangeListeners.removeListenerLocked(listener); 3793 } 3794 } 3795 3796 @Override 3797 public boolean isProtectedBroadcast(String actionName) { 3798 synchronized (mPackages) { 3799 return mProtectedBroadcasts.contains(actionName); 3800 } 3801 } 3802 3803 @Override 3804 public int checkSignatures(String pkg1, String pkg2) { 3805 synchronized (mPackages) { 3806 final PackageParser.Package p1 = mPackages.get(pkg1); 3807 final PackageParser.Package p2 = mPackages.get(pkg2); 3808 if (p1 == null || p1.mExtras == null 3809 || p2 == null || p2.mExtras == null) { 3810 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3811 } 3812 return compareSignatures(p1.mSignatures, p2.mSignatures); 3813 } 3814 } 3815 3816 @Override 3817 public int checkUidSignatures(int uid1, int uid2) { 3818 // Map to base uids. 3819 uid1 = UserHandle.getAppId(uid1); 3820 uid2 = UserHandle.getAppId(uid2); 3821 // reader 3822 synchronized (mPackages) { 3823 Signature[] s1; 3824 Signature[] s2; 3825 Object obj = mSettings.getUserIdLPr(uid1); 3826 if (obj != null) { 3827 if (obj instanceof SharedUserSetting) { 3828 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3829 } else if (obj instanceof PackageSetting) { 3830 s1 = ((PackageSetting)obj).signatures.mSignatures; 3831 } else { 3832 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3833 } 3834 } else { 3835 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3836 } 3837 obj = mSettings.getUserIdLPr(uid2); 3838 if (obj != null) { 3839 if (obj instanceof SharedUserSetting) { 3840 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3841 } else if (obj instanceof PackageSetting) { 3842 s2 = ((PackageSetting)obj).signatures.mSignatures; 3843 } else { 3844 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3845 } 3846 } else { 3847 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3848 } 3849 return compareSignatures(s1, s2); 3850 } 3851 } 3852 3853 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3854 final long identity = Binder.clearCallingIdentity(); 3855 try { 3856 if (sb instanceof SharedUserSetting) { 3857 SharedUserSetting sus = (SharedUserSetting) sb; 3858 final int packageCount = sus.packages.size(); 3859 for (int i = 0; i < packageCount; i++) { 3860 PackageSetting susPs = sus.packages.valueAt(i); 3861 if (userId == UserHandle.USER_ALL) { 3862 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3863 } else { 3864 final int uid = UserHandle.getUid(userId, susPs.appId); 3865 killUid(uid, reason); 3866 } 3867 } 3868 } else if (sb instanceof PackageSetting) { 3869 PackageSetting ps = (PackageSetting) sb; 3870 if (userId == UserHandle.USER_ALL) { 3871 killApplication(ps.pkg.packageName, ps.appId, reason); 3872 } else { 3873 final int uid = UserHandle.getUid(userId, ps.appId); 3874 killUid(uid, reason); 3875 } 3876 } 3877 } finally { 3878 Binder.restoreCallingIdentity(identity); 3879 } 3880 } 3881 3882 private static void killUid(int uid, String reason) { 3883 IActivityManager am = ActivityManagerNative.getDefault(); 3884 if (am != null) { 3885 try { 3886 am.killUid(uid, reason); 3887 } catch (RemoteException e) { 3888 /* ignore - same process */ 3889 } 3890 } 3891 } 3892 3893 /** 3894 * Compares two sets of signatures. Returns: 3895 * <br /> 3896 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3897 * <br /> 3898 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3899 * <br /> 3900 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3901 * <br /> 3902 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3903 * <br /> 3904 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3905 */ 3906 static int compareSignatures(Signature[] s1, Signature[] s2) { 3907 if (s1 == null) { 3908 return s2 == null 3909 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3910 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3911 } 3912 3913 if (s2 == null) { 3914 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3915 } 3916 3917 if (s1.length != s2.length) { 3918 return PackageManager.SIGNATURE_NO_MATCH; 3919 } 3920 3921 // Since both signature sets are of size 1, we can compare without HashSets. 3922 if (s1.length == 1) { 3923 return s1[0].equals(s2[0]) ? 3924 PackageManager.SIGNATURE_MATCH : 3925 PackageManager.SIGNATURE_NO_MATCH; 3926 } 3927 3928 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3929 for (Signature sig : s1) { 3930 set1.add(sig); 3931 } 3932 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3933 for (Signature sig : s2) { 3934 set2.add(sig); 3935 } 3936 // Make sure s2 contains all signatures in s1. 3937 if (set1.equals(set2)) { 3938 return PackageManager.SIGNATURE_MATCH; 3939 } 3940 return PackageManager.SIGNATURE_NO_MATCH; 3941 } 3942 3943 /** 3944 * If the database version for this type of package (internal storage or 3945 * external storage) is less than the version where package signatures 3946 * were updated, return true. 3947 */ 3948 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3949 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3950 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3951 } 3952 3953 /** 3954 * Used for backward compatibility to make sure any packages with 3955 * certificate chains get upgraded to the new style. {@code existingSigs} 3956 * will be in the old format (since they were stored on disk from before the 3957 * system upgrade) and {@code scannedSigs} will be in the newer format. 3958 */ 3959 private int compareSignaturesCompat(PackageSignatures existingSigs, 3960 PackageParser.Package scannedPkg) { 3961 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3962 return PackageManager.SIGNATURE_NO_MATCH; 3963 } 3964 3965 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3966 for (Signature sig : existingSigs.mSignatures) { 3967 existingSet.add(sig); 3968 } 3969 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3970 for (Signature sig : scannedPkg.mSignatures) { 3971 try { 3972 Signature[] chainSignatures = sig.getChainSignatures(); 3973 for (Signature chainSig : chainSignatures) { 3974 scannedCompatSet.add(chainSig); 3975 } 3976 } catch (CertificateEncodingException e) { 3977 scannedCompatSet.add(sig); 3978 } 3979 } 3980 /* 3981 * Make sure the expanded scanned set contains all signatures in the 3982 * existing one. 3983 */ 3984 if (scannedCompatSet.equals(existingSet)) { 3985 // Migrate the old signatures to the new scheme. 3986 existingSigs.assignSignatures(scannedPkg.mSignatures); 3987 // The new KeySets will be re-added later in the scanning process. 3988 synchronized (mPackages) { 3989 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3990 } 3991 return PackageManager.SIGNATURE_MATCH; 3992 } 3993 return PackageManager.SIGNATURE_NO_MATCH; 3994 } 3995 3996 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3997 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3998 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 3999 } 4000 4001 private int compareSignaturesRecover(PackageSignatures existingSigs, 4002 PackageParser.Package scannedPkg) { 4003 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4004 return PackageManager.SIGNATURE_NO_MATCH; 4005 } 4006 4007 String msg = null; 4008 try { 4009 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4010 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4011 + scannedPkg.packageName); 4012 return PackageManager.SIGNATURE_MATCH; 4013 } 4014 } catch (CertificateException e) { 4015 msg = e.getMessage(); 4016 } 4017 4018 logCriticalInfo(Log.INFO, 4019 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4020 return PackageManager.SIGNATURE_NO_MATCH; 4021 } 4022 4023 @Override 4024 public String[] getPackagesForUid(int uid) { 4025 uid = UserHandle.getAppId(uid); 4026 // reader 4027 synchronized (mPackages) { 4028 Object obj = mSettings.getUserIdLPr(uid); 4029 if (obj instanceof SharedUserSetting) { 4030 final SharedUserSetting sus = (SharedUserSetting) obj; 4031 final int N = sus.packages.size(); 4032 final String[] res = new String[N]; 4033 final Iterator<PackageSetting> it = sus.packages.iterator(); 4034 int i = 0; 4035 while (it.hasNext()) { 4036 res[i++] = it.next().name; 4037 } 4038 return res; 4039 } else if (obj instanceof PackageSetting) { 4040 final PackageSetting ps = (PackageSetting) obj; 4041 return new String[] { ps.name }; 4042 } 4043 } 4044 return null; 4045 } 4046 4047 @Override 4048 public String getNameForUid(int uid) { 4049 // reader 4050 synchronized (mPackages) { 4051 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4052 if (obj instanceof SharedUserSetting) { 4053 final SharedUserSetting sus = (SharedUserSetting) obj; 4054 return sus.name + ":" + sus.userId; 4055 } else if (obj instanceof PackageSetting) { 4056 final PackageSetting ps = (PackageSetting) obj; 4057 return ps.name; 4058 } 4059 } 4060 return null; 4061 } 4062 4063 @Override 4064 public int getUidForSharedUser(String sharedUserName) { 4065 if(sharedUserName == null) { 4066 return -1; 4067 } 4068 // reader 4069 synchronized (mPackages) { 4070 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4071 if (suid == null) { 4072 return -1; 4073 } 4074 return suid.userId; 4075 } 4076 } 4077 4078 @Override 4079 public int getFlagsForUid(int uid) { 4080 synchronized (mPackages) { 4081 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4082 if (obj instanceof SharedUserSetting) { 4083 final SharedUserSetting sus = (SharedUserSetting) obj; 4084 return sus.pkgFlags; 4085 } else if (obj instanceof PackageSetting) { 4086 final PackageSetting ps = (PackageSetting) obj; 4087 return ps.pkgFlags; 4088 } 4089 } 4090 return 0; 4091 } 4092 4093 @Override 4094 public int getPrivateFlagsForUid(int uid) { 4095 synchronized (mPackages) { 4096 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4097 if (obj instanceof SharedUserSetting) { 4098 final SharedUserSetting sus = (SharedUserSetting) obj; 4099 return sus.pkgPrivateFlags; 4100 } else if (obj instanceof PackageSetting) { 4101 final PackageSetting ps = (PackageSetting) obj; 4102 return ps.pkgPrivateFlags; 4103 } 4104 } 4105 return 0; 4106 } 4107 4108 @Override 4109 public boolean isUidPrivileged(int uid) { 4110 uid = UserHandle.getAppId(uid); 4111 // reader 4112 synchronized (mPackages) { 4113 Object obj = mSettings.getUserIdLPr(uid); 4114 if (obj instanceof SharedUserSetting) { 4115 final SharedUserSetting sus = (SharedUserSetting) obj; 4116 final Iterator<PackageSetting> it = sus.packages.iterator(); 4117 while (it.hasNext()) { 4118 if (it.next().isPrivileged()) { 4119 return true; 4120 } 4121 } 4122 } else if (obj instanceof PackageSetting) { 4123 final PackageSetting ps = (PackageSetting) obj; 4124 return ps.isPrivileged(); 4125 } 4126 } 4127 return false; 4128 } 4129 4130 @Override 4131 public String[] getAppOpPermissionPackages(String permissionName) { 4132 synchronized (mPackages) { 4133 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4134 if (pkgs == null) { 4135 return null; 4136 } 4137 return pkgs.toArray(new String[pkgs.size()]); 4138 } 4139 } 4140 4141 @Override 4142 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4143 int flags, int userId) { 4144 if (!sUserManager.exists(userId)) return null; 4145 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4146 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4147 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4148 } 4149 4150 @Override 4151 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4152 IntentFilter filter, int match, ComponentName activity) { 4153 final int userId = UserHandle.getCallingUserId(); 4154 if (DEBUG_PREFERRED) { 4155 Log.v(TAG, "setLastChosenActivity intent=" + intent 4156 + " resolvedType=" + resolvedType 4157 + " flags=" + flags 4158 + " filter=" + filter 4159 + " match=" + match 4160 + " activity=" + activity); 4161 filter.dump(new PrintStreamPrinter(System.out), " "); 4162 } 4163 intent.setComponent(null); 4164 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4165 // Find any earlier preferred or last chosen entries and nuke them 4166 findPreferredActivity(intent, resolvedType, 4167 flags, query, 0, false, true, false, userId); 4168 // Add the new activity as the last chosen for this filter 4169 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4170 "Setting last chosen"); 4171 } 4172 4173 @Override 4174 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4175 final int userId = UserHandle.getCallingUserId(); 4176 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4177 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4178 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4179 false, false, false, userId); 4180 } 4181 4182 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4183 int flags, List<ResolveInfo> query, int userId) { 4184 if (query != null) { 4185 final int N = query.size(); 4186 if (N == 1) { 4187 return query.get(0); 4188 } else if (N > 1) { 4189 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4190 // If there is more than one activity with the same priority, 4191 // then let the user decide between them. 4192 ResolveInfo r0 = query.get(0); 4193 ResolveInfo r1 = query.get(1); 4194 if (DEBUG_INTENT_MATCHING || debug) { 4195 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4196 + r1.activityInfo.name + "=" + r1.priority); 4197 } 4198 // If the first activity has a higher priority, or a different 4199 // default, then it is always desireable to pick it. 4200 if (r0.priority != r1.priority 4201 || r0.preferredOrder != r1.preferredOrder 4202 || r0.isDefault != r1.isDefault) { 4203 return query.get(0); 4204 } 4205 // If we have saved a preference for a preferred activity for 4206 // this Intent, use that. 4207 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4208 flags, query, r0.priority, true, false, debug, userId); 4209 if (ri != null) { 4210 return ri; 4211 } 4212 if (userId != 0) { 4213 ri = new ResolveInfo(mResolveInfo); 4214 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4215 ri.activityInfo.applicationInfo = new ApplicationInfo( 4216 ri.activityInfo.applicationInfo); 4217 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4218 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4219 return ri; 4220 } 4221 return mResolveInfo; 4222 } 4223 } 4224 return null; 4225 } 4226 4227 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4228 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4229 final int N = query.size(); 4230 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4231 .get(userId); 4232 // Get the list of persistent preferred activities that handle the intent 4233 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4234 List<PersistentPreferredActivity> pprefs = ppir != null 4235 ? ppir.queryIntent(intent, resolvedType, 4236 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4237 : null; 4238 if (pprefs != null && pprefs.size() > 0) { 4239 final int M = pprefs.size(); 4240 for (int i=0; i<M; i++) { 4241 final PersistentPreferredActivity ppa = pprefs.get(i); 4242 if (DEBUG_PREFERRED || debug) { 4243 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4244 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4245 + "\n component=" + ppa.mComponent); 4246 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4247 } 4248 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4249 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4250 if (DEBUG_PREFERRED || debug) { 4251 Slog.v(TAG, "Found persistent preferred activity:"); 4252 if (ai != null) { 4253 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4254 } else { 4255 Slog.v(TAG, " null"); 4256 } 4257 } 4258 if (ai == null) { 4259 // This previously registered persistent preferred activity 4260 // component is no longer known. Ignore it and do NOT remove it. 4261 continue; 4262 } 4263 for (int j=0; j<N; j++) { 4264 final ResolveInfo ri = query.get(j); 4265 if (!ri.activityInfo.applicationInfo.packageName 4266 .equals(ai.applicationInfo.packageName)) { 4267 continue; 4268 } 4269 if (!ri.activityInfo.name.equals(ai.name)) { 4270 continue; 4271 } 4272 // Found a persistent preference that can handle the intent. 4273 if (DEBUG_PREFERRED || debug) { 4274 Slog.v(TAG, "Returning persistent preferred activity: " + 4275 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4276 } 4277 return ri; 4278 } 4279 } 4280 } 4281 return null; 4282 } 4283 4284 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4285 List<ResolveInfo> query, int priority, boolean always, 4286 boolean removeMatches, boolean debug, int userId) { 4287 if (!sUserManager.exists(userId)) return null; 4288 // writer 4289 synchronized (mPackages) { 4290 if (intent.getSelector() != null) { 4291 intent = intent.getSelector(); 4292 } 4293 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4294 4295 // Try to find a matching persistent preferred activity. 4296 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4297 debug, userId); 4298 4299 // If a persistent preferred activity matched, use it. 4300 if (pri != null) { 4301 return pri; 4302 } 4303 4304 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4305 // Get the list of preferred activities that handle the intent 4306 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4307 List<PreferredActivity> prefs = pir != null 4308 ? pir.queryIntent(intent, resolvedType, 4309 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4310 : null; 4311 if (prefs != null && prefs.size() > 0) { 4312 boolean changed = false; 4313 try { 4314 // First figure out how good the original match set is. 4315 // We will only allow preferred activities that came 4316 // from the same match quality. 4317 int match = 0; 4318 4319 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4320 4321 final int N = query.size(); 4322 for (int j=0; j<N; j++) { 4323 final ResolveInfo ri = query.get(j); 4324 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4325 + ": 0x" + Integer.toHexString(match)); 4326 if (ri.match > match) { 4327 match = ri.match; 4328 } 4329 } 4330 4331 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4332 + Integer.toHexString(match)); 4333 4334 match &= IntentFilter.MATCH_CATEGORY_MASK; 4335 final int M = prefs.size(); 4336 for (int i=0; i<M; i++) { 4337 final PreferredActivity pa = prefs.get(i); 4338 if (DEBUG_PREFERRED || debug) { 4339 Slog.v(TAG, "Checking PreferredActivity ds=" 4340 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4341 + "\n component=" + pa.mPref.mComponent); 4342 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4343 } 4344 if (pa.mPref.mMatch != match) { 4345 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4346 + Integer.toHexString(pa.mPref.mMatch)); 4347 continue; 4348 } 4349 // If it's not an "always" type preferred activity and that's what we're 4350 // looking for, skip it. 4351 if (always && !pa.mPref.mAlways) { 4352 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4353 continue; 4354 } 4355 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4356 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4357 if (DEBUG_PREFERRED || debug) { 4358 Slog.v(TAG, "Found preferred activity:"); 4359 if (ai != null) { 4360 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4361 } else { 4362 Slog.v(TAG, " null"); 4363 } 4364 } 4365 if (ai == null) { 4366 // This previously registered preferred activity 4367 // component is no longer known. Most likely an update 4368 // to the app was installed and in the new version this 4369 // component no longer exists. Clean it up by removing 4370 // it from the preferred activities list, and skip it. 4371 Slog.w(TAG, "Removing dangling preferred activity: " 4372 + pa.mPref.mComponent); 4373 pir.removeFilter(pa); 4374 changed = true; 4375 continue; 4376 } 4377 for (int j=0; j<N; j++) { 4378 final ResolveInfo ri = query.get(j); 4379 if (!ri.activityInfo.applicationInfo.packageName 4380 .equals(ai.applicationInfo.packageName)) { 4381 continue; 4382 } 4383 if (!ri.activityInfo.name.equals(ai.name)) { 4384 continue; 4385 } 4386 4387 if (removeMatches) { 4388 pir.removeFilter(pa); 4389 changed = true; 4390 if (DEBUG_PREFERRED) { 4391 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4392 } 4393 break; 4394 } 4395 4396 // Okay we found a previously set preferred or last chosen app. 4397 // If the result set is different from when this 4398 // was created, we need to clear it and re-ask the 4399 // user their preference, if we're looking for an "always" type entry. 4400 if (always && !pa.mPref.sameSet(query)) { 4401 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4402 + intent + " type " + resolvedType); 4403 if (DEBUG_PREFERRED) { 4404 Slog.v(TAG, "Removing preferred activity since set changed " 4405 + pa.mPref.mComponent); 4406 } 4407 pir.removeFilter(pa); 4408 // Re-add the filter as a "last chosen" entry (!always) 4409 PreferredActivity lastChosen = new PreferredActivity( 4410 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4411 pir.addFilter(lastChosen); 4412 changed = true; 4413 return null; 4414 } 4415 4416 // Yay! Either the set matched or we're looking for the last chosen 4417 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4418 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4419 return ri; 4420 } 4421 } 4422 } finally { 4423 if (changed) { 4424 if (DEBUG_PREFERRED) { 4425 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4426 } 4427 scheduleWritePackageRestrictionsLocked(userId); 4428 } 4429 } 4430 } 4431 } 4432 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4433 return null; 4434 } 4435 4436 /* 4437 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4438 */ 4439 @Override 4440 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4441 int targetUserId) { 4442 mContext.enforceCallingOrSelfPermission( 4443 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4444 List<CrossProfileIntentFilter> matches = 4445 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4446 if (matches != null) { 4447 int size = matches.size(); 4448 for (int i = 0; i < size; i++) { 4449 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4450 } 4451 } 4452 if (hasWebURI(intent)) { 4453 // cross-profile app linking works only towards the parent. 4454 final UserInfo parent = getProfileParent(sourceUserId); 4455 synchronized(mPackages) { 4456 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4457 intent, resolvedType, 0, sourceUserId, parent.id); 4458 return xpDomainInfo != null; 4459 } 4460 } 4461 return false; 4462 } 4463 4464 private UserInfo getProfileParent(int userId) { 4465 final long identity = Binder.clearCallingIdentity(); 4466 try { 4467 return sUserManager.getProfileParent(userId); 4468 } finally { 4469 Binder.restoreCallingIdentity(identity); 4470 } 4471 } 4472 4473 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4474 String resolvedType, int userId) { 4475 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4476 if (resolver != null) { 4477 return resolver.queryIntent(intent, resolvedType, false, userId); 4478 } 4479 return null; 4480 } 4481 4482 @Override 4483 public List<ResolveInfo> queryIntentActivities(Intent intent, 4484 String resolvedType, int flags, int userId) { 4485 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4486 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4487 ComponentName comp = intent.getComponent(); 4488 if (comp == null) { 4489 if (intent.getSelector() != null) { 4490 intent = intent.getSelector(); 4491 comp = intent.getComponent(); 4492 } 4493 } 4494 4495 if (comp != null) { 4496 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4497 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4498 if (ai != null) { 4499 final ResolveInfo ri = new ResolveInfo(); 4500 ri.activityInfo = ai; 4501 list.add(ri); 4502 } 4503 return list; 4504 } 4505 4506 // reader 4507 synchronized (mPackages) { 4508 final String pkgName = intent.getPackage(); 4509 if (pkgName == null) { 4510 List<CrossProfileIntentFilter> matchingFilters = 4511 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4512 // Check for results that need to skip the current profile. 4513 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4514 resolvedType, flags, userId); 4515 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4516 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4517 result.add(xpResolveInfo); 4518 return filterIfNotPrimaryUser(result, userId); 4519 } 4520 4521 // Check for results in the current profile. 4522 List<ResolveInfo> result = mActivities.queryIntent( 4523 intent, resolvedType, flags, userId); 4524 4525 // Check for cross profile results. 4526 xpResolveInfo = queryCrossProfileIntents( 4527 matchingFilters, intent, resolvedType, flags, userId); 4528 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4529 result.add(xpResolveInfo); 4530 Collections.sort(result, mResolvePrioritySorter); 4531 } 4532 result = filterIfNotPrimaryUser(result, userId); 4533 if (hasWebURI(intent)) { 4534 CrossProfileDomainInfo xpDomainInfo = null; 4535 final UserInfo parent = getProfileParent(userId); 4536 if (parent != null) { 4537 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4538 flags, userId, parent.id); 4539 } 4540 if (xpDomainInfo != null) { 4541 if (xpResolveInfo != null) { 4542 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4543 // in the result. 4544 result.remove(xpResolveInfo); 4545 } 4546 if (result.size() == 0) { 4547 result.add(xpDomainInfo.resolveInfo); 4548 return result; 4549 } 4550 } else if (result.size() <= 1) { 4551 return result; 4552 } 4553 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4554 xpDomainInfo, userId); 4555 Collections.sort(result, mResolvePrioritySorter); 4556 } 4557 return result; 4558 } 4559 final PackageParser.Package pkg = mPackages.get(pkgName); 4560 if (pkg != null) { 4561 return filterIfNotPrimaryUser( 4562 mActivities.queryIntentForPackage( 4563 intent, resolvedType, flags, pkg.activities, userId), 4564 userId); 4565 } 4566 return new ArrayList<ResolveInfo>(); 4567 } 4568 } 4569 4570 private static class CrossProfileDomainInfo { 4571 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4572 ResolveInfo resolveInfo; 4573 /* Best domain verification status of the activities found in the other profile */ 4574 int bestDomainVerificationStatus; 4575 } 4576 4577 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4578 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4579 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4580 sourceUserId)) { 4581 return null; 4582 } 4583 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4584 resolvedType, flags, parentUserId); 4585 4586 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4587 return null; 4588 } 4589 CrossProfileDomainInfo result = null; 4590 int size = resultTargetUser.size(); 4591 for (int i = 0; i < size; i++) { 4592 ResolveInfo riTargetUser = resultTargetUser.get(i); 4593 // Intent filter verification is only for filters that specify a host. So don't return 4594 // those that handle all web uris. 4595 if (riTargetUser.handleAllWebDataURI) { 4596 continue; 4597 } 4598 String packageName = riTargetUser.activityInfo.packageName; 4599 PackageSetting ps = mSettings.mPackages.get(packageName); 4600 if (ps == null) { 4601 continue; 4602 } 4603 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4604 int status = (int)(verificationState >> 32); 4605 if (result == null) { 4606 result = new CrossProfileDomainInfo(); 4607 result.resolveInfo = 4608 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4609 result.bestDomainVerificationStatus = status; 4610 } else { 4611 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4612 result.bestDomainVerificationStatus); 4613 } 4614 } 4615 // Don't consider matches with status NEVER across profiles. 4616 if (result != null && result.bestDomainVerificationStatus 4617 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4618 return null; 4619 } 4620 return result; 4621 } 4622 4623 /** 4624 * Verification statuses are ordered from the worse to the best, except for 4625 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4626 */ 4627 private int bestDomainVerificationStatus(int status1, int status2) { 4628 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4629 return status2; 4630 } 4631 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4632 return status1; 4633 } 4634 return (int) MathUtils.max(status1, status2); 4635 } 4636 4637 private boolean isUserEnabled(int userId) { 4638 long callingId = Binder.clearCallingIdentity(); 4639 try { 4640 UserInfo userInfo = sUserManager.getUserInfo(userId); 4641 return userInfo != null && userInfo.isEnabled(); 4642 } finally { 4643 Binder.restoreCallingIdentity(callingId); 4644 } 4645 } 4646 4647 /** 4648 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4649 * 4650 * @return filtered list 4651 */ 4652 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4653 if (userId == UserHandle.USER_OWNER) { 4654 return resolveInfos; 4655 } 4656 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4657 ResolveInfo info = resolveInfos.get(i); 4658 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4659 resolveInfos.remove(i); 4660 } 4661 } 4662 return resolveInfos; 4663 } 4664 4665 private static boolean hasWebURI(Intent intent) { 4666 if (intent.getData() == null) { 4667 return false; 4668 } 4669 final String scheme = intent.getScheme(); 4670 if (TextUtils.isEmpty(scheme)) { 4671 return false; 4672 } 4673 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4674 } 4675 4676 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4677 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4678 int userId) { 4679 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4680 4681 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4682 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4683 candidates.size()); 4684 } 4685 4686 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4687 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4688 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4689 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4690 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4691 4692 synchronized (mPackages) { 4693 final int count = candidates.size(); 4694 // First, try to use linked apps. Partition the candidates into four lists: 4695 // one for the final results, one for the "do not use ever", one for "undefined status" 4696 // and finally one for "browser app type". 4697 for (int n=0; n<count; n++) { 4698 ResolveInfo info = candidates.get(n); 4699 String packageName = info.activityInfo.packageName; 4700 PackageSetting ps = mSettings.mPackages.get(packageName); 4701 if (ps != null) { 4702 // Add to the special match all list (Browser use case) 4703 if (info.handleAllWebDataURI) { 4704 matchAllList.add(info); 4705 continue; 4706 } 4707 // Try to get the status from User settings first 4708 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4709 int status = (int)(packedStatus >> 32); 4710 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4711 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4712 if (DEBUG_DOMAIN_VERIFICATION) { 4713 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4714 + " : linkgen=" + linkGeneration); 4715 } 4716 // Use link-enabled generation as preferredOrder, i.e. 4717 // prefer newly-enabled over earlier-enabled. 4718 info.preferredOrder = linkGeneration; 4719 alwaysList.add(info); 4720 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4721 if (DEBUG_DOMAIN_VERIFICATION) { 4722 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4723 } 4724 neverList.add(info); 4725 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4726 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4727 if (DEBUG_DOMAIN_VERIFICATION) { 4728 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4729 } 4730 undefinedList.add(info); 4731 } 4732 } 4733 } 4734 // First try to add the "always" resolution(s) for the current user, if any 4735 if (alwaysList.size() > 0) { 4736 result.addAll(alwaysList); 4737 // if there is an "always" for the parent user, add it. 4738 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4739 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4740 result.add(xpDomainInfo.resolveInfo); 4741 } else { 4742 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4743 result.addAll(undefinedList); 4744 if (xpDomainInfo != null && ( 4745 xpDomainInfo.bestDomainVerificationStatus 4746 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4747 || xpDomainInfo.bestDomainVerificationStatus 4748 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4749 result.add(xpDomainInfo.resolveInfo); 4750 } 4751 // Also add Browsers (all of them or only the default one) 4752 if ((matchFlags & MATCH_ALL) != 0) { 4753 result.addAll(matchAllList); 4754 } else { 4755 // Browser/generic handling case. If there's a default browser, go straight 4756 // to that (but only if there is no other higher-priority match). 4757 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4758 int maxMatchPrio = 0; 4759 ResolveInfo defaultBrowserMatch = null; 4760 final int numCandidates = matchAllList.size(); 4761 for (int n = 0; n < numCandidates; n++) { 4762 ResolveInfo info = matchAllList.get(n); 4763 // track the highest overall match priority... 4764 if (info.priority > maxMatchPrio) { 4765 maxMatchPrio = info.priority; 4766 } 4767 // ...and the highest-priority default browser match 4768 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4769 if (defaultBrowserMatch == null 4770 || (defaultBrowserMatch.priority < info.priority)) { 4771 if (debug) { 4772 Slog.v(TAG, "Considering default browser match " + info); 4773 } 4774 defaultBrowserMatch = info; 4775 } 4776 } 4777 } 4778 if (defaultBrowserMatch != null 4779 && defaultBrowserMatch.priority >= maxMatchPrio 4780 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4781 { 4782 if (debug) { 4783 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4784 } 4785 result.add(defaultBrowserMatch); 4786 } else { 4787 result.addAll(matchAllList); 4788 } 4789 } 4790 4791 // If there is nothing selected, add all candidates and remove the ones that the user 4792 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4793 if (result.size() == 0) { 4794 result.addAll(candidates); 4795 result.removeAll(neverList); 4796 } 4797 } 4798 } 4799 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4800 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4801 result.size()); 4802 for (ResolveInfo info : result) { 4803 Slog.v(TAG, " + " + info.activityInfo); 4804 } 4805 } 4806 return result; 4807 } 4808 4809 // Returns a packed value as a long: 4810 // 4811 // high 'int'-sized word: link status: undefined/ask/never/always. 4812 // low 'int'-sized word: relative priority among 'always' results. 4813 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4814 long result = ps.getDomainVerificationStatusForUser(userId); 4815 // if none available, get the master status 4816 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4817 if (ps.getIntentFilterVerificationInfo() != null) { 4818 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4819 } 4820 } 4821 return result; 4822 } 4823 4824 private ResolveInfo querySkipCurrentProfileIntents( 4825 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4826 int flags, int sourceUserId) { 4827 if (matchingFilters != null) { 4828 int size = matchingFilters.size(); 4829 for (int i = 0; i < size; i ++) { 4830 CrossProfileIntentFilter filter = matchingFilters.get(i); 4831 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4832 // Checking if there are activities in the target user that can handle the 4833 // intent. 4834 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4835 flags, sourceUserId); 4836 if (resolveInfo != null) { 4837 return resolveInfo; 4838 } 4839 } 4840 } 4841 } 4842 return null; 4843 } 4844 4845 // Return matching ResolveInfo if any for skip current profile intent filters. 4846 private ResolveInfo queryCrossProfileIntents( 4847 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4848 int flags, int sourceUserId) { 4849 if (matchingFilters != null) { 4850 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4851 // match the same intent. For performance reasons, it is better not to 4852 // run queryIntent twice for the same userId 4853 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4854 int size = matchingFilters.size(); 4855 for (int i = 0; i < size; i++) { 4856 CrossProfileIntentFilter filter = matchingFilters.get(i); 4857 int targetUserId = filter.getTargetUserId(); 4858 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4859 && !alreadyTriedUserIds.get(targetUserId)) { 4860 // Checking if there are activities in the target user that can handle the 4861 // intent. 4862 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4863 flags, sourceUserId); 4864 if (resolveInfo != null) return resolveInfo; 4865 alreadyTriedUserIds.put(targetUserId, true); 4866 } 4867 } 4868 } 4869 return null; 4870 } 4871 4872 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4873 String resolvedType, int flags, int sourceUserId) { 4874 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4875 resolvedType, flags, filter.getTargetUserId()); 4876 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4877 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4878 } 4879 return null; 4880 } 4881 4882 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4883 int sourceUserId, int targetUserId) { 4884 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4885 String className; 4886 if (targetUserId == UserHandle.USER_OWNER) { 4887 className = FORWARD_INTENT_TO_USER_OWNER; 4888 } else { 4889 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4890 } 4891 ComponentName forwardingActivityComponentName = new ComponentName( 4892 mAndroidApplication.packageName, className); 4893 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4894 sourceUserId); 4895 if (targetUserId == UserHandle.USER_OWNER) { 4896 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4897 forwardingResolveInfo.noResourceId = true; 4898 } 4899 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4900 forwardingResolveInfo.priority = 0; 4901 forwardingResolveInfo.preferredOrder = 0; 4902 forwardingResolveInfo.match = 0; 4903 forwardingResolveInfo.isDefault = true; 4904 forwardingResolveInfo.filter = filter; 4905 forwardingResolveInfo.targetUserId = targetUserId; 4906 return forwardingResolveInfo; 4907 } 4908 4909 @Override 4910 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4911 Intent[] specifics, String[] specificTypes, Intent intent, 4912 String resolvedType, int flags, int userId) { 4913 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4914 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4915 false, "query intent activity options"); 4916 final String resultsAction = intent.getAction(); 4917 4918 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4919 | PackageManager.GET_RESOLVED_FILTER, userId); 4920 4921 if (DEBUG_INTENT_MATCHING) { 4922 Log.v(TAG, "Query " + intent + ": " + results); 4923 } 4924 4925 int specificsPos = 0; 4926 int N; 4927 4928 // todo: note that the algorithm used here is O(N^2). This 4929 // isn't a problem in our current environment, but if we start running 4930 // into situations where we have more than 5 or 10 matches then this 4931 // should probably be changed to something smarter... 4932 4933 // First we go through and resolve each of the specific items 4934 // that were supplied, taking care of removing any corresponding 4935 // duplicate items in the generic resolve list. 4936 if (specifics != null) { 4937 for (int i=0; i<specifics.length; i++) { 4938 final Intent sintent = specifics[i]; 4939 if (sintent == null) { 4940 continue; 4941 } 4942 4943 if (DEBUG_INTENT_MATCHING) { 4944 Log.v(TAG, "Specific #" + i + ": " + sintent); 4945 } 4946 4947 String action = sintent.getAction(); 4948 if (resultsAction != null && resultsAction.equals(action)) { 4949 // If this action was explicitly requested, then don't 4950 // remove things that have it. 4951 action = null; 4952 } 4953 4954 ResolveInfo ri = null; 4955 ActivityInfo ai = null; 4956 4957 ComponentName comp = sintent.getComponent(); 4958 if (comp == null) { 4959 ri = resolveIntent( 4960 sintent, 4961 specificTypes != null ? specificTypes[i] : null, 4962 flags, userId); 4963 if (ri == null) { 4964 continue; 4965 } 4966 if (ri == mResolveInfo) { 4967 // ACK! Must do something better with this. 4968 } 4969 ai = ri.activityInfo; 4970 comp = new ComponentName(ai.applicationInfo.packageName, 4971 ai.name); 4972 } else { 4973 ai = getActivityInfo(comp, flags, userId); 4974 if (ai == null) { 4975 continue; 4976 } 4977 } 4978 4979 // Look for any generic query activities that are duplicates 4980 // of this specific one, and remove them from the results. 4981 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4982 N = results.size(); 4983 int j; 4984 for (j=specificsPos; j<N; j++) { 4985 ResolveInfo sri = results.get(j); 4986 if ((sri.activityInfo.name.equals(comp.getClassName()) 4987 && sri.activityInfo.applicationInfo.packageName.equals( 4988 comp.getPackageName())) 4989 || (action != null && sri.filter.matchAction(action))) { 4990 results.remove(j); 4991 if (DEBUG_INTENT_MATCHING) Log.v( 4992 TAG, "Removing duplicate item from " + j 4993 + " due to specific " + specificsPos); 4994 if (ri == null) { 4995 ri = sri; 4996 } 4997 j--; 4998 N--; 4999 } 5000 } 5001 5002 // Add this specific item to its proper place. 5003 if (ri == null) { 5004 ri = new ResolveInfo(); 5005 ri.activityInfo = ai; 5006 } 5007 results.add(specificsPos, ri); 5008 ri.specificIndex = i; 5009 specificsPos++; 5010 } 5011 } 5012 5013 // Now we go through the remaining generic results and remove any 5014 // duplicate actions that are found here. 5015 N = results.size(); 5016 for (int i=specificsPos; i<N-1; i++) { 5017 final ResolveInfo rii = results.get(i); 5018 if (rii.filter == null) { 5019 continue; 5020 } 5021 5022 // Iterate over all of the actions of this result's intent 5023 // filter... typically this should be just one. 5024 final Iterator<String> it = rii.filter.actionsIterator(); 5025 if (it == null) { 5026 continue; 5027 } 5028 while (it.hasNext()) { 5029 final String action = it.next(); 5030 if (resultsAction != null && resultsAction.equals(action)) { 5031 // If this action was explicitly requested, then don't 5032 // remove things that have it. 5033 continue; 5034 } 5035 for (int j=i+1; j<N; j++) { 5036 final ResolveInfo rij = results.get(j); 5037 if (rij.filter != null && rij.filter.hasAction(action)) { 5038 results.remove(j); 5039 if (DEBUG_INTENT_MATCHING) Log.v( 5040 TAG, "Removing duplicate item from " + j 5041 + " due to action " + action + " at " + i); 5042 j--; 5043 N--; 5044 } 5045 } 5046 } 5047 5048 // If the caller didn't request filter information, drop it now 5049 // so we don't have to marshall/unmarshall it. 5050 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5051 rii.filter = null; 5052 } 5053 } 5054 5055 // Filter out the caller activity if so requested. 5056 if (caller != null) { 5057 N = results.size(); 5058 for (int i=0; i<N; i++) { 5059 ActivityInfo ainfo = results.get(i).activityInfo; 5060 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5061 && caller.getClassName().equals(ainfo.name)) { 5062 results.remove(i); 5063 break; 5064 } 5065 } 5066 } 5067 5068 // If the caller didn't request filter information, 5069 // drop them now so we don't have to 5070 // marshall/unmarshall it. 5071 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5072 N = results.size(); 5073 for (int i=0; i<N; i++) { 5074 results.get(i).filter = null; 5075 } 5076 } 5077 5078 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5079 return results; 5080 } 5081 5082 @Override 5083 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5084 int userId) { 5085 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5086 ComponentName comp = intent.getComponent(); 5087 if (comp == null) { 5088 if (intent.getSelector() != null) { 5089 intent = intent.getSelector(); 5090 comp = intent.getComponent(); 5091 } 5092 } 5093 if (comp != null) { 5094 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5095 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5096 if (ai != null) { 5097 ResolveInfo ri = new ResolveInfo(); 5098 ri.activityInfo = ai; 5099 list.add(ri); 5100 } 5101 return list; 5102 } 5103 5104 // reader 5105 synchronized (mPackages) { 5106 String pkgName = intent.getPackage(); 5107 if (pkgName == null) { 5108 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5109 } 5110 final PackageParser.Package pkg = mPackages.get(pkgName); 5111 if (pkg != null) { 5112 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5113 userId); 5114 } 5115 return null; 5116 } 5117 } 5118 5119 @Override 5120 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5121 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5122 if (!sUserManager.exists(userId)) return null; 5123 if (query != null) { 5124 if (query.size() >= 1) { 5125 // If there is more than one service with the same priority, 5126 // just arbitrarily pick the first one. 5127 return query.get(0); 5128 } 5129 } 5130 return null; 5131 } 5132 5133 @Override 5134 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5135 int userId) { 5136 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5137 ComponentName comp = intent.getComponent(); 5138 if (comp == null) { 5139 if (intent.getSelector() != null) { 5140 intent = intent.getSelector(); 5141 comp = intent.getComponent(); 5142 } 5143 } 5144 if (comp != null) { 5145 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5146 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5147 if (si != null) { 5148 final ResolveInfo ri = new ResolveInfo(); 5149 ri.serviceInfo = si; 5150 list.add(ri); 5151 } 5152 return list; 5153 } 5154 5155 // reader 5156 synchronized (mPackages) { 5157 String pkgName = intent.getPackage(); 5158 if (pkgName == null) { 5159 return mServices.queryIntent(intent, resolvedType, flags, userId); 5160 } 5161 final PackageParser.Package pkg = mPackages.get(pkgName); 5162 if (pkg != null) { 5163 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5164 userId); 5165 } 5166 return null; 5167 } 5168 } 5169 5170 @Override 5171 public List<ResolveInfo> queryIntentContentProviders( 5172 Intent intent, String resolvedType, int flags, int userId) { 5173 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5174 ComponentName comp = intent.getComponent(); 5175 if (comp == null) { 5176 if (intent.getSelector() != null) { 5177 intent = intent.getSelector(); 5178 comp = intent.getComponent(); 5179 } 5180 } 5181 if (comp != null) { 5182 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5183 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5184 if (pi != null) { 5185 final ResolveInfo ri = new ResolveInfo(); 5186 ri.providerInfo = pi; 5187 list.add(ri); 5188 } 5189 return list; 5190 } 5191 5192 // reader 5193 synchronized (mPackages) { 5194 String pkgName = intent.getPackage(); 5195 if (pkgName == null) { 5196 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5197 } 5198 final PackageParser.Package pkg = mPackages.get(pkgName); 5199 if (pkg != null) { 5200 return mProviders.queryIntentForPackage( 5201 intent, resolvedType, flags, pkg.providers, userId); 5202 } 5203 return null; 5204 } 5205 } 5206 5207 @Override 5208 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5209 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5210 5211 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5212 5213 // writer 5214 synchronized (mPackages) { 5215 ArrayList<PackageInfo> list; 5216 if (listUninstalled) { 5217 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5218 for (PackageSetting ps : mSettings.mPackages.values()) { 5219 PackageInfo pi; 5220 if (ps.pkg != null) { 5221 pi = generatePackageInfo(ps.pkg, flags, userId); 5222 } else { 5223 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5224 } 5225 if (pi != null) { 5226 list.add(pi); 5227 } 5228 } 5229 } else { 5230 list = new ArrayList<PackageInfo>(mPackages.size()); 5231 for (PackageParser.Package p : mPackages.values()) { 5232 PackageInfo pi = generatePackageInfo(p, flags, userId); 5233 if (pi != null) { 5234 list.add(pi); 5235 } 5236 } 5237 } 5238 5239 return new ParceledListSlice<PackageInfo>(list); 5240 } 5241 } 5242 5243 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5244 String[] permissions, boolean[] tmp, int flags, int userId) { 5245 int numMatch = 0; 5246 final PermissionsState permissionsState = ps.getPermissionsState(); 5247 for (int i=0; i<permissions.length; i++) { 5248 final String permission = permissions[i]; 5249 if (permissionsState.hasPermission(permission, userId)) { 5250 tmp[i] = true; 5251 numMatch++; 5252 } else { 5253 tmp[i] = false; 5254 } 5255 } 5256 if (numMatch == 0) { 5257 return; 5258 } 5259 PackageInfo pi; 5260 if (ps.pkg != null) { 5261 pi = generatePackageInfo(ps.pkg, flags, userId); 5262 } else { 5263 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5264 } 5265 // The above might return null in cases of uninstalled apps or install-state 5266 // skew across users/profiles. 5267 if (pi != null) { 5268 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5269 if (numMatch == permissions.length) { 5270 pi.requestedPermissions = permissions; 5271 } else { 5272 pi.requestedPermissions = new String[numMatch]; 5273 numMatch = 0; 5274 for (int i=0; i<permissions.length; i++) { 5275 if (tmp[i]) { 5276 pi.requestedPermissions[numMatch] = permissions[i]; 5277 numMatch++; 5278 } 5279 } 5280 } 5281 } 5282 list.add(pi); 5283 } 5284 } 5285 5286 @Override 5287 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5288 String[] permissions, int flags, int userId) { 5289 if (!sUserManager.exists(userId)) return null; 5290 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5291 5292 // writer 5293 synchronized (mPackages) { 5294 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5295 boolean[] tmpBools = new boolean[permissions.length]; 5296 if (listUninstalled) { 5297 for (PackageSetting ps : mSettings.mPackages.values()) { 5298 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5299 } 5300 } else { 5301 for (PackageParser.Package pkg : mPackages.values()) { 5302 PackageSetting ps = (PackageSetting)pkg.mExtras; 5303 if (ps != null) { 5304 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5305 userId); 5306 } 5307 } 5308 } 5309 5310 return new ParceledListSlice<PackageInfo>(list); 5311 } 5312 } 5313 5314 @Override 5315 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5316 if (!sUserManager.exists(userId)) return null; 5317 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5318 5319 // writer 5320 synchronized (mPackages) { 5321 ArrayList<ApplicationInfo> list; 5322 if (listUninstalled) { 5323 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5324 for (PackageSetting ps : mSettings.mPackages.values()) { 5325 ApplicationInfo ai; 5326 if (ps.pkg != null) { 5327 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5328 ps.readUserState(userId), userId); 5329 } else { 5330 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5331 } 5332 if (ai != null) { 5333 list.add(ai); 5334 } 5335 } 5336 } else { 5337 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5338 for (PackageParser.Package p : mPackages.values()) { 5339 if (p.mExtras != null) { 5340 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5341 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5342 if (ai != null) { 5343 list.add(ai); 5344 } 5345 } 5346 } 5347 } 5348 5349 return new ParceledListSlice<ApplicationInfo>(list); 5350 } 5351 } 5352 5353 public List<ApplicationInfo> getPersistentApplications(int flags) { 5354 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5355 5356 // reader 5357 synchronized (mPackages) { 5358 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5359 final int userId = UserHandle.getCallingUserId(); 5360 while (i.hasNext()) { 5361 final PackageParser.Package p = i.next(); 5362 if (p.applicationInfo != null 5363 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5364 && (!mSafeMode || isSystemApp(p))) { 5365 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5366 if (ps != null) { 5367 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5368 ps.readUserState(userId), userId); 5369 if (ai != null) { 5370 finalList.add(ai); 5371 } 5372 } 5373 } 5374 } 5375 } 5376 5377 return finalList; 5378 } 5379 5380 @Override 5381 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5382 if (!sUserManager.exists(userId)) return null; 5383 // reader 5384 synchronized (mPackages) { 5385 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5386 PackageSetting ps = provider != null 5387 ? mSettings.mPackages.get(provider.owner.packageName) 5388 : null; 5389 return ps != null 5390 && mSettings.isEnabledLPr(provider.info, flags, userId) 5391 && (!mSafeMode || (provider.info.applicationInfo.flags 5392 &ApplicationInfo.FLAG_SYSTEM) != 0) 5393 ? PackageParser.generateProviderInfo(provider, flags, 5394 ps.readUserState(userId), userId) 5395 : null; 5396 } 5397 } 5398 5399 /** 5400 * @deprecated 5401 */ 5402 @Deprecated 5403 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5404 // reader 5405 synchronized (mPackages) { 5406 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5407 .entrySet().iterator(); 5408 final int userId = UserHandle.getCallingUserId(); 5409 while (i.hasNext()) { 5410 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5411 PackageParser.Provider p = entry.getValue(); 5412 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5413 5414 if (ps != null && p.syncable 5415 && (!mSafeMode || (p.info.applicationInfo.flags 5416 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5417 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5418 ps.readUserState(userId), userId); 5419 if (info != null) { 5420 outNames.add(entry.getKey()); 5421 outInfo.add(info); 5422 } 5423 } 5424 } 5425 } 5426 } 5427 5428 @Override 5429 public List<ProviderInfo> queryContentProviders(String processName, 5430 int uid, int flags) { 5431 ArrayList<ProviderInfo> finalList = null; 5432 // reader 5433 synchronized (mPackages) { 5434 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5435 final int userId = processName != null ? 5436 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5437 while (i.hasNext()) { 5438 final PackageParser.Provider p = i.next(); 5439 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5440 if (ps != null && p.info.authority != null 5441 && (processName == null 5442 || (p.info.processName.equals(processName) 5443 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5444 && mSettings.isEnabledLPr(p.info, flags, userId) 5445 && (!mSafeMode 5446 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5447 if (finalList == null) { 5448 finalList = new ArrayList<ProviderInfo>(3); 5449 } 5450 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5451 ps.readUserState(userId), userId); 5452 if (info != null) { 5453 finalList.add(info); 5454 } 5455 } 5456 } 5457 } 5458 5459 if (finalList != null) { 5460 Collections.sort(finalList, mProviderInitOrderSorter); 5461 } 5462 5463 return finalList; 5464 } 5465 5466 @Override 5467 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5468 int flags) { 5469 // reader 5470 synchronized (mPackages) { 5471 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5472 return PackageParser.generateInstrumentationInfo(i, flags); 5473 } 5474 } 5475 5476 @Override 5477 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5478 int flags) { 5479 ArrayList<InstrumentationInfo> finalList = 5480 new ArrayList<InstrumentationInfo>(); 5481 5482 // reader 5483 synchronized (mPackages) { 5484 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5485 while (i.hasNext()) { 5486 final PackageParser.Instrumentation p = i.next(); 5487 if (targetPackage == null 5488 || targetPackage.equals(p.info.targetPackage)) { 5489 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5490 flags); 5491 if (ii != null) { 5492 finalList.add(ii); 5493 } 5494 } 5495 } 5496 } 5497 5498 return finalList; 5499 } 5500 5501 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5502 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5503 if (overlays == null) { 5504 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5505 return; 5506 } 5507 for (PackageParser.Package opkg : overlays.values()) { 5508 // Not much to do if idmap fails: we already logged the error 5509 // and we certainly don't want to abort installation of pkg simply 5510 // because an overlay didn't fit properly. For these reasons, 5511 // ignore the return value of createIdmapForPackagePairLI. 5512 createIdmapForPackagePairLI(pkg, opkg); 5513 } 5514 } 5515 5516 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5517 PackageParser.Package opkg) { 5518 if (!opkg.mTrustedOverlay) { 5519 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5520 opkg.baseCodePath + ": overlay not trusted"); 5521 return false; 5522 } 5523 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5524 if (overlaySet == null) { 5525 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5526 opkg.baseCodePath + " but target package has no known overlays"); 5527 return false; 5528 } 5529 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5530 // TODO: generate idmap for split APKs 5531 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5532 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5533 + opkg.baseCodePath); 5534 return false; 5535 } 5536 PackageParser.Package[] overlayArray = 5537 overlaySet.values().toArray(new PackageParser.Package[0]); 5538 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5539 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5540 return p1.mOverlayPriority - p2.mOverlayPriority; 5541 } 5542 }; 5543 Arrays.sort(overlayArray, cmp); 5544 5545 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5546 int i = 0; 5547 for (PackageParser.Package p : overlayArray) { 5548 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5549 } 5550 return true; 5551 } 5552 5553 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5554 final File[] files = dir.listFiles(); 5555 if (ArrayUtils.isEmpty(files)) { 5556 Log.d(TAG, "No files in app dir " + dir); 5557 return; 5558 } 5559 5560 if (DEBUG_PACKAGE_SCANNING) { 5561 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5562 + " flags=0x" + Integer.toHexString(parseFlags)); 5563 } 5564 5565 for (File file : files) { 5566 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5567 && !PackageInstallerService.isStageName(file.getName()); 5568 if (!isPackage) { 5569 // Ignore entries which are not packages 5570 continue; 5571 } 5572 try { 5573 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5574 scanFlags, currentTime, null); 5575 } catch (PackageManagerException e) { 5576 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5577 5578 // Delete invalid userdata apps 5579 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5580 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5581 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5582 if (file.isDirectory()) { 5583 mInstaller.rmPackageDir(file.getAbsolutePath()); 5584 } else { 5585 file.delete(); 5586 } 5587 } 5588 } 5589 } 5590 } 5591 5592 private static File getSettingsProblemFile() { 5593 File dataDir = Environment.getDataDirectory(); 5594 File systemDir = new File(dataDir, "system"); 5595 File fname = new File(systemDir, "uiderrors.txt"); 5596 return fname; 5597 } 5598 5599 static void reportSettingsProblem(int priority, String msg) { 5600 logCriticalInfo(priority, msg); 5601 } 5602 5603 static void logCriticalInfo(int priority, String msg) { 5604 Slog.println(priority, TAG, msg); 5605 EventLogTags.writePmCriticalInfo(msg); 5606 try { 5607 File fname = getSettingsProblemFile(); 5608 FileOutputStream out = new FileOutputStream(fname, true); 5609 PrintWriter pw = new FastPrintWriter(out); 5610 SimpleDateFormat formatter = new SimpleDateFormat(); 5611 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5612 pw.println(dateString + ": " + msg); 5613 pw.close(); 5614 FileUtils.setPermissions( 5615 fname.toString(), 5616 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5617 -1, -1); 5618 } catch (java.io.IOException e) { 5619 } 5620 } 5621 5622 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5623 PackageParser.Package pkg, File srcFile, int parseFlags) 5624 throws PackageManagerException { 5625 if (ps != null 5626 && ps.codePath.equals(srcFile) 5627 && ps.timeStamp == srcFile.lastModified() 5628 && !isCompatSignatureUpdateNeeded(pkg) 5629 && !isRecoverSignatureUpdateNeeded(pkg)) { 5630 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5631 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5632 ArraySet<PublicKey> signingKs; 5633 synchronized (mPackages) { 5634 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5635 } 5636 if (ps.signatures.mSignatures != null 5637 && ps.signatures.mSignatures.length != 0 5638 && signingKs != null) { 5639 // Optimization: reuse the existing cached certificates 5640 // if the package appears to be unchanged. 5641 pkg.mSignatures = ps.signatures.mSignatures; 5642 pkg.mSigningKeys = signingKs; 5643 return; 5644 } 5645 5646 Slog.w(TAG, "PackageSetting for " + ps.name 5647 + " is missing signatures. Collecting certs again to recover them."); 5648 } else { 5649 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5650 } 5651 5652 try { 5653 pp.collectCertificates(pkg, parseFlags); 5654 pp.collectManifestDigest(pkg); 5655 } catch (PackageParserException e) { 5656 throw PackageManagerException.from(e); 5657 } 5658 } 5659 5660 /* 5661 * Scan a package and return the newly parsed package. 5662 * Returns null in case of errors and the error code is stored in mLastScanError 5663 */ 5664 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5665 long currentTime, UserHandle user) throws PackageManagerException { 5666 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5667 parseFlags |= mDefParseFlags; 5668 PackageParser pp = new PackageParser(); 5669 pp.setSeparateProcesses(mSeparateProcesses); 5670 pp.setOnlyCoreApps(mOnlyCore); 5671 pp.setDisplayMetrics(mMetrics); 5672 5673 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5674 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5675 } 5676 5677 final PackageParser.Package pkg; 5678 try { 5679 pkg = pp.parsePackage(scanFile, parseFlags); 5680 } catch (PackageParserException e) { 5681 throw PackageManagerException.from(e); 5682 } 5683 5684 PackageSetting ps = null; 5685 PackageSetting updatedPkg; 5686 // reader 5687 synchronized (mPackages) { 5688 // Look to see if we already know about this package. 5689 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5690 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5691 // This package has been renamed to its original name. Let's 5692 // use that. 5693 ps = mSettings.peekPackageLPr(oldName); 5694 } 5695 // If there was no original package, see one for the real package name. 5696 if (ps == null) { 5697 ps = mSettings.peekPackageLPr(pkg.packageName); 5698 } 5699 // Check to see if this package could be hiding/updating a system 5700 // package. Must look for it either under the original or real 5701 // package name depending on our state. 5702 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5703 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5704 } 5705 boolean updatedPkgBetter = false; 5706 // First check if this is a system package that may involve an update 5707 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5708 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5709 // it needs to drop FLAG_PRIVILEGED. 5710 if (locationIsPrivileged(scanFile)) { 5711 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5712 } else { 5713 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5714 } 5715 5716 if (ps != null && !ps.codePath.equals(scanFile)) { 5717 // The path has changed from what was last scanned... check the 5718 // version of the new path against what we have stored to determine 5719 // what to do. 5720 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5721 if (pkg.mVersionCode <= ps.versionCode) { 5722 // The system package has been updated and the code path does not match 5723 // Ignore entry. Skip it. 5724 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5725 + " ignored: updated version " + ps.versionCode 5726 + " better than this " + pkg.mVersionCode); 5727 if (!updatedPkg.codePath.equals(scanFile)) { 5728 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5729 + ps.name + " changing from " + updatedPkg.codePathString 5730 + " to " + scanFile); 5731 updatedPkg.codePath = scanFile; 5732 updatedPkg.codePathString = scanFile.toString(); 5733 updatedPkg.resourcePath = scanFile; 5734 updatedPkg.resourcePathString = scanFile.toString(); 5735 } 5736 updatedPkg.pkg = pkg; 5737 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5738 "Package " + ps.name + " at " + scanFile 5739 + " ignored: updated version " + ps.versionCode 5740 + " better than this " + pkg.mVersionCode); 5741 } else { 5742 // The current app on the system partition is better than 5743 // what we have updated to on the data partition; switch 5744 // back to the system partition version. 5745 // At this point, its safely assumed that package installation for 5746 // apps in system partition will go through. If not there won't be a working 5747 // version of the app 5748 // writer 5749 synchronized (mPackages) { 5750 // Just remove the loaded entries from package lists. 5751 mPackages.remove(ps.name); 5752 } 5753 5754 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5755 + " reverting from " + ps.codePathString 5756 + ": new version " + pkg.mVersionCode 5757 + " better than installed " + ps.versionCode); 5758 5759 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5760 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5761 synchronized (mInstallLock) { 5762 args.cleanUpResourcesLI(); 5763 } 5764 synchronized (mPackages) { 5765 mSettings.enableSystemPackageLPw(ps.name); 5766 } 5767 updatedPkgBetter = true; 5768 } 5769 } 5770 } 5771 5772 if (updatedPkg != null) { 5773 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5774 // initially 5775 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5776 5777 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5778 // flag set initially 5779 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5780 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5781 } 5782 } 5783 5784 // Verify certificates against what was last scanned 5785 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5786 5787 /* 5788 * A new system app appeared, but we already had a non-system one of the 5789 * same name installed earlier. 5790 */ 5791 boolean shouldHideSystemApp = false; 5792 if (updatedPkg == null && ps != null 5793 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5794 /* 5795 * Check to make sure the signatures match first. If they don't, 5796 * wipe the installed application and its data. 5797 */ 5798 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5799 != PackageManager.SIGNATURE_MATCH) { 5800 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5801 + " signatures don't match existing userdata copy; removing"); 5802 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5803 ps = null; 5804 } else { 5805 /* 5806 * If the newly-added system app is an older version than the 5807 * already installed version, hide it. It will be scanned later 5808 * and re-added like an update. 5809 */ 5810 if (pkg.mVersionCode <= ps.versionCode) { 5811 shouldHideSystemApp = true; 5812 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5813 + " but new version " + pkg.mVersionCode + " better than installed " 5814 + ps.versionCode + "; hiding system"); 5815 } else { 5816 /* 5817 * The newly found system app is a newer version that the 5818 * one previously installed. Simply remove the 5819 * already-installed application and replace it with our own 5820 * while keeping the application data. 5821 */ 5822 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5823 + " reverting from " + ps.codePathString + ": new version " 5824 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5825 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5826 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5827 synchronized (mInstallLock) { 5828 args.cleanUpResourcesLI(); 5829 } 5830 } 5831 } 5832 } 5833 5834 // The apk is forward locked (not public) if its code and resources 5835 // are kept in different files. (except for app in either system or 5836 // vendor path). 5837 // TODO grab this value from PackageSettings 5838 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5839 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5840 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5841 } 5842 } 5843 5844 // TODO: extend to support forward-locked splits 5845 String resourcePath = null; 5846 String baseResourcePath = null; 5847 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5848 if (ps != null && ps.resourcePathString != null) { 5849 resourcePath = ps.resourcePathString; 5850 baseResourcePath = ps.resourcePathString; 5851 } else { 5852 // Should not happen at all. Just log an error. 5853 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5854 } 5855 } else { 5856 resourcePath = pkg.codePath; 5857 baseResourcePath = pkg.baseCodePath; 5858 } 5859 5860 // Set application objects path explicitly. 5861 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5862 pkg.applicationInfo.setCodePath(pkg.codePath); 5863 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5864 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5865 pkg.applicationInfo.setResourcePath(resourcePath); 5866 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5867 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5868 5869 // Note that we invoke the following method only if we are about to unpack an application 5870 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5871 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5872 5873 /* 5874 * If the system app should be overridden by a previously installed 5875 * data, hide the system app now and let the /data/app scan pick it up 5876 * again. 5877 */ 5878 if (shouldHideSystemApp) { 5879 synchronized (mPackages) { 5880 /* 5881 * We have to grant systems permissions before we hide, because 5882 * grantPermissions will assume the package update is trying to 5883 * expand its permissions. 5884 */ 5885 grantPermissionsLPw(pkg, true, pkg.packageName); 5886 mSettings.disableSystemPackageLPw(pkg.packageName); 5887 } 5888 } 5889 5890 return scannedPkg; 5891 } 5892 5893 private static String fixProcessName(String defProcessName, 5894 String processName, int uid) { 5895 if (processName == null) { 5896 return defProcessName; 5897 } 5898 return processName; 5899 } 5900 5901 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5902 throws PackageManagerException { 5903 if (pkgSetting.signatures.mSignatures != null) { 5904 // Already existing package. Make sure signatures match 5905 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5906 == PackageManager.SIGNATURE_MATCH; 5907 if (!match) { 5908 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5909 == PackageManager.SIGNATURE_MATCH; 5910 } 5911 if (!match) { 5912 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5913 == PackageManager.SIGNATURE_MATCH; 5914 } 5915 if (!match) { 5916 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5917 + pkg.packageName + " signatures do not match the " 5918 + "previously installed version; ignoring!"); 5919 } 5920 } 5921 5922 // Check for shared user signatures 5923 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5924 // Already existing package. Make sure signatures match 5925 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5926 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5927 if (!match) { 5928 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5929 == PackageManager.SIGNATURE_MATCH; 5930 } 5931 if (!match) { 5932 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5933 == PackageManager.SIGNATURE_MATCH; 5934 } 5935 if (!match) { 5936 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5937 "Package " + pkg.packageName 5938 + " has no signatures that match those in shared user " 5939 + pkgSetting.sharedUser.name + "; ignoring!"); 5940 } 5941 } 5942 } 5943 5944 /** 5945 * Enforces that only the system UID or root's UID can call a method exposed 5946 * via Binder. 5947 * 5948 * @param message used as message if SecurityException is thrown 5949 * @throws SecurityException if the caller is not system or root 5950 */ 5951 private static final void enforceSystemOrRoot(String message) { 5952 final int uid = Binder.getCallingUid(); 5953 if (uid != Process.SYSTEM_UID && uid != 0) { 5954 throw new SecurityException(message); 5955 } 5956 } 5957 5958 @Override 5959 public void performBootDexOpt() { 5960 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5961 5962 // Before everything else, see whether we need to fstrim. 5963 try { 5964 IMountService ms = PackageHelper.getMountService(); 5965 if (ms != null) { 5966 final boolean isUpgrade = isUpgrade(); 5967 boolean doTrim = isUpgrade; 5968 if (doTrim) { 5969 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5970 } else { 5971 final long interval = android.provider.Settings.Global.getLong( 5972 mContext.getContentResolver(), 5973 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5974 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5975 if (interval > 0) { 5976 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5977 if (timeSinceLast > interval) { 5978 doTrim = true; 5979 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5980 + "; running immediately"); 5981 } 5982 } 5983 } 5984 if (doTrim) { 5985 if (!isFirstBoot()) { 5986 try { 5987 ActivityManagerNative.getDefault().showBootMessage( 5988 mContext.getResources().getString( 5989 R.string.android_upgrading_fstrim), true); 5990 } catch (RemoteException e) { 5991 } 5992 } 5993 ms.runMaintenance(); 5994 } 5995 } else { 5996 Slog.e(TAG, "Mount service unavailable!"); 5997 } 5998 } catch (RemoteException e) { 5999 // Can't happen; MountService is local 6000 } 6001 6002 final ArraySet<PackageParser.Package> pkgs; 6003 synchronized (mPackages) { 6004 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6005 } 6006 6007 if (pkgs != null) { 6008 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6009 // in case the device runs out of space. 6010 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6011 // Give priority to core apps. 6012 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6013 PackageParser.Package pkg = it.next(); 6014 if (pkg.coreApp) { 6015 if (DEBUG_DEXOPT) { 6016 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6017 } 6018 sortedPkgs.add(pkg); 6019 it.remove(); 6020 } 6021 } 6022 // Give priority to system apps that listen for pre boot complete. 6023 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6024 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6025 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6026 PackageParser.Package pkg = it.next(); 6027 if (pkgNames.contains(pkg.packageName)) { 6028 if (DEBUG_DEXOPT) { 6029 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6030 } 6031 sortedPkgs.add(pkg); 6032 it.remove(); 6033 } 6034 } 6035 // Give priority to system apps. 6036 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6037 PackageParser.Package pkg = it.next(); 6038 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6039 if (DEBUG_DEXOPT) { 6040 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6041 } 6042 sortedPkgs.add(pkg); 6043 it.remove(); 6044 } 6045 } 6046 // Give priority to updated system apps. 6047 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6048 PackageParser.Package pkg = it.next(); 6049 if (pkg.isUpdatedSystemApp()) { 6050 if (DEBUG_DEXOPT) { 6051 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6052 } 6053 sortedPkgs.add(pkg); 6054 it.remove(); 6055 } 6056 } 6057 // Give priority to apps that listen for boot complete. 6058 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6059 pkgNames = getPackageNamesForIntent(intent); 6060 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6061 PackageParser.Package pkg = it.next(); 6062 if (pkgNames.contains(pkg.packageName)) { 6063 if (DEBUG_DEXOPT) { 6064 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6065 } 6066 sortedPkgs.add(pkg); 6067 it.remove(); 6068 } 6069 } 6070 // Filter out packages that aren't recently used. 6071 filterRecentlyUsedApps(pkgs); 6072 // Add all remaining apps. 6073 for (PackageParser.Package pkg : pkgs) { 6074 if (DEBUG_DEXOPT) { 6075 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6076 } 6077 sortedPkgs.add(pkg); 6078 } 6079 6080 // If we want to be lazy, filter everything that wasn't recently used. 6081 if (mLazyDexOpt) { 6082 filterRecentlyUsedApps(sortedPkgs); 6083 } 6084 6085 int i = 0; 6086 int total = sortedPkgs.size(); 6087 File dataDir = Environment.getDataDirectory(); 6088 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6089 if (lowThreshold == 0) { 6090 throw new IllegalStateException("Invalid low memory threshold"); 6091 } 6092 for (PackageParser.Package pkg : sortedPkgs) { 6093 long usableSpace = dataDir.getUsableSpace(); 6094 if (usableSpace < lowThreshold) { 6095 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6096 break; 6097 } 6098 performBootDexOpt(pkg, ++i, total); 6099 } 6100 } 6101 } 6102 6103 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6104 // Filter out packages that aren't recently used. 6105 // 6106 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6107 // should do a full dexopt. 6108 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6109 int total = pkgs.size(); 6110 int skipped = 0; 6111 long now = System.currentTimeMillis(); 6112 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6113 PackageParser.Package pkg = i.next(); 6114 long then = pkg.mLastPackageUsageTimeInMills; 6115 if (then + mDexOptLRUThresholdInMills < now) { 6116 if (DEBUG_DEXOPT) { 6117 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6118 ((then == 0) ? "never" : new Date(then))); 6119 } 6120 i.remove(); 6121 skipped++; 6122 } 6123 } 6124 if (DEBUG_DEXOPT) { 6125 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6126 } 6127 } 6128 } 6129 6130 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6131 List<ResolveInfo> ris = null; 6132 try { 6133 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6134 intent, null, 0, UserHandle.USER_OWNER); 6135 } catch (RemoteException e) { 6136 } 6137 ArraySet<String> pkgNames = new ArraySet<String>(); 6138 if (ris != null) { 6139 for (ResolveInfo ri : ris) { 6140 pkgNames.add(ri.activityInfo.packageName); 6141 } 6142 } 6143 return pkgNames; 6144 } 6145 6146 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6147 if (DEBUG_DEXOPT) { 6148 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6149 } 6150 if (!isFirstBoot()) { 6151 try { 6152 ActivityManagerNative.getDefault().showBootMessage( 6153 mContext.getResources().getString(R.string.android_upgrading_apk, 6154 curr, total), true); 6155 } catch (RemoteException e) { 6156 } 6157 } 6158 PackageParser.Package p = pkg; 6159 synchronized (mInstallLock) { 6160 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6161 false /* force dex */, false /* defer */, true /* include dependencies */); 6162 } 6163 } 6164 6165 @Override 6166 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6167 return performDexOpt(packageName, instructionSet, false); 6168 } 6169 6170 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6171 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6172 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6173 if (!dexopt && !updateUsage) { 6174 // We aren't going to dexopt or update usage, so bail early. 6175 return false; 6176 } 6177 PackageParser.Package p; 6178 final String targetInstructionSet; 6179 synchronized (mPackages) { 6180 p = mPackages.get(packageName); 6181 if (p == null) { 6182 return false; 6183 } 6184 if (updateUsage) { 6185 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6186 } 6187 mPackageUsage.write(false); 6188 if (!dexopt) { 6189 // We aren't going to dexopt, so bail early. 6190 return false; 6191 } 6192 6193 targetInstructionSet = instructionSet != null ? instructionSet : 6194 getPrimaryInstructionSet(p.applicationInfo); 6195 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6196 return false; 6197 } 6198 } 6199 long callingId = Binder.clearCallingIdentity(); 6200 try { 6201 synchronized (mInstallLock) { 6202 final String[] instructionSets = new String[] { targetInstructionSet }; 6203 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6204 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6205 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6206 } 6207 } finally { 6208 Binder.restoreCallingIdentity(callingId); 6209 } 6210 } 6211 6212 public ArraySet<String> getPackagesThatNeedDexOpt() { 6213 ArraySet<String> pkgs = null; 6214 synchronized (mPackages) { 6215 for (PackageParser.Package p : mPackages.values()) { 6216 if (DEBUG_DEXOPT) { 6217 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6218 } 6219 if (!p.mDexOptPerformed.isEmpty()) { 6220 continue; 6221 } 6222 if (pkgs == null) { 6223 pkgs = new ArraySet<String>(); 6224 } 6225 pkgs.add(p.packageName); 6226 } 6227 } 6228 return pkgs; 6229 } 6230 6231 public void shutdown() { 6232 mPackageUsage.write(true); 6233 } 6234 6235 @Override 6236 public void forceDexOpt(String packageName) { 6237 enforceSystemOrRoot("forceDexOpt"); 6238 6239 PackageParser.Package pkg; 6240 synchronized (mPackages) { 6241 pkg = mPackages.get(packageName); 6242 if (pkg == null) { 6243 throw new IllegalArgumentException("Missing package: " + packageName); 6244 } 6245 } 6246 6247 synchronized (mInstallLock) { 6248 final String[] instructionSets = new String[] { 6249 getPrimaryInstructionSet(pkg.applicationInfo) }; 6250 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6251 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6252 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6253 throw new IllegalStateException("Failed to dexopt: " + res); 6254 } 6255 } 6256 } 6257 6258 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6259 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6260 Slog.w(TAG, "Unable to update from " + oldPkg.name 6261 + " to " + newPkg.packageName 6262 + ": old package not in system partition"); 6263 return false; 6264 } else if (mPackages.get(oldPkg.name) != null) { 6265 Slog.w(TAG, "Unable to update from " + oldPkg.name 6266 + " to " + newPkg.packageName 6267 + ": old package still exists"); 6268 return false; 6269 } 6270 return true; 6271 } 6272 6273 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6274 int[] users = sUserManager.getUserIds(); 6275 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6276 if (res < 0) { 6277 return res; 6278 } 6279 for (int user : users) { 6280 if (user != 0) { 6281 res = mInstaller.createUserData(volumeUuid, packageName, 6282 UserHandle.getUid(user, uid), user, seinfo); 6283 if (res < 0) { 6284 return res; 6285 } 6286 } 6287 } 6288 return res; 6289 } 6290 6291 private int removeDataDirsLI(String volumeUuid, String packageName) { 6292 int[] users = sUserManager.getUserIds(); 6293 int res = 0; 6294 for (int user : users) { 6295 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6296 if (resInner < 0) { 6297 res = resInner; 6298 } 6299 } 6300 6301 return res; 6302 } 6303 6304 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6305 int[] users = sUserManager.getUserIds(); 6306 int res = 0; 6307 for (int user : users) { 6308 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6309 if (resInner < 0) { 6310 res = resInner; 6311 } 6312 } 6313 return res; 6314 } 6315 6316 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6317 PackageParser.Package changingLib) { 6318 if (file.path != null) { 6319 usesLibraryFiles.add(file.path); 6320 return; 6321 } 6322 PackageParser.Package p = mPackages.get(file.apk); 6323 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6324 // If we are doing this while in the middle of updating a library apk, 6325 // then we need to make sure to use that new apk for determining the 6326 // dependencies here. (We haven't yet finished committing the new apk 6327 // to the package manager state.) 6328 if (p == null || p.packageName.equals(changingLib.packageName)) { 6329 p = changingLib; 6330 } 6331 } 6332 if (p != null) { 6333 usesLibraryFiles.addAll(p.getAllCodePaths()); 6334 } 6335 } 6336 6337 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6338 PackageParser.Package changingLib) throws PackageManagerException { 6339 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6340 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6341 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6342 for (int i=0; i<N; i++) { 6343 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6344 if (file == null) { 6345 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6346 "Package " + pkg.packageName + " requires unavailable shared library " 6347 + pkg.usesLibraries.get(i) + "; failing!"); 6348 } 6349 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6350 } 6351 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6352 for (int i=0; i<N; i++) { 6353 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6354 if (file == null) { 6355 Slog.w(TAG, "Package " + pkg.packageName 6356 + " desires unavailable shared library " 6357 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6358 } else { 6359 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6360 } 6361 } 6362 N = usesLibraryFiles.size(); 6363 if (N > 0) { 6364 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6365 } else { 6366 pkg.usesLibraryFiles = null; 6367 } 6368 } 6369 } 6370 6371 private static boolean hasString(List<String> list, List<String> which) { 6372 if (list == null) { 6373 return false; 6374 } 6375 for (int i=list.size()-1; i>=0; i--) { 6376 for (int j=which.size()-1; j>=0; j--) { 6377 if (which.get(j).equals(list.get(i))) { 6378 return true; 6379 } 6380 } 6381 } 6382 return false; 6383 } 6384 6385 private void updateAllSharedLibrariesLPw() { 6386 for (PackageParser.Package pkg : mPackages.values()) { 6387 try { 6388 updateSharedLibrariesLPw(pkg, null); 6389 } catch (PackageManagerException e) { 6390 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6391 } 6392 } 6393 } 6394 6395 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6396 PackageParser.Package changingPkg) { 6397 ArrayList<PackageParser.Package> res = null; 6398 for (PackageParser.Package pkg : mPackages.values()) { 6399 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6400 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6401 if (res == null) { 6402 res = new ArrayList<PackageParser.Package>(); 6403 } 6404 res.add(pkg); 6405 try { 6406 updateSharedLibrariesLPw(pkg, changingPkg); 6407 } catch (PackageManagerException e) { 6408 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6409 } 6410 } 6411 } 6412 return res; 6413 } 6414 6415 /** 6416 * Derive the value of the {@code cpuAbiOverride} based on the provided 6417 * value and an optional stored value from the package settings. 6418 */ 6419 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6420 String cpuAbiOverride = null; 6421 6422 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6423 cpuAbiOverride = null; 6424 } else if (abiOverride != null) { 6425 cpuAbiOverride = abiOverride; 6426 } else if (settings != null) { 6427 cpuAbiOverride = settings.cpuAbiOverrideString; 6428 } 6429 6430 return cpuAbiOverride; 6431 } 6432 6433 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6434 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6435 boolean success = false; 6436 try { 6437 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6438 currentTime, user); 6439 success = true; 6440 return res; 6441 } finally { 6442 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6443 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6444 } 6445 } 6446 } 6447 6448 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6449 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6450 final File scanFile = new File(pkg.codePath); 6451 if (pkg.applicationInfo.getCodePath() == null || 6452 pkg.applicationInfo.getResourcePath() == null) { 6453 // Bail out. The resource and code paths haven't been set. 6454 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6455 "Code and resource paths haven't been set correctly"); 6456 } 6457 6458 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6459 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6460 } else { 6461 // Only allow system apps to be flagged as core apps. 6462 pkg.coreApp = false; 6463 } 6464 6465 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6466 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6467 } 6468 6469 if (mCustomResolverComponentName != null && 6470 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6471 setUpCustomResolverActivity(pkg); 6472 } 6473 6474 if (pkg.packageName.equals("android")) { 6475 synchronized (mPackages) { 6476 if (mAndroidApplication != null) { 6477 Slog.w(TAG, "*************************************************"); 6478 Slog.w(TAG, "Core android package being redefined. Skipping."); 6479 Slog.w(TAG, " file=" + scanFile); 6480 Slog.w(TAG, "*************************************************"); 6481 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6482 "Core android package being redefined. Skipping."); 6483 } 6484 6485 // Set up information for our fall-back user intent resolution activity. 6486 mPlatformPackage = pkg; 6487 pkg.mVersionCode = mSdkVersion; 6488 mAndroidApplication = pkg.applicationInfo; 6489 6490 if (!mResolverReplaced) { 6491 mResolveActivity.applicationInfo = mAndroidApplication; 6492 mResolveActivity.name = ResolverActivity.class.getName(); 6493 mResolveActivity.packageName = mAndroidApplication.packageName; 6494 mResolveActivity.processName = "system:ui"; 6495 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6496 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6497 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6498 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6499 mResolveActivity.exported = true; 6500 mResolveActivity.enabled = true; 6501 mResolveInfo.activityInfo = mResolveActivity; 6502 mResolveInfo.priority = 0; 6503 mResolveInfo.preferredOrder = 0; 6504 mResolveInfo.match = 0; 6505 mResolveComponentName = new ComponentName( 6506 mAndroidApplication.packageName, mResolveActivity.name); 6507 } 6508 } 6509 } 6510 6511 if (DEBUG_PACKAGE_SCANNING) { 6512 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6513 Log.d(TAG, "Scanning package " + pkg.packageName); 6514 } 6515 6516 if (mPackages.containsKey(pkg.packageName) 6517 || mSharedLibraries.containsKey(pkg.packageName)) { 6518 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6519 "Application package " + pkg.packageName 6520 + " already installed. Skipping duplicate."); 6521 } 6522 6523 // If we're only installing presumed-existing packages, require that the 6524 // scanned APK is both already known and at the path previously established 6525 // for it. Previously unknown packages we pick up normally, but if we have an 6526 // a priori expectation about this package's install presence, enforce it. 6527 // With a singular exception for new system packages. When an OTA contains 6528 // a new system package, we allow the codepath to change from a system location 6529 // to the user-installed location. If we don't allow this change, any newer, 6530 // user-installed version of the application will be ignored. 6531 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6532 if (mExpectingBetter.containsKey(pkg.packageName)) { 6533 logCriticalInfo(Log.WARN, 6534 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6535 } else { 6536 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6537 if (known != null) { 6538 if (DEBUG_PACKAGE_SCANNING) { 6539 Log.d(TAG, "Examining " + pkg.codePath 6540 + " and requiring known paths " + known.codePathString 6541 + " & " + known.resourcePathString); 6542 } 6543 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6544 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6545 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6546 "Application package " + pkg.packageName 6547 + " found at " + pkg.applicationInfo.getCodePath() 6548 + " but expected at " + known.codePathString + "; ignoring."); 6549 } 6550 } 6551 } 6552 } 6553 6554 // Initialize package source and resource directories 6555 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6556 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6557 6558 SharedUserSetting suid = null; 6559 PackageSetting pkgSetting = null; 6560 6561 if (!isSystemApp(pkg)) { 6562 // Only system apps can use these features. 6563 pkg.mOriginalPackages = null; 6564 pkg.mRealPackage = null; 6565 pkg.mAdoptPermissions = null; 6566 } 6567 6568 // writer 6569 synchronized (mPackages) { 6570 if (pkg.mSharedUserId != null) { 6571 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6572 if (suid == null) { 6573 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6574 "Creating application package " + pkg.packageName 6575 + " for shared user failed"); 6576 } 6577 if (DEBUG_PACKAGE_SCANNING) { 6578 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6579 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6580 + "): packages=" + suid.packages); 6581 } 6582 } 6583 6584 // Check if we are renaming from an original package name. 6585 PackageSetting origPackage = null; 6586 String realName = null; 6587 if (pkg.mOriginalPackages != null) { 6588 // This package may need to be renamed to a previously 6589 // installed name. Let's check on that... 6590 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6591 if (pkg.mOriginalPackages.contains(renamed)) { 6592 // This package had originally been installed as the 6593 // original name, and we have already taken care of 6594 // transitioning to the new one. Just update the new 6595 // one to continue using the old name. 6596 realName = pkg.mRealPackage; 6597 if (!pkg.packageName.equals(renamed)) { 6598 // Callers into this function may have already taken 6599 // care of renaming the package; only do it here if 6600 // it is not already done. 6601 pkg.setPackageName(renamed); 6602 } 6603 6604 } else { 6605 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6606 if ((origPackage = mSettings.peekPackageLPr( 6607 pkg.mOriginalPackages.get(i))) != null) { 6608 // We do have the package already installed under its 6609 // original name... should we use it? 6610 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6611 // New package is not compatible with original. 6612 origPackage = null; 6613 continue; 6614 } else if (origPackage.sharedUser != null) { 6615 // Make sure uid is compatible between packages. 6616 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6617 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6618 + " to " + pkg.packageName + ": old uid " 6619 + origPackage.sharedUser.name 6620 + " differs from " + pkg.mSharedUserId); 6621 origPackage = null; 6622 continue; 6623 } 6624 } else { 6625 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6626 + pkg.packageName + " to old name " + origPackage.name); 6627 } 6628 break; 6629 } 6630 } 6631 } 6632 } 6633 6634 if (mTransferedPackages.contains(pkg.packageName)) { 6635 Slog.w(TAG, "Package " + pkg.packageName 6636 + " was transferred to another, but its .apk remains"); 6637 } 6638 6639 // Just create the setting, don't add it yet. For already existing packages 6640 // the PkgSetting exists already and doesn't have to be created. 6641 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6642 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6643 pkg.applicationInfo.primaryCpuAbi, 6644 pkg.applicationInfo.secondaryCpuAbi, 6645 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6646 user, false); 6647 if (pkgSetting == null) { 6648 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6649 "Creating application package " + pkg.packageName + " failed"); 6650 } 6651 6652 if (pkgSetting.origPackage != null) { 6653 // If we are first transitioning from an original package, 6654 // fix up the new package's name now. We need to do this after 6655 // looking up the package under its new name, so getPackageLP 6656 // can take care of fiddling things correctly. 6657 pkg.setPackageName(origPackage.name); 6658 6659 // File a report about this. 6660 String msg = "New package " + pkgSetting.realName 6661 + " renamed to replace old package " + pkgSetting.name; 6662 reportSettingsProblem(Log.WARN, msg); 6663 6664 // Make a note of it. 6665 mTransferedPackages.add(origPackage.name); 6666 6667 // No longer need to retain this. 6668 pkgSetting.origPackage = null; 6669 } 6670 6671 if (realName != null) { 6672 // Make a note of it. 6673 mTransferedPackages.add(pkg.packageName); 6674 } 6675 6676 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6677 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6678 } 6679 6680 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6681 // Check all shared libraries and map to their actual file path. 6682 // We only do this here for apps not on a system dir, because those 6683 // are the only ones that can fail an install due to this. We 6684 // will take care of the system apps by updating all of their 6685 // library paths after the scan is done. 6686 updateSharedLibrariesLPw(pkg, null); 6687 } 6688 6689 if (mFoundPolicyFile) { 6690 SELinuxMMAC.assignSeinfoValue(pkg); 6691 } 6692 6693 pkg.applicationInfo.uid = pkgSetting.appId; 6694 pkg.mExtras = pkgSetting; 6695 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6696 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6697 // We just determined the app is signed correctly, so bring 6698 // over the latest parsed certs. 6699 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6700 } else { 6701 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6702 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6703 "Package " + pkg.packageName + " upgrade keys do not match the " 6704 + "previously installed version"); 6705 } else { 6706 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6707 String msg = "System package " + pkg.packageName 6708 + " signature changed; retaining data."; 6709 reportSettingsProblem(Log.WARN, msg); 6710 } 6711 } 6712 } else { 6713 try { 6714 verifySignaturesLP(pkgSetting, pkg); 6715 // We just determined the app is signed correctly, so bring 6716 // over the latest parsed certs. 6717 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6718 } catch (PackageManagerException e) { 6719 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6720 throw e; 6721 } 6722 // The signature has changed, but this package is in the system 6723 // image... let's recover! 6724 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6725 // However... if this package is part of a shared user, but it 6726 // doesn't match the signature of the shared user, let's fail. 6727 // What this means is that you can't change the signatures 6728 // associated with an overall shared user, which doesn't seem all 6729 // that unreasonable. 6730 if (pkgSetting.sharedUser != null) { 6731 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6732 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6733 throw new PackageManagerException( 6734 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6735 "Signature mismatch for shared user : " 6736 + pkgSetting.sharedUser); 6737 } 6738 } 6739 // File a report about this. 6740 String msg = "System package " + pkg.packageName 6741 + " signature changed; retaining data."; 6742 reportSettingsProblem(Log.WARN, msg); 6743 } 6744 } 6745 // Verify that this new package doesn't have any content providers 6746 // that conflict with existing packages. Only do this if the 6747 // package isn't already installed, since we don't want to break 6748 // things that are installed. 6749 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6750 final int N = pkg.providers.size(); 6751 int i; 6752 for (i=0; i<N; i++) { 6753 PackageParser.Provider p = pkg.providers.get(i); 6754 if (p.info.authority != null) { 6755 String names[] = p.info.authority.split(";"); 6756 for (int j = 0; j < names.length; j++) { 6757 if (mProvidersByAuthority.containsKey(names[j])) { 6758 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6759 final String otherPackageName = 6760 ((other != null && other.getComponentName() != null) ? 6761 other.getComponentName().getPackageName() : "?"); 6762 throw new PackageManagerException( 6763 INSTALL_FAILED_CONFLICTING_PROVIDER, 6764 "Can't install because provider name " + names[j] 6765 + " (in package " + pkg.applicationInfo.packageName 6766 + ") is already used by " + otherPackageName); 6767 } 6768 } 6769 } 6770 } 6771 } 6772 6773 if (pkg.mAdoptPermissions != null) { 6774 // This package wants to adopt ownership of permissions from 6775 // another package. 6776 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6777 final String origName = pkg.mAdoptPermissions.get(i); 6778 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6779 if (orig != null) { 6780 if (verifyPackageUpdateLPr(orig, pkg)) { 6781 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6782 + pkg.packageName); 6783 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6784 } 6785 } 6786 } 6787 } 6788 } 6789 6790 final String pkgName = pkg.packageName; 6791 6792 final long scanFileTime = scanFile.lastModified(); 6793 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6794 pkg.applicationInfo.processName = fixProcessName( 6795 pkg.applicationInfo.packageName, 6796 pkg.applicationInfo.processName, 6797 pkg.applicationInfo.uid); 6798 6799 File dataPath; 6800 if (mPlatformPackage == pkg) { 6801 // The system package is special. 6802 dataPath = new File(Environment.getDataDirectory(), "system"); 6803 6804 pkg.applicationInfo.dataDir = dataPath.getPath(); 6805 6806 } else { 6807 // This is a normal package, need to make its data directory. 6808 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6809 UserHandle.USER_OWNER, pkg.packageName); 6810 6811 boolean uidError = false; 6812 if (dataPath.exists()) { 6813 int currentUid = 0; 6814 try { 6815 StructStat stat = Os.stat(dataPath.getPath()); 6816 currentUid = stat.st_uid; 6817 } catch (ErrnoException e) { 6818 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6819 } 6820 6821 // If we have mismatched owners for the data path, we have a problem. 6822 if (currentUid != pkg.applicationInfo.uid) { 6823 boolean recovered = false; 6824 if (currentUid == 0) { 6825 // The directory somehow became owned by root. Wow. 6826 // This is probably because the system was stopped while 6827 // installd was in the middle of messing with its libs 6828 // directory. Ask installd to fix that. 6829 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6830 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6831 if (ret >= 0) { 6832 recovered = true; 6833 String msg = "Package " + pkg.packageName 6834 + " unexpectedly changed to uid 0; recovered to " + 6835 + pkg.applicationInfo.uid; 6836 reportSettingsProblem(Log.WARN, msg); 6837 } 6838 } 6839 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6840 || (scanFlags&SCAN_BOOTING) != 0)) { 6841 // If this is a system app, we can at least delete its 6842 // current data so the application will still work. 6843 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6844 if (ret >= 0) { 6845 // TODO: Kill the processes first 6846 // Old data gone! 6847 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6848 ? "System package " : "Third party package "; 6849 String msg = prefix + pkg.packageName 6850 + " has changed from uid: " 6851 + currentUid + " to " 6852 + pkg.applicationInfo.uid + "; old data erased"; 6853 reportSettingsProblem(Log.WARN, msg); 6854 recovered = true; 6855 6856 // And now re-install the app. 6857 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6858 pkg.applicationInfo.seinfo); 6859 if (ret == -1) { 6860 // Ack should not happen! 6861 msg = prefix + pkg.packageName 6862 + " could not have data directory re-created after delete."; 6863 reportSettingsProblem(Log.WARN, msg); 6864 throw new PackageManagerException( 6865 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6866 } 6867 } 6868 if (!recovered) { 6869 mHasSystemUidErrors = true; 6870 } 6871 } else if (!recovered) { 6872 // If we allow this install to proceed, we will be broken. 6873 // Abort, abort! 6874 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6875 "scanPackageLI"); 6876 } 6877 if (!recovered) { 6878 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6879 + pkg.applicationInfo.uid + "/fs_" 6880 + currentUid; 6881 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6882 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6883 String msg = "Package " + pkg.packageName 6884 + " has mismatched uid: " 6885 + currentUid + " on disk, " 6886 + pkg.applicationInfo.uid + " in settings"; 6887 // writer 6888 synchronized (mPackages) { 6889 mSettings.mReadMessages.append(msg); 6890 mSettings.mReadMessages.append('\n'); 6891 uidError = true; 6892 if (!pkgSetting.uidError) { 6893 reportSettingsProblem(Log.ERROR, msg); 6894 } 6895 } 6896 } 6897 } 6898 pkg.applicationInfo.dataDir = dataPath.getPath(); 6899 if (mShouldRestoreconData) { 6900 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6901 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6902 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6903 } 6904 } else { 6905 if (DEBUG_PACKAGE_SCANNING) { 6906 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6907 Log.v(TAG, "Want this data dir: " + dataPath); 6908 } 6909 //invoke installer to do the actual installation 6910 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6911 pkg.applicationInfo.seinfo); 6912 if (ret < 0) { 6913 // Error from installer 6914 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6915 "Unable to create data dirs [errorCode=" + ret + "]"); 6916 } 6917 6918 if (dataPath.exists()) { 6919 pkg.applicationInfo.dataDir = dataPath.getPath(); 6920 } else { 6921 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6922 pkg.applicationInfo.dataDir = null; 6923 } 6924 } 6925 6926 pkgSetting.uidError = uidError; 6927 } 6928 6929 final String path = scanFile.getPath(); 6930 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6931 6932 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6933 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6934 6935 // Some system apps still use directory structure for native libraries 6936 // in which case we might end up not detecting abi solely based on apk 6937 // structure. Try to detect abi based on directory structure. 6938 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6939 pkg.applicationInfo.primaryCpuAbi == null) { 6940 setBundledAppAbisAndRoots(pkg, pkgSetting); 6941 setNativeLibraryPaths(pkg); 6942 } 6943 6944 } else { 6945 if ((scanFlags & SCAN_MOVE) != 0) { 6946 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6947 // but we already have this packages package info in the PackageSetting. We just 6948 // use that and derive the native library path based on the new codepath. 6949 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6950 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6951 } 6952 6953 // Set native library paths again. For moves, the path will be updated based on the 6954 // ABIs we've determined above. For non-moves, the path will be updated based on the 6955 // ABIs we determined during compilation, but the path will depend on the final 6956 // package path (after the rename away from the stage path). 6957 setNativeLibraryPaths(pkg); 6958 } 6959 6960 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6961 final int[] userIds = sUserManager.getUserIds(); 6962 synchronized (mInstallLock) { 6963 // Make sure all user data directories are ready to roll; we're okay 6964 // if they already exist 6965 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6966 for (int userId : userIds) { 6967 if (userId != 0) { 6968 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6969 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6970 pkg.applicationInfo.seinfo); 6971 } 6972 } 6973 } 6974 6975 // Create a native library symlink only if we have native libraries 6976 // and if the native libraries are 32 bit libraries. We do not provide 6977 // this symlink for 64 bit libraries. 6978 if (pkg.applicationInfo.primaryCpuAbi != null && 6979 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6980 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6981 for (int userId : userIds) { 6982 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6983 nativeLibPath, userId) < 0) { 6984 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6985 "Failed linking native library dir (user=" + userId + ")"); 6986 } 6987 } 6988 } 6989 } 6990 6991 // This is a special case for the "system" package, where the ABI is 6992 // dictated by the zygote configuration (and init.rc). We should keep track 6993 // of this ABI so that we can deal with "normal" applications that run under 6994 // the same UID correctly. 6995 if (mPlatformPackage == pkg) { 6996 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6997 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6998 } 6999 7000 // If there's a mismatch between the abi-override in the package setting 7001 // and the abiOverride specified for the install. Warn about this because we 7002 // would've already compiled the app without taking the package setting into 7003 // account. 7004 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7005 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7006 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7007 " for package: " + pkg.packageName); 7008 } 7009 } 7010 7011 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7012 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7013 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7014 7015 // Copy the derived override back to the parsed package, so that we can 7016 // update the package settings accordingly. 7017 pkg.cpuAbiOverride = cpuAbiOverride; 7018 7019 if (DEBUG_ABI_SELECTION) { 7020 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7021 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7022 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7023 } 7024 7025 // Push the derived path down into PackageSettings so we know what to 7026 // clean up at uninstall time. 7027 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7028 7029 if (DEBUG_ABI_SELECTION) { 7030 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7031 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7032 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7033 } 7034 7035 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7036 // We don't do this here during boot because we can do it all 7037 // at once after scanning all existing packages. 7038 // 7039 // We also do this *before* we perform dexopt on this package, so that 7040 // we can avoid redundant dexopts, and also to make sure we've got the 7041 // code and package path correct. 7042 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7043 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7044 } 7045 7046 if ((scanFlags & SCAN_NO_DEX) == 0) { 7047 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7048 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7049 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7050 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7051 } 7052 } 7053 if (mFactoryTest && pkg.requestedPermissions.contains( 7054 android.Manifest.permission.FACTORY_TEST)) { 7055 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7056 } 7057 7058 ArrayList<PackageParser.Package> clientLibPkgs = null; 7059 7060 // writer 7061 synchronized (mPackages) { 7062 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7063 // Only system apps can add new shared libraries. 7064 if (pkg.libraryNames != null) { 7065 for (int i=0; i<pkg.libraryNames.size(); i++) { 7066 String name = pkg.libraryNames.get(i); 7067 boolean allowed = false; 7068 if (pkg.isUpdatedSystemApp()) { 7069 // New library entries can only be added through the 7070 // system image. This is important to get rid of a lot 7071 // of nasty edge cases: for example if we allowed a non- 7072 // system update of the app to add a library, then uninstalling 7073 // the update would make the library go away, and assumptions 7074 // we made such as through app install filtering would now 7075 // have allowed apps on the device which aren't compatible 7076 // with it. Better to just have the restriction here, be 7077 // conservative, and create many fewer cases that can negatively 7078 // impact the user experience. 7079 final PackageSetting sysPs = mSettings 7080 .getDisabledSystemPkgLPr(pkg.packageName); 7081 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7082 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7083 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7084 allowed = true; 7085 allowed = true; 7086 break; 7087 } 7088 } 7089 } 7090 } else { 7091 allowed = true; 7092 } 7093 if (allowed) { 7094 if (!mSharedLibraries.containsKey(name)) { 7095 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7096 } else if (!name.equals(pkg.packageName)) { 7097 Slog.w(TAG, "Package " + pkg.packageName + " library " 7098 + name + " already exists; skipping"); 7099 } 7100 } else { 7101 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7102 + name + " that is not declared on system image; skipping"); 7103 } 7104 } 7105 if ((scanFlags&SCAN_BOOTING) == 0) { 7106 // If we are not booting, we need to update any applications 7107 // that are clients of our shared library. If we are booting, 7108 // this will all be done once the scan is complete. 7109 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7110 } 7111 } 7112 } 7113 } 7114 7115 // We also need to dexopt any apps that are dependent on this library. Note that 7116 // if these fail, we should abort the install since installing the library will 7117 // result in some apps being broken. 7118 if (clientLibPkgs != null) { 7119 if ((scanFlags & SCAN_NO_DEX) == 0) { 7120 for (int i = 0; i < clientLibPkgs.size(); i++) { 7121 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7122 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7123 null /* instruction sets */, forceDex, 7124 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7125 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7126 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7127 "scanPackageLI failed to dexopt clientLibPkgs"); 7128 } 7129 } 7130 } 7131 } 7132 7133 // Request the ActivityManager to kill the process(only for existing packages) 7134 // so that we do not end up in a confused state while the user is still using the older 7135 // version of the application while the new one gets installed. 7136 if ((scanFlags & SCAN_REPLACING) != 0) { 7137 killApplication(pkg.applicationInfo.packageName, 7138 pkg.applicationInfo.uid, "replace pkg"); 7139 } 7140 7141 // Also need to kill any apps that are dependent on the library. 7142 if (clientLibPkgs != null) { 7143 for (int i=0; i<clientLibPkgs.size(); i++) { 7144 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7145 killApplication(clientPkg.applicationInfo.packageName, 7146 clientPkg.applicationInfo.uid, "update lib"); 7147 } 7148 } 7149 7150 // Make sure we're not adding any bogus keyset info 7151 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7152 ksms.assertScannedPackageValid(pkg); 7153 7154 // writer 7155 synchronized (mPackages) { 7156 // We don't expect installation to fail beyond this point 7157 7158 // Add the new setting to mSettings 7159 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7160 // Add the new setting to mPackages 7161 mPackages.put(pkg.applicationInfo.packageName, pkg); 7162 // Make sure we don't accidentally delete its data. 7163 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7164 while (iter.hasNext()) { 7165 PackageCleanItem item = iter.next(); 7166 if (pkgName.equals(item.packageName)) { 7167 iter.remove(); 7168 } 7169 } 7170 7171 // Take care of first install / last update times. 7172 if (currentTime != 0) { 7173 if (pkgSetting.firstInstallTime == 0) { 7174 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7175 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7176 pkgSetting.lastUpdateTime = currentTime; 7177 } 7178 } else if (pkgSetting.firstInstallTime == 0) { 7179 // We need *something*. Take time time stamp of the file. 7180 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7181 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7182 if (scanFileTime != pkgSetting.timeStamp) { 7183 // A package on the system image has changed; consider this 7184 // to be an update. 7185 pkgSetting.lastUpdateTime = scanFileTime; 7186 } 7187 } 7188 7189 // Add the package's KeySets to the global KeySetManagerService 7190 ksms.addScannedPackageLPw(pkg); 7191 7192 int N = pkg.providers.size(); 7193 StringBuilder r = null; 7194 int i; 7195 for (i=0; i<N; i++) { 7196 PackageParser.Provider p = pkg.providers.get(i); 7197 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7198 p.info.processName, pkg.applicationInfo.uid); 7199 mProviders.addProvider(p); 7200 p.syncable = p.info.isSyncable; 7201 if (p.info.authority != null) { 7202 String names[] = p.info.authority.split(";"); 7203 p.info.authority = null; 7204 for (int j = 0; j < names.length; j++) { 7205 if (j == 1 && p.syncable) { 7206 // We only want the first authority for a provider to possibly be 7207 // syncable, so if we already added this provider using a different 7208 // authority clear the syncable flag. We copy the provider before 7209 // changing it because the mProviders object contains a reference 7210 // to a provider that we don't want to change. 7211 // Only do this for the second authority since the resulting provider 7212 // object can be the same for all future authorities for this provider. 7213 p = new PackageParser.Provider(p); 7214 p.syncable = false; 7215 } 7216 if (!mProvidersByAuthority.containsKey(names[j])) { 7217 mProvidersByAuthority.put(names[j], p); 7218 if (p.info.authority == null) { 7219 p.info.authority = names[j]; 7220 } else { 7221 p.info.authority = p.info.authority + ";" + names[j]; 7222 } 7223 if (DEBUG_PACKAGE_SCANNING) { 7224 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7225 Log.d(TAG, "Registered content provider: " + names[j] 7226 + ", className = " + p.info.name + ", isSyncable = " 7227 + p.info.isSyncable); 7228 } 7229 } else { 7230 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7231 Slog.w(TAG, "Skipping provider name " + names[j] + 7232 " (in package " + pkg.applicationInfo.packageName + 7233 "): name already used by " 7234 + ((other != null && other.getComponentName() != null) 7235 ? other.getComponentName().getPackageName() : "?")); 7236 } 7237 } 7238 } 7239 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7240 if (r == null) { 7241 r = new StringBuilder(256); 7242 } else { 7243 r.append(' '); 7244 } 7245 r.append(p.info.name); 7246 } 7247 } 7248 if (r != null) { 7249 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7250 } 7251 7252 N = pkg.services.size(); 7253 r = null; 7254 for (i=0; i<N; i++) { 7255 PackageParser.Service s = pkg.services.get(i); 7256 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7257 s.info.processName, pkg.applicationInfo.uid); 7258 mServices.addService(s); 7259 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7260 if (r == null) { 7261 r = new StringBuilder(256); 7262 } else { 7263 r.append(' '); 7264 } 7265 r.append(s.info.name); 7266 } 7267 } 7268 if (r != null) { 7269 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7270 } 7271 7272 N = pkg.receivers.size(); 7273 r = null; 7274 for (i=0; i<N; i++) { 7275 PackageParser.Activity a = pkg.receivers.get(i); 7276 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7277 a.info.processName, pkg.applicationInfo.uid); 7278 mReceivers.addActivity(a, "receiver"); 7279 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7280 if (r == null) { 7281 r = new StringBuilder(256); 7282 } else { 7283 r.append(' '); 7284 } 7285 r.append(a.info.name); 7286 } 7287 } 7288 if (r != null) { 7289 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7290 } 7291 7292 N = pkg.activities.size(); 7293 r = null; 7294 for (i=0; i<N; i++) { 7295 PackageParser.Activity a = pkg.activities.get(i); 7296 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7297 a.info.processName, pkg.applicationInfo.uid); 7298 mActivities.addActivity(a, "activity"); 7299 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7300 if (r == null) { 7301 r = new StringBuilder(256); 7302 } else { 7303 r.append(' '); 7304 } 7305 r.append(a.info.name); 7306 } 7307 } 7308 if (r != null) { 7309 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7310 } 7311 7312 N = pkg.permissionGroups.size(); 7313 r = null; 7314 for (i=0; i<N; i++) { 7315 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7316 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7317 if (cur == null) { 7318 mPermissionGroups.put(pg.info.name, pg); 7319 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7320 if (r == null) { 7321 r = new StringBuilder(256); 7322 } else { 7323 r.append(' '); 7324 } 7325 r.append(pg.info.name); 7326 } 7327 } else { 7328 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7329 + pg.info.packageName + " ignored: original from " 7330 + cur.info.packageName); 7331 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(pg.info.name); 7339 } 7340 } 7341 } 7342 if (r != null) { 7343 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7344 } 7345 7346 N = pkg.permissions.size(); 7347 r = null; 7348 for (i=0; i<N; i++) { 7349 PackageParser.Permission p = pkg.permissions.get(i); 7350 7351 // Assume by default that we did not install this permission into the system. 7352 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7353 7354 // Now that permission groups have a special meaning, we ignore permission 7355 // groups for legacy apps to prevent unexpected behavior. In particular, 7356 // permissions for one app being granted to someone just becuase they happen 7357 // to be in a group defined by another app (before this had no implications). 7358 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7359 p.group = mPermissionGroups.get(p.info.group); 7360 // Warn for a permission in an unknown group. 7361 if (p.info.group != null && p.group == null) { 7362 Slog.w(TAG, "Permission " + p.info.name + " from package " 7363 + p.info.packageName + " in an unknown group " + p.info.group); 7364 } 7365 } 7366 7367 ArrayMap<String, BasePermission> permissionMap = 7368 p.tree ? mSettings.mPermissionTrees 7369 : mSettings.mPermissions; 7370 BasePermission bp = permissionMap.get(p.info.name); 7371 7372 // Allow system apps to redefine non-system permissions 7373 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7374 final boolean currentOwnerIsSystem = (bp.perm != null 7375 && isSystemApp(bp.perm.owner)); 7376 if (isSystemApp(p.owner)) { 7377 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7378 // It's a built-in permission and no owner, take ownership now 7379 bp.packageSetting = pkgSetting; 7380 bp.perm = p; 7381 bp.uid = pkg.applicationInfo.uid; 7382 bp.sourcePackage = p.info.packageName; 7383 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7384 } else if (!currentOwnerIsSystem) { 7385 String msg = "New decl " + p.owner + " of permission " 7386 + p.info.name + " is system; overriding " + bp.sourcePackage; 7387 reportSettingsProblem(Log.WARN, msg); 7388 bp = null; 7389 } 7390 } 7391 } 7392 7393 if (bp == null) { 7394 bp = new BasePermission(p.info.name, p.info.packageName, 7395 BasePermission.TYPE_NORMAL); 7396 permissionMap.put(p.info.name, bp); 7397 } 7398 7399 if (bp.perm == null) { 7400 if (bp.sourcePackage == null 7401 || bp.sourcePackage.equals(p.info.packageName)) { 7402 BasePermission tree = findPermissionTreeLP(p.info.name); 7403 if (tree == null 7404 || tree.sourcePackage.equals(p.info.packageName)) { 7405 bp.packageSetting = pkgSetting; 7406 bp.perm = p; 7407 bp.uid = pkg.applicationInfo.uid; 7408 bp.sourcePackage = p.info.packageName; 7409 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7410 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7411 if (r == null) { 7412 r = new StringBuilder(256); 7413 } else { 7414 r.append(' '); 7415 } 7416 r.append(p.info.name); 7417 } 7418 } else { 7419 Slog.w(TAG, "Permission " + p.info.name + " from package " 7420 + p.info.packageName + " ignored: base tree " 7421 + tree.name + " is from package " 7422 + tree.sourcePackage); 7423 } 7424 } else { 7425 Slog.w(TAG, "Permission " + p.info.name + " from package " 7426 + p.info.packageName + " ignored: original from " 7427 + bp.sourcePackage); 7428 } 7429 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7430 if (r == null) { 7431 r = new StringBuilder(256); 7432 } else { 7433 r.append(' '); 7434 } 7435 r.append("DUP:"); 7436 r.append(p.info.name); 7437 } 7438 if (bp.perm == p) { 7439 bp.protectionLevel = p.info.protectionLevel; 7440 } 7441 } 7442 7443 if (r != null) { 7444 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7445 } 7446 7447 N = pkg.instrumentation.size(); 7448 r = null; 7449 for (i=0; i<N; i++) { 7450 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7451 a.info.packageName = pkg.applicationInfo.packageName; 7452 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7453 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7454 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7455 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7456 a.info.dataDir = pkg.applicationInfo.dataDir; 7457 7458 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7459 // need other information about the application, like the ABI and what not ? 7460 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7461 mInstrumentation.put(a.getComponentName(), a); 7462 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7463 if (r == null) { 7464 r = new StringBuilder(256); 7465 } else { 7466 r.append(' '); 7467 } 7468 r.append(a.info.name); 7469 } 7470 } 7471 if (r != null) { 7472 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7473 } 7474 7475 if (pkg.protectedBroadcasts != null) { 7476 N = pkg.protectedBroadcasts.size(); 7477 for (i=0; i<N; i++) { 7478 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7479 } 7480 } 7481 7482 pkgSetting.setTimeStamp(scanFileTime); 7483 7484 // Create idmap files for pairs of (packages, overlay packages). 7485 // Note: "android", ie framework-res.apk, is handled by native layers. 7486 if (pkg.mOverlayTarget != null) { 7487 // This is an overlay package. 7488 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7489 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7490 mOverlays.put(pkg.mOverlayTarget, 7491 new ArrayMap<String, PackageParser.Package>()); 7492 } 7493 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7494 map.put(pkg.packageName, pkg); 7495 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7496 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7497 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7498 "scanPackageLI failed to createIdmap"); 7499 } 7500 } 7501 } else if (mOverlays.containsKey(pkg.packageName) && 7502 !pkg.packageName.equals("android")) { 7503 // This is a regular package, with one or more known overlay packages. 7504 createIdmapsForPackageLI(pkg); 7505 } 7506 } 7507 7508 return pkg; 7509 } 7510 7511 /** 7512 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7513 * is derived purely on the basis of the contents of {@code scanFile} and 7514 * {@code cpuAbiOverride}. 7515 * 7516 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7517 */ 7518 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7519 String cpuAbiOverride, boolean extractLibs) 7520 throws PackageManagerException { 7521 // TODO: We can probably be smarter about this stuff. For installed apps, 7522 // we can calculate this information at install time once and for all. For 7523 // system apps, we can probably assume that this information doesn't change 7524 // after the first boot scan. As things stand, we do lots of unnecessary work. 7525 7526 // Give ourselves some initial paths; we'll come back for another 7527 // pass once we've determined ABI below. 7528 setNativeLibraryPaths(pkg); 7529 7530 // We would never need to extract libs for forward-locked and external packages, 7531 // since the container service will do it for us. We shouldn't attempt to 7532 // extract libs from system app when it was not updated. 7533 if (pkg.isForwardLocked() || isExternal(pkg) || 7534 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7535 extractLibs = false; 7536 } 7537 7538 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7539 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7540 7541 NativeLibraryHelper.Handle handle = null; 7542 try { 7543 handle = NativeLibraryHelper.Handle.create(pkg); 7544 // TODO(multiArch): This can be null for apps that didn't go through the 7545 // usual installation process. We can calculate it again, like we 7546 // do during install time. 7547 // 7548 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7549 // unnecessary. 7550 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7551 7552 // Null out the abis so that they can be recalculated. 7553 pkg.applicationInfo.primaryCpuAbi = null; 7554 pkg.applicationInfo.secondaryCpuAbi = null; 7555 if (isMultiArch(pkg.applicationInfo)) { 7556 // Warn if we've set an abiOverride for multi-lib packages.. 7557 // By definition, we need to copy both 32 and 64 bit libraries for 7558 // such packages. 7559 if (pkg.cpuAbiOverride != null 7560 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7561 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7562 } 7563 7564 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7565 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7566 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7567 if (extractLibs) { 7568 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7569 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7570 useIsaSpecificSubdirs); 7571 } else { 7572 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7573 } 7574 } 7575 7576 maybeThrowExceptionForMultiArchCopy( 7577 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7578 7579 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7580 if (extractLibs) { 7581 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7582 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7583 useIsaSpecificSubdirs); 7584 } else { 7585 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7586 } 7587 } 7588 7589 maybeThrowExceptionForMultiArchCopy( 7590 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7591 7592 if (abi64 >= 0) { 7593 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7594 } 7595 7596 if (abi32 >= 0) { 7597 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7598 if (abi64 >= 0) { 7599 pkg.applicationInfo.secondaryCpuAbi = abi; 7600 } else { 7601 pkg.applicationInfo.primaryCpuAbi = abi; 7602 } 7603 } 7604 } else { 7605 String[] abiList = (cpuAbiOverride != null) ? 7606 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7607 7608 // Enable gross and lame hacks for apps that are built with old 7609 // SDK tools. We must scan their APKs for renderscript bitcode and 7610 // not launch them if it's present. Don't bother checking on devices 7611 // that don't have 64 bit support. 7612 boolean needsRenderScriptOverride = false; 7613 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7614 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7615 abiList = Build.SUPPORTED_32_BIT_ABIS; 7616 needsRenderScriptOverride = true; 7617 } 7618 7619 final int copyRet; 7620 if (extractLibs) { 7621 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7622 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7623 } else { 7624 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7625 } 7626 7627 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7628 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7629 "Error unpackaging native libs for app, errorCode=" + copyRet); 7630 } 7631 7632 if (copyRet >= 0) { 7633 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7634 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7635 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7636 } else if (needsRenderScriptOverride) { 7637 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7638 } 7639 } 7640 } catch (IOException ioe) { 7641 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7642 } finally { 7643 IoUtils.closeQuietly(handle); 7644 } 7645 7646 // Now that we've calculated the ABIs and determined if it's an internal app, 7647 // we will go ahead and populate the nativeLibraryPath. 7648 setNativeLibraryPaths(pkg); 7649 } 7650 7651 /** 7652 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7653 * i.e, so that all packages can be run inside a single process if required. 7654 * 7655 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7656 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7657 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7658 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7659 * updating a package that belongs to a shared user. 7660 * 7661 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7662 * adds unnecessary complexity. 7663 */ 7664 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7665 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7666 String requiredInstructionSet = null; 7667 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7668 requiredInstructionSet = VMRuntime.getInstructionSet( 7669 scannedPackage.applicationInfo.primaryCpuAbi); 7670 } 7671 7672 PackageSetting requirer = null; 7673 for (PackageSetting ps : packagesForUser) { 7674 // If packagesForUser contains scannedPackage, we skip it. This will happen 7675 // when scannedPackage is an update of an existing package. Without this check, 7676 // we will never be able to change the ABI of any package belonging to a shared 7677 // user, even if it's compatible with other packages. 7678 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7679 if (ps.primaryCpuAbiString == null) { 7680 continue; 7681 } 7682 7683 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7684 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7685 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7686 // this but there's not much we can do. 7687 String errorMessage = "Instruction set mismatch, " 7688 + ((requirer == null) ? "[caller]" : requirer) 7689 + " requires " + requiredInstructionSet + " whereas " + ps 7690 + " requires " + instructionSet; 7691 Slog.w(TAG, errorMessage); 7692 } 7693 7694 if (requiredInstructionSet == null) { 7695 requiredInstructionSet = instructionSet; 7696 requirer = ps; 7697 } 7698 } 7699 } 7700 7701 if (requiredInstructionSet != null) { 7702 String adjustedAbi; 7703 if (requirer != null) { 7704 // requirer != null implies that either scannedPackage was null or that scannedPackage 7705 // did not require an ABI, in which case we have to adjust scannedPackage to match 7706 // the ABI of the set (which is the same as requirer's ABI) 7707 adjustedAbi = requirer.primaryCpuAbiString; 7708 if (scannedPackage != null) { 7709 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7710 } 7711 } else { 7712 // requirer == null implies that we're updating all ABIs in the set to 7713 // match scannedPackage. 7714 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7715 } 7716 7717 for (PackageSetting ps : packagesForUser) { 7718 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7719 if (ps.primaryCpuAbiString != null) { 7720 continue; 7721 } 7722 7723 ps.primaryCpuAbiString = adjustedAbi; 7724 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7725 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7726 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7727 7728 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7729 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7730 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7731 ps.primaryCpuAbiString = null; 7732 ps.pkg.applicationInfo.primaryCpuAbi = null; 7733 return; 7734 } else { 7735 mInstaller.rmdex(ps.codePathString, 7736 getDexCodeInstructionSet(getPreferredInstructionSet())); 7737 } 7738 } 7739 } 7740 } 7741 } 7742 } 7743 7744 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7745 synchronized (mPackages) { 7746 mResolverReplaced = true; 7747 // Set up information for custom user intent resolution activity. 7748 mResolveActivity.applicationInfo = pkg.applicationInfo; 7749 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7750 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7751 mResolveActivity.processName = pkg.applicationInfo.packageName; 7752 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7753 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7754 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7755 mResolveActivity.theme = 0; 7756 mResolveActivity.exported = true; 7757 mResolveActivity.enabled = true; 7758 mResolveInfo.activityInfo = mResolveActivity; 7759 mResolveInfo.priority = 0; 7760 mResolveInfo.preferredOrder = 0; 7761 mResolveInfo.match = 0; 7762 mResolveComponentName = mCustomResolverComponentName; 7763 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7764 mResolveComponentName); 7765 } 7766 } 7767 7768 private static String calculateBundledApkRoot(final String codePathString) { 7769 final File codePath = new File(codePathString); 7770 final File codeRoot; 7771 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7772 codeRoot = Environment.getRootDirectory(); 7773 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7774 codeRoot = Environment.getOemDirectory(); 7775 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7776 codeRoot = Environment.getVendorDirectory(); 7777 } else { 7778 // Unrecognized code path; take its top real segment as the apk root: 7779 // e.g. /something/app/blah.apk => /something 7780 try { 7781 File f = codePath.getCanonicalFile(); 7782 File parent = f.getParentFile(); // non-null because codePath is a file 7783 File tmp; 7784 while ((tmp = parent.getParentFile()) != null) { 7785 f = parent; 7786 parent = tmp; 7787 } 7788 codeRoot = f; 7789 Slog.w(TAG, "Unrecognized code path " 7790 + codePath + " - using " + codeRoot); 7791 } catch (IOException e) { 7792 // Can't canonicalize the code path -- shenanigans? 7793 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7794 return Environment.getRootDirectory().getPath(); 7795 } 7796 } 7797 return codeRoot.getPath(); 7798 } 7799 7800 /** 7801 * Derive and set the location of native libraries for the given package, 7802 * which varies depending on where and how the package was installed. 7803 */ 7804 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7805 final ApplicationInfo info = pkg.applicationInfo; 7806 final String codePath = pkg.codePath; 7807 final File codeFile = new File(codePath); 7808 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7809 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7810 7811 info.nativeLibraryRootDir = null; 7812 info.nativeLibraryRootRequiresIsa = false; 7813 info.nativeLibraryDir = null; 7814 info.secondaryNativeLibraryDir = null; 7815 7816 if (isApkFile(codeFile)) { 7817 // Monolithic install 7818 if (bundledApp) { 7819 // If "/system/lib64/apkname" exists, assume that is the per-package 7820 // native library directory to use; otherwise use "/system/lib/apkname". 7821 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7822 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7823 getPrimaryInstructionSet(info)); 7824 7825 // This is a bundled system app so choose the path based on the ABI. 7826 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7827 // is just the default path. 7828 final String apkName = deriveCodePathName(codePath); 7829 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7830 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7831 apkName).getAbsolutePath(); 7832 7833 if (info.secondaryCpuAbi != null) { 7834 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7835 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7836 secondaryLibDir, apkName).getAbsolutePath(); 7837 } 7838 } else if (asecApp) { 7839 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7840 .getAbsolutePath(); 7841 } else { 7842 final String apkName = deriveCodePathName(codePath); 7843 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7844 .getAbsolutePath(); 7845 } 7846 7847 info.nativeLibraryRootRequiresIsa = false; 7848 info.nativeLibraryDir = info.nativeLibraryRootDir; 7849 } else { 7850 // Cluster install 7851 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7852 info.nativeLibraryRootRequiresIsa = true; 7853 7854 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7855 getPrimaryInstructionSet(info)).getAbsolutePath(); 7856 7857 if (info.secondaryCpuAbi != null) { 7858 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7859 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7860 } 7861 } 7862 } 7863 7864 /** 7865 * Calculate the abis and roots for a bundled app. These can uniquely 7866 * be determined from the contents of the system partition, i.e whether 7867 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7868 * of this information, and instead assume that the system was built 7869 * sensibly. 7870 */ 7871 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7872 PackageSetting pkgSetting) { 7873 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7874 7875 // If "/system/lib64/apkname" exists, assume that is the per-package 7876 // native library directory to use; otherwise use "/system/lib/apkname". 7877 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7878 setBundledAppAbi(pkg, apkRoot, apkName); 7879 // pkgSetting might be null during rescan following uninstall of updates 7880 // to a bundled app, so accommodate that possibility. The settings in 7881 // that case will be established later from the parsed package. 7882 // 7883 // If the settings aren't null, sync them up with what we've just derived. 7884 // note that apkRoot isn't stored in the package settings. 7885 if (pkgSetting != null) { 7886 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7887 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7888 } 7889 } 7890 7891 /** 7892 * Deduces the ABI of a bundled app and sets the relevant fields on the 7893 * parsed pkg object. 7894 * 7895 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7896 * under which system libraries are installed. 7897 * @param apkName the name of the installed package. 7898 */ 7899 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7900 final File codeFile = new File(pkg.codePath); 7901 7902 final boolean has64BitLibs; 7903 final boolean has32BitLibs; 7904 if (isApkFile(codeFile)) { 7905 // Monolithic install 7906 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7907 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7908 } else { 7909 // Cluster install 7910 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7911 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7912 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7913 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7914 has64BitLibs = (new File(rootDir, isa)).exists(); 7915 } else { 7916 has64BitLibs = false; 7917 } 7918 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7919 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7920 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7921 has32BitLibs = (new File(rootDir, isa)).exists(); 7922 } else { 7923 has32BitLibs = false; 7924 } 7925 } 7926 7927 if (has64BitLibs && !has32BitLibs) { 7928 // The package has 64 bit libs, but not 32 bit libs. Its primary 7929 // ABI should be 64 bit. We can safely assume here that the bundled 7930 // native libraries correspond to the most preferred ABI in the list. 7931 7932 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7933 pkg.applicationInfo.secondaryCpuAbi = null; 7934 } else if (has32BitLibs && !has64BitLibs) { 7935 // The package has 32 bit libs but not 64 bit libs. Its primary 7936 // ABI should be 32 bit. 7937 7938 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7939 pkg.applicationInfo.secondaryCpuAbi = null; 7940 } else if (has32BitLibs && has64BitLibs) { 7941 // The application has both 64 and 32 bit bundled libraries. We check 7942 // here that the app declares multiArch support, and warn if it doesn't. 7943 // 7944 // We will be lenient here and record both ABIs. The primary will be the 7945 // ABI that's higher on the list, i.e, a device that's configured to prefer 7946 // 64 bit apps will see a 64 bit primary ABI, 7947 7948 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7949 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7950 } 7951 7952 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7953 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7954 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7955 } else { 7956 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7957 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7958 } 7959 } else { 7960 pkg.applicationInfo.primaryCpuAbi = null; 7961 pkg.applicationInfo.secondaryCpuAbi = null; 7962 } 7963 } 7964 7965 private void killApplication(String pkgName, int appId, String reason) { 7966 // Request the ActivityManager to kill the process(only for existing packages) 7967 // so that we do not end up in a confused state while the user is still using the older 7968 // version of the application while the new one gets installed. 7969 IActivityManager am = ActivityManagerNative.getDefault(); 7970 if (am != null) { 7971 try { 7972 am.killApplicationWithAppId(pkgName, appId, reason); 7973 } catch (RemoteException e) { 7974 } 7975 } 7976 } 7977 7978 void removePackageLI(PackageSetting ps, boolean chatty) { 7979 if (DEBUG_INSTALL) { 7980 if (chatty) 7981 Log.d(TAG, "Removing package " + ps.name); 7982 } 7983 7984 // writer 7985 synchronized (mPackages) { 7986 mPackages.remove(ps.name); 7987 final PackageParser.Package pkg = ps.pkg; 7988 if (pkg != null) { 7989 cleanPackageDataStructuresLILPw(pkg, chatty); 7990 } 7991 } 7992 } 7993 7994 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7995 if (DEBUG_INSTALL) { 7996 if (chatty) 7997 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7998 } 7999 8000 // writer 8001 synchronized (mPackages) { 8002 mPackages.remove(pkg.applicationInfo.packageName); 8003 cleanPackageDataStructuresLILPw(pkg, chatty); 8004 } 8005 } 8006 8007 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8008 int N = pkg.providers.size(); 8009 StringBuilder r = null; 8010 int i; 8011 for (i=0; i<N; i++) { 8012 PackageParser.Provider p = pkg.providers.get(i); 8013 mProviders.removeProvider(p); 8014 if (p.info.authority == null) { 8015 8016 /* There was another ContentProvider with this authority when 8017 * this app was installed so this authority is null, 8018 * Ignore it as we don't have to unregister the provider. 8019 */ 8020 continue; 8021 } 8022 String names[] = p.info.authority.split(";"); 8023 for (int j = 0; j < names.length; j++) { 8024 if (mProvidersByAuthority.get(names[j]) == p) { 8025 mProvidersByAuthority.remove(names[j]); 8026 if (DEBUG_REMOVE) { 8027 if (chatty) 8028 Log.d(TAG, "Unregistered content provider: " + names[j] 8029 + ", className = " + p.info.name + ", isSyncable = " 8030 + p.info.isSyncable); 8031 } 8032 } 8033 } 8034 if (DEBUG_REMOVE && chatty) { 8035 if (r == null) { 8036 r = new StringBuilder(256); 8037 } else { 8038 r.append(' '); 8039 } 8040 r.append(p.info.name); 8041 } 8042 } 8043 if (r != null) { 8044 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8045 } 8046 8047 N = pkg.services.size(); 8048 r = null; 8049 for (i=0; i<N; i++) { 8050 PackageParser.Service s = pkg.services.get(i); 8051 mServices.removeService(s); 8052 if (chatty) { 8053 if (r == null) { 8054 r = new StringBuilder(256); 8055 } else { 8056 r.append(' '); 8057 } 8058 r.append(s.info.name); 8059 } 8060 } 8061 if (r != null) { 8062 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8063 } 8064 8065 N = pkg.receivers.size(); 8066 r = null; 8067 for (i=0; i<N; i++) { 8068 PackageParser.Activity a = pkg.receivers.get(i); 8069 mReceivers.removeActivity(a, "receiver"); 8070 if (DEBUG_REMOVE && chatty) { 8071 if (r == null) { 8072 r = new StringBuilder(256); 8073 } else { 8074 r.append(' '); 8075 } 8076 r.append(a.info.name); 8077 } 8078 } 8079 if (r != null) { 8080 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8081 } 8082 8083 N = pkg.activities.size(); 8084 r = null; 8085 for (i=0; i<N; i++) { 8086 PackageParser.Activity a = pkg.activities.get(i); 8087 mActivities.removeActivity(a, "activity"); 8088 if (DEBUG_REMOVE && chatty) { 8089 if (r == null) { 8090 r = new StringBuilder(256); 8091 } else { 8092 r.append(' '); 8093 } 8094 r.append(a.info.name); 8095 } 8096 } 8097 if (r != null) { 8098 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8099 } 8100 8101 N = pkg.permissions.size(); 8102 r = null; 8103 for (i=0; i<N; i++) { 8104 PackageParser.Permission p = pkg.permissions.get(i); 8105 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8106 if (bp == null) { 8107 bp = mSettings.mPermissionTrees.get(p.info.name); 8108 } 8109 if (bp != null && bp.perm == p) { 8110 bp.perm = null; 8111 if (DEBUG_REMOVE && chatty) { 8112 if (r == null) { 8113 r = new StringBuilder(256); 8114 } else { 8115 r.append(' '); 8116 } 8117 r.append(p.info.name); 8118 } 8119 } 8120 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8121 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8122 if (appOpPerms != null) { 8123 appOpPerms.remove(pkg.packageName); 8124 } 8125 } 8126 } 8127 if (r != null) { 8128 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8129 } 8130 8131 N = pkg.requestedPermissions.size(); 8132 r = null; 8133 for (i=0; i<N; i++) { 8134 String perm = pkg.requestedPermissions.get(i); 8135 BasePermission bp = mSettings.mPermissions.get(perm); 8136 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8137 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8138 if (appOpPerms != null) { 8139 appOpPerms.remove(pkg.packageName); 8140 if (appOpPerms.isEmpty()) { 8141 mAppOpPermissionPackages.remove(perm); 8142 } 8143 } 8144 } 8145 } 8146 if (r != null) { 8147 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8148 } 8149 8150 N = pkg.instrumentation.size(); 8151 r = null; 8152 for (i=0; i<N; i++) { 8153 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8154 mInstrumentation.remove(a.getComponentName()); 8155 if (DEBUG_REMOVE && chatty) { 8156 if (r == null) { 8157 r = new StringBuilder(256); 8158 } else { 8159 r.append(' '); 8160 } 8161 r.append(a.info.name); 8162 } 8163 } 8164 if (r != null) { 8165 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8166 } 8167 8168 r = null; 8169 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8170 // Only system apps can hold shared libraries. 8171 if (pkg.libraryNames != null) { 8172 for (i=0; i<pkg.libraryNames.size(); i++) { 8173 String name = pkg.libraryNames.get(i); 8174 SharedLibraryEntry cur = mSharedLibraries.get(name); 8175 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8176 mSharedLibraries.remove(name); 8177 if (DEBUG_REMOVE && chatty) { 8178 if (r == null) { 8179 r = new StringBuilder(256); 8180 } else { 8181 r.append(' '); 8182 } 8183 r.append(name); 8184 } 8185 } 8186 } 8187 } 8188 } 8189 if (r != null) { 8190 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8191 } 8192 } 8193 8194 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8195 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8196 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8197 return true; 8198 } 8199 } 8200 return false; 8201 } 8202 8203 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8204 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8205 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8206 8207 private void updatePermissionsLPw(String changingPkg, 8208 PackageParser.Package pkgInfo, int flags) { 8209 // Make sure there are no dangling permission trees. 8210 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8211 while (it.hasNext()) { 8212 final BasePermission bp = it.next(); 8213 if (bp.packageSetting == null) { 8214 // We may not yet have parsed the package, so just see if 8215 // we still know about its settings. 8216 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8217 } 8218 if (bp.packageSetting == null) { 8219 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8220 + " from package " + bp.sourcePackage); 8221 it.remove(); 8222 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8223 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8224 Slog.i(TAG, "Removing old permission tree: " + bp.name 8225 + " from package " + bp.sourcePackage); 8226 flags |= UPDATE_PERMISSIONS_ALL; 8227 it.remove(); 8228 } 8229 } 8230 } 8231 8232 // Make sure all dynamic permissions have been assigned to a package, 8233 // and make sure there are no dangling permissions. 8234 it = mSettings.mPermissions.values().iterator(); 8235 while (it.hasNext()) { 8236 final BasePermission bp = it.next(); 8237 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8238 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8239 + bp.name + " pkg=" + bp.sourcePackage 8240 + " info=" + bp.pendingInfo); 8241 if (bp.packageSetting == null && bp.pendingInfo != null) { 8242 final BasePermission tree = findPermissionTreeLP(bp.name); 8243 if (tree != null && tree.perm != null) { 8244 bp.packageSetting = tree.packageSetting; 8245 bp.perm = new PackageParser.Permission(tree.perm.owner, 8246 new PermissionInfo(bp.pendingInfo)); 8247 bp.perm.info.packageName = tree.perm.info.packageName; 8248 bp.perm.info.name = bp.name; 8249 bp.uid = tree.uid; 8250 } 8251 } 8252 } 8253 if (bp.packageSetting == null) { 8254 // We may not yet have parsed the package, so just see if 8255 // we still know about its settings. 8256 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8257 } 8258 if (bp.packageSetting == null) { 8259 Slog.w(TAG, "Removing dangling permission: " + bp.name 8260 + " from package " + bp.sourcePackage); 8261 it.remove(); 8262 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8263 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8264 Slog.i(TAG, "Removing old permission: " + bp.name 8265 + " from package " + bp.sourcePackage); 8266 flags |= UPDATE_PERMISSIONS_ALL; 8267 it.remove(); 8268 } 8269 } 8270 } 8271 8272 // Now update the permissions for all packages, in particular 8273 // replace the granted permissions of the system packages. 8274 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8275 for (PackageParser.Package pkg : mPackages.values()) { 8276 if (pkg != pkgInfo) { 8277 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8278 changingPkg); 8279 } 8280 } 8281 } 8282 8283 if (pkgInfo != null) { 8284 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8285 } 8286 } 8287 8288 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8289 String packageOfInterest) { 8290 // IMPORTANT: There are two types of permissions: install and runtime. 8291 // Install time permissions are granted when the app is installed to 8292 // all device users and users added in the future. Runtime permissions 8293 // are granted at runtime explicitly to specific users. Normal and signature 8294 // protected permissions are install time permissions. Dangerous permissions 8295 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8296 // otherwise they are runtime permissions. This function does not manage 8297 // runtime permissions except for the case an app targeting Lollipop MR1 8298 // being upgraded to target a newer SDK, in which case dangerous permissions 8299 // are transformed from install time to runtime ones. 8300 8301 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8302 if (ps == null) { 8303 return; 8304 } 8305 8306 PermissionsState permissionsState = ps.getPermissionsState(); 8307 PermissionsState origPermissions = permissionsState; 8308 8309 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8310 8311 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8312 8313 boolean changedInstallPermission = false; 8314 8315 if (replace) { 8316 ps.installPermissionsFixed = false; 8317 if (!ps.isSharedUser()) { 8318 origPermissions = new PermissionsState(permissionsState); 8319 permissionsState.reset(); 8320 } 8321 } 8322 8323 permissionsState.setGlobalGids(mGlobalGids); 8324 8325 final int N = pkg.requestedPermissions.size(); 8326 for (int i=0; i<N; i++) { 8327 final String name = pkg.requestedPermissions.get(i); 8328 final BasePermission bp = mSettings.mPermissions.get(name); 8329 8330 if (DEBUG_INSTALL) { 8331 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8332 } 8333 8334 if (bp == null || bp.packageSetting == null) { 8335 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8336 Slog.w(TAG, "Unknown permission " + name 8337 + " in package " + pkg.packageName); 8338 } 8339 continue; 8340 } 8341 8342 final String perm = bp.name; 8343 boolean allowedSig = false; 8344 int grant = GRANT_DENIED; 8345 8346 // Keep track of app op permissions. 8347 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8348 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8349 if (pkgs == null) { 8350 pkgs = new ArraySet<>(); 8351 mAppOpPermissionPackages.put(bp.name, pkgs); 8352 } 8353 pkgs.add(pkg.packageName); 8354 } 8355 8356 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8357 switch (level) { 8358 case PermissionInfo.PROTECTION_NORMAL: { 8359 // For all apps normal permissions are install time ones. 8360 grant = GRANT_INSTALL; 8361 } break; 8362 8363 case PermissionInfo.PROTECTION_DANGEROUS: { 8364 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8365 // For legacy apps dangerous permissions are install time ones. 8366 grant = GRANT_INSTALL_LEGACY; 8367 } else if (origPermissions.hasInstallPermission(bp.name)) { 8368 // For legacy apps that became modern, install becomes runtime. 8369 grant = GRANT_UPGRADE; 8370 } else { 8371 // For modern apps keep runtime permissions unchanged. 8372 grant = GRANT_RUNTIME; 8373 } 8374 } break; 8375 8376 case PermissionInfo.PROTECTION_SIGNATURE: { 8377 // For all apps signature permissions are install time ones. 8378 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8379 if (allowedSig) { 8380 grant = GRANT_INSTALL; 8381 } 8382 } break; 8383 } 8384 8385 if (DEBUG_INSTALL) { 8386 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8387 } 8388 8389 if (grant != GRANT_DENIED) { 8390 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8391 // If this is an existing, non-system package, then 8392 // we can't add any new permissions to it. 8393 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8394 // Except... if this is a permission that was added 8395 // to the platform (note: need to only do this when 8396 // updating the platform). 8397 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8398 grant = GRANT_DENIED; 8399 } 8400 } 8401 } 8402 8403 switch (grant) { 8404 case GRANT_INSTALL: { 8405 // Revoke this as runtime permission to handle the case of 8406 // a runtime permission being downgraded to an install one. 8407 for (int userId : UserManagerService.getInstance().getUserIds()) { 8408 if (origPermissions.getRuntimePermissionState( 8409 bp.name, userId) != null) { 8410 // Revoke the runtime permission and clear the flags. 8411 origPermissions.revokeRuntimePermission(bp, userId); 8412 origPermissions.updatePermissionFlags(bp, userId, 8413 PackageManager.MASK_PERMISSION_FLAGS, 0); 8414 // If we revoked a permission permission, we have to write. 8415 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8416 changedRuntimePermissionUserIds, userId); 8417 } 8418 } 8419 // Grant an install permission. 8420 if (permissionsState.grantInstallPermission(bp) != 8421 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8422 changedInstallPermission = true; 8423 } 8424 } break; 8425 8426 case GRANT_INSTALL_LEGACY: { 8427 // Grant an install permission. 8428 if (permissionsState.grantInstallPermission(bp) != 8429 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8430 changedInstallPermission = true; 8431 } 8432 } break; 8433 8434 case GRANT_RUNTIME: { 8435 // Grant previously granted runtime permissions. 8436 for (int userId : UserManagerService.getInstance().getUserIds()) { 8437 PermissionState permissionState = origPermissions 8438 .getRuntimePermissionState(bp.name, userId); 8439 final int flags = permissionState != null 8440 ? permissionState.getFlags() : 0; 8441 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8442 if (permissionsState.grantRuntimePermission(bp, userId) == 8443 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8444 // If we cannot put the permission as it was, we have to write. 8445 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8446 changedRuntimePermissionUserIds, userId); 8447 } 8448 } 8449 // Propagate the permission flags. 8450 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8451 } 8452 } break; 8453 8454 case GRANT_UPGRADE: { 8455 // Grant runtime permissions for a previously held install permission. 8456 PermissionState permissionState = origPermissions 8457 .getInstallPermissionState(bp.name); 8458 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8459 8460 if (origPermissions.revokeInstallPermission(bp) 8461 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8462 // We will be transferring the permission flags, so clear them. 8463 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8464 PackageManager.MASK_PERMISSION_FLAGS, 0); 8465 changedInstallPermission = true; 8466 } 8467 8468 // If the permission is not to be promoted to runtime we ignore it and 8469 // also its other flags as they are not applicable to install permissions. 8470 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8471 for (int userId : currentUserIds) { 8472 if (permissionsState.grantRuntimePermission(bp, userId) != 8473 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8474 // Transfer the permission flags. 8475 permissionsState.updatePermissionFlags(bp, userId, 8476 flags, flags); 8477 // If we granted the permission, we have to write. 8478 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8479 changedRuntimePermissionUserIds, userId); 8480 } 8481 } 8482 } 8483 } break; 8484 8485 default: { 8486 if (packageOfInterest == null 8487 || packageOfInterest.equals(pkg.packageName)) { 8488 Slog.w(TAG, "Not granting permission " + perm 8489 + " to package " + pkg.packageName 8490 + " because it was previously installed without"); 8491 } 8492 } break; 8493 } 8494 } else { 8495 if (permissionsState.revokeInstallPermission(bp) != 8496 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8497 // Also drop the permission flags. 8498 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8499 PackageManager.MASK_PERMISSION_FLAGS, 0); 8500 changedInstallPermission = true; 8501 Slog.i(TAG, "Un-granting permission " + perm 8502 + " from package " + pkg.packageName 8503 + " (protectionLevel=" + bp.protectionLevel 8504 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8505 + ")"); 8506 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8507 // Don't print warning for app op permissions, since it is fine for them 8508 // not to be granted, there is a UI for the user to decide. 8509 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8510 Slog.w(TAG, "Not granting permission " + perm 8511 + " to package " + pkg.packageName 8512 + " (protectionLevel=" + bp.protectionLevel 8513 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8514 + ")"); 8515 } 8516 } 8517 } 8518 } 8519 8520 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8521 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8522 // This is the first that we have heard about this package, so the 8523 // permissions we have now selected are fixed until explicitly 8524 // changed. 8525 ps.installPermissionsFixed = true; 8526 } 8527 8528 // Persist the runtime permissions state for users with changes. 8529 for (int userId : changedRuntimePermissionUserIds) { 8530 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8531 } 8532 } 8533 8534 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8535 boolean allowed = false; 8536 final int NP = PackageParser.NEW_PERMISSIONS.length; 8537 for (int ip=0; ip<NP; ip++) { 8538 final PackageParser.NewPermissionInfo npi 8539 = PackageParser.NEW_PERMISSIONS[ip]; 8540 if (npi.name.equals(perm) 8541 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8542 allowed = true; 8543 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8544 + pkg.packageName); 8545 break; 8546 } 8547 } 8548 return allowed; 8549 } 8550 8551 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8552 BasePermission bp, PermissionsState origPermissions) { 8553 boolean allowed; 8554 allowed = (compareSignatures( 8555 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8556 == PackageManager.SIGNATURE_MATCH) 8557 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8558 == PackageManager.SIGNATURE_MATCH); 8559 if (!allowed && (bp.protectionLevel 8560 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8561 if (isSystemApp(pkg)) { 8562 // For updated system applications, a system permission 8563 // is granted only if it had been defined by the original application. 8564 if (pkg.isUpdatedSystemApp()) { 8565 final PackageSetting sysPs = mSettings 8566 .getDisabledSystemPkgLPr(pkg.packageName); 8567 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8568 // If the original was granted this permission, we take 8569 // that grant decision as read and propagate it to the 8570 // update. 8571 if (sysPs.isPrivileged()) { 8572 allowed = true; 8573 } 8574 } else { 8575 // The system apk may have been updated with an older 8576 // version of the one on the data partition, but which 8577 // granted a new system permission that it didn't have 8578 // before. In this case we do want to allow the app to 8579 // now get the new permission if the ancestral apk is 8580 // privileged to get it. 8581 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8582 for (int j=0; 8583 j<sysPs.pkg.requestedPermissions.size(); j++) { 8584 if (perm.equals( 8585 sysPs.pkg.requestedPermissions.get(j))) { 8586 allowed = true; 8587 break; 8588 } 8589 } 8590 } 8591 } 8592 } else { 8593 allowed = isPrivilegedApp(pkg); 8594 } 8595 } 8596 } 8597 if (!allowed) { 8598 if (!allowed && (bp.protectionLevel 8599 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8600 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8601 // If this was a previously normal/dangerous permission that got moved 8602 // to a system permission as part of the runtime permission redesign, then 8603 // we still want to blindly grant it to old apps. 8604 allowed = true; 8605 } 8606 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8607 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8608 // If this permission is to be granted to the system installer and 8609 // this app is an installer, then it gets the permission. 8610 allowed = true; 8611 } 8612 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8613 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8614 // If this permission is to be granted to the system verifier and 8615 // this app is a verifier, then it gets the permission. 8616 allowed = true; 8617 } 8618 if (!allowed && (bp.protectionLevel 8619 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8620 && isSystemApp(pkg)) { 8621 // Any pre-installed system app is allowed to get this permission. 8622 allowed = true; 8623 } 8624 if (!allowed && (bp.protectionLevel 8625 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8626 // For development permissions, a development permission 8627 // is granted only if it was already granted. 8628 allowed = origPermissions.hasInstallPermission(perm); 8629 } 8630 } 8631 return allowed; 8632 } 8633 8634 final class ActivityIntentResolver 8635 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8636 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8637 boolean defaultOnly, int userId) { 8638 if (!sUserManager.exists(userId)) return null; 8639 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8640 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8641 } 8642 8643 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8644 int userId) { 8645 if (!sUserManager.exists(userId)) return null; 8646 mFlags = flags; 8647 return super.queryIntent(intent, resolvedType, 8648 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8649 } 8650 8651 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8652 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8653 if (!sUserManager.exists(userId)) return null; 8654 if (packageActivities == null) { 8655 return null; 8656 } 8657 mFlags = flags; 8658 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8659 final int N = packageActivities.size(); 8660 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8661 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8662 8663 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8664 for (int i = 0; i < N; ++i) { 8665 intentFilters = packageActivities.get(i).intents; 8666 if (intentFilters != null && intentFilters.size() > 0) { 8667 PackageParser.ActivityIntentInfo[] array = 8668 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8669 intentFilters.toArray(array); 8670 listCut.add(array); 8671 } 8672 } 8673 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8674 } 8675 8676 public final void addActivity(PackageParser.Activity a, String type) { 8677 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8678 mActivities.put(a.getComponentName(), a); 8679 if (DEBUG_SHOW_INFO) 8680 Log.v( 8681 TAG, " " + type + " " + 8682 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8683 if (DEBUG_SHOW_INFO) 8684 Log.v(TAG, " Class=" + a.info.name); 8685 final int NI = a.intents.size(); 8686 for (int j=0; j<NI; j++) { 8687 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8688 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8689 intent.setPriority(0); 8690 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8691 + a.className + " with priority > 0, forcing to 0"); 8692 } 8693 if (DEBUG_SHOW_INFO) { 8694 Log.v(TAG, " IntentFilter:"); 8695 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8696 } 8697 if (!intent.debugCheck()) { 8698 Log.w(TAG, "==> For Activity " + a.info.name); 8699 } 8700 addFilter(intent); 8701 } 8702 } 8703 8704 public final void removeActivity(PackageParser.Activity a, String type) { 8705 mActivities.remove(a.getComponentName()); 8706 if (DEBUG_SHOW_INFO) { 8707 Log.v(TAG, " " + type + " " 8708 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8709 : a.info.name) + ":"); 8710 Log.v(TAG, " Class=" + a.info.name); 8711 } 8712 final int NI = a.intents.size(); 8713 for (int j=0; j<NI; j++) { 8714 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8715 if (DEBUG_SHOW_INFO) { 8716 Log.v(TAG, " IntentFilter:"); 8717 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8718 } 8719 removeFilter(intent); 8720 } 8721 } 8722 8723 @Override 8724 protected boolean allowFilterResult( 8725 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8726 ActivityInfo filterAi = filter.activity.info; 8727 for (int i=dest.size()-1; i>=0; i--) { 8728 ActivityInfo destAi = dest.get(i).activityInfo; 8729 if (destAi.name == filterAi.name 8730 && destAi.packageName == filterAi.packageName) { 8731 return false; 8732 } 8733 } 8734 return true; 8735 } 8736 8737 @Override 8738 protected ActivityIntentInfo[] newArray(int size) { 8739 return new ActivityIntentInfo[size]; 8740 } 8741 8742 @Override 8743 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8744 if (!sUserManager.exists(userId)) return true; 8745 PackageParser.Package p = filter.activity.owner; 8746 if (p != null) { 8747 PackageSetting ps = (PackageSetting)p.mExtras; 8748 if (ps != null) { 8749 // System apps are never considered stopped for purposes of 8750 // filtering, because there may be no way for the user to 8751 // actually re-launch them. 8752 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8753 && ps.getStopped(userId); 8754 } 8755 } 8756 return false; 8757 } 8758 8759 @Override 8760 protected boolean isPackageForFilter(String packageName, 8761 PackageParser.ActivityIntentInfo info) { 8762 return packageName.equals(info.activity.owner.packageName); 8763 } 8764 8765 @Override 8766 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8767 int match, int userId) { 8768 if (!sUserManager.exists(userId)) return null; 8769 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8770 return null; 8771 } 8772 final PackageParser.Activity activity = info.activity; 8773 if (mSafeMode && (activity.info.applicationInfo.flags 8774 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8775 return null; 8776 } 8777 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8778 if (ps == null) { 8779 return null; 8780 } 8781 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8782 ps.readUserState(userId), userId); 8783 if (ai == null) { 8784 return null; 8785 } 8786 final ResolveInfo res = new ResolveInfo(); 8787 res.activityInfo = ai; 8788 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8789 res.filter = info; 8790 } 8791 if (info != null) { 8792 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8793 } 8794 res.priority = info.getPriority(); 8795 res.preferredOrder = activity.owner.mPreferredOrder; 8796 //System.out.println("Result: " + res.activityInfo.className + 8797 // " = " + res.priority); 8798 res.match = match; 8799 res.isDefault = info.hasDefault; 8800 res.labelRes = info.labelRes; 8801 res.nonLocalizedLabel = info.nonLocalizedLabel; 8802 if (userNeedsBadging(userId)) { 8803 res.noResourceId = true; 8804 } else { 8805 res.icon = info.icon; 8806 } 8807 res.iconResourceId = info.icon; 8808 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8809 return res; 8810 } 8811 8812 @Override 8813 protected void sortResults(List<ResolveInfo> results) { 8814 Collections.sort(results, mResolvePrioritySorter); 8815 } 8816 8817 @Override 8818 protected void dumpFilter(PrintWriter out, String prefix, 8819 PackageParser.ActivityIntentInfo filter) { 8820 out.print(prefix); out.print( 8821 Integer.toHexString(System.identityHashCode(filter.activity))); 8822 out.print(' '); 8823 filter.activity.printComponentShortName(out); 8824 out.print(" filter "); 8825 out.println(Integer.toHexString(System.identityHashCode(filter))); 8826 } 8827 8828 @Override 8829 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8830 return filter.activity; 8831 } 8832 8833 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8834 PackageParser.Activity activity = (PackageParser.Activity)label; 8835 out.print(prefix); out.print( 8836 Integer.toHexString(System.identityHashCode(activity))); 8837 out.print(' '); 8838 activity.printComponentShortName(out); 8839 if (count > 1) { 8840 out.print(" ("); out.print(count); out.print(" filters)"); 8841 } 8842 out.println(); 8843 } 8844 8845// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8846// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8847// final List<ResolveInfo> retList = Lists.newArrayList(); 8848// while (i.hasNext()) { 8849// final ResolveInfo resolveInfo = i.next(); 8850// if (isEnabledLP(resolveInfo.activityInfo)) { 8851// retList.add(resolveInfo); 8852// } 8853// } 8854// return retList; 8855// } 8856 8857 // Keys are String (activity class name), values are Activity. 8858 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8859 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8860 private int mFlags; 8861 } 8862 8863 private final class ServiceIntentResolver 8864 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8865 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8866 boolean defaultOnly, int userId) { 8867 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8868 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8869 } 8870 8871 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8872 int userId) { 8873 if (!sUserManager.exists(userId)) return null; 8874 mFlags = flags; 8875 return super.queryIntent(intent, resolvedType, 8876 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8877 } 8878 8879 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8880 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8881 if (!sUserManager.exists(userId)) return null; 8882 if (packageServices == null) { 8883 return null; 8884 } 8885 mFlags = flags; 8886 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8887 final int N = packageServices.size(); 8888 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8889 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8890 8891 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8892 for (int i = 0; i < N; ++i) { 8893 intentFilters = packageServices.get(i).intents; 8894 if (intentFilters != null && intentFilters.size() > 0) { 8895 PackageParser.ServiceIntentInfo[] array = 8896 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8897 intentFilters.toArray(array); 8898 listCut.add(array); 8899 } 8900 } 8901 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8902 } 8903 8904 public final void addService(PackageParser.Service s) { 8905 mServices.put(s.getComponentName(), s); 8906 if (DEBUG_SHOW_INFO) { 8907 Log.v(TAG, " " 8908 + (s.info.nonLocalizedLabel != null 8909 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8910 Log.v(TAG, " Class=" + s.info.name); 8911 } 8912 final int NI = s.intents.size(); 8913 int j; 8914 for (j=0; j<NI; j++) { 8915 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8916 if (DEBUG_SHOW_INFO) { 8917 Log.v(TAG, " IntentFilter:"); 8918 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8919 } 8920 if (!intent.debugCheck()) { 8921 Log.w(TAG, "==> For Service " + s.info.name); 8922 } 8923 addFilter(intent); 8924 } 8925 } 8926 8927 public final void removeService(PackageParser.Service s) { 8928 mServices.remove(s.getComponentName()); 8929 if (DEBUG_SHOW_INFO) { 8930 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8931 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8932 Log.v(TAG, " Class=" + s.info.name); 8933 } 8934 final int NI = s.intents.size(); 8935 int j; 8936 for (j=0; j<NI; j++) { 8937 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8938 if (DEBUG_SHOW_INFO) { 8939 Log.v(TAG, " IntentFilter:"); 8940 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8941 } 8942 removeFilter(intent); 8943 } 8944 } 8945 8946 @Override 8947 protected boolean allowFilterResult( 8948 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8949 ServiceInfo filterSi = filter.service.info; 8950 for (int i=dest.size()-1; i>=0; i--) { 8951 ServiceInfo destAi = dest.get(i).serviceInfo; 8952 if (destAi.name == filterSi.name 8953 && destAi.packageName == filterSi.packageName) { 8954 return false; 8955 } 8956 } 8957 return true; 8958 } 8959 8960 @Override 8961 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8962 return new PackageParser.ServiceIntentInfo[size]; 8963 } 8964 8965 @Override 8966 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8967 if (!sUserManager.exists(userId)) return true; 8968 PackageParser.Package p = filter.service.owner; 8969 if (p != null) { 8970 PackageSetting ps = (PackageSetting)p.mExtras; 8971 if (ps != null) { 8972 // System apps are never considered stopped for purposes of 8973 // filtering, because there may be no way for the user to 8974 // actually re-launch them. 8975 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8976 && ps.getStopped(userId); 8977 } 8978 } 8979 return false; 8980 } 8981 8982 @Override 8983 protected boolean isPackageForFilter(String packageName, 8984 PackageParser.ServiceIntentInfo info) { 8985 return packageName.equals(info.service.owner.packageName); 8986 } 8987 8988 @Override 8989 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8990 int match, int userId) { 8991 if (!sUserManager.exists(userId)) return null; 8992 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8993 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8994 return null; 8995 } 8996 final PackageParser.Service service = info.service; 8997 if (mSafeMode && (service.info.applicationInfo.flags 8998 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8999 return null; 9000 } 9001 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9002 if (ps == null) { 9003 return null; 9004 } 9005 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9006 ps.readUserState(userId), userId); 9007 if (si == null) { 9008 return null; 9009 } 9010 final ResolveInfo res = new ResolveInfo(); 9011 res.serviceInfo = si; 9012 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9013 res.filter = filter; 9014 } 9015 res.priority = info.getPriority(); 9016 res.preferredOrder = service.owner.mPreferredOrder; 9017 res.match = match; 9018 res.isDefault = info.hasDefault; 9019 res.labelRes = info.labelRes; 9020 res.nonLocalizedLabel = info.nonLocalizedLabel; 9021 res.icon = info.icon; 9022 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9023 return res; 9024 } 9025 9026 @Override 9027 protected void sortResults(List<ResolveInfo> results) { 9028 Collections.sort(results, mResolvePrioritySorter); 9029 } 9030 9031 @Override 9032 protected void dumpFilter(PrintWriter out, String prefix, 9033 PackageParser.ServiceIntentInfo filter) { 9034 out.print(prefix); out.print( 9035 Integer.toHexString(System.identityHashCode(filter.service))); 9036 out.print(' '); 9037 filter.service.printComponentShortName(out); 9038 out.print(" filter "); 9039 out.println(Integer.toHexString(System.identityHashCode(filter))); 9040 } 9041 9042 @Override 9043 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9044 return filter.service; 9045 } 9046 9047 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9048 PackageParser.Service service = (PackageParser.Service)label; 9049 out.print(prefix); out.print( 9050 Integer.toHexString(System.identityHashCode(service))); 9051 out.print(' '); 9052 service.printComponentShortName(out); 9053 if (count > 1) { 9054 out.print(" ("); out.print(count); out.print(" filters)"); 9055 } 9056 out.println(); 9057 } 9058 9059// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9060// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9061// final List<ResolveInfo> retList = Lists.newArrayList(); 9062// while (i.hasNext()) { 9063// final ResolveInfo resolveInfo = (ResolveInfo) i; 9064// if (isEnabledLP(resolveInfo.serviceInfo)) { 9065// retList.add(resolveInfo); 9066// } 9067// } 9068// return retList; 9069// } 9070 9071 // Keys are String (activity class name), values are Activity. 9072 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9073 = new ArrayMap<ComponentName, PackageParser.Service>(); 9074 private int mFlags; 9075 }; 9076 9077 private final class ProviderIntentResolver 9078 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9079 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9080 boolean defaultOnly, int userId) { 9081 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9082 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9083 } 9084 9085 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9086 int userId) { 9087 if (!sUserManager.exists(userId)) 9088 return null; 9089 mFlags = flags; 9090 return super.queryIntent(intent, resolvedType, 9091 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9092 } 9093 9094 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9095 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9096 if (!sUserManager.exists(userId)) 9097 return null; 9098 if (packageProviders == null) { 9099 return null; 9100 } 9101 mFlags = flags; 9102 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9103 final int N = packageProviders.size(); 9104 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9105 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9106 9107 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9108 for (int i = 0; i < N; ++i) { 9109 intentFilters = packageProviders.get(i).intents; 9110 if (intentFilters != null && intentFilters.size() > 0) { 9111 PackageParser.ProviderIntentInfo[] array = 9112 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9113 intentFilters.toArray(array); 9114 listCut.add(array); 9115 } 9116 } 9117 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9118 } 9119 9120 public final void addProvider(PackageParser.Provider p) { 9121 if (mProviders.containsKey(p.getComponentName())) { 9122 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9123 return; 9124 } 9125 9126 mProviders.put(p.getComponentName(), p); 9127 if (DEBUG_SHOW_INFO) { 9128 Log.v(TAG, " " 9129 + (p.info.nonLocalizedLabel != null 9130 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9131 Log.v(TAG, " Class=" + p.info.name); 9132 } 9133 final int NI = p.intents.size(); 9134 int j; 9135 for (j = 0; j < NI; j++) { 9136 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9137 if (DEBUG_SHOW_INFO) { 9138 Log.v(TAG, " IntentFilter:"); 9139 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9140 } 9141 if (!intent.debugCheck()) { 9142 Log.w(TAG, "==> For Provider " + p.info.name); 9143 } 9144 addFilter(intent); 9145 } 9146 } 9147 9148 public final void removeProvider(PackageParser.Provider p) { 9149 mProviders.remove(p.getComponentName()); 9150 if (DEBUG_SHOW_INFO) { 9151 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9152 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9153 Log.v(TAG, " Class=" + p.info.name); 9154 } 9155 final int NI = p.intents.size(); 9156 int j; 9157 for (j = 0; j < NI; j++) { 9158 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9159 if (DEBUG_SHOW_INFO) { 9160 Log.v(TAG, " IntentFilter:"); 9161 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9162 } 9163 removeFilter(intent); 9164 } 9165 } 9166 9167 @Override 9168 protected boolean allowFilterResult( 9169 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9170 ProviderInfo filterPi = filter.provider.info; 9171 for (int i = dest.size() - 1; i >= 0; i--) { 9172 ProviderInfo destPi = dest.get(i).providerInfo; 9173 if (destPi.name == filterPi.name 9174 && destPi.packageName == filterPi.packageName) { 9175 return false; 9176 } 9177 } 9178 return true; 9179 } 9180 9181 @Override 9182 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9183 return new PackageParser.ProviderIntentInfo[size]; 9184 } 9185 9186 @Override 9187 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9188 if (!sUserManager.exists(userId)) 9189 return true; 9190 PackageParser.Package p = filter.provider.owner; 9191 if (p != null) { 9192 PackageSetting ps = (PackageSetting) p.mExtras; 9193 if (ps != null) { 9194 // System apps are never considered stopped for purposes of 9195 // filtering, because there may be no way for the user to 9196 // actually re-launch them. 9197 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9198 && ps.getStopped(userId); 9199 } 9200 } 9201 return false; 9202 } 9203 9204 @Override 9205 protected boolean isPackageForFilter(String packageName, 9206 PackageParser.ProviderIntentInfo info) { 9207 return packageName.equals(info.provider.owner.packageName); 9208 } 9209 9210 @Override 9211 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9212 int match, int userId) { 9213 if (!sUserManager.exists(userId)) 9214 return null; 9215 final PackageParser.ProviderIntentInfo info = filter; 9216 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9217 return null; 9218 } 9219 final PackageParser.Provider provider = info.provider; 9220 if (mSafeMode && (provider.info.applicationInfo.flags 9221 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9222 return null; 9223 } 9224 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9225 if (ps == null) { 9226 return null; 9227 } 9228 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9229 ps.readUserState(userId), userId); 9230 if (pi == null) { 9231 return null; 9232 } 9233 final ResolveInfo res = new ResolveInfo(); 9234 res.providerInfo = pi; 9235 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9236 res.filter = filter; 9237 } 9238 res.priority = info.getPriority(); 9239 res.preferredOrder = provider.owner.mPreferredOrder; 9240 res.match = match; 9241 res.isDefault = info.hasDefault; 9242 res.labelRes = info.labelRes; 9243 res.nonLocalizedLabel = info.nonLocalizedLabel; 9244 res.icon = info.icon; 9245 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9246 return res; 9247 } 9248 9249 @Override 9250 protected void sortResults(List<ResolveInfo> results) { 9251 Collections.sort(results, mResolvePrioritySorter); 9252 } 9253 9254 @Override 9255 protected void dumpFilter(PrintWriter out, String prefix, 9256 PackageParser.ProviderIntentInfo filter) { 9257 out.print(prefix); 9258 out.print( 9259 Integer.toHexString(System.identityHashCode(filter.provider))); 9260 out.print(' '); 9261 filter.provider.printComponentShortName(out); 9262 out.print(" filter "); 9263 out.println(Integer.toHexString(System.identityHashCode(filter))); 9264 } 9265 9266 @Override 9267 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9268 return filter.provider; 9269 } 9270 9271 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9272 PackageParser.Provider provider = (PackageParser.Provider)label; 9273 out.print(prefix); out.print( 9274 Integer.toHexString(System.identityHashCode(provider))); 9275 out.print(' '); 9276 provider.printComponentShortName(out); 9277 if (count > 1) { 9278 out.print(" ("); out.print(count); out.print(" filters)"); 9279 } 9280 out.println(); 9281 } 9282 9283 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9284 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9285 private int mFlags; 9286 }; 9287 9288 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9289 new Comparator<ResolveInfo>() { 9290 public int compare(ResolveInfo r1, ResolveInfo r2) { 9291 int v1 = r1.priority; 9292 int v2 = r2.priority; 9293 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9294 if (v1 != v2) { 9295 return (v1 > v2) ? -1 : 1; 9296 } 9297 v1 = r1.preferredOrder; 9298 v2 = r2.preferredOrder; 9299 if (v1 != v2) { 9300 return (v1 > v2) ? -1 : 1; 9301 } 9302 if (r1.isDefault != r2.isDefault) { 9303 return r1.isDefault ? -1 : 1; 9304 } 9305 v1 = r1.match; 9306 v2 = r2.match; 9307 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9308 if (v1 != v2) { 9309 return (v1 > v2) ? -1 : 1; 9310 } 9311 if (r1.system != r2.system) { 9312 return r1.system ? -1 : 1; 9313 } 9314 return 0; 9315 } 9316 }; 9317 9318 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9319 new Comparator<ProviderInfo>() { 9320 public int compare(ProviderInfo p1, ProviderInfo p2) { 9321 final int v1 = p1.initOrder; 9322 final int v2 = p2.initOrder; 9323 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9324 } 9325 }; 9326 9327 final void sendPackageBroadcast(final String action, final String pkg, 9328 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9329 final int[] userIds) { 9330 mHandler.post(new Runnable() { 9331 @Override 9332 public void run() { 9333 try { 9334 final IActivityManager am = ActivityManagerNative.getDefault(); 9335 if (am == null) return; 9336 final int[] resolvedUserIds; 9337 if (userIds == null) { 9338 resolvedUserIds = am.getRunningUserIds(); 9339 } else { 9340 resolvedUserIds = userIds; 9341 } 9342 for (int id : resolvedUserIds) { 9343 final Intent intent = new Intent(action, 9344 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9345 if (extras != null) { 9346 intent.putExtras(extras); 9347 } 9348 if (targetPkg != null) { 9349 intent.setPackage(targetPkg); 9350 } 9351 // Modify the UID when posting to other users 9352 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9353 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9354 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9355 intent.putExtra(Intent.EXTRA_UID, uid); 9356 } 9357 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9358 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9359 if (DEBUG_BROADCASTS) { 9360 RuntimeException here = new RuntimeException("here"); 9361 here.fillInStackTrace(); 9362 Slog.d(TAG, "Sending to user " + id + ": " 9363 + intent.toShortString(false, true, false, false) 9364 + " " + intent.getExtras(), here); 9365 } 9366 am.broadcastIntent(null, intent, null, finishedReceiver, 9367 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9368 null, finishedReceiver != null, false, id); 9369 } 9370 } catch (RemoteException ex) { 9371 } 9372 } 9373 }); 9374 } 9375 9376 /** 9377 * Check if the external storage media is available. This is true if there 9378 * is a mounted external storage medium or if the external storage is 9379 * emulated. 9380 */ 9381 private boolean isExternalMediaAvailable() { 9382 return mMediaMounted || Environment.isExternalStorageEmulated(); 9383 } 9384 9385 @Override 9386 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9387 // writer 9388 synchronized (mPackages) { 9389 if (!isExternalMediaAvailable()) { 9390 // If the external storage is no longer mounted at this point, 9391 // the caller may not have been able to delete all of this 9392 // packages files and can not delete any more. Bail. 9393 return null; 9394 } 9395 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9396 if (lastPackage != null) { 9397 pkgs.remove(lastPackage); 9398 } 9399 if (pkgs.size() > 0) { 9400 return pkgs.get(0); 9401 } 9402 } 9403 return null; 9404 } 9405 9406 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9407 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9408 userId, andCode ? 1 : 0, packageName); 9409 if (mSystemReady) { 9410 msg.sendToTarget(); 9411 } else { 9412 if (mPostSystemReadyMessages == null) { 9413 mPostSystemReadyMessages = new ArrayList<>(); 9414 } 9415 mPostSystemReadyMessages.add(msg); 9416 } 9417 } 9418 9419 void startCleaningPackages() { 9420 // reader 9421 synchronized (mPackages) { 9422 if (!isExternalMediaAvailable()) { 9423 return; 9424 } 9425 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9426 return; 9427 } 9428 } 9429 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9430 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9431 IActivityManager am = ActivityManagerNative.getDefault(); 9432 if (am != null) { 9433 try { 9434 am.startService(null, intent, null, mContext.getOpPackageName(), 9435 UserHandle.USER_OWNER); 9436 } catch (RemoteException e) { 9437 } 9438 } 9439 } 9440 9441 @Override 9442 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9443 int installFlags, String installerPackageName, VerificationParams verificationParams, 9444 String packageAbiOverride) { 9445 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9446 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9447 } 9448 9449 @Override 9450 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9451 int installFlags, String installerPackageName, VerificationParams verificationParams, 9452 String packageAbiOverride, int userId) { 9453 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9454 9455 final int callingUid = Binder.getCallingUid(); 9456 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9457 9458 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9459 try { 9460 if (observer != null) { 9461 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9462 } 9463 } catch (RemoteException re) { 9464 } 9465 return; 9466 } 9467 9468 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9469 installFlags |= PackageManager.INSTALL_FROM_ADB; 9470 9471 } else { 9472 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9473 // about installerPackageName. 9474 9475 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9476 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9477 } 9478 9479 UserHandle user; 9480 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9481 user = UserHandle.ALL; 9482 } else { 9483 user = new UserHandle(userId); 9484 } 9485 9486 // Only system components can circumvent runtime permissions when installing. 9487 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9488 && mContext.checkCallingOrSelfPermission(Manifest.permission 9489 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9490 throw new SecurityException("You need the " 9491 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9492 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9493 } 9494 9495 verificationParams.setInstallerUid(callingUid); 9496 9497 final File originFile = new File(originPath); 9498 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9499 9500 final Message msg = mHandler.obtainMessage(INIT_COPY); 9501 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9502 null, verificationParams, user, packageAbiOverride, null); 9503 mHandler.sendMessage(msg); 9504 } 9505 9506 void installStage(String packageName, File stagedDir, String stagedCid, 9507 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9508 String installerPackageName, int installerUid, UserHandle user) { 9509 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9510 params.referrerUri, installerUid, null); 9511 verifParams.setInstallerUid(installerUid); 9512 9513 final OriginInfo origin; 9514 if (stagedDir != null) { 9515 origin = OriginInfo.fromStagedFile(stagedDir); 9516 } else { 9517 origin = OriginInfo.fromStagedContainer(stagedCid); 9518 } 9519 9520 final Message msg = mHandler.obtainMessage(INIT_COPY); 9521 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9522 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9523 params.grantedRuntimePermissions); 9524 mHandler.sendMessage(msg); 9525 } 9526 9527 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9528 Bundle extras = new Bundle(1); 9529 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9530 9531 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9532 packageName, extras, null, null, new int[] {userId}); 9533 try { 9534 IActivityManager am = ActivityManagerNative.getDefault(); 9535 final boolean isSystem = 9536 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9537 if (isSystem && am.isUserRunning(userId, false)) { 9538 // The just-installed/enabled app is bundled on the system, so presumed 9539 // to be able to run automatically without needing an explicit launch. 9540 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9541 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9542 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9543 .setPackage(packageName); 9544 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9545 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9546 } 9547 } catch (RemoteException e) { 9548 // shouldn't happen 9549 Slog.w(TAG, "Unable to bootstrap installed package", e); 9550 } 9551 } 9552 9553 @Override 9554 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9555 int userId) { 9556 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9557 PackageSetting pkgSetting; 9558 final int uid = Binder.getCallingUid(); 9559 enforceCrossUserPermission(uid, userId, true, true, 9560 "setApplicationHiddenSetting for user " + userId); 9561 9562 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9563 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9564 return false; 9565 } 9566 9567 long callingId = Binder.clearCallingIdentity(); 9568 try { 9569 boolean sendAdded = false; 9570 boolean sendRemoved = false; 9571 // writer 9572 synchronized (mPackages) { 9573 pkgSetting = mSettings.mPackages.get(packageName); 9574 if (pkgSetting == null) { 9575 return false; 9576 } 9577 if (pkgSetting.getHidden(userId) != hidden) { 9578 pkgSetting.setHidden(hidden, userId); 9579 mSettings.writePackageRestrictionsLPr(userId); 9580 if (hidden) { 9581 sendRemoved = true; 9582 } else { 9583 sendAdded = true; 9584 } 9585 } 9586 } 9587 if (sendAdded) { 9588 sendPackageAddedForUser(packageName, pkgSetting, userId); 9589 return true; 9590 } 9591 if (sendRemoved) { 9592 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9593 "hiding pkg"); 9594 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9595 } 9596 } finally { 9597 Binder.restoreCallingIdentity(callingId); 9598 } 9599 return false; 9600 } 9601 9602 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9603 int userId) { 9604 final PackageRemovedInfo info = new PackageRemovedInfo(); 9605 info.removedPackage = packageName; 9606 info.removedUsers = new int[] {userId}; 9607 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9608 info.sendBroadcast(false, false, false); 9609 } 9610 9611 /** 9612 * Returns true if application is not found or there was an error. Otherwise it returns 9613 * the hidden state of the package for the given user. 9614 */ 9615 @Override 9616 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9617 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9618 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9619 false, "getApplicationHidden for user " + userId); 9620 PackageSetting pkgSetting; 9621 long callingId = Binder.clearCallingIdentity(); 9622 try { 9623 // writer 9624 synchronized (mPackages) { 9625 pkgSetting = mSettings.mPackages.get(packageName); 9626 if (pkgSetting == null) { 9627 return true; 9628 } 9629 return pkgSetting.getHidden(userId); 9630 } 9631 } finally { 9632 Binder.restoreCallingIdentity(callingId); 9633 } 9634 } 9635 9636 /** 9637 * @hide 9638 */ 9639 @Override 9640 public int installExistingPackageAsUser(String packageName, int userId) { 9641 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9642 null); 9643 PackageSetting pkgSetting; 9644 final int uid = Binder.getCallingUid(); 9645 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9646 + userId); 9647 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9648 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9649 } 9650 9651 long callingId = Binder.clearCallingIdentity(); 9652 try { 9653 boolean sendAdded = false; 9654 9655 // writer 9656 synchronized (mPackages) { 9657 pkgSetting = mSettings.mPackages.get(packageName); 9658 if (pkgSetting == null) { 9659 return PackageManager.INSTALL_FAILED_INVALID_URI; 9660 } 9661 if (!pkgSetting.getInstalled(userId)) { 9662 pkgSetting.setInstalled(true, userId); 9663 pkgSetting.setHidden(false, userId); 9664 mSettings.writePackageRestrictionsLPr(userId); 9665 sendAdded = true; 9666 } 9667 } 9668 9669 if (sendAdded) { 9670 sendPackageAddedForUser(packageName, pkgSetting, userId); 9671 } 9672 } finally { 9673 Binder.restoreCallingIdentity(callingId); 9674 } 9675 9676 return PackageManager.INSTALL_SUCCEEDED; 9677 } 9678 9679 boolean isUserRestricted(int userId, String restrictionKey) { 9680 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9681 if (restrictions.getBoolean(restrictionKey, false)) { 9682 Log.w(TAG, "User is restricted: " + restrictionKey); 9683 return true; 9684 } 9685 return false; 9686 } 9687 9688 @Override 9689 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9690 mContext.enforceCallingOrSelfPermission( 9691 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9692 "Only package verification agents can verify applications"); 9693 9694 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9695 final PackageVerificationResponse response = new PackageVerificationResponse( 9696 verificationCode, Binder.getCallingUid()); 9697 msg.arg1 = id; 9698 msg.obj = response; 9699 mHandler.sendMessage(msg); 9700 } 9701 9702 @Override 9703 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9704 long millisecondsToDelay) { 9705 mContext.enforceCallingOrSelfPermission( 9706 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9707 "Only package verification agents can extend verification timeouts"); 9708 9709 final PackageVerificationState state = mPendingVerification.get(id); 9710 final PackageVerificationResponse response = new PackageVerificationResponse( 9711 verificationCodeAtTimeout, Binder.getCallingUid()); 9712 9713 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9714 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9715 } 9716 if (millisecondsToDelay < 0) { 9717 millisecondsToDelay = 0; 9718 } 9719 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9720 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9721 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9722 } 9723 9724 if ((state != null) && !state.timeoutExtended()) { 9725 state.extendTimeout(); 9726 9727 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9728 msg.arg1 = id; 9729 msg.obj = response; 9730 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9731 } 9732 } 9733 9734 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9735 int verificationCode, UserHandle user) { 9736 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9737 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9738 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9739 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9740 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9741 9742 mContext.sendBroadcastAsUser(intent, user, 9743 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9744 } 9745 9746 private ComponentName matchComponentForVerifier(String packageName, 9747 List<ResolveInfo> receivers) { 9748 ActivityInfo targetReceiver = null; 9749 9750 final int NR = receivers.size(); 9751 for (int i = 0; i < NR; i++) { 9752 final ResolveInfo info = receivers.get(i); 9753 if (info.activityInfo == null) { 9754 continue; 9755 } 9756 9757 if (packageName.equals(info.activityInfo.packageName)) { 9758 targetReceiver = info.activityInfo; 9759 break; 9760 } 9761 } 9762 9763 if (targetReceiver == null) { 9764 return null; 9765 } 9766 9767 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9768 } 9769 9770 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9771 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9772 if (pkgInfo.verifiers.length == 0) { 9773 return null; 9774 } 9775 9776 final int N = pkgInfo.verifiers.length; 9777 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9778 for (int i = 0; i < N; i++) { 9779 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9780 9781 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9782 receivers); 9783 if (comp == null) { 9784 continue; 9785 } 9786 9787 final int verifierUid = getUidForVerifier(verifierInfo); 9788 if (verifierUid == -1) { 9789 continue; 9790 } 9791 9792 if (DEBUG_VERIFY) { 9793 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9794 + " with the correct signature"); 9795 } 9796 sufficientVerifiers.add(comp); 9797 verificationState.addSufficientVerifier(verifierUid); 9798 } 9799 9800 return sufficientVerifiers; 9801 } 9802 9803 private int getUidForVerifier(VerifierInfo verifierInfo) { 9804 synchronized (mPackages) { 9805 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9806 if (pkg == null) { 9807 return -1; 9808 } else if (pkg.mSignatures.length != 1) { 9809 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9810 + " has more than one signature; ignoring"); 9811 return -1; 9812 } 9813 9814 /* 9815 * If the public key of the package's signature does not match 9816 * our expected public key, then this is a different package and 9817 * we should skip. 9818 */ 9819 9820 final byte[] expectedPublicKey; 9821 try { 9822 final Signature verifierSig = pkg.mSignatures[0]; 9823 final PublicKey publicKey = verifierSig.getPublicKey(); 9824 expectedPublicKey = publicKey.getEncoded(); 9825 } catch (CertificateException e) { 9826 return -1; 9827 } 9828 9829 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9830 9831 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9832 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9833 + " does not have the expected public key; ignoring"); 9834 return -1; 9835 } 9836 9837 return pkg.applicationInfo.uid; 9838 } 9839 } 9840 9841 @Override 9842 public void finishPackageInstall(int token) { 9843 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9844 9845 if (DEBUG_INSTALL) { 9846 Slog.v(TAG, "BM finishing package install for " + token); 9847 } 9848 9849 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9850 mHandler.sendMessage(msg); 9851 } 9852 9853 /** 9854 * Get the verification agent timeout. 9855 * 9856 * @return verification timeout in milliseconds 9857 */ 9858 private long getVerificationTimeout() { 9859 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9860 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9861 DEFAULT_VERIFICATION_TIMEOUT); 9862 } 9863 9864 /** 9865 * Get the default verification agent response code. 9866 * 9867 * @return default verification response code 9868 */ 9869 private int getDefaultVerificationResponse() { 9870 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9871 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9872 DEFAULT_VERIFICATION_RESPONSE); 9873 } 9874 9875 /** 9876 * Check whether or not package verification has been enabled. 9877 * 9878 * @return true if verification should be performed 9879 */ 9880 private boolean isVerificationEnabled(int userId, int installFlags) { 9881 if (!DEFAULT_VERIFY_ENABLE) { 9882 return false; 9883 } 9884 9885 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9886 9887 // Check if installing from ADB 9888 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9889 // Do not run verification in a test harness environment 9890 if (ActivityManager.isRunningInTestHarness()) { 9891 return false; 9892 } 9893 if (ensureVerifyAppsEnabled) { 9894 return true; 9895 } 9896 // Check if the developer does not want package verification for ADB installs 9897 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9898 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9899 return false; 9900 } 9901 } 9902 9903 if (ensureVerifyAppsEnabled) { 9904 return true; 9905 } 9906 9907 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9908 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9909 } 9910 9911 @Override 9912 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9913 throws RemoteException { 9914 mContext.enforceCallingOrSelfPermission( 9915 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9916 "Only intentfilter verification agents can verify applications"); 9917 9918 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9919 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9920 Binder.getCallingUid(), verificationCode, failedDomains); 9921 msg.arg1 = id; 9922 msg.obj = response; 9923 mHandler.sendMessage(msg); 9924 } 9925 9926 @Override 9927 public int getIntentVerificationStatus(String packageName, int userId) { 9928 synchronized (mPackages) { 9929 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9930 } 9931 } 9932 9933 @Override 9934 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9935 mContext.enforceCallingOrSelfPermission( 9936 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9937 9938 boolean result = false; 9939 synchronized (mPackages) { 9940 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9941 } 9942 if (result) { 9943 scheduleWritePackageRestrictionsLocked(userId); 9944 } 9945 return result; 9946 } 9947 9948 @Override 9949 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9950 synchronized (mPackages) { 9951 return mSettings.getIntentFilterVerificationsLPr(packageName); 9952 } 9953 } 9954 9955 @Override 9956 public List<IntentFilter> getAllIntentFilters(String packageName) { 9957 if (TextUtils.isEmpty(packageName)) { 9958 return Collections.<IntentFilter>emptyList(); 9959 } 9960 synchronized (mPackages) { 9961 PackageParser.Package pkg = mPackages.get(packageName); 9962 if (pkg == null || pkg.activities == null) { 9963 return Collections.<IntentFilter>emptyList(); 9964 } 9965 final int count = pkg.activities.size(); 9966 ArrayList<IntentFilter> result = new ArrayList<>(); 9967 for (int n=0; n<count; n++) { 9968 PackageParser.Activity activity = pkg.activities.get(n); 9969 if (activity.intents != null || activity.intents.size() > 0) { 9970 result.addAll(activity.intents); 9971 } 9972 } 9973 return result; 9974 } 9975 } 9976 9977 @Override 9978 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9979 mContext.enforceCallingOrSelfPermission( 9980 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9981 9982 synchronized (mPackages) { 9983 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9984 if (packageName != null) { 9985 result |= updateIntentVerificationStatus(packageName, 9986 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9987 userId); 9988 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9989 packageName, userId); 9990 } 9991 return result; 9992 } 9993 } 9994 9995 @Override 9996 public String getDefaultBrowserPackageName(int userId) { 9997 synchronized (mPackages) { 9998 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9999 } 10000 } 10001 10002 /** 10003 * Get the "allow unknown sources" setting. 10004 * 10005 * @return the current "allow unknown sources" setting 10006 */ 10007 private int getUnknownSourcesSettings() { 10008 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10009 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10010 -1); 10011 } 10012 10013 @Override 10014 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10015 final int uid = Binder.getCallingUid(); 10016 // writer 10017 synchronized (mPackages) { 10018 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10019 if (targetPackageSetting == null) { 10020 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10021 } 10022 10023 PackageSetting installerPackageSetting; 10024 if (installerPackageName != null) { 10025 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10026 if (installerPackageSetting == null) { 10027 throw new IllegalArgumentException("Unknown installer package: " 10028 + installerPackageName); 10029 } 10030 } else { 10031 installerPackageSetting = null; 10032 } 10033 10034 Signature[] callerSignature; 10035 Object obj = mSettings.getUserIdLPr(uid); 10036 if (obj != null) { 10037 if (obj instanceof SharedUserSetting) { 10038 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10039 } else if (obj instanceof PackageSetting) { 10040 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10041 } else { 10042 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10043 } 10044 } else { 10045 throw new SecurityException("Unknown calling uid " + uid); 10046 } 10047 10048 // Verify: can't set installerPackageName to a package that is 10049 // not signed with the same cert as the caller. 10050 if (installerPackageSetting != null) { 10051 if (compareSignatures(callerSignature, 10052 installerPackageSetting.signatures.mSignatures) 10053 != PackageManager.SIGNATURE_MATCH) { 10054 throw new SecurityException( 10055 "Caller does not have same cert as new installer package " 10056 + installerPackageName); 10057 } 10058 } 10059 10060 // Verify: if target already has an installer package, it must 10061 // be signed with the same cert as the caller. 10062 if (targetPackageSetting.installerPackageName != null) { 10063 PackageSetting setting = mSettings.mPackages.get( 10064 targetPackageSetting.installerPackageName); 10065 // If the currently set package isn't valid, then it's always 10066 // okay to change it. 10067 if (setting != null) { 10068 if (compareSignatures(callerSignature, 10069 setting.signatures.mSignatures) 10070 != PackageManager.SIGNATURE_MATCH) { 10071 throw new SecurityException( 10072 "Caller does not have same cert as old installer package " 10073 + targetPackageSetting.installerPackageName); 10074 } 10075 } 10076 } 10077 10078 // Okay! 10079 targetPackageSetting.installerPackageName = installerPackageName; 10080 scheduleWriteSettingsLocked(); 10081 } 10082 } 10083 10084 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10085 // Queue up an async operation since the package installation may take a little while. 10086 mHandler.post(new Runnable() { 10087 public void run() { 10088 mHandler.removeCallbacks(this); 10089 // Result object to be returned 10090 PackageInstalledInfo res = new PackageInstalledInfo(); 10091 res.returnCode = currentStatus; 10092 res.uid = -1; 10093 res.pkg = null; 10094 res.removedInfo = new PackageRemovedInfo(); 10095 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10096 args.doPreInstall(res.returnCode); 10097 synchronized (mInstallLock) { 10098 installPackageLI(args, res); 10099 } 10100 args.doPostInstall(res.returnCode, res.uid); 10101 } 10102 10103 // A restore should be performed at this point if (a) the install 10104 // succeeded, (b) the operation is not an update, and (c) the new 10105 // package has not opted out of backup participation. 10106 final boolean update = res.removedInfo.removedPackage != null; 10107 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10108 boolean doRestore = !update 10109 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10110 10111 // Set up the post-install work request bookkeeping. This will be used 10112 // and cleaned up by the post-install event handling regardless of whether 10113 // there's a restore pass performed. Token values are >= 1. 10114 int token; 10115 if (mNextInstallToken < 0) mNextInstallToken = 1; 10116 token = mNextInstallToken++; 10117 10118 PostInstallData data = new PostInstallData(args, res); 10119 mRunningInstalls.put(token, data); 10120 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10121 10122 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10123 // Pass responsibility to the Backup Manager. It will perform a 10124 // restore if appropriate, then pass responsibility back to the 10125 // Package Manager to run the post-install observer callbacks 10126 // and broadcasts. 10127 IBackupManager bm = IBackupManager.Stub.asInterface( 10128 ServiceManager.getService(Context.BACKUP_SERVICE)); 10129 if (bm != null) { 10130 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10131 + " to BM for possible restore"); 10132 try { 10133 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10134 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10135 } else { 10136 doRestore = false; 10137 } 10138 } catch (RemoteException e) { 10139 // can't happen; the backup manager is local 10140 } catch (Exception e) { 10141 Slog.e(TAG, "Exception trying to enqueue restore", e); 10142 doRestore = false; 10143 } 10144 } else { 10145 Slog.e(TAG, "Backup Manager not found!"); 10146 doRestore = false; 10147 } 10148 } 10149 10150 if (!doRestore) { 10151 // No restore possible, or the Backup Manager was mysteriously not 10152 // available -- just fire the post-install work request directly. 10153 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10154 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10155 mHandler.sendMessage(msg); 10156 } 10157 } 10158 }); 10159 } 10160 10161 private abstract class HandlerParams { 10162 private static final int MAX_RETRIES = 4; 10163 10164 /** 10165 * Number of times startCopy() has been attempted and had a non-fatal 10166 * error. 10167 */ 10168 private int mRetries = 0; 10169 10170 /** User handle for the user requesting the information or installation. */ 10171 private final UserHandle mUser; 10172 10173 HandlerParams(UserHandle user) { 10174 mUser = user; 10175 } 10176 10177 UserHandle getUser() { 10178 return mUser; 10179 } 10180 10181 final boolean startCopy() { 10182 boolean res; 10183 try { 10184 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10185 10186 if (++mRetries > MAX_RETRIES) { 10187 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10188 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10189 handleServiceError(); 10190 return false; 10191 } else { 10192 handleStartCopy(); 10193 res = true; 10194 } 10195 } catch (RemoteException e) { 10196 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10197 mHandler.sendEmptyMessage(MCS_RECONNECT); 10198 res = false; 10199 } 10200 handleReturnCode(); 10201 return res; 10202 } 10203 10204 final void serviceError() { 10205 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10206 handleServiceError(); 10207 handleReturnCode(); 10208 } 10209 10210 abstract void handleStartCopy() throws RemoteException; 10211 abstract void handleServiceError(); 10212 abstract void handleReturnCode(); 10213 } 10214 10215 class MeasureParams extends HandlerParams { 10216 private final PackageStats mStats; 10217 private boolean mSuccess; 10218 10219 private final IPackageStatsObserver mObserver; 10220 10221 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10222 super(new UserHandle(stats.userHandle)); 10223 mObserver = observer; 10224 mStats = stats; 10225 } 10226 10227 @Override 10228 public String toString() { 10229 return "MeasureParams{" 10230 + Integer.toHexString(System.identityHashCode(this)) 10231 + " " + mStats.packageName + "}"; 10232 } 10233 10234 @Override 10235 void handleStartCopy() throws RemoteException { 10236 synchronized (mInstallLock) { 10237 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10238 } 10239 10240 if (mSuccess) { 10241 final boolean mounted; 10242 if (Environment.isExternalStorageEmulated()) { 10243 mounted = true; 10244 } else { 10245 final String status = Environment.getExternalStorageState(); 10246 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10247 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10248 } 10249 10250 if (mounted) { 10251 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10252 10253 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10254 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10255 10256 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10257 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10258 10259 // Always subtract cache size, since it's a subdirectory 10260 mStats.externalDataSize -= mStats.externalCacheSize; 10261 10262 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10263 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10264 10265 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10266 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10267 } 10268 } 10269 } 10270 10271 @Override 10272 void handleReturnCode() { 10273 if (mObserver != null) { 10274 try { 10275 mObserver.onGetStatsCompleted(mStats, mSuccess); 10276 } catch (RemoteException e) { 10277 Slog.i(TAG, "Observer no longer exists."); 10278 } 10279 } 10280 } 10281 10282 @Override 10283 void handleServiceError() { 10284 Slog.e(TAG, "Could not measure application " + mStats.packageName 10285 + " external storage"); 10286 } 10287 } 10288 10289 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10290 throws RemoteException { 10291 long result = 0; 10292 for (File path : paths) { 10293 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10294 } 10295 return result; 10296 } 10297 10298 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10299 for (File path : paths) { 10300 try { 10301 mcs.clearDirectory(path.getAbsolutePath()); 10302 } catch (RemoteException e) { 10303 } 10304 } 10305 } 10306 10307 static class OriginInfo { 10308 /** 10309 * Location where install is coming from, before it has been 10310 * copied/renamed into place. This could be a single monolithic APK 10311 * file, or a cluster directory. This location may be untrusted. 10312 */ 10313 final File file; 10314 final String cid; 10315 10316 /** 10317 * Flag indicating that {@link #file} or {@link #cid} has already been 10318 * staged, meaning downstream users don't need to defensively copy the 10319 * contents. 10320 */ 10321 final boolean staged; 10322 10323 /** 10324 * Flag indicating that {@link #file} or {@link #cid} is an already 10325 * installed app that is being moved. 10326 */ 10327 final boolean existing; 10328 10329 final String resolvedPath; 10330 final File resolvedFile; 10331 10332 static OriginInfo fromNothing() { 10333 return new OriginInfo(null, null, false, false); 10334 } 10335 10336 static OriginInfo fromUntrustedFile(File file) { 10337 return new OriginInfo(file, null, false, false); 10338 } 10339 10340 static OriginInfo fromExistingFile(File file) { 10341 return new OriginInfo(file, null, false, true); 10342 } 10343 10344 static OriginInfo fromStagedFile(File file) { 10345 return new OriginInfo(file, null, true, false); 10346 } 10347 10348 static OriginInfo fromStagedContainer(String cid) { 10349 return new OriginInfo(null, cid, true, false); 10350 } 10351 10352 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10353 this.file = file; 10354 this.cid = cid; 10355 this.staged = staged; 10356 this.existing = existing; 10357 10358 if (cid != null) { 10359 resolvedPath = PackageHelper.getSdDir(cid); 10360 resolvedFile = new File(resolvedPath); 10361 } else if (file != null) { 10362 resolvedPath = file.getAbsolutePath(); 10363 resolvedFile = file; 10364 } else { 10365 resolvedPath = null; 10366 resolvedFile = null; 10367 } 10368 } 10369 } 10370 10371 class MoveInfo { 10372 final int moveId; 10373 final String fromUuid; 10374 final String toUuid; 10375 final String packageName; 10376 final String dataAppName; 10377 final int appId; 10378 final String seinfo; 10379 10380 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10381 String dataAppName, int appId, String seinfo) { 10382 this.moveId = moveId; 10383 this.fromUuid = fromUuid; 10384 this.toUuid = toUuid; 10385 this.packageName = packageName; 10386 this.dataAppName = dataAppName; 10387 this.appId = appId; 10388 this.seinfo = seinfo; 10389 } 10390 } 10391 10392 class InstallParams extends HandlerParams { 10393 final OriginInfo origin; 10394 final MoveInfo move; 10395 final IPackageInstallObserver2 observer; 10396 int installFlags; 10397 final String installerPackageName; 10398 final String volumeUuid; 10399 final VerificationParams verificationParams; 10400 private InstallArgs mArgs; 10401 private int mRet; 10402 final String packageAbiOverride; 10403 final String[] grantedRuntimePermissions; 10404 10405 10406 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10407 int installFlags, String installerPackageName, String volumeUuid, 10408 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10409 String[] grantedPermissions) { 10410 super(user); 10411 this.origin = origin; 10412 this.move = move; 10413 this.observer = observer; 10414 this.installFlags = installFlags; 10415 this.installerPackageName = installerPackageName; 10416 this.volumeUuid = volumeUuid; 10417 this.verificationParams = verificationParams; 10418 this.packageAbiOverride = packageAbiOverride; 10419 this.grantedRuntimePermissions = grantedPermissions; 10420 } 10421 10422 @Override 10423 public String toString() { 10424 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10425 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10426 } 10427 10428 public ManifestDigest getManifestDigest() { 10429 if (verificationParams == null) { 10430 return null; 10431 } 10432 return verificationParams.getManifestDigest(); 10433 } 10434 10435 private int installLocationPolicy(PackageInfoLite pkgLite) { 10436 String packageName = pkgLite.packageName; 10437 int installLocation = pkgLite.installLocation; 10438 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10439 // reader 10440 synchronized (mPackages) { 10441 PackageParser.Package pkg = mPackages.get(packageName); 10442 if (pkg != null) { 10443 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10444 // Check for downgrading. 10445 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10446 try { 10447 checkDowngrade(pkg, pkgLite); 10448 } catch (PackageManagerException e) { 10449 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10450 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10451 } 10452 } 10453 // Check for updated system application. 10454 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10455 if (onSd) { 10456 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10457 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10458 } 10459 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10460 } else { 10461 if (onSd) { 10462 // Install flag overrides everything. 10463 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10464 } 10465 // If current upgrade specifies particular preference 10466 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10467 // Application explicitly specified internal. 10468 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10469 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10470 // App explictly prefers external. Let policy decide 10471 } else { 10472 // Prefer previous location 10473 if (isExternal(pkg)) { 10474 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10475 } 10476 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10477 } 10478 } 10479 } else { 10480 // Invalid install. Return error code 10481 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10482 } 10483 } 10484 } 10485 // All the special cases have been taken care of. 10486 // Return result based on recommended install location. 10487 if (onSd) { 10488 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10489 } 10490 return pkgLite.recommendedInstallLocation; 10491 } 10492 10493 /* 10494 * Invoke remote method to get package information and install 10495 * location values. Override install location based on default 10496 * policy if needed and then create install arguments based 10497 * on the install location. 10498 */ 10499 public void handleStartCopy() throws RemoteException { 10500 int ret = PackageManager.INSTALL_SUCCEEDED; 10501 10502 // If we're already staged, we've firmly committed to an install location 10503 if (origin.staged) { 10504 if (origin.file != null) { 10505 installFlags |= PackageManager.INSTALL_INTERNAL; 10506 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10507 } else if (origin.cid != null) { 10508 installFlags |= PackageManager.INSTALL_EXTERNAL; 10509 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10510 } else { 10511 throw new IllegalStateException("Invalid stage location"); 10512 } 10513 } 10514 10515 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10516 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10517 10518 PackageInfoLite pkgLite = null; 10519 10520 if (onInt && onSd) { 10521 // Check if both bits are set. 10522 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10523 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10524 } else { 10525 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10526 packageAbiOverride); 10527 10528 /* 10529 * If we have too little free space, try to free cache 10530 * before giving up. 10531 */ 10532 if (!origin.staged && pkgLite.recommendedInstallLocation 10533 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10534 // TODO: focus freeing disk space on the target device 10535 final StorageManager storage = StorageManager.from(mContext); 10536 final long lowThreshold = storage.getStorageLowBytes( 10537 Environment.getDataDirectory()); 10538 10539 final long sizeBytes = mContainerService.calculateInstalledSize( 10540 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10541 10542 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10543 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10544 installFlags, packageAbiOverride); 10545 } 10546 10547 /* 10548 * The cache free must have deleted the file we 10549 * downloaded to install. 10550 * 10551 * TODO: fix the "freeCache" call to not delete 10552 * the file we care about. 10553 */ 10554 if (pkgLite.recommendedInstallLocation 10555 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10556 pkgLite.recommendedInstallLocation 10557 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10558 } 10559 } 10560 } 10561 10562 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10563 int loc = pkgLite.recommendedInstallLocation; 10564 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10565 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10566 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10567 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10568 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10569 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10570 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10571 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10572 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10573 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10574 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10575 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10576 } else { 10577 // Override with defaults if needed. 10578 loc = installLocationPolicy(pkgLite); 10579 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10580 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10581 } else if (!onSd && !onInt) { 10582 // Override install location with flags 10583 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10584 // Set the flag to install on external media. 10585 installFlags |= PackageManager.INSTALL_EXTERNAL; 10586 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10587 } else { 10588 // Make sure the flag for installing on external 10589 // media is unset 10590 installFlags |= PackageManager.INSTALL_INTERNAL; 10591 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10592 } 10593 } 10594 } 10595 } 10596 10597 final InstallArgs args = createInstallArgs(this); 10598 mArgs = args; 10599 10600 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10601 /* 10602 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10603 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10604 */ 10605 int userIdentifier = getUser().getIdentifier(); 10606 if (userIdentifier == UserHandle.USER_ALL 10607 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10608 userIdentifier = UserHandle.USER_OWNER; 10609 } 10610 10611 /* 10612 * Determine if we have any installed package verifiers. If we 10613 * do, then we'll defer to them to verify the packages. 10614 */ 10615 final int requiredUid = mRequiredVerifierPackage == null ? -1 10616 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10617 if (!origin.existing && requiredUid != -1 10618 && isVerificationEnabled(userIdentifier, installFlags)) { 10619 final Intent verification = new Intent( 10620 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10621 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10622 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10623 PACKAGE_MIME_TYPE); 10624 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10625 10626 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10627 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10628 0 /* TODO: Which userId? */); 10629 10630 if (DEBUG_VERIFY) { 10631 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10632 + verification.toString() + " with " + pkgLite.verifiers.length 10633 + " optional verifiers"); 10634 } 10635 10636 final int verificationId = mPendingVerificationToken++; 10637 10638 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10639 10640 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10641 installerPackageName); 10642 10643 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10644 installFlags); 10645 10646 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10647 pkgLite.packageName); 10648 10649 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10650 pkgLite.versionCode); 10651 10652 if (verificationParams != null) { 10653 if (verificationParams.getVerificationURI() != null) { 10654 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10655 verificationParams.getVerificationURI()); 10656 } 10657 if (verificationParams.getOriginatingURI() != null) { 10658 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10659 verificationParams.getOriginatingURI()); 10660 } 10661 if (verificationParams.getReferrer() != null) { 10662 verification.putExtra(Intent.EXTRA_REFERRER, 10663 verificationParams.getReferrer()); 10664 } 10665 if (verificationParams.getOriginatingUid() >= 0) { 10666 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10667 verificationParams.getOriginatingUid()); 10668 } 10669 if (verificationParams.getInstallerUid() >= 0) { 10670 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10671 verificationParams.getInstallerUid()); 10672 } 10673 } 10674 10675 final PackageVerificationState verificationState = new PackageVerificationState( 10676 requiredUid, args); 10677 10678 mPendingVerification.append(verificationId, verificationState); 10679 10680 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10681 receivers, verificationState); 10682 10683 // Apps installed for "all" users use the device owner to verify the app 10684 UserHandle verifierUser = getUser(); 10685 if (verifierUser == UserHandle.ALL) { 10686 verifierUser = UserHandle.OWNER; 10687 } 10688 10689 /* 10690 * If any sufficient verifiers were listed in the package 10691 * manifest, attempt to ask them. 10692 */ 10693 if (sufficientVerifiers != null) { 10694 final int N = sufficientVerifiers.size(); 10695 if (N == 0) { 10696 Slog.i(TAG, "Additional verifiers required, but none installed."); 10697 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10698 } else { 10699 for (int i = 0; i < N; i++) { 10700 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10701 10702 final Intent sufficientIntent = new Intent(verification); 10703 sufficientIntent.setComponent(verifierComponent); 10704 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10705 } 10706 } 10707 } 10708 10709 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10710 mRequiredVerifierPackage, receivers); 10711 if (ret == PackageManager.INSTALL_SUCCEEDED 10712 && mRequiredVerifierPackage != null) { 10713 /* 10714 * Send the intent to the required verification agent, 10715 * but only start the verification timeout after the 10716 * target BroadcastReceivers have run. 10717 */ 10718 verification.setComponent(requiredVerifierComponent); 10719 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10720 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10721 new BroadcastReceiver() { 10722 @Override 10723 public void onReceive(Context context, Intent intent) { 10724 final Message msg = mHandler 10725 .obtainMessage(CHECK_PENDING_VERIFICATION); 10726 msg.arg1 = verificationId; 10727 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10728 } 10729 }, null, 0, null, null); 10730 10731 /* 10732 * We don't want the copy to proceed until verification 10733 * succeeds, so null out this field. 10734 */ 10735 mArgs = null; 10736 } 10737 } else { 10738 /* 10739 * No package verification is enabled, so immediately start 10740 * the remote call to initiate copy using temporary file. 10741 */ 10742 ret = args.copyApk(mContainerService, true); 10743 } 10744 } 10745 10746 mRet = ret; 10747 } 10748 10749 @Override 10750 void handleReturnCode() { 10751 // If mArgs is null, then MCS couldn't be reached. When it 10752 // reconnects, it will try again to install. At that point, this 10753 // will succeed. 10754 if (mArgs != null) { 10755 processPendingInstall(mArgs, mRet); 10756 } 10757 } 10758 10759 @Override 10760 void handleServiceError() { 10761 mArgs = createInstallArgs(this); 10762 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10763 } 10764 10765 public boolean isForwardLocked() { 10766 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10767 } 10768 } 10769 10770 /** 10771 * Used during creation of InstallArgs 10772 * 10773 * @param installFlags package installation flags 10774 * @return true if should be installed on external storage 10775 */ 10776 private static boolean installOnExternalAsec(int installFlags) { 10777 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10778 return false; 10779 } 10780 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10781 return true; 10782 } 10783 return false; 10784 } 10785 10786 /** 10787 * Used during creation of InstallArgs 10788 * 10789 * @param installFlags package installation flags 10790 * @return true if should be installed as forward locked 10791 */ 10792 private static boolean installForwardLocked(int installFlags) { 10793 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10794 } 10795 10796 private InstallArgs createInstallArgs(InstallParams params) { 10797 if (params.move != null) { 10798 return new MoveInstallArgs(params); 10799 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10800 return new AsecInstallArgs(params); 10801 } else { 10802 return new FileInstallArgs(params); 10803 } 10804 } 10805 10806 /** 10807 * Create args that describe an existing installed package. Typically used 10808 * when cleaning up old installs, or used as a move source. 10809 */ 10810 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10811 String resourcePath, String[] instructionSets) { 10812 final boolean isInAsec; 10813 if (installOnExternalAsec(installFlags)) { 10814 /* Apps on SD card are always in ASEC containers. */ 10815 isInAsec = true; 10816 } else if (installForwardLocked(installFlags) 10817 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10818 /* 10819 * Forward-locked apps are only in ASEC containers if they're the 10820 * new style 10821 */ 10822 isInAsec = true; 10823 } else { 10824 isInAsec = false; 10825 } 10826 10827 if (isInAsec) { 10828 return new AsecInstallArgs(codePath, instructionSets, 10829 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10830 } else { 10831 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10832 } 10833 } 10834 10835 static abstract class InstallArgs { 10836 /** @see InstallParams#origin */ 10837 final OriginInfo origin; 10838 /** @see InstallParams#move */ 10839 final MoveInfo move; 10840 10841 final IPackageInstallObserver2 observer; 10842 // Always refers to PackageManager flags only 10843 final int installFlags; 10844 final String installerPackageName; 10845 final String volumeUuid; 10846 final ManifestDigest manifestDigest; 10847 final UserHandle user; 10848 final String abiOverride; 10849 final String[] installGrantPermissions; 10850 10851 // The list of instruction sets supported by this app. This is currently 10852 // only used during the rmdex() phase to clean up resources. We can get rid of this 10853 // if we move dex files under the common app path. 10854 /* nullable */ String[] instructionSets; 10855 10856 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10857 int installFlags, String installerPackageName, String volumeUuid, 10858 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10859 String abiOverride, String[] installGrantPermissions) { 10860 this.origin = origin; 10861 this.move = move; 10862 this.installFlags = installFlags; 10863 this.observer = observer; 10864 this.installerPackageName = installerPackageName; 10865 this.volumeUuid = volumeUuid; 10866 this.manifestDigest = manifestDigest; 10867 this.user = user; 10868 this.instructionSets = instructionSets; 10869 this.abiOverride = abiOverride; 10870 this.installGrantPermissions = installGrantPermissions; 10871 } 10872 10873 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10874 abstract int doPreInstall(int status); 10875 10876 /** 10877 * Rename package into final resting place. All paths on the given 10878 * scanned package should be updated to reflect the rename. 10879 */ 10880 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10881 abstract int doPostInstall(int status, int uid); 10882 10883 /** @see PackageSettingBase#codePathString */ 10884 abstract String getCodePath(); 10885 /** @see PackageSettingBase#resourcePathString */ 10886 abstract String getResourcePath(); 10887 10888 // Need installer lock especially for dex file removal. 10889 abstract void cleanUpResourcesLI(); 10890 abstract boolean doPostDeleteLI(boolean delete); 10891 10892 /** 10893 * Called before the source arguments are copied. This is used mostly 10894 * for MoveParams when it needs to read the source file to put it in the 10895 * destination. 10896 */ 10897 int doPreCopy() { 10898 return PackageManager.INSTALL_SUCCEEDED; 10899 } 10900 10901 /** 10902 * Called after the source arguments are copied. This is used mostly for 10903 * MoveParams when it needs to read the source file to put it in the 10904 * destination. 10905 * 10906 * @return 10907 */ 10908 int doPostCopy(int uid) { 10909 return PackageManager.INSTALL_SUCCEEDED; 10910 } 10911 10912 protected boolean isFwdLocked() { 10913 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10914 } 10915 10916 protected boolean isExternalAsec() { 10917 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10918 } 10919 10920 UserHandle getUser() { 10921 return user; 10922 } 10923 } 10924 10925 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10926 if (!allCodePaths.isEmpty()) { 10927 if (instructionSets == null) { 10928 throw new IllegalStateException("instructionSet == null"); 10929 } 10930 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10931 for (String codePath : allCodePaths) { 10932 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10933 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10934 if (retCode < 0) { 10935 Slog.w(TAG, "Couldn't remove dex file for package: " 10936 + " at location " + codePath + ", retcode=" + retCode); 10937 // we don't consider this to be a failure of the core package deletion 10938 } 10939 } 10940 } 10941 } 10942 } 10943 10944 /** 10945 * Logic to handle installation of non-ASEC applications, including copying 10946 * and renaming logic. 10947 */ 10948 class FileInstallArgs extends InstallArgs { 10949 private File codeFile; 10950 private File resourceFile; 10951 10952 // Example topology: 10953 // /data/app/com.example/base.apk 10954 // /data/app/com.example/split_foo.apk 10955 // /data/app/com.example/lib/arm/libfoo.so 10956 // /data/app/com.example/lib/arm64/libfoo.so 10957 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10958 10959 /** New install */ 10960 FileInstallArgs(InstallParams params) { 10961 super(params.origin, params.move, params.observer, params.installFlags, 10962 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10963 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 10964 params.grantedRuntimePermissions); 10965 if (isFwdLocked()) { 10966 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10967 } 10968 } 10969 10970 /** Existing install */ 10971 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10972 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10973 null, null); 10974 this.codeFile = (codePath != null) ? new File(codePath) : null; 10975 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10976 } 10977 10978 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10979 if (origin.staged) { 10980 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10981 codeFile = origin.file; 10982 resourceFile = origin.file; 10983 return PackageManager.INSTALL_SUCCEEDED; 10984 } 10985 10986 try { 10987 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10988 codeFile = tempDir; 10989 resourceFile = tempDir; 10990 } catch (IOException e) { 10991 Slog.w(TAG, "Failed to create copy file: " + e); 10992 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10993 } 10994 10995 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10996 @Override 10997 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10998 if (!FileUtils.isValidExtFilename(name)) { 10999 throw new IllegalArgumentException("Invalid filename: " + name); 11000 } 11001 try { 11002 final File file = new File(codeFile, name); 11003 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11004 O_RDWR | O_CREAT, 0644); 11005 Os.chmod(file.getAbsolutePath(), 0644); 11006 return new ParcelFileDescriptor(fd); 11007 } catch (ErrnoException e) { 11008 throw new RemoteException("Failed to open: " + e.getMessage()); 11009 } 11010 } 11011 }; 11012 11013 int ret = PackageManager.INSTALL_SUCCEEDED; 11014 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11015 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11016 Slog.e(TAG, "Failed to copy package"); 11017 return ret; 11018 } 11019 11020 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11021 NativeLibraryHelper.Handle handle = null; 11022 try { 11023 handle = NativeLibraryHelper.Handle.create(codeFile); 11024 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11025 abiOverride); 11026 } catch (IOException e) { 11027 Slog.e(TAG, "Copying native libraries failed", e); 11028 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11029 } finally { 11030 IoUtils.closeQuietly(handle); 11031 } 11032 11033 return ret; 11034 } 11035 11036 int doPreInstall(int status) { 11037 if (status != PackageManager.INSTALL_SUCCEEDED) { 11038 cleanUp(); 11039 } 11040 return status; 11041 } 11042 11043 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11044 if (status != PackageManager.INSTALL_SUCCEEDED) { 11045 cleanUp(); 11046 return false; 11047 } 11048 11049 final File targetDir = codeFile.getParentFile(); 11050 final File beforeCodeFile = codeFile; 11051 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11052 11053 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11054 try { 11055 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11056 } catch (ErrnoException e) { 11057 Slog.w(TAG, "Failed to rename", e); 11058 return false; 11059 } 11060 11061 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11062 Slog.w(TAG, "Failed to restorecon"); 11063 return false; 11064 } 11065 11066 // Reflect the rename internally 11067 codeFile = afterCodeFile; 11068 resourceFile = afterCodeFile; 11069 11070 // Reflect the rename in scanned details 11071 pkg.codePath = afterCodeFile.getAbsolutePath(); 11072 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11073 pkg.baseCodePath); 11074 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11075 pkg.splitCodePaths); 11076 11077 // Reflect the rename in app info 11078 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11079 pkg.applicationInfo.setCodePath(pkg.codePath); 11080 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11081 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11082 pkg.applicationInfo.setResourcePath(pkg.codePath); 11083 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11084 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11085 11086 return true; 11087 } 11088 11089 int doPostInstall(int status, int uid) { 11090 if (status != PackageManager.INSTALL_SUCCEEDED) { 11091 cleanUp(); 11092 } 11093 return status; 11094 } 11095 11096 @Override 11097 String getCodePath() { 11098 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11099 } 11100 11101 @Override 11102 String getResourcePath() { 11103 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11104 } 11105 11106 private boolean cleanUp() { 11107 if (codeFile == null || !codeFile.exists()) { 11108 return false; 11109 } 11110 11111 if (codeFile.isDirectory()) { 11112 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11113 } else { 11114 codeFile.delete(); 11115 } 11116 11117 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11118 resourceFile.delete(); 11119 } 11120 11121 return true; 11122 } 11123 11124 void cleanUpResourcesLI() { 11125 // Try enumerating all code paths before deleting 11126 List<String> allCodePaths = Collections.EMPTY_LIST; 11127 if (codeFile != null && codeFile.exists()) { 11128 try { 11129 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11130 allCodePaths = pkg.getAllCodePaths(); 11131 } catch (PackageParserException e) { 11132 // Ignored; we tried our best 11133 } 11134 } 11135 11136 cleanUp(); 11137 removeDexFiles(allCodePaths, instructionSets); 11138 } 11139 11140 boolean doPostDeleteLI(boolean delete) { 11141 // XXX err, shouldn't we respect the delete flag? 11142 cleanUpResourcesLI(); 11143 return true; 11144 } 11145 } 11146 11147 private boolean isAsecExternal(String cid) { 11148 final String asecPath = PackageHelper.getSdFilesystem(cid); 11149 return !asecPath.startsWith(mAsecInternalPath); 11150 } 11151 11152 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11153 PackageManagerException { 11154 if (copyRet < 0) { 11155 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11156 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11157 throw new PackageManagerException(copyRet, message); 11158 } 11159 } 11160 } 11161 11162 /** 11163 * Extract the MountService "container ID" from the full code path of an 11164 * .apk. 11165 */ 11166 static String cidFromCodePath(String fullCodePath) { 11167 int eidx = fullCodePath.lastIndexOf("/"); 11168 String subStr1 = fullCodePath.substring(0, eidx); 11169 int sidx = subStr1.lastIndexOf("/"); 11170 return subStr1.substring(sidx+1, eidx); 11171 } 11172 11173 /** 11174 * Logic to handle installation of ASEC applications, including copying and 11175 * renaming logic. 11176 */ 11177 class AsecInstallArgs extends InstallArgs { 11178 static final String RES_FILE_NAME = "pkg.apk"; 11179 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11180 11181 String cid; 11182 String packagePath; 11183 String resourcePath; 11184 11185 /** New install */ 11186 AsecInstallArgs(InstallParams params) { 11187 super(params.origin, params.move, params.observer, params.installFlags, 11188 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11189 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11190 params.grantedRuntimePermissions); 11191 } 11192 11193 /** Existing install */ 11194 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11195 boolean isExternal, boolean isForwardLocked) { 11196 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11197 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11198 instructionSets, null, null); 11199 // Hackily pretend we're still looking at a full code path 11200 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11201 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11202 } 11203 11204 // Extract cid from fullCodePath 11205 int eidx = fullCodePath.lastIndexOf("/"); 11206 String subStr1 = fullCodePath.substring(0, eidx); 11207 int sidx = subStr1.lastIndexOf("/"); 11208 cid = subStr1.substring(sidx+1, eidx); 11209 setMountPath(subStr1); 11210 } 11211 11212 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11213 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11214 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11215 instructionSets, null, null); 11216 this.cid = cid; 11217 setMountPath(PackageHelper.getSdDir(cid)); 11218 } 11219 11220 void createCopyFile() { 11221 cid = mInstallerService.allocateExternalStageCidLegacy(); 11222 } 11223 11224 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11225 if (origin.staged) { 11226 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11227 cid = origin.cid; 11228 setMountPath(PackageHelper.getSdDir(cid)); 11229 return PackageManager.INSTALL_SUCCEEDED; 11230 } 11231 11232 if (temp) { 11233 createCopyFile(); 11234 } else { 11235 /* 11236 * Pre-emptively destroy the container since it's destroyed if 11237 * copying fails due to it existing anyway. 11238 */ 11239 PackageHelper.destroySdDir(cid); 11240 } 11241 11242 final String newMountPath = imcs.copyPackageToContainer( 11243 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11244 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11245 11246 if (newMountPath != null) { 11247 setMountPath(newMountPath); 11248 return PackageManager.INSTALL_SUCCEEDED; 11249 } else { 11250 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11251 } 11252 } 11253 11254 @Override 11255 String getCodePath() { 11256 return packagePath; 11257 } 11258 11259 @Override 11260 String getResourcePath() { 11261 return resourcePath; 11262 } 11263 11264 int doPreInstall(int status) { 11265 if (status != PackageManager.INSTALL_SUCCEEDED) { 11266 // Destroy container 11267 PackageHelper.destroySdDir(cid); 11268 } else { 11269 boolean mounted = PackageHelper.isContainerMounted(cid); 11270 if (!mounted) { 11271 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11272 Process.SYSTEM_UID); 11273 if (newMountPath != null) { 11274 setMountPath(newMountPath); 11275 } else { 11276 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11277 } 11278 } 11279 } 11280 return status; 11281 } 11282 11283 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11284 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11285 String newMountPath = null; 11286 if (PackageHelper.isContainerMounted(cid)) { 11287 // Unmount the container 11288 if (!PackageHelper.unMountSdDir(cid)) { 11289 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11290 return false; 11291 } 11292 } 11293 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11294 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11295 " which might be stale. Will try to clean up."); 11296 // Clean up the stale container and proceed to recreate. 11297 if (!PackageHelper.destroySdDir(newCacheId)) { 11298 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11299 return false; 11300 } 11301 // Successfully cleaned up stale container. Try to rename again. 11302 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11303 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11304 + " inspite of cleaning it up."); 11305 return false; 11306 } 11307 } 11308 if (!PackageHelper.isContainerMounted(newCacheId)) { 11309 Slog.w(TAG, "Mounting container " + newCacheId); 11310 newMountPath = PackageHelper.mountSdDir(newCacheId, 11311 getEncryptKey(), Process.SYSTEM_UID); 11312 } else { 11313 newMountPath = PackageHelper.getSdDir(newCacheId); 11314 } 11315 if (newMountPath == null) { 11316 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11317 return false; 11318 } 11319 Log.i(TAG, "Succesfully renamed " + cid + 11320 " to " + newCacheId + 11321 " at new path: " + newMountPath); 11322 cid = newCacheId; 11323 11324 final File beforeCodeFile = new File(packagePath); 11325 setMountPath(newMountPath); 11326 final File afterCodeFile = new File(packagePath); 11327 11328 // Reflect the rename in scanned details 11329 pkg.codePath = afterCodeFile.getAbsolutePath(); 11330 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11331 pkg.baseCodePath); 11332 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11333 pkg.splitCodePaths); 11334 11335 // Reflect the rename in app info 11336 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11337 pkg.applicationInfo.setCodePath(pkg.codePath); 11338 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11339 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11340 pkg.applicationInfo.setResourcePath(pkg.codePath); 11341 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11342 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11343 11344 return true; 11345 } 11346 11347 private void setMountPath(String mountPath) { 11348 final File mountFile = new File(mountPath); 11349 11350 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11351 if (monolithicFile.exists()) { 11352 packagePath = monolithicFile.getAbsolutePath(); 11353 if (isFwdLocked()) { 11354 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11355 } else { 11356 resourcePath = packagePath; 11357 } 11358 } else { 11359 packagePath = mountFile.getAbsolutePath(); 11360 resourcePath = packagePath; 11361 } 11362 } 11363 11364 int doPostInstall(int status, int uid) { 11365 if (status != PackageManager.INSTALL_SUCCEEDED) { 11366 cleanUp(); 11367 } else { 11368 final int groupOwner; 11369 final String protectedFile; 11370 if (isFwdLocked()) { 11371 groupOwner = UserHandle.getSharedAppGid(uid); 11372 protectedFile = RES_FILE_NAME; 11373 } else { 11374 groupOwner = -1; 11375 protectedFile = null; 11376 } 11377 11378 if (uid < Process.FIRST_APPLICATION_UID 11379 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11380 Slog.e(TAG, "Failed to finalize " + cid); 11381 PackageHelper.destroySdDir(cid); 11382 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11383 } 11384 11385 boolean mounted = PackageHelper.isContainerMounted(cid); 11386 if (!mounted) { 11387 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11388 } 11389 } 11390 return status; 11391 } 11392 11393 private void cleanUp() { 11394 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11395 11396 // Destroy secure container 11397 PackageHelper.destroySdDir(cid); 11398 } 11399 11400 private List<String> getAllCodePaths() { 11401 final File codeFile = new File(getCodePath()); 11402 if (codeFile != null && codeFile.exists()) { 11403 try { 11404 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11405 return pkg.getAllCodePaths(); 11406 } catch (PackageParserException e) { 11407 // Ignored; we tried our best 11408 } 11409 } 11410 return Collections.EMPTY_LIST; 11411 } 11412 11413 void cleanUpResourcesLI() { 11414 // Enumerate all code paths before deleting 11415 cleanUpResourcesLI(getAllCodePaths()); 11416 } 11417 11418 private void cleanUpResourcesLI(List<String> allCodePaths) { 11419 cleanUp(); 11420 removeDexFiles(allCodePaths, instructionSets); 11421 } 11422 11423 String getPackageName() { 11424 return getAsecPackageName(cid); 11425 } 11426 11427 boolean doPostDeleteLI(boolean delete) { 11428 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11429 final List<String> allCodePaths = getAllCodePaths(); 11430 boolean mounted = PackageHelper.isContainerMounted(cid); 11431 if (mounted) { 11432 // Unmount first 11433 if (PackageHelper.unMountSdDir(cid)) { 11434 mounted = false; 11435 } 11436 } 11437 if (!mounted && delete) { 11438 cleanUpResourcesLI(allCodePaths); 11439 } 11440 return !mounted; 11441 } 11442 11443 @Override 11444 int doPreCopy() { 11445 if (isFwdLocked()) { 11446 if (!PackageHelper.fixSdPermissions(cid, 11447 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11448 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11449 } 11450 } 11451 11452 return PackageManager.INSTALL_SUCCEEDED; 11453 } 11454 11455 @Override 11456 int doPostCopy(int uid) { 11457 if (isFwdLocked()) { 11458 if (uid < Process.FIRST_APPLICATION_UID 11459 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11460 RES_FILE_NAME)) { 11461 Slog.e(TAG, "Failed to finalize " + cid); 11462 PackageHelper.destroySdDir(cid); 11463 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11464 } 11465 } 11466 11467 return PackageManager.INSTALL_SUCCEEDED; 11468 } 11469 } 11470 11471 /** 11472 * Logic to handle movement of existing installed applications. 11473 */ 11474 class MoveInstallArgs extends InstallArgs { 11475 private File codeFile; 11476 private File resourceFile; 11477 11478 /** New install */ 11479 MoveInstallArgs(InstallParams params) { 11480 super(params.origin, params.move, params.observer, params.installFlags, 11481 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11482 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11483 params.grantedRuntimePermissions); 11484 } 11485 11486 int copyApk(IMediaContainerService imcs, boolean temp) { 11487 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11488 + move.fromUuid + " to " + move.toUuid); 11489 synchronized (mInstaller) { 11490 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11491 move.dataAppName, move.appId, move.seinfo) != 0) { 11492 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11493 } 11494 } 11495 11496 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11497 resourceFile = codeFile; 11498 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11499 11500 return PackageManager.INSTALL_SUCCEEDED; 11501 } 11502 11503 int doPreInstall(int status) { 11504 if (status != PackageManager.INSTALL_SUCCEEDED) { 11505 cleanUp(move.toUuid); 11506 } 11507 return status; 11508 } 11509 11510 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11511 if (status != PackageManager.INSTALL_SUCCEEDED) { 11512 cleanUp(move.toUuid); 11513 return false; 11514 } 11515 11516 // Reflect the move in app info 11517 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11518 pkg.applicationInfo.setCodePath(pkg.codePath); 11519 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11520 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11521 pkg.applicationInfo.setResourcePath(pkg.codePath); 11522 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11523 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11524 11525 return true; 11526 } 11527 11528 int doPostInstall(int status, int uid) { 11529 if (status == PackageManager.INSTALL_SUCCEEDED) { 11530 cleanUp(move.fromUuid); 11531 } else { 11532 cleanUp(move.toUuid); 11533 } 11534 return status; 11535 } 11536 11537 @Override 11538 String getCodePath() { 11539 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11540 } 11541 11542 @Override 11543 String getResourcePath() { 11544 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11545 } 11546 11547 private boolean cleanUp(String volumeUuid) { 11548 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11549 move.dataAppName); 11550 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11551 synchronized (mInstallLock) { 11552 // Clean up both app data and code 11553 removeDataDirsLI(volumeUuid, move.packageName); 11554 if (codeFile.isDirectory()) { 11555 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11556 } else { 11557 codeFile.delete(); 11558 } 11559 } 11560 return true; 11561 } 11562 11563 void cleanUpResourcesLI() { 11564 throw new UnsupportedOperationException(); 11565 } 11566 11567 boolean doPostDeleteLI(boolean delete) { 11568 throw new UnsupportedOperationException(); 11569 } 11570 } 11571 11572 static String getAsecPackageName(String packageCid) { 11573 int idx = packageCid.lastIndexOf("-"); 11574 if (idx == -1) { 11575 return packageCid; 11576 } 11577 return packageCid.substring(0, idx); 11578 } 11579 11580 // Utility method used to create code paths based on package name and available index. 11581 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11582 String idxStr = ""; 11583 int idx = 1; 11584 // Fall back to default value of idx=1 if prefix is not 11585 // part of oldCodePath 11586 if (oldCodePath != null) { 11587 String subStr = oldCodePath; 11588 // Drop the suffix right away 11589 if (suffix != null && subStr.endsWith(suffix)) { 11590 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11591 } 11592 // If oldCodePath already contains prefix find out the 11593 // ending index to either increment or decrement. 11594 int sidx = subStr.lastIndexOf(prefix); 11595 if (sidx != -1) { 11596 subStr = subStr.substring(sidx + prefix.length()); 11597 if (subStr != null) { 11598 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11599 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11600 } 11601 try { 11602 idx = Integer.parseInt(subStr); 11603 if (idx <= 1) { 11604 idx++; 11605 } else { 11606 idx--; 11607 } 11608 } catch(NumberFormatException e) { 11609 } 11610 } 11611 } 11612 } 11613 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11614 return prefix + idxStr; 11615 } 11616 11617 private File getNextCodePath(File targetDir, String packageName) { 11618 int suffix = 1; 11619 File result; 11620 do { 11621 result = new File(targetDir, packageName + "-" + suffix); 11622 suffix++; 11623 } while (result.exists()); 11624 return result; 11625 } 11626 11627 // Utility method that returns the relative package path with respect 11628 // to the installation directory. Like say for /data/data/com.test-1.apk 11629 // string com.test-1 is returned. 11630 static String deriveCodePathName(String codePath) { 11631 if (codePath == null) { 11632 return null; 11633 } 11634 final File codeFile = new File(codePath); 11635 final String name = codeFile.getName(); 11636 if (codeFile.isDirectory()) { 11637 return name; 11638 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11639 final int lastDot = name.lastIndexOf('.'); 11640 return name.substring(0, lastDot); 11641 } else { 11642 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11643 return null; 11644 } 11645 } 11646 11647 class PackageInstalledInfo { 11648 String name; 11649 int uid; 11650 // The set of users that originally had this package installed. 11651 int[] origUsers; 11652 // The set of users that now have this package installed. 11653 int[] newUsers; 11654 PackageParser.Package pkg; 11655 int returnCode; 11656 String returnMsg; 11657 PackageRemovedInfo removedInfo; 11658 11659 public void setError(int code, String msg) { 11660 returnCode = code; 11661 returnMsg = msg; 11662 Slog.w(TAG, msg); 11663 } 11664 11665 public void setError(String msg, PackageParserException e) { 11666 returnCode = e.error; 11667 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11668 Slog.w(TAG, msg, e); 11669 } 11670 11671 public void setError(String msg, PackageManagerException e) { 11672 returnCode = e.error; 11673 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11674 Slog.w(TAG, msg, e); 11675 } 11676 11677 // In some error cases we want to convey more info back to the observer 11678 String origPackage; 11679 String origPermission; 11680 } 11681 11682 /* 11683 * Install a non-existing package. 11684 */ 11685 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11686 UserHandle user, String installerPackageName, String volumeUuid, 11687 PackageInstalledInfo res) { 11688 // Remember this for later, in case we need to rollback this install 11689 String pkgName = pkg.packageName; 11690 11691 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11692 final boolean dataDirExists = Environment 11693 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11694 synchronized(mPackages) { 11695 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11696 // A package with the same name is already installed, though 11697 // it has been renamed to an older name. The package we 11698 // are trying to install should be installed as an update to 11699 // the existing one, but that has not been requested, so bail. 11700 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11701 + " without first uninstalling package running as " 11702 + mSettings.mRenamedPackages.get(pkgName)); 11703 return; 11704 } 11705 if (mPackages.containsKey(pkgName)) { 11706 // Don't allow installation over an existing package with the same name. 11707 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11708 + " without first uninstalling."); 11709 return; 11710 } 11711 } 11712 11713 try { 11714 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11715 System.currentTimeMillis(), user); 11716 11717 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11718 // delete the partially installed application. the data directory will have to be 11719 // restored if it was already existing 11720 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11721 // remove package from internal structures. Note that we want deletePackageX to 11722 // delete the package data and cache directories that it created in 11723 // scanPackageLocked, unless those directories existed before we even tried to 11724 // install. 11725 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11726 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11727 res.removedInfo, true); 11728 } 11729 11730 } catch (PackageManagerException e) { 11731 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11732 } 11733 } 11734 11735 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11736 // Can't rotate keys during boot or if sharedUser. 11737 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11738 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11739 return false; 11740 } 11741 // app is using upgradeKeySets; make sure all are valid 11742 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11743 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11744 for (int i = 0; i < upgradeKeySets.length; i++) { 11745 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11746 Slog.wtf(TAG, "Package " 11747 + (oldPs.name != null ? oldPs.name : "<null>") 11748 + " contains upgrade-key-set reference to unknown key-set: " 11749 + upgradeKeySets[i] 11750 + " reverting to signatures check."); 11751 return false; 11752 } 11753 } 11754 return true; 11755 } 11756 11757 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11758 // Upgrade keysets are being used. Determine if new package has a superset of the 11759 // required keys. 11760 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11761 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11762 for (int i = 0; i < upgradeKeySets.length; i++) { 11763 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11764 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11765 return true; 11766 } 11767 } 11768 return false; 11769 } 11770 11771 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11772 UserHandle user, String installerPackageName, String volumeUuid, 11773 PackageInstalledInfo res) { 11774 final PackageParser.Package oldPackage; 11775 final String pkgName = pkg.packageName; 11776 final int[] allUsers; 11777 final boolean[] perUserInstalled; 11778 11779 // First find the old package info and check signatures 11780 synchronized(mPackages) { 11781 oldPackage = mPackages.get(pkgName); 11782 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11783 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11784 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11785 if(!checkUpgradeKeySetLP(ps, pkg)) { 11786 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11787 "New package not signed by keys specified by upgrade-keysets: " 11788 + pkgName); 11789 return; 11790 } 11791 } else { 11792 // default to original signature matching 11793 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11794 != PackageManager.SIGNATURE_MATCH) { 11795 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11796 "New package has a different signature: " + pkgName); 11797 return; 11798 } 11799 } 11800 11801 // In case of rollback, remember per-user/profile install state 11802 allUsers = sUserManager.getUserIds(); 11803 perUserInstalled = new boolean[allUsers.length]; 11804 for (int i = 0; i < allUsers.length; i++) { 11805 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11806 } 11807 } 11808 11809 boolean sysPkg = (isSystemApp(oldPackage)); 11810 if (sysPkg) { 11811 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11812 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11813 } else { 11814 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11815 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11816 } 11817 } 11818 11819 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11820 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11821 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11822 String volumeUuid, PackageInstalledInfo res) { 11823 String pkgName = deletedPackage.packageName; 11824 boolean deletedPkg = true; 11825 boolean updatedSettings = false; 11826 11827 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11828 + deletedPackage); 11829 long origUpdateTime; 11830 if (pkg.mExtras != null) { 11831 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11832 } else { 11833 origUpdateTime = 0; 11834 } 11835 11836 // First delete the existing package while retaining the data directory 11837 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11838 res.removedInfo, true)) { 11839 // If the existing package wasn't successfully deleted 11840 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11841 deletedPkg = false; 11842 } else { 11843 // Successfully deleted the old package; proceed with replace. 11844 11845 // If deleted package lived in a container, give users a chance to 11846 // relinquish resources before killing. 11847 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11848 if (DEBUG_INSTALL) { 11849 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11850 } 11851 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11852 final ArrayList<String> pkgList = new ArrayList<String>(1); 11853 pkgList.add(deletedPackage.applicationInfo.packageName); 11854 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11855 } 11856 11857 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11858 try { 11859 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11860 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11861 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11862 perUserInstalled, res, user); 11863 updatedSettings = true; 11864 } catch (PackageManagerException e) { 11865 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11866 } 11867 } 11868 11869 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11870 // remove package from internal structures. Note that we want deletePackageX to 11871 // delete the package data and cache directories that it created in 11872 // scanPackageLocked, unless those directories existed before we even tried to 11873 // install. 11874 if(updatedSettings) { 11875 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11876 deletePackageLI( 11877 pkgName, null, true, allUsers, perUserInstalled, 11878 PackageManager.DELETE_KEEP_DATA, 11879 res.removedInfo, true); 11880 } 11881 // Since we failed to install the new package we need to restore the old 11882 // package that we deleted. 11883 if (deletedPkg) { 11884 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11885 File restoreFile = new File(deletedPackage.codePath); 11886 // Parse old package 11887 boolean oldExternal = isExternal(deletedPackage); 11888 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11889 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11890 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11891 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11892 try { 11893 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11894 } catch (PackageManagerException e) { 11895 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11896 + e.getMessage()); 11897 return; 11898 } 11899 // Restore of old package succeeded. Update permissions. 11900 // writer 11901 synchronized (mPackages) { 11902 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11903 UPDATE_PERMISSIONS_ALL); 11904 // can downgrade to reader 11905 mSettings.writeLPr(); 11906 } 11907 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11908 } 11909 } 11910 } 11911 11912 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11913 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11914 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11915 String volumeUuid, PackageInstalledInfo res) { 11916 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11917 + ", old=" + deletedPackage); 11918 boolean disabledSystem = false; 11919 boolean updatedSettings = false; 11920 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11921 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11922 != 0) { 11923 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11924 } 11925 String packageName = deletedPackage.packageName; 11926 if (packageName == null) { 11927 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11928 "Attempt to delete null packageName."); 11929 return; 11930 } 11931 PackageParser.Package oldPkg; 11932 PackageSetting oldPkgSetting; 11933 // reader 11934 synchronized (mPackages) { 11935 oldPkg = mPackages.get(packageName); 11936 oldPkgSetting = mSettings.mPackages.get(packageName); 11937 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11938 (oldPkgSetting == null)) { 11939 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11940 "Couldn't find package:" + packageName + " information"); 11941 return; 11942 } 11943 } 11944 11945 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 11946 11947 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11948 res.removedInfo.removedPackage = packageName; 11949 // Remove existing system package 11950 removePackageLI(oldPkgSetting, true); 11951 // writer 11952 synchronized (mPackages) { 11953 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11954 if (!disabledSystem && deletedPackage != null) { 11955 // We didn't need to disable the .apk as a current system package, 11956 // which means we are replacing another update that is already 11957 // installed. We need to make sure to delete the older one's .apk. 11958 res.removedInfo.args = createInstallArgsForExisting(0, 11959 deletedPackage.applicationInfo.getCodePath(), 11960 deletedPackage.applicationInfo.getResourcePath(), 11961 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11962 } else { 11963 res.removedInfo.args = null; 11964 } 11965 } 11966 11967 // Successfully disabled the old package. Now proceed with re-installation 11968 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11969 11970 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11971 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11972 11973 PackageParser.Package newPackage = null; 11974 try { 11975 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11976 if (newPackage.mExtras != null) { 11977 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11978 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11979 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11980 11981 // is the update attempting to change shared user? that isn't going to work... 11982 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11983 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11984 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11985 + " to " + newPkgSetting.sharedUser); 11986 updatedSettings = true; 11987 } 11988 } 11989 11990 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11991 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11992 perUserInstalled, res, user); 11993 updatedSettings = true; 11994 } 11995 11996 } catch (PackageManagerException e) { 11997 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11998 } 11999 12000 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12001 // Re installation failed. Restore old information 12002 // Remove new pkg information 12003 if (newPackage != null) { 12004 removeInstalledPackageLI(newPackage, true); 12005 } 12006 // Add back the old system package 12007 try { 12008 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12009 } catch (PackageManagerException e) { 12010 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12011 } 12012 // Restore the old system information in Settings 12013 synchronized (mPackages) { 12014 if (disabledSystem) { 12015 mSettings.enableSystemPackageLPw(packageName); 12016 } 12017 if (updatedSettings) { 12018 mSettings.setInstallerPackageName(packageName, 12019 oldPkgSetting.installerPackageName); 12020 } 12021 mSettings.writeLPr(); 12022 } 12023 } 12024 } 12025 12026 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12027 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12028 UserHandle user) { 12029 String pkgName = newPackage.packageName; 12030 synchronized (mPackages) { 12031 //write settings. the installStatus will be incomplete at this stage. 12032 //note that the new package setting would have already been 12033 //added to mPackages. It hasn't been persisted yet. 12034 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12035 mSettings.writeLPr(); 12036 } 12037 12038 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12039 12040 synchronized (mPackages) { 12041 updatePermissionsLPw(newPackage.packageName, newPackage, 12042 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12043 ? UPDATE_PERMISSIONS_ALL : 0)); 12044 // For system-bundled packages, we assume that installing an upgraded version 12045 // of the package implies that the user actually wants to run that new code, 12046 // so we enable the package. 12047 PackageSetting ps = mSettings.mPackages.get(pkgName); 12048 if (ps != null) { 12049 if (isSystemApp(newPackage)) { 12050 // NB: implicit assumption that system package upgrades apply to all users 12051 if (DEBUG_INSTALL) { 12052 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12053 } 12054 if (res.origUsers != null) { 12055 for (int userHandle : res.origUsers) { 12056 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12057 userHandle, installerPackageName); 12058 } 12059 } 12060 // Also convey the prior install/uninstall state 12061 if (allUsers != null && perUserInstalled != null) { 12062 for (int i = 0; i < allUsers.length; i++) { 12063 if (DEBUG_INSTALL) { 12064 Slog.d(TAG, " user " + allUsers[i] 12065 + " => " + perUserInstalled[i]); 12066 } 12067 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12068 } 12069 // these install state changes will be persisted in the 12070 // upcoming call to mSettings.writeLPr(). 12071 } 12072 } 12073 // It's implied that when a user requests installation, they want the app to be 12074 // installed and enabled. 12075 int userId = user.getIdentifier(); 12076 if (userId != UserHandle.USER_ALL) { 12077 ps.setInstalled(true, userId); 12078 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12079 } 12080 } 12081 res.name = pkgName; 12082 res.uid = newPackage.applicationInfo.uid; 12083 res.pkg = newPackage; 12084 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12085 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12086 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12087 //to update install status 12088 mSettings.writeLPr(); 12089 } 12090 } 12091 12092 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12093 final int installFlags = args.installFlags; 12094 final String installerPackageName = args.installerPackageName; 12095 final String volumeUuid = args.volumeUuid; 12096 final File tmpPackageFile = new File(args.getCodePath()); 12097 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12098 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12099 || (args.volumeUuid != null)); 12100 boolean replace = false; 12101 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12102 if (args.move != null) { 12103 // moving a complete application; perfom an initial scan on the new install location 12104 scanFlags |= SCAN_INITIAL; 12105 } 12106 // Result object to be returned 12107 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12108 12109 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12110 // Retrieve PackageSettings and parse package 12111 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12112 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12113 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12114 PackageParser pp = new PackageParser(); 12115 pp.setSeparateProcesses(mSeparateProcesses); 12116 pp.setDisplayMetrics(mMetrics); 12117 12118 final PackageParser.Package pkg; 12119 try { 12120 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12121 } catch (PackageParserException e) { 12122 res.setError("Failed parse during installPackageLI", e); 12123 return; 12124 } 12125 12126 // Mark that we have an install time CPU ABI override. 12127 pkg.cpuAbiOverride = args.abiOverride; 12128 12129 String pkgName = res.name = pkg.packageName; 12130 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12131 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12132 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12133 return; 12134 } 12135 } 12136 12137 try { 12138 pp.collectCertificates(pkg, parseFlags); 12139 pp.collectManifestDigest(pkg); 12140 } catch (PackageParserException e) { 12141 res.setError("Failed collect during installPackageLI", e); 12142 return; 12143 } 12144 12145 /* If the installer passed in a manifest digest, compare it now. */ 12146 if (args.manifestDigest != null) { 12147 if (DEBUG_INSTALL) { 12148 final String parsedManifest = pkg.manifestDigest == null ? "null" 12149 : pkg.manifestDigest.toString(); 12150 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12151 + parsedManifest); 12152 } 12153 12154 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12155 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12156 return; 12157 } 12158 } else if (DEBUG_INSTALL) { 12159 final String parsedManifest = pkg.manifestDigest == null 12160 ? "null" : pkg.manifestDigest.toString(); 12161 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12162 } 12163 12164 // Get rid of all references to package scan path via parser. 12165 pp = null; 12166 String oldCodePath = null; 12167 boolean systemApp = false; 12168 synchronized (mPackages) { 12169 // Check if installing already existing package 12170 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12171 String oldName = mSettings.mRenamedPackages.get(pkgName); 12172 if (pkg.mOriginalPackages != null 12173 && pkg.mOriginalPackages.contains(oldName) 12174 && mPackages.containsKey(oldName)) { 12175 // This package is derived from an original package, 12176 // and this device has been updating from that original 12177 // name. We must continue using the original name, so 12178 // rename the new package here. 12179 pkg.setPackageName(oldName); 12180 pkgName = pkg.packageName; 12181 replace = true; 12182 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12183 + oldName + " pkgName=" + pkgName); 12184 } else if (mPackages.containsKey(pkgName)) { 12185 // This package, under its official name, already exists 12186 // on the device; we should replace it. 12187 replace = true; 12188 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12189 } 12190 12191 // Prevent apps opting out from runtime permissions 12192 if (replace) { 12193 PackageParser.Package oldPackage = mPackages.get(pkgName); 12194 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12195 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12196 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12197 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12198 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12199 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12200 + " doesn't support runtime permissions but the old" 12201 + " target SDK " + oldTargetSdk + " does."); 12202 return; 12203 } 12204 } 12205 } 12206 12207 PackageSetting ps = mSettings.mPackages.get(pkgName); 12208 if (ps != null) { 12209 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12210 12211 // Quick sanity check that we're signed correctly if updating; 12212 // we'll check this again later when scanning, but we want to 12213 // bail early here before tripping over redefined permissions. 12214 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12215 if (!checkUpgradeKeySetLP(ps, pkg)) { 12216 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12217 + pkg.packageName + " upgrade keys do not match the " 12218 + "previously installed version"); 12219 return; 12220 } 12221 } else { 12222 try { 12223 verifySignaturesLP(ps, pkg); 12224 } catch (PackageManagerException e) { 12225 res.setError(e.error, e.getMessage()); 12226 return; 12227 } 12228 } 12229 12230 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12231 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12232 systemApp = (ps.pkg.applicationInfo.flags & 12233 ApplicationInfo.FLAG_SYSTEM) != 0; 12234 } 12235 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12236 } 12237 12238 // Check whether the newly-scanned package wants to define an already-defined perm 12239 int N = pkg.permissions.size(); 12240 for (int i = N-1; i >= 0; i--) { 12241 PackageParser.Permission perm = pkg.permissions.get(i); 12242 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12243 if (bp != null) { 12244 // If the defining package is signed with our cert, it's okay. This 12245 // also includes the "updating the same package" case, of course. 12246 // "updating same package" could also involve key-rotation. 12247 final boolean sigsOk; 12248 if (bp.sourcePackage.equals(pkg.packageName) 12249 && (bp.packageSetting instanceof PackageSetting) 12250 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12251 scanFlags))) { 12252 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12253 } else { 12254 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12255 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12256 } 12257 if (!sigsOk) { 12258 // If the owning package is the system itself, we log but allow 12259 // install to proceed; we fail the install on all other permission 12260 // redefinitions. 12261 if (!bp.sourcePackage.equals("android")) { 12262 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12263 + pkg.packageName + " attempting to redeclare permission " 12264 + perm.info.name + " already owned by " + bp.sourcePackage); 12265 res.origPermission = perm.info.name; 12266 res.origPackage = bp.sourcePackage; 12267 return; 12268 } else { 12269 Slog.w(TAG, "Package " + pkg.packageName 12270 + " attempting to redeclare system permission " 12271 + perm.info.name + "; ignoring new declaration"); 12272 pkg.permissions.remove(i); 12273 } 12274 } 12275 } 12276 } 12277 12278 } 12279 12280 if (systemApp && onExternal) { 12281 // Disable updates to system apps on sdcard 12282 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12283 "Cannot install updates to system apps on sdcard"); 12284 return; 12285 } 12286 12287 if (args.move != null) { 12288 // We did an in-place move, so dex is ready to roll 12289 scanFlags |= SCAN_NO_DEX; 12290 scanFlags |= SCAN_MOVE; 12291 12292 synchronized (mPackages) { 12293 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12294 if (ps == null) { 12295 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12296 "Missing settings for moved package " + pkgName); 12297 } 12298 12299 // We moved the entire application as-is, so bring over the 12300 // previously derived ABI information. 12301 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12302 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12303 } 12304 12305 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12306 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12307 scanFlags |= SCAN_NO_DEX; 12308 12309 try { 12310 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12311 true /* extract libs */); 12312 } catch (PackageManagerException pme) { 12313 Slog.e(TAG, "Error deriving application ABI", pme); 12314 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12315 return; 12316 } 12317 12318 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12319 int result = mPackageDexOptimizer 12320 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12321 false /* defer */, false /* inclDependencies */); 12322 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12323 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12324 return; 12325 } 12326 } 12327 12328 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12329 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12330 return; 12331 } 12332 12333 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12334 12335 if (replace) { 12336 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12337 installerPackageName, volumeUuid, res); 12338 } else { 12339 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12340 args.user, installerPackageName, volumeUuid, res); 12341 } 12342 synchronized (mPackages) { 12343 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12344 if (ps != null) { 12345 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12346 } 12347 } 12348 } 12349 12350 private void startIntentFilterVerifications(int userId, boolean replacing, 12351 PackageParser.Package pkg) { 12352 if (mIntentFilterVerifierComponent == null) { 12353 Slog.w(TAG, "No IntentFilter verification will not be done as " 12354 + "there is no IntentFilterVerifier available!"); 12355 return; 12356 } 12357 12358 final int verifierUid = getPackageUid( 12359 mIntentFilterVerifierComponent.getPackageName(), 12360 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12361 12362 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12363 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12364 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12365 mHandler.sendMessage(msg); 12366 } 12367 12368 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12369 PackageParser.Package pkg) { 12370 int size = pkg.activities.size(); 12371 if (size == 0) { 12372 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12373 "No activity, so no need to verify any IntentFilter!"); 12374 return; 12375 } 12376 12377 final boolean hasDomainURLs = hasDomainURLs(pkg); 12378 if (!hasDomainURLs) { 12379 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12380 "No domain URLs, so no need to verify any IntentFilter!"); 12381 return; 12382 } 12383 12384 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12385 + " if any IntentFilter from the " + size 12386 + " Activities needs verification ..."); 12387 12388 int count = 0; 12389 final String packageName = pkg.packageName; 12390 12391 synchronized (mPackages) { 12392 // If this is a new install and we see that we've already run verification for this 12393 // package, we have nothing to do: it means the state was restored from backup. 12394 if (!replacing) { 12395 IntentFilterVerificationInfo ivi = 12396 mSettings.getIntentFilterVerificationLPr(packageName); 12397 if (ivi != null) { 12398 if (DEBUG_DOMAIN_VERIFICATION) { 12399 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12400 + ivi.getStatusString()); 12401 } 12402 return; 12403 } 12404 } 12405 12406 // If any filters need to be verified, then all need to be. 12407 boolean needToVerify = false; 12408 for (PackageParser.Activity a : pkg.activities) { 12409 for (ActivityIntentInfo filter : a.intents) { 12410 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12411 if (DEBUG_DOMAIN_VERIFICATION) { 12412 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12413 } 12414 needToVerify = true; 12415 break; 12416 } 12417 } 12418 } 12419 12420 if (needToVerify) { 12421 final int verificationId = mIntentFilterVerificationToken++; 12422 for (PackageParser.Activity a : pkg.activities) { 12423 for (ActivityIntentInfo filter : a.intents) { 12424 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12425 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12426 "Verification needed for IntentFilter:" + filter.toString()); 12427 mIntentFilterVerifier.addOneIntentFilterVerification( 12428 verifierUid, userId, verificationId, filter, packageName); 12429 count++; 12430 } 12431 } 12432 } 12433 } 12434 } 12435 12436 if (count > 0) { 12437 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12438 + " IntentFilter verification" + (count > 1 ? "s" : "") 12439 + " for userId:" + userId); 12440 mIntentFilterVerifier.startVerifications(userId); 12441 } else { 12442 if (DEBUG_DOMAIN_VERIFICATION) { 12443 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12444 } 12445 } 12446 } 12447 12448 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12449 final ComponentName cn = filter.activity.getComponentName(); 12450 final String packageName = cn.getPackageName(); 12451 12452 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12453 packageName); 12454 if (ivi == null) { 12455 return true; 12456 } 12457 int status = ivi.getStatus(); 12458 switch (status) { 12459 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12460 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12461 return true; 12462 12463 default: 12464 // Nothing to do 12465 return false; 12466 } 12467 } 12468 12469 private static boolean isMultiArch(PackageSetting ps) { 12470 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12471 } 12472 12473 private static boolean isMultiArch(ApplicationInfo info) { 12474 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12475 } 12476 12477 private static boolean isExternal(PackageParser.Package pkg) { 12478 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12479 } 12480 12481 private static boolean isExternal(PackageSetting ps) { 12482 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12483 } 12484 12485 private static boolean isExternal(ApplicationInfo info) { 12486 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12487 } 12488 12489 private static boolean isSystemApp(PackageParser.Package pkg) { 12490 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12491 } 12492 12493 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12494 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12495 } 12496 12497 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12498 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12499 } 12500 12501 private static boolean isSystemApp(PackageSetting ps) { 12502 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12503 } 12504 12505 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12506 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12507 } 12508 12509 private int packageFlagsToInstallFlags(PackageSetting ps) { 12510 int installFlags = 0; 12511 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12512 // This existing package was an external ASEC install when we have 12513 // the external flag without a UUID 12514 installFlags |= PackageManager.INSTALL_EXTERNAL; 12515 } 12516 if (ps.isForwardLocked()) { 12517 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12518 } 12519 return installFlags; 12520 } 12521 12522 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12523 if (isExternal(pkg)) { 12524 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12525 return mSettings.getExternalVersion(); 12526 } else { 12527 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12528 } 12529 } else { 12530 return mSettings.getInternalVersion(); 12531 } 12532 } 12533 12534 private void deleteTempPackageFiles() { 12535 final FilenameFilter filter = new FilenameFilter() { 12536 public boolean accept(File dir, String name) { 12537 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12538 } 12539 }; 12540 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12541 file.delete(); 12542 } 12543 } 12544 12545 @Override 12546 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12547 int flags) { 12548 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12549 flags); 12550 } 12551 12552 @Override 12553 public void deletePackage(final String packageName, 12554 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12555 mContext.enforceCallingOrSelfPermission( 12556 android.Manifest.permission.DELETE_PACKAGES, null); 12557 Preconditions.checkNotNull(packageName); 12558 Preconditions.checkNotNull(observer); 12559 final int uid = Binder.getCallingUid(); 12560 if (UserHandle.getUserId(uid) != userId) { 12561 mContext.enforceCallingPermission( 12562 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12563 "deletePackage for user " + userId); 12564 } 12565 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12566 try { 12567 observer.onPackageDeleted(packageName, 12568 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12569 } catch (RemoteException re) { 12570 } 12571 return; 12572 } 12573 12574 boolean uninstallBlocked = false; 12575 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12576 int[] users = sUserManager.getUserIds(); 12577 for (int i = 0; i < users.length; ++i) { 12578 if (getBlockUninstallForUser(packageName, users[i])) { 12579 uninstallBlocked = true; 12580 break; 12581 } 12582 } 12583 } else { 12584 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12585 } 12586 if (uninstallBlocked) { 12587 try { 12588 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12589 null); 12590 } catch (RemoteException re) { 12591 } 12592 return; 12593 } 12594 12595 if (DEBUG_REMOVE) { 12596 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12597 } 12598 // Queue up an async operation since the package deletion may take a little while. 12599 mHandler.post(new Runnable() { 12600 public void run() { 12601 mHandler.removeCallbacks(this); 12602 final int returnCode = deletePackageX(packageName, userId, flags); 12603 if (observer != null) { 12604 try { 12605 observer.onPackageDeleted(packageName, returnCode, null); 12606 } catch (RemoteException e) { 12607 Log.i(TAG, "Observer no longer exists."); 12608 } //end catch 12609 } //end if 12610 } //end run 12611 }); 12612 } 12613 12614 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12615 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12616 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12617 try { 12618 if (dpm != null) { 12619 if (dpm.isDeviceOwner(packageName)) { 12620 return true; 12621 } 12622 int[] users; 12623 if (userId == UserHandle.USER_ALL) { 12624 users = sUserManager.getUserIds(); 12625 } else { 12626 users = new int[]{userId}; 12627 } 12628 for (int i = 0; i < users.length; ++i) { 12629 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12630 return true; 12631 } 12632 } 12633 } 12634 } catch (RemoteException e) { 12635 } 12636 return false; 12637 } 12638 12639 /** 12640 * This method is an internal method that could be get invoked either 12641 * to delete an installed package or to clean up a failed installation. 12642 * After deleting an installed package, a broadcast is sent to notify any 12643 * listeners that the package has been installed. For cleaning up a failed 12644 * installation, the broadcast is not necessary since the package's 12645 * installation wouldn't have sent the initial broadcast either 12646 * The key steps in deleting a package are 12647 * deleting the package information in internal structures like mPackages, 12648 * deleting the packages base directories through installd 12649 * updating mSettings to reflect current status 12650 * persisting settings for later use 12651 * sending a broadcast if necessary 12652 */ 12653 private int deletePackageX(String packageName, int userId, int flags) { 12654 final PackageRemovedInfo info = new PackageRemovedInfo(); 12655 final boolean res; 12656 12657 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12658 ? UserHandle.ALL : new UserHandle(userId); 12659 12660 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12661 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12662 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12663 } 12664 12665 boolean removedForAllUsers = false; 12666 boolean systemUpdate = false; 12667 12668 // for the uninstall-updates case and restricted profiles, remember the per- 12669 // userhandle installed state 12670 int[] allUsers; 12671 boolean[] perUserInstalled; 12672 synchronized (mPackages) { 12673 PackageSetting ps = mSettings.mPackages.get(packageName); 12674 allUsers = sUserManager.getUserIds(); 12675 perUserInstalled = new boolean[allUsers.length]; 12676 for (int i = 0; i < allUsers.length; i++) { 12677 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12678 } 12679 } 12680 12681 synchronized (mInstallLock) { 12682 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12683 res = deletePackageLI(packageName, removeForUser, 12684 true, allUsers, perUserInstalled, 12685 flags | REMOVE_CHATTY, info, true); 12686 systemUpdate = info.isRemovedPackageSystemUpdate; 12687 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12688 removedForAllUsers = true; 12689 } 12690 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12691 + " removedForAllUsers=" + removedForAllUsers); 12692 } 12693 12694 if (res) { 12695 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12696 12697 // If the removed package was a system update, the old system package 12698 // was re-enabled; we need to broadcast this information 12699 if (systemUpdate) { 12700 Bundle extras = new Bundle(1); 12701 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12702 ? info.removedAppId : info.uid); 12703 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12704 12705 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12706 extras, null, null, null); 12707 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12708 extras, null, null, null); 12709 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12710 null, packageName, null, null); 12711 } 12712 } 12713 // Force a gc here. 12714 Runtime.getRuntime().gc(); 12715 // Delete the resources here after sending the broadcast to let 12716 // other processes clean up before deleting resources. 12717 if (info.args != null) { 12718 synchronized (mInstallLock) { 12719 info.args.doPostDeleteLI(true); 12720 } 12721 } 12722 12723 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12724 } 12725 12726 class PackageRemovedInfo { 12727 String removedPackage; 12728 int uid = -1; 12729 int removedAppId = -1; 12730 int[] removedUsers = null; 12731 boolean isRemovedPackageSystemUpdate = false; 12732 // Clean up resources deleted packages. 12733 InstallArgs args = null; 12734 12735 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12736 Bundle extras = new Bundle(1); 12737 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12738 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12739 if (replacing) { 12740 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12741 } 12742 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12743 if (removedPackage != null) { 12744 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12745 extras, null, null, removedUsers); 12746 if (fullRemove && !replacing) { 12747 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12748 extras, null, null, removedUsers); 12749 } 12750 } 12751 if (removedAppId >= 0) { 12752 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12753 removedUsers); 12754 } 12755 } 12756 } 12757 12758 /* 12759 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12760 * flag is not set, the data directory is removed as well. 12761 * make sure this flag is set for partially installed apps. If not its meaningless to 12762 * delete a partially installed application. 12763 */ 12764 private void removePackageDataLI(PackageSetting ps, 12765 int[] allUserHandles, boolean[] perUserInstalled, 12766 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12767 String packageName = ps.name; 12768 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12769 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12770 // Retrieve object to delete permissions for shared user later on 12771 final PackageSetting deletedPs; 12772 // reader 12773 synchronized (mPackages) { 12774 deletedPs = mSettings.mPackages.get(packageName); 12775 if (outInfo != null) { 12776 outInfo.removedPackage = packageName; 12777 outInfo.removedUsers = deletedPs != null 12778 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12779 : null; 12780 } 12781 } 12782 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12783 removeDataDirsLI(ps.volumeUuid, packageName); 12784 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12785 } 12786 // writer 12787 synchronized (mPackages) { 12788 if (deletedPs != null) { 12789 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12790 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12791 clearDefaultBrowserIfNeeded(packageName); 12792 if (outInfo != null) { 12793 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12794 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12795 } 12796 updatePermissionsLPw(deletedPs.name, null, 0); 12797 if (deletedPs.sharedUser != null) { 12798 // Remove permissions associated with package. Since runtime 12799 // permissions are per user we have to kill the removed package 12800 // or packages running under the shared user of the removed 12801 // package if revoking the permissions requested only by the removed 12802 // package is successful and this causes a change in gids. 12803 for (int userId : UserManagerService.getInstance().getUserIds()) { 12804 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12805 userId); 12806 if (userIdToKill == UserHandle.USER_ALL 12807 || userIdToKill >= UserHandle.USER_OWNER) { 12808 // If gids changed for this user, kill all affected packages. 12809 mHandler.post(new Runnable() { 12810 @Override 12811 public void run() { 12812 // This has to happen with no lock held. 12813 killSettingPackagesForUser(deletedPs, userIdToKill, 12814 KILL_APP_REASON_GIDS_CHANGED); 12815 } 12816 }); 12817 break; 12818 } 12819 } 12820 } 12821 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12822 } 12823 // make sure to preserve per-user disabled state if this removal was just 12824 // a downgrade of a system app to the factory package 12825 if (allUserHandles != null && perUserInstalled != null) { 12826 if (DEBUG_REMOVE) { 12827 Slog.d(TAG, "Propagating install state across downgrade"); 12828 } 12829 for (int i = 0; i < allUserHandles.length; i++) { 12830 if (DEBUG_REMOVE) { 12831 Slog.d(TAG, " user " + allUserHandles[i] 12832 + " => " + perUserInstalled[i]); 12833 } 12834 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12835 } 12836 } 12837 } 12838 // can downgrade to reader 12839 if (writeSettings) { 12840 // Save settings now 12841 mSettings.writeLPr(); 12842 } 12843 } 12844 if (outInfo != null) { 12845 // A user ID was deleted here. Go through all users and remove it 12846 // from KeyStore. 12847 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12848 } 12849 } 12850 12851 static boolean locationIsPrivileged(File path) { 12852 try { 12853 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12854 .getCanonicalPath(); 12855 return path.getCanonicalPath().startsWith(privilegedAppDir); 12856 } catch (IOException e) { 12857 Slog.e(TAG, "Unable to access code path " + path); 12858 } 12859 return false; 12860 } 12861 12862 /* 12863 * Tries to delete system package. 12864 */ 12865 private boolean deleteSystemPackageLI(PackageSetting newPs, 12866 int[] allUserHandles, boolean[] perUserInstalled, 12867 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12868 final boolean applyUserRestrictions 12869 = (allUserHandles != null) && (perUserInstalled != null); 12870 PackageSetting disabledPs = null; 12871 // Confirm if the system package has been updated 12872 // An updated system app can be deleted. This will also have to restore 12873 // the system pkg from system partition 12874 // reader 12875 synchronized (mPackages) { 12876 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12877 } 12878 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12879 + " disabledPs=" + disabledPs); 12880 if (disabledPs == null) { 12881 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12882 return false; 12883 } else if (DEBUG_REMOVE) { 12884 Slog.d(TAG, "Deleting system pkg from data partition"); 12885 } 12886 if (DEBUG_REMOVE) { 12887 if (applyUserRestrictions) { 12888 Slog.d(TAG, "Remembering install states:"); 12889 for (int i = 0; i < allUserHandles.length; i++) { 12890 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12891 } 12892 } 12893 } 12894 // Delete the updated package 12895 outInfo.isRemovedPackageSystemUpdate = true; 12896 if (disabledPs.versionCode < newPs.versionCode) { 12897 // Delete data for downgrades 12898 flags &= ~PackageManager.DELETE_KEEP_DATA; 12899 } else { 12900 // Preserve data by setting flag 12901 flags |= PackageManager.DELETE_KEEP_DATA; 12902 } 12903 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12904 allUserHandles, perUserInstalled, outInfo, writeSettings); 12905 if (!ret) { 12906 return false; 12907 } 12908 // writer 12909 synchronized (mPackages) { 12910 // Reinstate the old system package 12911 mSettings.enableSystemPackageLPw(newPs.name); 12912 // Remove any native libraries from the upgraded package. 12913 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12914 } 12915 // Install the system package 12916 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12917 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12918 if (locationIsPrivileged(disabledPs.codePath)) { 12919 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12920 } 12921 12922 final PackageParser.Package newPkg; 12923 try { 12924 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12925 } catch (PackageManagerException e) { 12926 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12927 return false; 12928 } 12929 12930 // writer 12931 synchronized (mPackages) { 12932 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12933 12934 updatePermissionsLPw(newPkg.packageName, newPkg, 12935 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12936 12937 if (applyUserRestrictions) { 12938 if (DEBUG_REMOVE) { 12939 Slog.d(TAG, "Propagating install state across reinstall"); 12940 } 12941 for (int i = 0; i < allUserHandles.length; i++) { 12942 if (DEBUG_REMOVE) { 12943 Slog.d(TAG, " user " + allUserHandles[i] 12944 + " => " + perUserInstalled[i]); 12945 } 12946 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12947 12948 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 12949 } 12950 // Regardless of writeSettings we need to ensure that this restriction 12951 // state propagation is persisted 12952 mSettings.writeAllUsersPackageRestrictionsLPr(); 12953 } 12954 // can downgrade to reader here 12955 if (writeSettings) { 12956 mSettings.writeLPr(); 12957 } 12958 } 12959 return true; 12960 } 12961 12962 private boolean deleteInstalledPackageLI(PackageSetting ps, 12963 boolean deleteCodeAndResources, int flags, 12964 int[] allUserHandles, boolean[] perUserInstalled, 12965 PackageRemovedInfo outInfo, boolean writeSettings) { 12966 if (outInfo != null) { 12967 outInfo.uid = ps.appId; 12968 } 12969 12970 // Delete package data from internal structures and also remove data if flag is set 12971 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12972 12973 // Delete application code and resources 12974 if (deleteCodeAndResources && (outInfo != null)) { 12975 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12976 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12977 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12978 } 12979 return true; 12980 } 12981 12982 @Override 12983 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12984 int userId) { 12985 mContext.enforceCallingOrSelfPermission( 12986 android.Manifest.permission.DELETE_PACKAGES, null); 12987 synchronized (mPackages) { 12988 PackageSetting ps = mSettings.mPackages.get(packageName); 12989 if (ps == null) { 12990 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12991 return false; 12992 } 12993 if (!ps.getInstalled(userId)) { 12994 // Can't block uninstall for an app that is not installed or enabled. 12995 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12996 return false; 12997 } 12998 ps.setBlockUninstall(blockUninstall, userId); 12999 mSettings.writePackageRestrictionsLPr(userId); 13000 } 13001 return true; 13002 } 13003 13004 @Override 13005 public boolean getBlockUninstallForUser(String packageName, int userId) { 13006 synchronized (mPackages) { 13007 PackageSetting ps = mSettings.mPackages.get(packageName); 13008 if (ps == null) { 13009 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13010 return false; 13011 } 13012 return ps.getBlockUninstall(userId); 13013 } 13014 } 13015 13016 /* 13017 * This method handles package deletion in general 13018 */ 13019 private boolean deletePackageLI(String packageName, UserHandle user, 13020 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13021 int flags, PackageRemovedInfo outInfo, 13022 boolean writeSettings) { 13023 if (packageName == null) { 13024 Slog.w(TAG, "Attempt to delete null packageName."); 13025 return false; 13026 } 13027 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13028 PackageSetting ps; 13029 boolean dataOnly = false; 13030 int removeUser = -1; 13031 int appId = -1; 13032 synchronized (mPackages) { 13033 ps = mSettings.mPackages.get(packageName); 13034 if (ps == null) { 13035 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13036 return false; 13037 } 13038 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13039 && user.getIdentifier() != UserHandle.USER_ALL) { 13040 // The caller is asking that the package only be deleted for a single 13041 // user. To do this, we just mark its uninstalled state and delete 13042 // its data. If this is a system app, we only allow this to happen if 13043 // they have set the special DELETE_SYSTEM_APP which requests different 13044 // semantics than normal for uninstalling system apps. 13045 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13046 ps.setUserState(user.getIdentifier(), 13047 COMPONENT_ENABLED_STATE_DEFAULT, 13048 false, //installed 13049 true, //stopped 13050 true, //notLaunched 13051 false, //hidden 13052 null, null, null, 13053 false, // blockUninstall 13054 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0); 13055 if (!isSystemApp(ps)) { 13056 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13057 // Other user still have this package installed, so all 13058 // we need to do is clear this user's data and save that 13059 // it is uninstalled. 13060 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13061 removeUser = user.getIdentifier(); 13062 appId = ps.appId; 13063 scheduleWritePackageRestrictionsLocked(removeUser); 13064 } else { 13065 // We need to set it back to 'installed' so the uninstall 13066 // broadcasts will be sent correctly. 13067 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13068 ps.setInstalled(true, user.getIdentifier()); 13069 } 13070 } else { 13071 // This is a system app, so we assume that the 13072 // other users still have this package installed, so all 13073 // we need to do is clear this user's data and save that 13074 // it is uninstalled. 13075 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13076 removeUser = user.getIdentifier(); 13077 appId = ps.appId; 13078 scheduleWritePackageRestrictionsLocked(removeUser); 13079 } 13080 } 13081 } 13082 13083 if (removeUser >= 0) { 13084 // From above, we determined that we are deleting this only 13085 // for a single user. Continue the work here. 13086 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13087 if (outInfo != null) { 13088 outInfo.removedPackage = packageName; 13089 outInfo.removedAppId = appId; 13090 outInfo.removedUsers = new int[] {removeUser}; 13091 } 13092 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13093 removeKeystoreDataIfNeeded(removeUser, appId); 13094 schedulePackageCleaning(packageName, removeUser, false); 13095 synchronized (mPackages) { 13096 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13097 scheduleWritePackageRestrictionsLocked(removeUser); 13098 } 13099 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13100 } 13101 return true; 13102 } 13103 13104 if (dataOnly) { 13105 // Delete application data first 13106 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13107 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13108 return true; 13109 } 13110 13111 boolean ret = false; 13112 if (isSystemApp(ps)) { 13113 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13114 // When an updated system application is deleted we delete the existing resources as well and 13115 // fall back to existing code in system partition 13116 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13117 flags, outInfo, writeSettings); 13118 } else { 13119 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13120 // Kill application pre-emptively especially for apps on sd. 13121 killApplication(packageName, ps.appId, "uninstall pkg"); 13122 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13123 allUserHandles, perUserInstalled, 13124 outInfo, writeSettings); 13125 } 13126 13127 return ret; 13128 } 13129 13130 private final class ClearStorageConnection implements ServiceConnection { 13131 IMediaContainerService mContainerService; 13132 13133 @Override 13134 public void onServiceConnected(ComponentName name, IBinder service) { 13135 synchronized (this) { 13136 mContainerService = IMediaContainerService.Stub.asInterface(service); 13137 notifyAll(); 13138 } 13139 } 13140 13141 @Override 13142 public void onServiceDisconnected(ComponentName name) { 13143 } 13144 } 13145 13146 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13147 final boolean mounted; 13148 if (Environment.isExternalStorageEmulated()) { 13149 mounted = true; 13150 } else { 13151 final String status = Environment.getExternalStorageState(); 13152 13153 mounted = status.equals(Environment.MEDIA_MOUNTED) 13154 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13155 } 13156 13157 if (!mounted) { 13158 return; 13159 } 13160 13161 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13162 int[] users; 13163 if (userId == UserHandle.USER_ALL) { 13164 users = sUserManager.getUserIds(); 13165 } else { 13166 users = new int[] { userId }; 13167 } 13168 final ClearStorageConnection conn = new ClearStorageConnection(); 13169 if (mContext.bindServiceAsUser( 13170 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13171 try { 13172 for (int curUser : users) { 13173 long timeout = SystemClock.uptimeMillis() + 5000; 13174 synchronized (conn) { 13175 long now = SystemClock.uptimeMillis(); 13176 while (conn.mContainerService == null && now < timeout) { 13177 try { 13178 conn.wait(timeout - now); 13179 } catch (InterruptedException e) { 13180 } 13181 } 13182 } 13183 if (conn.mContainerService == null) { 13184 return; 13185 } 13186 13187 final UserEnvironment userEnv = new UserEnvironment(curUser); 13188 clearDirectory(conn.mContainerService, 13189 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13190 if (allData) { 13191 clearDirectory(conn.mContainerService, 13192 userEnv.buildExternalStorageAppDataDirs(packageName)); 13193 clearDirectory(conn.mContainerService, 13194 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13195 } 13196 } 13197 } finally { 13198 mContext.unbindService(conn); 13199 } 13200 } 13201 } 13202 13203 @Override 13204 public void clearApplicationUserData(final String packageName, 13205 final IPackageDataObserver observer, final int userId) { 13206 mContext.enforceCallingOrSelfPermission( 13207 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13208 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13209 // Queue up an async operation since the package deletion may take a little while. 13210 mHandler.post(new Runnable() { 13211 public void run() { 13212 mHandler.removeCallbacks(this); 13213 final boolean succeeded; 13214 synchronized (mInstallLock) { 13215 succeeded = clearApplicationUserDataLI(packageName, userId); 13216 } 13217 clearExternalStorageDataSync(packageName, userId, true); 13218 if (succeeded) { 13219 // invoke DeviceStorageMonitor's update method to clear any notifications 13220 DeviceStorageMonitorInternal 13221 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13222 if (dsm != null) { 13223 dsm.checkMemory(); 13224 } 13225 } 13226 if(observer != null) { 13227 try { 13228 observer.onRemoveCompleted(packageName, succeeded); 13229 } catch (RemoteException e) { 13230 Log.i(TAG, "Observer no longer exists."); 13231 } 13232 } //end if observer 13233 } //end run 13234 }); 13235 } 13236 13237 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13238 if (packageName == null) { 13239 Slog.w(TAG, "Attempt to delete null packageName."); 13240 return false; 13241 } 13242 13243 // Try finding details about the requested package 13244 PackageParser.Package pkg; 13245 synchronized (mPackages) { 13246 pkg = mPackages.get(packageName); 13247 if (pkg == null) { 13248 final PackageSetting ps = mSettings.mPackages.get(packageName); 13249 if (ps != null) { 13250 pkg = ps.pkg; 13251 } 13252 } 13253 13254 if (pkg == null) { 13255 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13256 return false; 13257 } 13258 13259 PackageSetting ps = (PackageSetting) pkg.mExtras; 13260 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13261 } 13262 13263 // Always delete data directories for package, even if we found no other 13264 // record of app. This helps users recover from UID mismatches without 13265 // resorting to a full data wipe. 13266 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13267 if (retCode < 0) { 13268 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13269 return false; 13270 } 13271 13272 final int appId = pkg.applicationInfo.uid; 13273 removeKeystoreDataIfNeeded(userId, appId); 13274 13275 // Create a native library symlink only if we have native libraries 13276 // and if the native libraries are 32 bit libraries. We do not provide 13277 // this symlink for 64 bit libraries. 13278 if (pkg.applicationInfo.primaryCpuAbi != null && 13279 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13280 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13281 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13282 nativeLibPath, userId) < 0) { 13283 Slog.w(TAG, "Failed linking native library dir"); 13284 return false; 13285 } 13286 } 13287 13288 return true; 13289 } 13290 13291 /** 13292 * Reverts user permission state changes (permissions and flags) in 13293 * all packages for a given user. 13294 * 13295 * @param userId The device user for which to do a reset. 13296 */ 13297 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13298 final int packageCount = mPackages.size(); 13299 for (int i = 0; i < packageCount; i++) { 13300 PackageParser.Package pkg = mPackages.valueAt(i); 13301 PackageSetting ps = (PackageSetting) pkg.mExtras; 13302 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13303 } 13304 } 13305 13306 /** 13307 * Reverts user permission state changes (permissions and flags). 13308 * 13309 * @param ps The package for which to reset. 13310 * @param userId The device user for which to do a reset. 13311 */ 13312 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13313 final PackageSetting ps, final int userId) { 13314 if (ps.pkg == null) { 13315 return; 13316 } 13317 13318 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13319 | FLAG_PERMISSION_USER_FIXED 13320 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13321 13322 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13323 | FLAG_PERMISSION_POLICY_FIXED; 13324 13325 boolean writeInstallPermissions = false; 13326 boolean writeRuntimePermissions = false; 13327 13328 final int permissionCount = ps.pkg.requestedPermissions.size(); 13329 for (int i = 0; i < permissionCount; i++) { 13330 String permission = ps.pkg.requestedPermissions.get(i); 13331 13332 BasePermission bp = mSettings.mPermissions.get(permission); 13333 if (bp == null) { 13334 continue; 13335 } 13336 13337 // If shared user we just reset the state to which only this app contributed. 13338 if (ps.sharedUser != null) { 13339 boolean used = false; 13340 final int packageCount = ps.sharedUser.packages.size(); 13341 for (int j = 0; j < packageCount; j++) { 13342 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13343 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13344 && pkg.pkg.requestedPermissions.contains(permission)) { 13345 used = true; 13346 break; 13347 } 13348 } 13349 if (used) { 13350 continue; 13351 } 13352 } 13353 13354 PermissionsState permissionsState = ps.getPermissionsState(); 13355 13356 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13357 13358 // Always clear the user settable flags. 13359 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13360 bp.name) != null; 13361 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13362 if (hasInstallState) { 13363 writeInstallPermissions = true; 13364 } else { 13365 writeRuntimePermissions = true; 13366 } 13367 } 13368 13369 // Below is only runtime permission handling. 13370 if (!bp.isRuntime()) { 13371 continue; 13372 } 13373 13374 // Never clobber system or policy. 13375 if ((oldFlags & policyOrSystemFlags) != 0) { 13376 continue; 13377 } 13378 13379 // If this permission was granted by default, make sure it is. 13380 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13381 if (permissionsState.grantRuntimePermission(bp, userId) 13382 != PERMISSION_OPERATION_FAILURE) { 13383 writeRuntimePermissions = true; 13384 } 13385 } else { 13386 // Otherwise, reset the permission. 13387 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13388 switch (revokeResult) { 13389 case PERMISSION_OPERATION_SUCCESS: { 13390 writeRuntimePermissions = true; 13391 } break; 13392 13393 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13394 writeRuntimePermissions = true; 13395 // If gids changed for this user, kill all affected packages. 13396 mHandler.post(new Runnable() { 13397 @Override 13398 public void run() { 13399 // This has to happen with no lock held. 13400 killSettingPackagesForUser(ps, userId, 13401 KILL_APP_REASON_GIDS_CHANGED); 13402 } 13403 }); 13404 } break; 13405 } 13406 } 13407 } 13408 13409 // Synchronously write as we are taking permissions away. 13410 if (writeRuntimePermissions) { 13411 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13412 } 13413 13414 // Synchronously write as we are taking permissions away. 13415 if (writeInstallPermissions) { 13416 mSettings.writeLPr(); 13417 } 13418 } 13419 13420 /** 13421 * Remove entries from the keystore daemon. Will only remove it if the 13422 * {@code appId} is valid. 13423 */ 13424 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13425 if (appId < 0) { 13426 return; 13427 } 13428 13429 final KeyStore keyStore = KeyStore.getInstance(); 13430 if (keyStore != null) { 13431 if (userId == UserHandle.USER_ALL) { 13432 for (final int individual : sUserManager.getUserIds()) { 13433 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13434 } 13435 } else { 13436 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13437 } 13438 } else { 13439 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13440 } 13441 } 13442 13443 @Override 13444 public void deleteApplicationCacheFiles(final String packageName, 13445 final IPackageDataObserver observer) { 13446 mContext.enforceCallingOrSelfPermission( 13447 android.Manifest.permission.DELETE_CACHE_FILES, null); 13448 // Queue up an async operation since the package deletion may take a little while. 13449 final int userId = UserHandle.getCallingUserId(); 13450 mHandler.post(new Runnable() { 13451 public void run() { 13452 mHandler.removeCallbacks(this); 13453 final boolean succeded; 13454 synchronized (mInstallLock) { 13455 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13456 } 13457 clearExternalStorageDataSync(packageName, userId, false); 13458 if (observer != null) { 13459 try { 13460 observer.onRemoveCompleted(packageName, succeded); 13461 } catch (RemoteException e) { 13462 Log.i(TAG, "Observer no longer exists."); 13463 } 13464 } //end if observer 13465 } //end run 13466 }); 13467 } 13468 13469 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13470 if (packageName == null) { 13471 Slog.w(TAG, "Attempt to delete null packageName."); 13472 return false; 13473 } 13474 PackageParser.Package p; 13475 synchronized (mPackages) { 13476 p = mPackages.get(packageName); 13477 } 13478 if (p == null) { 13479 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13480 return false; 13481 } 13482 final ApplicationInfo applicationInfo = p.applicationInfo; 13483 if (applicationInfo == null) { 13484 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13485 return false; 13486 } 13487 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13488 if (retCode < 0) { 13489 Slog.w(TAG, "Couldn't remove cache files for package: " 13490 + packageName + " u" + userId); 13491 return false; 13492 } 13493 return true; 13494 } 13495 13496 @Override 13497 public void getPackageSizeInfo(final String packageName, int userHandle, 13498 final IPackageStatsObserver observer) { 13499 mContext.enforceCallingOrSelfPermission( 13500 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13501 if (packageName == null) { 13502 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13503 } 13504 13505 PackageStats stats = new PackageStats(packageName, userHandle); 13506 13507 /* 13508 * Queue up an async operation since the package measurement may take a 13509 * little while. 13510 */ 13511 Message msg = mHandler.obtainMessage(INIT_COPY); 13512 msg.obj = new MeasureParams(stats, observer); 13513 mHandler.sendMessage(msg); 13514 } 13515 13516 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13517 PackageStats pStats) { 13518 if (packageName == null) { 13519 Slog.w(TAG, "Attempt to get size of null packageName."); 13520 return false; 13521 } 13522 PackageParser.Package p; 13523 boolean dataOnly = false; 13524 String libDirRoot = null; 13525 String asecPath = null; 13526 PackageSetting ps = null; 13527 synchronized (mPackages) { 13528 p = mPackages.get(packageName); 13529 ps = mSettings.mPackages.get(packageName); 13530 if(p == null) { 13531 dataOnly = true; 13532 if((ps == null) || (ps.pkg == null)) { 13533 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13534 return false; 13535 } 13536 p = ps.pkg; 13537 } 13538 if (ps != null) { 13539 libDirRoot = ps.legacyNativeLibraryPathString; 13540 } 13541 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13542 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13543 if (secureContainerId != null) { 13544 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13545 } 13546 } 13547 } 13548 String publicSrcDir = null; 13549 if(!dataOnly) { 13550 final ApplicationInfo applicationInfo = p.applicationInfo; 13551 if (applicationInfo == null) { 13552 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13553 return false; 13554 } 13555 if (p.isForwardLocked()) { 13556 publicSrcDir = applicationInfo.getBaseResourcePath(); 13557 } 13558 } 13559 // TODO: extend to measure size of split APKs 13560 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13561 // not just the first level. 13562 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13563 // just the primary. 13564 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13565 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13566 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13567 if (res < 0) { 13568 return false; 13569 } 13570 13571 // Fix-up for forward-locked applications in ASEC containers. 13572 if (!isExternal(p)) { 13573 pStats.codeSize += pStats.externalCodeSize; 13574 pStats.externalCodeSize = 0L; 13575 } 13576 13577 return true; 13578 } 13579 13580 13581 @Override 13582 public void addPackageToPreferred(String packageName) { 13583 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13584 } 13585 13586 @Override 13587 public void removePackageFromPreferred(String packageName) { 13588 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13589 } 13590 13591 @Override 13592 public List<PackageInfo> getPreferredPackages(int flags) { 13593 return new ArrayList<PackageInfo>(); 13594 } 13595 13596 private int getUidTargetSdkVersionLockedLPr(int uid) { 13597 Object obj = mSettings.getUserIdLPr(uid); 13598 if (obj instanceof SharedUserSetting) { 13599 final SharedUserSetting sus = (SharedUserSetting) obj; 13600 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13601 final Iterator<PackageSetting> it = sus.packages.iterator(); 13602 while (it.hasNext()) { 13603 final PackageSetting ps = it.next(); 13604 if (ps.pkg != null) { 13605 int v = ps.pkg.applicationInfo.targetSdkVersion; 13606 if (v < vers) vers = v; 13607 } 13608 } 13609 return vers; 13610 } else if (obj instanceof PackageSetting) { 13611 final PackageSetting ps = (PackageSetting) obj; 13612 if (ps.pkg != null) { 13613 return ps.pkg.applicationInfo.targetSdkVersion; 13614 } 13615 } 13616 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13617 } 13618 13619 @Override 13620 public void addPreferredActivity(IntentFilter filter, int match, 13621 ComponentName[] set, ComponentName activity, int userId) { 13622 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13623 "Adding preferred"); 13624 } 13625 13626 private void addPreferredActivityInternal(IntentFilter filter, int match, 13627 ComponentName[] set, ComponentName activity, boolean always, int userId, 13628 String opname) { 13629 // writer 13630 int callingUid = Binder.getCallingUid(); 13631 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13632 if (filter.countActions() == 0) { 13633 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13634 return; 13635 } 13636 synchronized (mPackages) { 13637 if (mContext.checkCallingOrSelfPermission( 13638 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13639 != PackageManager.PERMISSION_GRANTED) { 13640 if (getUidTargetSdkVersionLockedLPr(callingUid) 13641 < Build.VERSION_CODES.FROYO) { 13642 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13643 + callingUid); 13644 return; 13645 } 13646 mContext.enforceCallingOrSelfPermission( 13647 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13648 } 13649 13650 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13651 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13652 + userId + ":"); 13653 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13654 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13655 scheduleWritePackageRestrictionsLocked(userId); 13656 } 13657 } 13658 13659 @Override 13660 public void replacePreferredActivity(IntentFilter filter, int match, 13661 ComponentName[] set, ComponentName activity, int userId) { 13662 if (filter.countActions() != 1) { 13663 throw new IllegalArgumentException( 13664 "replacePreferredActivity expects filter to have only 1 action."); 13665 } 13666 if (filter.countDataAuthorities() != 0 13667 || filter.countDataPaths() != 0 13668 || filter.countDataSchemes() > 1 13669 || filter.countDataTypes() != 0) { 13670 throw new IllegalArgumentException( 13671 "replacePreferredActivity expects filter to have no data authorities, " + 13672 "paths, or types; and at most one scheme."); 13673 } 13674 13675 final int callingUid = Binder.getCallingUid(); 13676 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13677 synchronized (mPackages) { 13678 if (mContext.checkCallingOrSelfPermission( 13679 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13680 != PackageManager.PERMISSION_GRANTED) { 13681 if (getUidTargetSdkVersionLockedLPr(callingUid) 13682 < Build.VERSION_CODES.FROYO) { 13683 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13684 + Binder.getCallingUid()); 13685 return; 13686 } 13687 mContext.enforceCallingOrSelfPermission( 13688 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13689 } 13690 13691 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13692 if (pir != null) { 13693 // Get all of the existing entries that exactly match this filter. 13694 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13695 if (existing != null && existing.size() == 1) { 13696 PreferredActivity cur = existing.get(0); 13697 if (DEBUG_PREFERRED) { 13698 Slog.i(TAG, "Checking replace of preferred:"); 13699 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13700 if (!cur.mPref.mAlways) { 13701 Slog.i(TAG, " -- CUR; not mAlways!"); 13702 } else { 13703 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13704 Slog.i(TAG, " -- CUR: mSet=" 13705 + Arrays.toString(cur.mPref.mSetComponents)); 13706 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13707 Slog.i(TAG, " -- NEW: mMatch=" 13708 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13709 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13710 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13711 } 13712 } 13713 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13714 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13715 && cur.mPref.sameSet(set)) { 13716 // Setting the preferred activity to what it happens to be already 13717 if (DEBUG_PREFERRED) { 13718 Slog.i(TAG, "Replacing with same preferred activity " 13719 + cur.mPref.mShortComponent + " for user " 13720 + userId + ":"); 13721 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13722 } 13723 return; 13724 } 13725 } 13726 13727 if (existing != null) { 13728 if (DEBUG_PREFERRED) { 13729 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13730 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13731 } 13732 for (int i = 0; i < existing.size(); i++) { 13733 PreferredActivity pa = existing.get(i); 13734 if (DEBUG_PREFERRED) { 13735 Slog.i(TAG, "Removing existing preferred activity " 13736 + pa.mPref.mComponent + ":"); 13737 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13738 } 13739 pir.removeFilter(pa); 13740 } 13741 } 13742 } 13743 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13744 "Replacing preferred"); 13745 } 13746 } 13747 13748 @Override 13749 public void clearPackagePreferredActivities(String packageName) { 13750 final int uid = Binder.getCallingUid(); 13751 // writer 13752 synchronized (mPackages) { 13753 PackageParser.Package pkg = mPackages.get(packageName); 13754 if (pkg == null || pkg.applicationInfo.uid != uid) { 13755 if (mContext.checkCallingOrSelfPermission( 13756 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13757 != PackageManager.PERMISSION_GRANTED) { 13758 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13759 < Build.VERSION_CODES.FROYO) { 13760 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13761 + Binder.getCallingUid()); 13762 return; 13763 } 13764 mContext.enforceCallingOrSelfPermission( 13765 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13766 } 13767 } 13768 13769 int user = UserHandle.getCallingUserId(); 13770 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13771 scheduleWritePackageRestrictionsLocked(user); 13772 } 13773 } 13774 } 13775 13776 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13777 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13778 ArrayList<PreferredActivity> removed = null; 13779 boolean changed = false; 13780 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13781 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13782 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13783 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13784 continue; 13785 } 13786 Iterator<PreferredActivity> it = pir.filterIterator(); 13787 while (it.hasNext()) { 13788 PreferredActivity pa = it.next(); 13789 // Mark entry for removal only if it matches the package name 13790 // and the entry is of type "always". 13791 if (packageName == null || 13792 (pa.mPref.mComponent.getPackageName().equals(packageName) 13793 && pa.mPref.mAlways)) { 13794 if (removed == null) { 13795 removed = new ArrayList<PreferredActivity>(); 13796 } 13797 removed.add(pa); 13798 } 13799 } 13800 if (removed != null) { 13801 for (int j=0; j<removed.size(); j++) { 13802 PreferredActivity pa = removed.get(j); 13803 pir.removeFilter(pa); 13804 } 13805 changed = true; 13806 } 13807 } 13808 return changed; 13809 } 13810 13811 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13812 private void clearIntentFilterVerificationsLPw(int userId) { 13813 final int packageCount = mPackages.size(); 13814 for (int i = 0; i < packageCount; i++) { 13815 PackageParser.Package pkg = mPackages.valueAt(i); 13816 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13817 } 13818 } 13819 13820 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13821 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13822 if (userId == UserHandle.USER_ALL) { 13823 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13824 sUserManager.getUserIds())) { 13825 for (int oneUserId : sUserManager.getUserIds()) { 13826 scheduleWritePackageRestrictionsLocked(oneUserId); 13827 } 13828 } 13829 } else { 13830 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13831 scheduleWritePackageRestrictionsLocked(userId); 13832 } 13833 } 13834 } 13835 13836 void clearDefaultBrowserIfNeeded(String packageName) { 13837 for (int oneUserId : sUserManager.getUserIds()) { 13838 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13839 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13840 if (packageName.equals(defaultBrowserPackageName)) { 13841 setDefaultBrowserPackageName(null, oneUserId); 13842 } 13843 } 13844 } 13845 13846 @Override 13847 public void resetApplicationPreferences(int userId) { 13848 mContext.enforceCallingOrSelfPermission( 13849 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13850 // writer 13851 synchronized (mPackages) { 13852 final long identity = Binder.clearCallingIdentity(); 13853 try { 13854 clearPackagePreferredActivitiesLPw(null, userId); 13855 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13856 // TODO: We have to reset the default SMS and Phone. This requires 13857 // significant refactoring to keep all default apps in the package 13858 // manager (cleaner but more work) or have the services provide 13859 // callbacks to the package manager to request a default app reset. 13860 applyFactoryDefaultBrowserLPw(userId); 13861 clearIntentFilterVerificationsLPw(userId); 13862 primeDomainVerificationsLPw(userId); 13863 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 13864 scheduleWritePackageRestrictionsLocked(userId); 13865 } finally { 13866 Binder.restoreCallingIdentity(identity); 13867 } 13868 } 13869 } 13870 13871 @Override 13872 public int getPreferredActivities(List<IntentFilter> outFilters, 13873 List<ComponentName> outActivities, String packageName) { 13874 13875 int num = 0; 13876 final int userId = UserHandle.getCallingUserId(); 13877 // reader 13878 synchronized (mPackages) { 13879 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13880 if (pir != null) { 13881 final Iterator<PreferredActivity> it = pir.filterIterator(); 13882 while (it.hasNext()) { 13883 final PreferredActivity pa = it.next(); 13884 if (packageName == null 13885 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13886 && pa.mPref.mAlways)) { 13887 if (outFilters != null) { 13888 outFilters.add(new IntentFilter(pa)); 13889 } 13890 if (outActivities != null) { 13891 outActivities.add(pa.mPref.mComponent); 13892 } 13893 } 13894 } 13895 } 13896 } 13897 13898 return num; 13899 } 13900 13901 @Override 13902 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13903 int userId) { 13904 int callingUid = Binder.getCallingUid(); 13905 if (callingUid != Process.SYSTEM_UID) { 13906 throw new SecurityException( 13907 "addPersistentPreferredActivity can only be run by the system"); 13908 } 13909 if (filter.countActions() == 0) { 13910 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13911 return; 13912 } 13913 synchronized (mPackages) { 13914 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13915 " :"); 13916 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13917 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13918 new PersistentPreferredActivity(filter, activity)); 13919 scheduleWritePackageRestrictionsLocked(userId); 13920 } 13921 } 13922 13923 @Override 13924 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13925 int callingUid = Binder.getCallingUid(); 13926 if (callingUid != Process.SYSTEM_UID) { 13927 throw new SecurityException( 13928 "clearPackagePersistentPreferredActivities can only be run by the system"); 13929 } 13930 ArrayList<PersistentPreferredActivity> removed = null; 13931 boolean changed = false; 13932 synchronized (mPackages) { 13933 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13934 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13935 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13936 .valueAt(i); 13937 if (userId != thisUserId) { 13938 continue; 13939 } 13940 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13941 while (it.hasNext()) { 13942 PersistentPreferredActivity ppa = it.next(); 13943 // Mark entry for removal only if it matches the package name. 13944 if (ppa.mComponent.getPackageName().equals(packageName)) { 13945 if (removed == null) { 13946 removed = new ArrayList<PersistentPreferredActivity>(); 13947 } 13948 removed.add(ppa); 13949 } 13950 } 13951 if (removed != null) { 13952 for (int j=0; j<removed.size(); j++) { 13953 PersistentPreferredActivity ppa = removed.get(j); 13954 ppir.removeFilter(ppa); 13955 } 13956 changed = true; 13957 } 13958 } 13959 13960 if (changed) { 13961 scheduleWritePackageRestrictionsLocked(userId); 13962 } 13963 } 13964 } 13965 13966 /** 13967 * Common machinery for picking apart a restored XML blob and passing 13968 * it to a caller-supplied functor to be applied to the running system. 13969 */ 13970 private void restoreFromXml(XmlPullParser parser, int userId, 13971 String expectedStartTag, BlobXmlRestorer functor) 13972 throws IOException, XmlPullParserException { 13973 int type; 13974 while ((type = parser.next()) != XmlPullParser.START_TAG 13975 && type != XmlPullParser.END_DOCUMENT) { 13976 } 13977 if (type != XmlPullParser.START_TAG) { 13978 // oops didn't find a start tag?! 13979 if (DEBUG_BACKUP) { 13980 Slog.e(TAG, "Didn't find start tag during restore"); 13981 } 13982 return; 13983 } 13984 13985 // this is supposed to be TAG_PREFERRED_BACKUP 13986 if (!expectedStartTag.equals(parser.getName())) { 13987 if (DEBUG_BACKUP) { 13988 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13989 } 13990 return; 13991 } 13992 13993 // skip interfering stuff, then we're aligned with the backing implementation 13994 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13995 functor.apply(parser, userId); 13996 } 13997 13998 private interface BlobXmlRestorer { 13999 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14000 } 14001 14002 /** 14003 * Non-Binder method, support for the backup/restore mechanism: write the 14004 * full set of preferred activities in its canonical XML format. Returns the 14005 * XML output as a byte array, or null if there is none. 14006 */ 14007 @Override 14008 public byte[] getPreferredActivityBackup(int userId) { 14009 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14010 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14011 } 14012 14013 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14014 try { 14015 final XmlSerializer serializer = new FastXmlSerializer(); 14016 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14017 serializer.startDocument(null, true); 14018 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14019 14020 synchronized (mPackages) { 14021 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14022 } 14023 14024 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14025 serializer.endDocument(); 14026 serializer.flush(); 14027 } catch (Exception e) { 14028 if (DEBUG_BACKUP) { 14029 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14030 } 14031 return null; 14032 } 14033 14034 return dataStream.toByteArray(); 14035 } 14036 14037 @Override 14038 public void restorePreferredActivities(byte[] backup, int userId) { 14039 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14040 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14041 } 14042 14043 try { 14044 final XmlPullParser parser = Xml.newPullParser(); 14045 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14046 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14047 new BlobXmlRestorer() { 14048 @Override 14049 public void apply(XmlPullParser parser, int userId) 14050 throws XmlPullParserException, IOException { 14051 synchronized (mPackages) { 14052 mSettings.readPreferredActivitiesLPw(parser, userId); 14053 } 14054 } 14055 } ); 14056 } catch (Exception e) { 14057 if (DEBUG_BACKUP) { 14058 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14059 } 14060 } 14061 } 14062 14063 /** 14064 * Non-Binder method, support for the backup/restore mechanism: write the 14065 * default browser (etc) settings in its canonical XML format. Returns the default 14066 * browser XML representation as a byte array, or null if there is none. 14067 */ 14068 @Override 14069 public byte[] getDefaultAppsBackup(int userId) { 14070 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14071 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14072 } 14073 14074 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14075 try { 14076 final XmlSerializer serializer = new FastXmlSerializer(); 14077 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14078 serializer.startDocument(null, true); 14079 serializer.startTag(null, TAG_DEFAULT_APPS); 14080 14081 synchronized (mPackages) { 14082 mSettings.writeDefaultAppsLPr(serializer, userId); 14083 } 14084 14085 serializer.endTag(null, TAG_DEFAULT_APPS); 14086 serializer.endDocument(); 14087 serializer.flush(); 14088 } catch (Exception e) { 14089 if (DEBUG_BACKUP) { 14090 Slog.e(TAG, "Unable to write default apps for backup", e); 14091 } 14092 return null; 14093 } 14094 14095 return dataStream.toByteArray(); 14096 } 14097 14098 @Override 14099 public void restoreDefaultApps(byte[] backup, int userId) { 14100 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14101 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14102 } 14103 14104 try { 14105 final XmlPullParser parser = Xml.newPullParser(); 14106 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14107 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14108 new BlobXmlRestorer() { 14109 @Override 14110 public void apply(XmlPullParser parser, int userId) 14111 throws XmlPullParserException, IOException { 14112 synchronized (mPackages) { 14113 mSettings.readDefaultAppsLPw(parser, userId); 14114 } 14115 } 14116 } ); 14117 } catch (Exception e) { 14118 if (DEBUG_BACKUP) { 14119 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14120 } 14121 } 14122 } 14123 14124 @Override 14125 public byte[] getIntentFilterVerificationBackup(int userId) { 14126 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14127 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14128 } 14129 14130 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14131 try { 14132 final XmlSerializer serializer = new FastXmlSerializer(); 14133 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14134 serializer.startDocument(null, true); 14135 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14136 14137 synchronized (mPackages) { 14138 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14139 } 14140 14141 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14142 serializer.endDocument(); 14143 serializer.flush(); 14144 } catch (Exception e) { 14145 if (DEBUG_BACKUP) { 14146 Slog.e(TAG, "Unable to write default apps for backup", e); 14147 } 14148 return null; 14149 } 14150 14151 return dataStream.toByteArray(); 14152 } 14153 14154 @Override 14155 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14156 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14157 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14158 } 14159 14160 try { 14161 final XmlPullParser parser = Xml.newPullParser(); 14162 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14163 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14164 new BlobXmlRestorer() { 14165 @Override 14166 public void apply(XmlPullParser parser, int userId) 14167 throws XmlPullParserException, IOException { 14168 synchronized (mPackages) { 14169 mSettings.readAllDomainVerificationsLPr(parser, userId); 14170 mSettings.writeLPr(); 14171 } 14172 } 14173 } ); 14174 } catch (Exception e) { 14175 if (DEBUG_BACKUP) { 14176 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14177 } 14178 } 14179 } 14180 14181 @Override 14182 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14183 int sourceUserId, int targetUserId, int flags) { 14184 mContext.enforceCallingOrSelfPermission( 14185 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14186 int callingUid = Binder.getCallingUid(); 14187 enforceOwnerRights(ownerPackage, callingUid); 14188 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14189 if (intentFilter.countActions() == 0) { 14190 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14191 return; 14192 } 14193 synchronized (mPackages) { 14194 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14195 ownerPackage, targetUserId, flags); 14196 CrossProfileIntentResolver resolver = 14197 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14198 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14199 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14200 if (existing != null) { 14201 int size = existing.size(); 14202 for (int i = 0; i < size; i++) { 14203 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14204 return; 14205 } 14206 } 14207 } 14208 resolver.addFilter(newFilter); 14209 scheduleWritePackageRestrictionsLocked(sourceUserId); 14210 } 14211 } 14212 14213 @Override 14214 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14215 mContext.enforceCallingOrSelfPermission( 14216 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14217 int callingUid = Binder.getCallingUid(); 14218 enforceOwnerRights(ownerPackage, callingUid); 14219 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14220 synchronized (mPackages) { 14221 CrossProfileIntentResolver resolver = 14222 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14223 ArraySet<CrossProfileIntentFilter> set = 14224 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14225 for (CrossProfileIntentFilter filter : set) { 14226 if (filter.getOwnerPackage().equals(ownerPackage)) { 14227 resolver.removeFilter(filter); 14228 } 14229 } 14230 scheduleWritePackageRestrictionsLocked(sourceUserId); 14231 } 14232 } 14233 14234 // Enforcing that callingUid is owning pkg on userId 14235 private void enforceOwnerRights(String pkg, int callingUid) { 14236 // The system owns everything. 14237 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14238 return; 14239 } 14240 int callingUserId = UserHandle.getUserId(callingUid); 14241 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14242 if (pi == null) { 14243 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14244 + callingUserId); 14245 } 14246 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14247 throw new SecurityException("Calling uid " + callingUid 14248 + " does not own package " + pkg); 14249 } 14250 } 14251 14252 @Override 14253 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14254 Intent intent = new Intent(Intent.ACTION_MAIN); 14255 intent.addCategory(Intent.CATEGORY_HOME); 14256 14257 final int callingUserId = UserHandle.getCallingUserId(); 14258 List<ResolveInfo> list = queryIntentActivities(intent, null, 14259 PackageManager.GET_META_DATA, callingUserId); 14260 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14261 true, false, false, callingUserId); 14262 14263 allHomeCandidates.clear(); 14264 if (list != null) { 14265 for (ResolveInfo ri : list) { 14266 allHomeCandidates.add(ri); 14267 } 14268 } 14269 return (preferred == null || preferred.activityInfo == null) 14270 ? null 14271 : new ComponentName(preferred.activityInfo.packageName, 14272 preferred.activityInfo.name); 14273 } 14274 14275 @Override 14276 public void setApplicationEnabledSetting(String appPackageName, 14277 int newState, int flags, int userId, String callingPackage) { 14278 if (!sUserManager.exists(userId)) return; 14279 if (callingPackage == null) { 14280 callingPackage = Integer.toString(Binder.getCallingUid()); 14281 } 14282 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14283 } 14284 14285 @Override 14286 public void setComponentEnabledSetting(ComponentName componentName, 14287 int newState, int flags, int userId) { 14288 if (!sUserManager.exists(userId)) return; 14289 setEnabledSetting(componentName.getPackageName(), 14290 componentName.getClassName(), newState, flags, userId, null); 14291 } 14292 14293 private void setEnabledSetting(final String packageName, String className, int newState, 14294 final int flags, int userId, String callingPackage) { 14295 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14296 || newState == COMPONENT_ENABLED_STATE_ENABLED 14297 || newState == COMPONENT_ENABLED_STATE_DISABLED 14298 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14299 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14300 throw new IllegalArgumentException("Invalid new component state: " 14301 + newState); 14302 } 14303 PackageSetting pkgSetting; 14304 final int uid = Binder.getCallingUid(); 14305 final int permission = mContext.checkCallingOrSelfPermission( 14306 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14307 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14308 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14309 boolean sendNow = false; 14310 boolean isApp = (className == null); 14311 String componentName = isApp ? packageName : className; 14312 int packageUid = -1; 14313 ArrayList<String> components; 14314 14315 // writer 14316 synchronized (mPackages) { 14317 pkgSetting = mSettings.mPackages.get(packageName); 14318 if (pkgSetting == null) { 14319 if (className == null) { 14320 throw new IllegalArgumentException( 14321 "Unknown package: " + packageName); 14322 } 14323 throw new IllegalArgumentException( 14324 "Unknown component: " + packageName 14325 + "/" + className); 14326 } 14327 // Allow root and verify that userId is not being specified by a different user 14328 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14329 throw new SecurityException( 14330 "Permission Denial: attempt to change component state from pid=" 14331 + Binder.getCallingPid() 14332 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14333 } 14334 if (className == null) { 14335 // We're dealing with an application/package level state change 14336 if (pkgSetting.getEnabled(userId) == newState) { 14337 // Nothing to do 14338 return; 14339 } 14340 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14341 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14342 // Don't care about who enables an app. 14343 callingPackage = null; 14344 } 14345 pkgSetting.setEnabled(newState, userId, callingPackage); 14346 // pkgSetting.pkg.mSetEnabled = newState; 14347 } else { 14348 // We're dealing with a component level state change 14349 // First, verify that this is a valid class name. 14350 PackageParser.Package pkg = pkgSetting.pkg; 14351 if (pkg == null || !pkg.hasComponentClassName(className)) { 14352 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14353 throw new IllegalArgumentException("Component class " + className 14354 + " does not exist in " + packageName); 14355 } else { 14356 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14357 + className + " does not exist in " + packageName); 14358 } 14359 } 14360 switch (newState) { 14361 case COMPONENT_ENABLED_STATE_ENABLED: 14362 if (!pkgSetting.enableComponentLPw(className, userId)) { 14363 return; 14364 } 14365 break; 14366 case COMPONENT_ENABLED_STATE_DISABLED: 14367 if (!pkgSetting.disableComponentLPw(className, userId)) { 14368 return; 14369 } 14370 break; 14371 case COMPONENT_ENABLED_STATE_DEFAULT: 14372 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14373 return; 14374 } 14375 break; 14376 default: 14377 Slog.e(TAG, "Invalid new component state: " + newState); 14378 return; 14379 } 14380 } 14381 scheduleWritePackageRestrictionsLocked(userId); 14382 components = mPendingBroadcasts.get(userId, packageName); 14383 final boolean newPackage = components == null; 14384 if (newPackage) { 14385 components = new ArrayList<String>(); 14386 } 14387 if (!components.contains(componentName)) { 14388 components.add(componentName); 14389 } 14390 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14391 sendNow = true; 14392 // Purge entry from pending broadcast list if another one exists already 14393 // since we are sending one right away. 14394 mPendingBroadcasts.remove(userId, packageName); 14395 } else { 14396 if (newPackage) { 14397 mPendingBroadcasts.put(userId, packageName, components); 14398 } 14399 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14400 // Schedule a message 14401 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14402 } 14403 } 14404 } 14405 14406 long callingId = Binder.clearCallingIdentity(); 14407 try { 14408 if (sendNow) { 14409 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14410 sendPackageChangedBroadcast(packageName, 14411 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14412 } 14413 } finally { 14414 Binder.restoreCallingIdentity(callingId); 14415 } 14416 } 14417 14418 private void sendPackageChangedBroadcast(String packageName, 14419 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14420 if (DEBUG_INSTALL) 14421 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14422 + componentNames); 14423 Bundle extras = new Bundle(4); 14424 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14425 String nameList[] = new String[componentNames.size()]; 14426 componentNames.toArray(nameList); 14427 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14428 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14429 extras.putInt(Intent.EXTRA_UID, packageUid); 14430 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14431 new int[] {UserHandle.getUserId(packageUid)}); 14432 } 14433 14434 @Override 14435 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14436 if (!sUserManager.exists(userId)) return; 14437 final int uid = Binder.getCallingUid(); 14438 final int permission = mContext.checkCallingOrSelfPermission( 14439 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14440 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14441 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14442 // writer 14443 synchronized (mPackages) { 14444 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14445 allowedByPermission, uid, userId)) { 14446 scheduleWritePackageRestrictionsLocked(userId); 14447 } 14448 } 14449 } 14450 14451 @Override 14452 public String getInstallerPackageName(String packageName) { 14453 // reader 14454 synchronized (mPackages) { 14455 return mSettings.getInstallerPackageNameLPr(packageName); 14456 } 14457 } 14458 14459 @Override 14460 public int getApplicationEnabledSetting(String packageName, int userId) { 14461 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14462 int uid = Binder.getCallingUid(); 14463 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14464 // reader 14465 synchronized (mPackages) { 14466 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14467 } 14468 } 14469 14470 @Override 14471 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14472 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14473 int uid = Binder.getCallingUid(); 14474 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14475 // reader 14476 synchronized (mPackages) { 14477 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14478 } 14479 } 14480 14481 @Override 14482 public void enterSafeMode() { 14483 enforceSystemOrRoot("Only the system can request entering safe mode"); 14484 14485 if (!mSystemReady) { 14486 mSafeMode = true; 14487 } 14488 } 14489 14490 @Override 14491 public void systemReady() { 14492 mSystemReady = true; 14493 14494 // Read the compatibilty setting when the system is ready. 14495 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14496 mContext.getContentResolver(), 14497 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14498 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14499 if (DEBUG_SETTINGS) { 14500 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14501 } 14502 14503 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14504 14505 synchronized (mPackages) { 14506 // Verify that all of the preferred activity components actually 14507 // exist. It is possible for applications to be updated and at 14508 // that point remove a previously declared activity component that 14509 // had been set as a preferred activity. We try to clean this up 14510 // the next time we encounter that preferred activity, but it is 14511 // possible for the user flow to never be able to return to that 14512 // situation so here we do a sanity check to make sure we haven't 14513 // left any junk around. 14514 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14515 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14516 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14517 removed.clear(); 14518 for (PreferredActivity pa : pir.filterSet()) { 14519 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14520 removed.add(pa); 14521 } 14522 } 14523 if (removed.size() > 0) { 14524 for (int r=0; r<removed.size(); r++) { 14525 PreferredActivity pa = removed.get(r); 14526 Slog.w(TAG, "Removing dangling preferred activity: " 14527 + pa.mPref.mComponent); 14528 pir.removeFilter(pa); 14529 } 14530 mSettings.writePackageRestrictionsLPr( 14531 mSettings.mPreferredActivities.keyAt(i)); 14532 } 14533 } 14534 14535 for (int userId : UserManagerService.getInstance().getUserIds()) { 14536 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14537 grantPermissionsUserIds = ArrayUtils.appendInt( 14538 grantPermissionsUserIds, userId); 14539 } 14540 } 14541 } 14542 sUserManager.systemReady(); 14543 14544 // If we upgraded grant all default permissions before kicking off. 14545 for (int userId : grantPermissionsUserIds) { 14546 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14547 } 14548 14549 // Kick off any messages waiting for system ready 14550 if (mPostSystemReadyMessages != null) { 14551 for (Message msg : mPostSystemReadyMessages) { 14552 msg.sendToTarget(); 14553 } 14554 mPostSystemReadyMessages = null; 14555 } 14556 14557 // Watch for external volumes that come and go over time 14558 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14559 storage.registerListener(mStorageListener); 14560 14561 mInstallerService.systemReady(); 14562 mPackageDexOptimizer.systemReady(); 14563 14564 MountServiceInternal mountServiceInternal = LocalServices.getService( 14565 MountServiceInternal.class); 14566 mountServiceInternal.addExternalStoragePolicy( 14567 new MountServiceInternal.ExternalStorageMountPolicy() { 14568 @Override 14569 public int getMountMode(int uid, String packageName) { 14570 if (Process.isIsolated(uid)) { 14571 return Zygote.MOUNT_EXTERNAL_NONE; 14572 } 14573 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14574 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14575 } 14576 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14577 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14578 } 14579 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14580 return Zygote.MOUNT_EXTERNAL_READ; 14581 } 14582 return Zygote.MOUNT_EXTERNAL_WRITE; 14583 } 14584 14585 @Override 14586 public boolean hasExternalStorage(int uid, String packageName) { 14587 return true; 14588 } 14589 }); 14590 } 14591 14592 @Override 14593 public boolean isSafeMode() { 14594 return mSafeMode; 14595 } 14596 14597 @Override 14598 public boolean hasSystemUidErrors() { 14599 return mHasSystemUidErrors; 14600 } 14601 14602 static String arrayToString(int[] array) { 14603 StringBuffer buf = new StringBuffer(128); 14604 buf.append('['); 14605 if (array != null) { 14606 for (int i=0; i<array.length; i++) { 14607 if (i > 0) buf.append(", "); 14608 buf.append(array[i]); 14609 } 14610 } 14611 buf.append(']'); 14612 return buf.toString(); 14613 } 14614 14615 static class DumpState { 14616 public static final int DUMP_LIBS = 1 << 0; 14617 public static final int DUMP_FEATURES = 1 << 1; 14618 public static final int DUMP_RESOLVERS = 1 << 2; 14619 public static final int DUMP_PERMISSIONS = 1 << 3; 14620 public static final int DUMP_PACKAGES = 1 << 4; 14621 public static final int DUMP_SHARED_USERS = 1 << 5; 14622 public static final int DUMP_MESSAGES = 1 << 6; 14623 public static final int DUMP_PROVIDERS = 1 << 7; 14624 public static final int DUMP_VERIFIERS = 1 << 8; 14625 public static final int DUMP_PREFERRED = 1 << 9; 14626 public static final int DUMP_PREFERRED_XML = 1 << 10; 14627 public static final int DUMP_KEYSETS = 1 << 11; 14628 public static final int DUMP_VERSION = 1 << 12; 14629 public static final int DUMP_INSTALLS = 1 << 13; 14630 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14631 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14632 14633 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14634 14635 private int mTypes; 14636 14637 private int mOptions; 14638 14639 private boolean mTitlePrinted; 14640 14641 private SharedUserSetting mSharedUser; 14642 14643 public boolean isDumping(int type) { 14644 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14645 return true; 14646 } 14647 14648 return (mTypes & type) != 0; 14649 } 14650 14651 public void setDump(int type) { 14652 mTypes |= type; 14653 } 14654 14655 public boolean isOptionEnabled(int option) { 14656 return (mOptions & option) != 0; 14657 } 14658 14659 public void setOptionEnabled(int option) { 14660 mOptions |= option; 14661 } 14662 14663 public boolean onTitlePrinted() { 14664 final boolean printed = mTitlePrinted; 14665 mTitlePrinted = true; 14666 return printed; 14667 } 14668 14669 public boolean getTitlePrinted() { 14670 return mTitlePrinted; 14671 } 14672 14673 public void setTitlePrinted(boolean enabled) { 14674 mTitlePrinted = enabled; 14675 } 14676 14677 public SharedUserSetting getSharedUser() { 14678 return mSharedUser; 14679 } 14680 14681 public void setSharedUser(SharedUserSetting user) { 14682 mSharedUser = user; 14683 } 14684 } 14685 14686 @Override 14687 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14688 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14689 != PackageManager.PERMISSION_GRANTED) { 14690 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14691 + Binder.getCallingPid() 14692 + ", uid=" + Binder.getCallingUid() 14693 + " without permission " 14694 + android.Manifest.permission.DUMP); 14695 return; 14696 } 14697 14698 DumpState dumpState = new DumpState(); 14699 boolean fullPreferred = false; 14700 boolean checkin = false; 14701 14702 String packageName = null; 14703 ArraySet<String> permissionNames = null; 14704 14705 int opti = 0; 14706 while (opti < args.length) { 14707 String opt = args[opti]; 14708 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14709 break; 14710 } 14711 opti++; 14712 14713 if ("-a".equals(opt)) { 14714 // Right now we only know how to print all. 14715 } else if ("-h".equals(opt)) { 14716 pw.println("Package manager dump options:"); 14717 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14718 pw.println(" --checkin: dump for a checkin"); 14719 pw.println(" -f: print details of intent filters"); 14720 pw.println(" -h: print this help"); 14721 pw.println(" cmd may be one of:"); 14722 pw.println(" l[ibraries]: list known shared libraries"); 14723 pw.println(" f[ibraries]: list device features"); 14724 pw.println(" k[eysets]: print known keysets"); 14725 pw.println(" r[esolvers]: dump intent resolvers"); 14726 pw.println(" perm[issions]: dump permissions"); 14727 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14728 pw.println(" pref[erred]: print preferred package settings"); 14729 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14730 pw.println(" prov[iders]: dump content providers"); 14731 pw.println(" p[ackages]: dump installed packages"); 14732 pw.println(" s[hared-users]: dump shared user IDs"); 14733 pw.println(" m[essages]: print collected runtime messages"); 14734 pw.println(" v[erifiers]: print package verifier info"); 14735 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14736 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14737 pw.println(" version: print database version info"); 14738 pw.println(" write: write current settings now"); 14739 pw.println(" installs: details about install sessions"); 14740 pw.println(" <package.name>: info about given package"); 14741 return; 14742 } else if ("--checkin".equals(opt)) { 14743 checkin = true; 14744 } else if ("-f".equals(opt)) { 14745 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14746 } else { 14747 pw.println("Unknown argument: " + opt + "; use -h for help"); 14748 } 14749 } 14750 14751 // Is the caller requesting to dump a particular piece of data? 14752 if (opti < args.length) { 14753 String cmd = args[opti]; 14754 opti++; 14755 // Is this a package name? 14756 if ("android".equals(cmd) || cmd.contains(".")) { 14757 packageName = cmd; 14758 // When dumping a single package, we always dump all of its 14759 // filter information since the amount of data will be reasonable. 14760 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14761 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14762 dumpState.setDump(DumpState.DUMP_LIBS); 14763 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14764 dumpState.setDump(DumpState.DUMP_FEATURES); 14765 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14766 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14767 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14768 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14769 } else if ("permission".equals(cmd)) { 14770 if (opti >= args.length) { 14771 pw.println("Error: permission requires permission name"); 14772 return; 14773 } 14774 permissionNames = new ArraySet<>(); 14775 while (opti < args.length) { 14776 permissionNames.add(args[opti]); 14777 opti++; 14778 } 14779 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14780 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14781 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14782 dumpState.setDump(DumpState.DUMP_PREFERRED); 14783 } else if ("preferred-xml".equals(cmd)) { 14784 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14785 if (opti < args.length && "--full".equals(args[opti])) { 14786 fullPreferred = true; 14787 opti++; 14788 } 14789 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14790 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14791 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14792 dumpState.setDump(DumpState.DUMP_PACKAGES); 14793 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14794 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14795 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14796 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14797 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14798 dumpState.setDump(DumpState.DUMP_MESSAGES); 14799 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14800 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14801 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14802 || "intent-filter-verifiers".equals(cmd)) { 14803 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14804 } else if ("version".equals(cmd)) { 14805 dumpState.setDump(DumpState.DUMP_VERSION); 14806 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14807 dumpState.setDump(DumpState.DUMP_KEYSETS); 14808 } else if ("installs".equals(cmd)) { 14809 dumpState.setDump(DumpState.DUMP_INSTALLS); 14810 } else if ("write".equals(cmd)) { 14811 synchronized (mPackages) { 14812 mSettings.writeLPr(); 14813 pw.println("Settings written."); 14814 return; 14815 } 14816 } 14817 } 14818 14819 if (checkin) { 14820 pw.println("vers,1"); 14821 } 14822 14823 // reader 14824 synchronized (mPackages) { 14825 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14826 if (!checkin) { 14827 if (dumpState.onTitlePrinted()) 14828 pw.println(); 14829 pw.println("Database versions:"); 14830 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 14831 } 14832 } 14833 14834 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14835 if (!checkin) { 14836 if (dumpState.onTitlePrinted()) 14837 pw.println(); 14838 pw.println("Verifiers:"); 14839 pw.print(" Required: "); 14840 pw.print(mRequiredVerifierPackage); 14841 pw.print(" (uid="); 14842 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14843 pw.println(")"); 14844 } else if (mRequiredVerifierPackage != null) { 14845 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14846 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14847 } 14848 } 14849 14850 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14851 packageName == null) { 14852 if (mIntentFilterVerifierComponent != null) { 14853 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14854 if (!checkin) { 14855 if (dumpState.onTitlePrinted()) 14856 pw.println(); 14857 pw.println("Intent Filter Verifier:"); 14858 pw.print(" Using: "); 14859 pw.print(verifierPackageName); 14860 pw.print(" (uid="); 14861 pw.print(getPackageUid(verifierPackageName, 0)); 14862 pw.println(")"); 14863 } else if (verifierPackageName != null) { 14864 pw.print("ifv,"); pw.print(verifierPackageName); 14865 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14866 } 14867 } else { 14868 pw.println(); 14869 pw.println("No Intent Filter Verifier available!"); 14870 } 14871 } 14872 14873 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14874 boolean printedHeader = false; 14875 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14876 while (it.hasNext()) { 14877 String name = it.next(); 14878 SharedLibraryEntry ent = mSharedLibraries.get(name); 14879 if (!checkin) { 14880 if (!printedHeader) { 14881 if (dumpState.onTitlePrinted()) 14882 pw.println(); 14883 pw.println("Libraries:"); 14884 printedHeader = true; 14885 } 14886 pw.print(" "); 14887 } else { 14888 pw.print("lib,"); 14889 } 14890 pw.print(name); 14891 if (!checkin) { 14892 pw.print(" -> "); 14893 } 14894 if (ent.path != null) { 14895 if (!checkin) { 14896 pw.print("(jar) "); 14897 pw.print(ent.path); 14898 } else { 14899 pw.print(",jar,"); 14900 pw.print(ent.path); 14901 } 14902 } else { 14903 if (!checkin) { 14904 pw.print("(apk) "); 14905 pw.print(ent.apk); 14906 } else { 14907 pw.print(",apk,"); 14908 pw.print(ent.apk); 14909 } 14910 } 14911 pw.println(); 14912 } 14913 } 14914 14915 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14916 if (dumpState.onTitlePrinted()) 14917 pw.println(); 14918 if (!checkin) { 14919 pw.println("Features:"); 14920 } 14921 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14922 while (it.hasNext()) { 14923 String name = it.next(); 14924 if (!checkin) { 14925 pw.print(" "); 14926 } else { 14927 pw.print("feat,"); 14928 } 14929 pw.println(name); 14930 } 14931 } 14932 14933 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14934 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14935 : "Activity Resolver Table:", " ", packageName, 14936 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14937 dumpState.setTitlePrinted(true); 14938 } 14939 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14940 : "Receiver Resolver Table:", " ", packageName, 14941 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14942 dumpState.setTitlePrinted(true); 14943 } 14944 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14945 : "Service Resolver Table:", " ", packageName, 14946 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14947 dumpState.setTitlePrinted(true); 14948 } 14949 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14950 : "Provider Resolver Table:", " ", packageName, 14951 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14952 dumpState.setTitlePrinted(true); 14953 } 14954 } 14955 14956 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14957 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14958 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14959 int user = mSettings.mPreferredActivities.keyAt(i); 14960 if (pir.dump(pw, 14961 dumpState.getTitlePrinted() 14962 ? "\nPreferred Activities User " + user + ":" 14963 : "Preferred Activities User " + user + ":", " ", 14964 packageName, true, false)) { 14965 dumpState.setTitlePrinted(true); 14966 } 14967 } 14968 } 14969 14970 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14971 pw.flush(); 14972 FileOutputStream fout = new FileOutputStream(fd); 14973 BufferedOutputStream str = new BufferedOutputStream(fout); 14974 XmlSerializer serializer = new FastXmlSerializer(); 14975 try { 14976 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14977 serializer.startDocument(null, true); 14978 serializer.setFeature( 14979 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14980 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14981 serializer.endDocument(); 14982 serializer.flush(); 14983 } catch (IllegalArgumentException e) { 14984 pw.println("Failed writing: " + e); 14985 } catch (IllegalStateException e) { 14986 pw.println("Failed writing: " + e); 14987 } catch (IOException e) { 14988 pw.println("Failed writing: " + e); 14989 } 14990 } 14991 14992 if (!checkin 14993 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14994 && packageName == null) { 14995 pw.println(); 14996 int count = mSettings.mPackages.size(); 14997 if (count == 0) { 14998 pw.println("No applications!"); 14999 pw.println(); 15000 } else { 15001 final String prefix = " "; 15002 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15003 if (allPackageSettings.size() == 0) { 15004 pw.println("No domain preferred apps!"); 15005 pw.println(); 15006 } else { 15007 pw.println("App verification status:"); 15008 pw.println(); 15009 count = 0; 15010 for (PackageSetting ps : allPackageSettings) { 15011 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15012 if (ivi == null || ivi.getPackageName() == null) continue; 15013 pw.println(prefix + "Package: " + ivi.getPackageName()); 15014 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15015 pw.println(prefix + "Status: " + ivi.getStatusString()); 15016 pw.println(); 15017 count++; 15018 } 15019 if (count == 0) { 15020 pw.println(prefix + "No app verification established."); 15021 pw.println(); 15022 } 15023 for (int userId : sUserManager.getUserIds()) { 15024 pw.println("App linkages for user " + userId + ":"); 15025 pw.println(); 15026 count = 0; 15027 for (PackageSetting ps : allPackageSettings) { 15028 final long status = ps.getDomainVerificationStatusForUser(userId); 15029 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15030 continue; 15031 } 15032 pw.println(prefix + "Package: " + ps.name); 15033 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15034 String statusStr = IntentFilterVerificationInfo. 15035 getStatusStringFromValue(status); 15036 pw.println(prefix + "Status: " + statusStr); 15037 pw.println(); 15038 count++; 15039 } 15040 if (count == 0) { 15041 pw.println(prefix + "No configured app linkages."); 15042 pw.println(); 15043 } 15044 } 15045 } 15046 } 15047 } 15048 15049 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15050 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15051 if (packageName == null && permissionNames == null) { 15052 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15053 if (iperm == 0) { 15054 if (dumpState.onTitlePrinted()) 15055 pw.println(); 15056 pw.println("AppOp Permissions:"); 15057 } 15058 pw.print(" AppOp Permission "); 15059 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15060 pw.println(":"); 15061 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15062 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15063 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15064 } 15065 } 15066 } 15067 } 15068 15069 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15070 boolean printedSomething = false; 15071 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15072 if (packageName != null && !packageName.equals(p.info.packageName)) { 15073 continue; 15074 } 15075 if (!printedSomething) { 15076 if (dumpState.onTitlePrinted()) 15077 pw.println(); 15078 pw.println("Registered ContentProviders:"); 15079 printedSomething = true; 15080 } 15081 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15082 pw.print(" "); pw.println(p.toString()); 15083 } 15084 printedSomething = false; 15085 for (Map.Entry<String, PackageParser.Provider> entry : 15086 mProvidersByAuthority.entrySet()) { 15087 PackageParser.Provider p = entry.getValue(); 15088 if (packageName != null && !packageName.equals(p.info.packageName)) { 15089 continue; 15090 } 15091 if (!printedSomething) { 15092 if (dumpState.onTitlePrinted()) 15093 pw.println(); 15094 pw.println("ContentProvider Authorities:"); 15095 printedSomething = true; 15096 } 15097 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15098 pw.print(" "); pw.println(p.toString()); 15099 if (p.info != null && p.info.applicationInfo != null) { 15100 final String appInfo = p.info.applicationInfo.toString(); 15101 pw.print(" applicationInfo="); pw.println(appInfo); 15102 } 15103 } 15104 } 15105 15106 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15107 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15108 } 15109 15110 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15111 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15112 } 15113 15114 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15115 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15116 } 15117 15118 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15119 // XXX should handle packageName != null by dumping only install data that 15120 // the given package is involved with. 15121 if (dumpState.onTitlePrinted()) pw.println(); 15122 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15123 } 15124 15125 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15126 if (dumpState.onTitlePrinted()) pw.println(); 15127 mSettings.dumpReadMessagesLPr(pw, dumpState); 15128 15129 pw.println(); 15130 pw.println("Package warning messages:"); 15131 BufferedReader in = null; 15132 String line = null; 15133 try { 15134 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15135 while ((line = in.readLine()) != null) { 15136 if (line.contains("ignored: updated version")) continue; 15137 pw.println(line); 15138 } 15139 } catch (IOException ignored) { 15140 } finally { 15141 IoUtils.closeQuietly(in); 15142 } 15143 } 15144 15145 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15146 BufferedReader in = null; 15147 String line = null; 15148 try { 15149 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15150 while ((line = in.readLine()) != null) { 15151 if (line.contains("ignored: updated version")) continue; 15152 pw.print("msg,"); 15153 pw.println(line); 15154 } 15155 } catch (IOException ignored) { 15156 } finally { 15157 IoUtils.closeQuietly(in); 15158 } 15159 } 15160 } 15161 } 15162 15163 private String dumpDomainString(String packageName) { 15164 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15165 List<IntentFilter> filters = getAllIntentFilters(packageName); 15166 15167 ArraySet<String> result = new ArraySet<>(); 15168 if (iviList.size() > 0) { 15169 for (IntentFilterVerificationInfo ivi : iviList) { 15170 for (String host : ivi.getDomains()) { 15171 result.add(host); 15172 } 15173 } 15174 } 15175 if (filters != null && filters.size() > 0) { 15176 for (IntentFilter filter : filters) { 15177 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15178 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15179 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15180 result.addAll(filter.getHostsList()); 15181 } 15182 } 15183 } 15184 15185 StringBuilder sb = new StringBuilder(result.size() * 16); 15186 for (String domain : result) { 15187 if (sb.length() > 0) sb.append(" "); 15188 sb.append(domain); 15189 } 15190 return sb.toString(); 15191 } 15192 15193 // ------- apps on sdcard specific code ------- 15194 static final boolean DEBUG_SD_INSTALL = false; 15195 15196 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15197 15198 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15199 15200 private boolean mMediaMounted = false; 15201 15202 static String getEncryptKey() { 15203 try { 15204 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15205 SD_ENCRYPTION_KEYSTORE_NAME); 15206 if (sdEncKey == null) { 15207 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15208 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15209 if (sdEncKey == null) { 15210 Slog.e(TAG, "Failed to create encryption keys"); 15211 return null; 15212 } 15213 } 15214 return sdEncKey; 15215 } catch (NoSuchAlgorithmException nsae) { 15216 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15217 return null; 15218 } catch (IOException ioe) { 15219 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15220 return null; 15221 } 15222 } 15223 15224 /* 15225 * Update media status on PackageManager. 15226 */ 15227 @Override 15228 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15229 int callingUid = Binder.getCallingUid(); 15230 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15231 throw new SecurityException("Media status can only be updated by the system"); 15232 } 15233 // reader; this apparently protects mMediaMounted, but should probably 15234 // be a different lock in that case. 15235 synchronized (mPackages) { 15236 Log.i(TAG, "Updating external media status from " 15237 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15238 + (mediaStatus ? "mounted" : "unmounted")); 15239 if (DEBUG_SD_INSTALL) 15240 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15241 + ", mMediaMounted=" + mMediaMounted); 15242 if (mediaStatus == mMediaMounted) { 15243 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15244 : 0, -1); 15245 mHandler.sendMessage(msg); 15246 return; 15247 } 15248 mMediaMounted = mediaStatus; 15249 } 15250 // Queue up an async operation since the package installation may take a 15251 // little while. 15252 mHandler.post(new Runnable() { 15253 public void run() { 15254 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15255 } 15256 }); 15257 } 15258 15259 /** 15260 * Called by MountService when the initial ASECs to scan are available. 15261 * Should block until all the ASEC containers are finished being scanned. 15262 */ 15263 public void scanAvailableAsecs() { 15264 updateExternalMediaStatusInner(true, false, false); 15265 if (mShouldRestoreconData) { 15266 SELinuxMMAC.setRestoreconDone(); 15267 mShouldRestoreconData = false; 15268 } 15269 } 15270 15271 /* 15272 * Collect information of applications on external media, map them against 15273 * existing containers and update information based on current mount status. 15274 * Please note that we always have to report status if reportStatus has been 15275 * set to true especially when unloading packages. 15276 */ 15277 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15278 boolean externalStorage) { 15279 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15280 int[] uidArr = EmptyArray.INT; 15281 15282 final String[] list = PackageHelper.getSecureContainerList(); 15283 if (ArrayUtils.isEmpty(list)) { 15284 Log.i(TAG, "No secure containers found"); 15285 } else { 15286 // Process list of secure containers and categorize them 15287 // as active or stale based on their package internal state. 15288 15289 // reader 15290 synchronized (mPackages) { 15291 for (String cid : list) { 15292 // Leave stages untouched for now; installer service owns them 15293 if (PackageInstallerService.isStageName(cid)) continue; 15294 15295 if (DEBUG_SD_INSTALL) 15296 Log.i(TAG, "Processing container " + cid); 15297 String pkgName = getAsecPackageName(cid); 15298 if (pkgName == null) { 15299 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15300 continue; 15301 } 15302 if (DEBUG_SD_INSTALL) 15303 Log.i(TAG, "Looking for pkg : " + pkgName); 15304 15305 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15306 if (ps == null) { 15307 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15308 continue; 15309 } 15310 15311 /* 15312 * Skip packages that are not external if we're unmounting 15313 * external storage. 15314 */ 15315 if (externalStorage && !isMounted && !isExternal(ps)) { 15316 continue; 15317 } 15318 15319 final AsecInstallArgs args = new AsecInstallArgs(cid, 15320 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15321 // The package status is changed only if the code path 15322 // matches between settings and the container id. 15323 if (ps.codePathString != null 15324 && ps.codePathString.startsWith(args.getCodePath())) { 15325 if (DEBUG_SD_INSTALL) { 15326 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15327 + " at code path: " + ps.codePathString); 15328 } 15329 15330 // We do have a valid package installed on sdcard 15331 processCids.put(args, ps.codePathString); 15332 final int uid = ps.appId; 15333 if (uid != -1) { 15334 uidArr = ArrayUtils.appendInt(uidArr, uid); 15335 } 15336 } else { 15337 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15338 + ps.codePathString); 15339 } 15340 } 15341 } 15342 15343 Arrays.sort(uidArr); 15344 } 15345 15346 // Process packages with valid entries. 15347 if (isMounted) { 15348 if (DEBUG_SD_INSTALL) 15349 Log.i(TAG, "Loading packages"); 15350 loadMediaPackages(processCids, uidArr); 15351 startCleaningPackages(); 15352 mInstallerService.onSecureContainersAvailable(); 15353 } else { 15354 if (DEBUG_SD_INSTALL) 15355 Log.i(TAG, "Unloading packages"); 15356 unloadMediaPackages(processCids, uidArr, reportStatus); 15357 } 15358 } 15359 15360 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15361 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15362 final int size = infos.size(); 15363 final String[] packageNames = new String[size]; 15364 final int[] packageUids = new int[size]; 15365 for (int i = 0; i < size; i++) { 15366 final ApplicationInfo info = infos.get(i); 15367 packageNames[i] = info.packageName; 15368 packageUids[i] = info.uid; 15369 } 15370 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15371 finishedReceiver); 15372 } 15373 15374 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15375 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15376 sendResourcesChangedBroadcast(mediaStatus, replacing, 15377 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15378 } 15379 15380 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15381 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15382 int size = pkgList.length; 15383 if (size > 0) { 15384 // Send broadcasts here 15385 Bundle extras = new Bundle(); 15386 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15387 if (uidArr != null) { 15388 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15389 } 15390 if (replacing) { 15391 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15392 } 15393 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15394 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15395 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15396 } 15397 } 15398 15399 /* 15400 * Look at potentially valid container ids from processCids If package 15401 * information doesn't match the one on record or package scanning fails, 15402 * the cid is added to list of removeCids. We currently don't delete stale 15403 * containers. 15404 */ 15405 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15406 ArrayList<String> pkgList = new ArrayList<String>(); 15407 Set<AsecInstallArgs> keys = processCids.keySet(); 15408 15409 for (AsecInstallArgs args : keys) { 15410 String codePath = processCids.get(args); 15411 if (DEBUG_SD_INSTALL) 15412 Log.i(TAG, "Loading container : " + args.cid); 15413 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15414 try { 15415 // Make sure there are no container errors first. 15416 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15417 Slog.e(TAG, "Failed to mount cid : " + args.cid 15418 + " when installing from sdcard"); 15419 continue; 15420 } 15421 // Check code path here. 15422 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15423 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15424 + " does not match one in settings " + codePath); 15425 continue; 15426 } 15427 // Parse package 15428 int parseFlags = mDefParseFlags; 15429 if (args.isExternalAsec()) { 15430 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15431 } 15432 if (args.isFwdLocked()) { 15433 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15434 } 15435 15436 synchronized (mInstallLock) { 15437 PackageParser.Package pkg = null; 15438 try { 15439 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15440 } catch (PackageManagerException e) { 15441 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15442 } 15443 // Scan the package 15444 if (pkg != null) { 15445 /* 15446 * TODO why is the lock being held? doPostInstall is 15447 * called in other places without the lock. This needs 15448 * to be straightened out. 15449 */ 15450 // writer 15451 synchronized (mPackages) { 15452 retCode = PackageManager.INSTALL_SUCCEEDED; 15453 pkgList.add(pkg.packageName); 15454 // Post process args 15455 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15456 pkg.applicationInfo.uid); 15457 } 15458 } else { 15459 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15460 } 15461 } 15462 15463 } finally { 15464 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15465 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15466 } 15467 } 15468 } 15469 // writer 15470 synchronized (mPackages) { 15471 // If the platform SDK has changed since the last time we booted, 15472 // we need to re-grant app permission to catch any new ones that 15473 // appear. This is really a hack, and means that apps can in some 15474 // cases get permissions that the user didn't initially explicitly 15475 // allow... it would be nice to have some better way to handle 15476 // this situation. 15477 final VersionInfo ver = mSettings.getExternalVersion(); 15478 15479 int updateFlags = UPDATE_PERMISSIONS_ALL; 15480 if (ver.sdkVersion != mSdkVersion) { 15481 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15482 + mSdkVersion + "; regranting permissions for external"); 15483 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15484 } 15485 updatePermissionsLPw(null, null, updateFlags); 15486 15487 // Yay, everything is now upgraded 15488 ver.forceCurrent(); 15489 15490 // can downgrade to reader 15491 // Persist settings 15492 mSettings.writeLPr(); 15493 } 15494 // Send a broadcast to let everyone know we are done processing 15495 if (pkgList.size() > 0) { 15496 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15497 } 15498 } 15499 15500 /* 15501 * Utility method to unload a list of specified containers 15502 */ 15503 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15504 // Just unmount all valid containers. 15505 for (AsecInstallArgs arg : cidArgs) { 15506 synchronized (mInstallLock) { 15507 arg.doPostDeleteLI(false); 15508 } 15509 } 15510 } 15511 15512 /* 15513 * Unload packages mounted on external media. This involves deleting package 15514 * data from internal structures, sending broadcasts about diabled packages, 15515 * gc'ing to free up references, unmounting all secure containers 15516 * corresponding to packages on external media, and posting a 15517 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15518 * that we always have to post this message if status has been requested no 15519 * matter what. 15520 */ 15521 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15522 final boolean reportStatus) { 15523 if (DEBUG_SD_INSTALL) 15524 Log.i(TAG, "unloading media packages"); 15525 ArrayList<String> pkgList = new ArrayList<String>(); 15526 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15527 final Set<AsecInstallArgs> keys = processCids.keySet(); 15528 for (AsecInstallArgs args : keys) { 15529 String pkgName = args.getPackageName(); 15530 if (DEBUG_SD_INSTALL) 15531 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15532 // Delete package internally 15533 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15534 synchronized (mInstallLock) { 15535 boolean res = deletePackageLI(pkgName, null, false, null, null, 15536 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15537 if (res) { 15538 pkgList.add(pkgName); 15539 } else { 15540 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15541 failedList.add(args); 15542 } 15543 } 15544 } 15545 15546 // reader 15547 synchronized (mPackages) { 15548 // We didn't update the settings after removing each package; 15549 // write them now for all packages. 15550 mSettings.writeLPr(); 15551 } 15552 15553 // We have to absolutely send UPDATED_MEDIA_STATUS only 15554 // after confirming that all the receivers processed the ordered 15555 // broadcast when packages get disabled, force a gc to clean things up. 15556 // and unload all the containers. 15557 if (pkgList.size() > 0) { 15558 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15559 new IIntentReceiver.Stub() { 15560 public void performReceive(Intent intent, int resultCode, String data, 15561 Bundle extras, boolean ordered, boolean sticky, 15562 int sendingUser) throws RemoteException { 15563 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15564 reportStatus ? 1 : 0, 1, keys); 15565 mHandler.sendMessage(msg); 15566 } 15567 }); 15568 } else { 15569 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15570 keys); 15571 mHandler.sendMessage(msg); 15572 } 15573 } 15574 15575 private void loadPrivatePackages(VolumeInfo vol) { 15576 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15577 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15578 synchronized (mInstallLock) { 15579 synchronized (mPackages) { 15580 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15581 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15582 for (PackageSetting ps : packages) { 15583 final PackageParser.Package pkg; 15584 try { 15585 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15586 loaded.add(pkg.applicationInfo); 15587 } catch (PackageManagerException e) { 15588 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15589 } 15590 15591 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15592 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15593 } 15594 } 15595 15596 int updateFlags = UPDATE_PERMISSIONS_ALL; 15597 if (ver.sdkVersion != mSdkVersion) { 15598 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15599 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15600 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15601 } 15602 updatePermissionsLPw(null, null, updateFlags); 15603 15604 // Yay, everything is now upgraded 15605 ver.forceCurrent(); 15606 15607 mSettings.writeLPr(); 15608 } 15609 } 15610 15611 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15612 sendResourcesChangedBroadcast(true, false, loaded, null); 15613 } 15614 15615 private void unloadPrivatePackages(VolumeInfo vol) { 15616 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15617 synchronized (mInstallLock) { 15618 synchronized (mPackages) { 15619 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15620 for (PackageSetting ps : packages) { 15621 if (ps.pkg == null) continue; 15622 15623 final ApplicationInfo info = ps.pkg.applicationInfo; 15624 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15625 if (deletePackageLI(ps.name, null, false, null, null, 15626 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15627 unloaded.add(info); 15628 } else { 15629 Slog.w(TAG, "Failed to unload " + ps.codePath); 15630 } 15631 } 15632 15633 mSettings.writeLPr(); 15634 } 15635 } 15636 15637 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15638 sendResourcesChangedBroadcast(false, false, unloaded, null); 15639 } 15640 15641 /** 15642 * Examine all users present on given mounted volume, and destroy data 15643 * belonging to users that are no longer valid, or whose user ID has been 15644 * recycled. 15645 */ 15646 private void reconcileUsers(String volumeUuid) { 15647 final File[] files = FileUtils 15648 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15649 for (File file : files) { 15650 if (!file.isDirectory()) continue; 15651 15652 final int userId; 15653 final UserInfo info; 15654 try { 15655 userId = Integer.parseInt(file.getName()); 15656 info = sUserManager.getUserInfo(userId); 15657 } catch (NumberFormatException e) { 15658 Slog.w(TAG, "Invalid user directory " + file); 15659 continue; 15660 } 15661 15662 boolean destroyUser = false; 15663 if (info == null) { 15664 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15665 + " because no matching user was found"); 15666 destroyUser = true; 15667 } else { 15668 try { 15669 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15670 } catch (IOException e) { 15671 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15672 + " because we failed to enforce serial number: " + e); 15673 destroyUser = true; 15674 } 15675 } 15676 15677 if (destroyUser) { 15678 synchronized (mInstallLock) { 15679 mInstaller.removeUserDataDirs(volumeUuid, userId); 15680 } 15681 } 15682 } 15683 15684 final UserManager um = mContext.getSystemService(UserManager.class); 15685 for (UserInfo user : um.getUsers()) { 15686 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15687 if (userDir.exists()) continue; 15688 15689 try { 15690 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15691 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15692 } catch (IOException e) { 15693 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15694 } 15695 } 15696 } 15697 15698 /** 15699 * Examine all apps present on given mounted volume, and destroy apps that 15700 * aren't expected, either due to uninstallation or reinstallation on 15701 * another volume. 15702 */ 15703 private void reconcileApps(String volumeUuid) { 15704 final File[] files = FileUtils 15705 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15706 for (File file : files) { 15707 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15708 && !PackageInstallerService.isStageName(file.getName()); 15709 if (!isPackage) { 15710 // Ignore entries which are not packages 15711 continue; 15712 } 15713 15714 boolean destroyApp = false; 15715 String packageName = null; 15716 try { 15717 final PackageLite pkg = PackageParser.parsePackageLite(file, 15718 PackageParser.PARSE_MUST_BE_APK); 15719 packageName = pkg.packageName; 15720 15721 synchronized (mPackages) { 15722 final PackageSetting ps = mSettings.mPackages.get(packageName); 15723 if (ps == null) { 15724 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15725 + volumeUuid + " because we found no install record"); 15726 destroyApp = true; 15727 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15728 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15729 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15730 destroyApp = true; 15731 } 15732 } 15733 15734 } catch (PackageParserException e) { 15735 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15736 destroyApp = true; 15737 } 15738 15739 if (destroyApp) { 15740 synchronized (mInstallLock) { 15741 if (packageName != null) { 15742 removeDataDirsLI(volumeUuid, packageName); 15743 } 15744 if (file.isDirectory()) { 15745 mInstaller.rmPackageDir(file.getAbsolutePath()); 15746 } else { 15747 file.delete(); 15748 } 15749 } 15750 } 15751 } 15752 } 15753 15754 private void unfreezePackage(String packageName) { 15755 synchronized (mPackages) { 15756 final PackageSetting ps = mSettings.mPackages.get(packageName); 15757 if (ps != null) { 15758 ps.frozen = false; 15759 } 15760 } 15761 } 15762 15763 @Override 15764 public int movePackage(final String packageName, final String volumeUuid) { 15765 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15766 15767 final int moveId = mNextMoveId.getAndIncrement(); 15768 try { 15769 movePackageInternal(packageName, volumeUuid, moveId); 15770 } catch (PackageManagerException e) { 15771 Slog.w(TAG, "Failed to move " + packageName, e); 15772 mMoveCallbacks.notifyStatusChanged(moveId, 15773 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15774 } 15775 return moveId; 15776 } 15777 15778 private void movePackageInternal(final String packageName, final String volumeUuid, 15779 final int moveId) throws PackageManagerException { 15780 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15781 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15782 final PackageManager pm = mContext.getPackageManager(); 15783 15784 final boolean currentAsec; 15785 final String currentVolumeUuid; 15786 final File codeFile; 15787 final String installerPackageName; 15788 final String packageAbiOverride; 15789 final int appId; 15790 final String seinfo; 15791 final String label; 15792 15793 // reader 15794 synchronized (mPackages) { 15795 final PackageParser.Package pkg = mPackages.get(packageName); 15796 final PackageSetting ps = mSettings.mPackages.get(packageName); 15797 if (pkg == null || ps == null) { 15798 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15799 } 15800 15801 if (pkg.applicationInfo.isSystemApp()) { 15802 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15803 "Cannot move system application"); 15804 } 15805 15806 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15807 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15808 "Package already moved to " + volumeUuid); 15809 } 15810 15811 final File probe = new File(pkg.codePath); 15812 final File probeOat = new File(probe, "oat"); 15813 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15814 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15815 "Move only supported for modern cluster style installs"); 15816 } 15817 15818 if (ps.frozen) { 15819 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15820 "Failed to move already frozen package"); 15821 } 15822 ps.frozen = true; 15823 15824 currentAsec = pkg.applicationInfo.isForwardLocked() 15825 || pkg.applicationInfo.isExternalAsec(); 15826 currentVolumeUuid = ps.volumeUuid; 15827 codeFile = new File(pkg.codePath); 15828 installerPackageName = ps.installerPackageName; 15829 packageAbiOverride = ps.cpuAbiOverrideString; 15830 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15831 seinfo = pkg.applicationInfo.seinfo; 15832 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15833 } 15834 15835 // Now that we're guarded by frozen state, kill app during move 15836 final long token = Binder.clearCallingIdentity(); 15837 try { 15838 killApplication(packageName, appId, "move pkg"); 15839 } finally { 15840 Binder.restoreCallingIdentity(token); 15841 } 15842 15843 final Bundle extras = new Bundle(); 15844 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15845 extras.putString(Intent.EXTRA_TITLE, label); 15846 mMoveCallbacks.notifyCreated(moveId, extras); 15847 15848 int installFlags; 15849 final boolean moveCompleteApp; 15850 final File measurePath; 15851 15852 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15853 installFlags = INSTALL_INTERNAL; 15854 moveCompleteApp = !currentAsec; 15855 measurePath = Environment.getDataAppDirectory(volumeUuid); 15856 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15857 installFlags = INSTALL_EXTERNAL; 15858 moveCompleteApp = false; 15859 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15860 } else { 15861 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15862 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15863 || !volume.isMountedWritable()) { 15864 unfreezePackage(packageName); 15865 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15866 "Move location not mounted private volume"); 15867 } 15868 15869 Preconditions.checkState(!currentAsec); 15870 15871 installFlags = INSTALL_INTERNAL; 15872 moveCompleteApp = true; 15873 measurePath = Environment.getDataAppDirectory(volumeUuid); 15874 } 15875 15876 final PackageStats stats = new PackageStats(null, -1); 15877 synchronized (mInstaller) { 15878 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15879 unfreezePackage(packageName); 15880 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15881 "Failed to measure package size"); 15882 } 15883 } 15884 15885 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15886 + stats.dataSize); 15887 15888 final long startFreeBytes = measurePath.getFreeSpace(); 15889 final long sizeBytes; 15890 if (moveCompleteApp) { 15891 sizeBytes = stats.codeSize + stats.dataSize; 15892 } else { 15893 sizeBytes = stats.codeSize; 15894 } 15895 15896 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15897 unfreezePackage(packageName); 15898 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15899 "Not enough free space to move"); 15900 } 15901 15902 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15903 15904 final CountDownLatch installedLatch = new CountDownLatch(1); 15905 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15906 @Override 15907 public void onUserActionRequired(Intent intent) throws RemoteException { 15908 throw new IllegalStateException(); 15909 } 15910 15911 @Override 15912 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15913 Bundle extras) throws RemoteException { 15914 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15915 + PackageManager.installStatusToString(returnCode, msg)); 15916 15917 installedLatch.countDown(); 15918 15919 // Regardless of success or failure of the move operation, 15920 // always unfreeze the package 15921 unfreezePackage(packageName); 15922 15923 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15924 switch (status) { 15925 case PackageInstaller.STATUS_SUCCESS: 15926 mMoveCallbacks.notifyStatusChanged(moveId, 15927 PackageManager.MOVE_SUCCEEDED); 15928 break; 15929 case PackageInstaller.STATUS_FAILURE_STORAGE: 15930 mMoveCallbacks.notifyStatusChanged(moveId, 15931 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15932 break; 15933 default: 15934 mMoveCallbacks.notifyStatusChanged(moveId, 15935 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15936 break; 15937 } 15938 } 15939 }; 15940 15941 final MoveInfo move; 15942 if (moveCompleteApp) { 15943 // Kick off a thread to report progress estimates 15944 new Thread() { 15945 @Override 15946 public void run() { 15947 while (true) { 15948 try { 15949 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15950 break; 15951 } 15952 } catch (InterruptedException ignored) { 15953 } 15954 15955 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15956 final int progress = 10 + (int) MathUtils.constrain( 15957 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15958 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15959 } 15960 } 15961 }.start(); 15962 15963 final String dataAppName = codeFile.getName(); 15964 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15965 dataAppName, appId, seinfo); 15966 } else { 15967 move = null; 15968 } 15969 15970 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15971 15972 final Message msg = mHandler.obtainMessage(INIT_COPY); 15973 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15974 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15975 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 15976 mHandler.sendMessage(msg); 15977 } 15978 15979 @Override 15980 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15981 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15982 15983 final int realMoveId = mNextMoveId.getAndIncrement(); 15984 final Bundle extras = new Bundle(); 15985 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15986 mMoveCallbacks.notifyCreated(realMoveId, extras); 15987 15988 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15989 @Override 15990 public void onCreated(int moveId, Bundle extras) { 15991 // Ignored 15992 } 15993 15994 @Override 15995 public void onStatusChanged(int moveId, int status, long estMillis) { 15996 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15997 } 15998 }; 15999 16000 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16001 storage.setPrimaryStorageUuid(volumeUuid, callback); 16002 return realMoveId; 16003 } 16004 16005 @Override 16006 public int getMoveStatus(int moveId) { 16007 mContext.enforceCallingOrSelfPermission( 16008 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16009 return mMoveCallbacks.mLastStatus.get(moveId); 16010 } 16011 16012 @Override 16013 public void registerMoveCallback(IPackageMoveObserver callback) { 16014 mContext.enforceCallingOrSelfPermission( 16015 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16016 mMoveCallbacks.register(callback); 16017 } 16018 16019 @Override 16020 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16021 mContext.enforceCallingOrSelfPermission( 16022 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16023 mMoveCallbacks.unregister(callback); 16024 } 16025 16026 @Override 16027 public boolean setInstallLocation(int loc) { 16028 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16029 null); 16030 if (getInstallLocation() == loc) { 16031 return true; 16032 } 16033 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16034 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16035 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16036 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16037 return true; 16038 } 16039 return false; 16040 } 16041 16042 @Override 16043 public int getInstallLocation() { 16044 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16045 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16046 PackageHelper.APP_INSTALL_AUTO); 16047 } 16048 16049 /** Called by UserManagerService */ 16050 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16051 mDirtyUsers.remove(userHandle); 16052 mSettings.removeUserLPw(userHandle); 16053 mPendingBroadcasts.remove(userHandle); 16054 if (mInstaller != null) { 16055 // Technically, we shouldn't be doing this with the package lock 16056 // held. However, this is very rare, and there is already so much 16057 // other disk I/O going on, that we'll let it slide for now. 16058 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16059 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16060 final String volumeUuid = vol.getFsUuid(); 16061 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16062 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16063 } 16064 } 16065 mUserNeedsBadging.delete(userHandle); 16066 removeUnusedPackagesLILPw(userManager, userHandle); 16067 } 16068 16069 /** 16070 * We're removing userHandle and would like to remove any downloaded packages 16071 * that are no longer in use by any other user. 16072 * @param userHandle the user being removed 16073 */ 16074 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16075 final boolean DEBUG_CLEAN_APKS = false; 16076 int [] users = userManager.getUserIdsLPr(); 16077 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16078 while (psit.hasNext()) { 16079 PackageSetting ps = psit.next(); 16080 if (ps.pkg == null) { 16081 continue; 16082 } 16083 final String packageName = ps.pkg.packageName; 16084 // Skip over if system app 16085 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16086 continue; 16087 } 16088 if (DEBUG_CLEAN_APKS) { 16089 Slog.i(TAG, "Checking package " + packageName); 16090 } 16091 boolean keep = false; 16092 for (int i = 0; i < users.length; i++) { 16093 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16094 keep = true; 16095 if (DEBUG_CLEAN_APKS) { 16096 Slog.i(TAG, " Keeping package " + packageName + " for user " 16097 + users[i]); 16098 } 16099 break; 16100 } 16101 } 16102 if (!keep) { 16103 if (DEBUG_CLEAN_APKS) { 16104 Slog.i(TAG, " Removing package " + packageName); 16105 } 16106 mHandler.post(new Runnable() { 16107 public void run() { 16108 deletePackageX(packageName, userHandle, 0); 16109 } //end run 16110 }); 16111 } 16112 } 16113 } 16114 16115 /** Called by UserManagerService */ 16116 void createNewUserLILPw(int userHandle) { 16117 if (mInstaller != null) { 16118 mInstaller.createUserConfig(userHandle); 16119 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16120 applyFactoryDefaultBrowserLPw(userHandle); 16121 primeDomainVerificationsLPw(userHandle); 16122 } 16123 } 16124 16125 void newUserCreated(final int userHandle) { 16126 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16127 } 16128 16129 @Override 16130 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16131 mContext.enforceCallingOrSelfPermission( 16132 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16133 "Only package verification agents can read the verifier device identity"); 16134 16135 synchronized (mPackages) { 16136 return mSettings.getVerifierDeviceIdentityLPw(); 16137 } 16138 } 16139 16140 @Override 16141 public void setPermissionEnforced(String permission, boolean enforced) { 16142 // TODO: Now that we no longer change GID for storage, this should to away. 16143 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16144 "setPermissionEnforced"); 16145 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16146 synchronized (mPackages) { 16147 if (mSettings.mReadExternalStorageEnforced == null 16148 || mSettings.mReadExternalStorageEnforced != enforced) { 16149 mSettings.mReadExternalStorageEnforced = enforced; 16150 mSettings.writeLPr(); 16151 } 16152 } 16153 // kill any non-foreground processes so we restart them and 16154 // grant/revoke the GID. 16155 final IActivityManager am = ActivityManagerNative.getDefault(); 16156 if (am != null) { 16157 final long token = Binder.clearCallingIdentity(); 16158 try { 16159 am.killProcessesBelowForeground("setPermissionEnforcement"); 16160 } catch (RemoteException e) { 16161 } finally { 16162 Binder.restoreCallingIdentity(token); 16163 } 16164 } 16165 } else { 16166 throw new IllegalArgumentException("No selective enforcement for " + permission); 16167 } 16168 } 16169 16170 @Override 16171 @Deprecated 16172 public boolean isPermissionEnforced(String permission) { 16173 return true; 16174 } 16175 16176 @Override 16177 public boolean isStorageLow() { 16178 final long token = Binder.clearCallingIdentity(); 16179 try { 16180 final DeviceStorageMonitorInternal 16181 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16182 if (dsm != null) { 16183 return dsm.isMemoryLow(); 16184 } else { 16185 return false; 16186 } 16187 } finally { 16188 Binder.restoreCallingIdentity(token); 16189 } 16190 } 16191 16192 @Override 16193 public IPackageInstaller getPackageInstaller() { 16194 return mInstallerService; 16195 } 16196 16197 private boolean userNeedsBadging(int userId) { 16198 int index = mUserNeedsBadging.indexOfKey(userId); 16199 if (index < 0) { 16200 final UserInfo userInfo; 16201 final long token = Binder.clearCallingIdentity(); 16202 try { 16203 userInfo = sUserManager.getUserInfo(userId); 16204 } finally { 16205 Binder.restoreCallingIdentity(token); 16206 } 16207 final boolean b; 16208 if (userInfo != null && userInfo.isManagedProfile()) { 16209 b = true; 16210 } else { 16211 b = false; 16212 } 16213 mUserNeedsBadging.put(userId, b); 16214 return b; 16215 } 16216 return mUserNeedsBadging.valueAt(index); 16217 } 16218 16219 @Override 16220 public KeySet getKeySetByAlias(String packageName, String alias) { 16221 if (packageName == null || alias == null) { 16222 return null; 16223 } 16224 synchronized(mPackages) { 16225 final PackageParser.Package pkg = mPackages.get(packageName); 16226 if (pkg == null) { 16227 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16228 throw new IllegalArgumentException("Unknown package: " + packageName); 16229 } 16230 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16231 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16232 } 16233 } 16234 16235 @Override 16236 public KeySet getSigningKeySet(String packageName) { 16237 if (packageName == null) { 16238 return null; 16239 } 16240 synchronized(mPackages) { 16241 final PackageParser.Package pkg = mPackages.get(packageName); 16242 if (pkg == null) { 16243 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16244 throw new IllegalArgumentException("Unknown package: " + packageName); 16245 } 16246 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16247 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16248 throw new SecurityException("May not access signing KeySet of other apps."); 16249 } 16250 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16251 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16252 } 16253 } 16254 16255 @Override 16256 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16257 if (packageName == null || ks == null) { 16258 return false; 16259 } 16260 synchronized(mPackages) { 16261 final PackageParser.Package pkg = mPackages.get(packageName); 16262 if (pkg == null) { 16263 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16264 throw new IllegalArgumentException("Unknown package: " + packageName); 16265 } 16266 IBinder ksh = ks.getToken(); 16267 if (ksh instanceof KeySetHandle) { 16268 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16269 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16270 } 16271 return false; 16272 } 16273 } 16274 16275 @Override 16276 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16277 if (packageName == null || ks == null) { 16278 return false; 16279 } 16280 synchronized(mPackages) { 16281 final PackageParser.Package pkg = mPackages.get(packageName); 16282 if (pkg == null) { 16283 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16284 throw new IllegalArgumentException("Unknown package: " + packageName); 16285 } 16286 IBinder ksh = ks.getToken(); 16287 if (ksh instanceof KeySetHandle) { 16288 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16289 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16290 } 16291 return false; 16292 } 16293 } 16294 16295 public void getUsageStatsIfNoPackageUsageInfo() { 16296 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16297 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16298 if (usm == null) { 16299 throw new IllegalStateException("UsageStatsManager must be initialized"); 16300 } 16301 long now = System.currentTimeMillis(); 16302 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16303 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16304 String packageName = entry.getKey(); 16305 PackageParser.Package pkg = mPackages.get(packageName); 16306 if (pkg == null) { 16307 continue; 16308 } 16309 UsageStats usage = entry.getValue(); 16310 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16311 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16312 } 16313 } 16314 } 16315 16316 /** 16317 * Check and throw if the given before/after packages would be considered a 16318 * downgrade. 16319 */ 16320 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16321 throws PackageManagerException { 16322 if (after.versionCode < before.mVersionCode) { 16323 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16324 "Update version code " + after.versionCode + " is older than current " 16325 + before.mVersionCode); 16326 } else if (after.versionCode == before.mVersionCode) { 16327 if (after.baseRevisionCode < before.baseRevisionCode) { 16328 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16329 "Update base revision code " + after.baseRevisionCode 16330 + " is older than current " + before.baseRevisionCode); 16331 } 16332 16333 if (!ArrayUtils.isEmpty(after.splitNames)) { 16334 for (int i = 0; i < after.splitNames.length; i++) { 16335 final String splitName = after.splitNames[i]; 16336 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16337 if (j != -1) { 16338 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16339 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16340 "Update split " + splitName + " revision code " 16341 + after.splitRevisionCodes[i] + " is older than current " 16342 + before.splitRevisionCodes[j]); 16343 } 16344 } 16345 } 16346 } 16347 } 16348 } 16349 16350 private static class MoveCallbacks extends Handler { 16351 private static final int MSG_CREATED = 1; 16352 private static final int MSG_STATUS_CHANGED = 2; 16353 16354 private final RemoteCallbackList<IPackageMoveObserver> 16355 mCallbacks = new RemoteCallbackList<>(); 16356 16357 private final SparseIntArray mLastStatus = new SparseIntArray(); 16358 16359 public MoveCallbacks(Looper looper) { 16360 super(looper); 16361 } 16362 16363 public void register(IPackageMoveObserver callback) { 16364 mCallbacks.register(callback); 16365 } 16366 16367 public void unregister(IPackageMoveObserver callback) { 16368 mCallbacks.unregister(callback); 16369 } 16370 16371 @Override 16372 public void handleMessage(Message msg) { 16373 final SomeArgs args = (SomeArgs) msg.obj; 16374 final int n = mCallbacks.beginBroadcast(); 16375 for (int i = 0; i < n; i++) { 16376 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16377 try { 16378 invokeCallback(callback, msg.what, args); 16379 } catch (RemoteException ignored) { 16380 } 16381 } 16382 mCallbacks.finishBroadcast(); 16383 args.recycle(); 16384 } 16385 16386 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16387 throws RemoteException { 16388 switch (what) { 16389 case MSG_CREATED: { 16390 callback.onCreated(args.argi1, (Bundle) args.arg2); 16391 break; 16392 } 16393 case MSG_STATUS_CHANGED: { 16394 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16395 break; 16396 } 16397 } 16398 } 16399 16400 private void notifyCreated(int moveId, Bundle extras) { 16401 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16402 16403 final SomeArgs args = SomeArgs.obtain(); 16404 args.argi1 = moveId; 16405 args.arg2 = extras; 16406 obtainMessage(MSG_CREATED, args).sendToTarget(); 16407 } 16408 16409 private void notifyStatusChanged(int moveId, int status) { 16410 notifyStatusChanged(moveId, status, -1); 16411 } 16412 16413 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16414 Slog.v(TAG, "Move " + moveId + " status " + status); 16415 16416 final SomeArgs args = SomeArgs.obtain(); 16417 args.argi1 = moveId; 16418 args.argi2 = status; 16419 args.arg3 = estMillis; 16420 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16421 16422 synchronized (mLastStatus) { 16423 mLastStatus.put(moveId, status); 16424 } 16425 } 16426 } 16427 16428 private final class OnPermissionChangeListeners extends Handler { 16429 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16430 16431 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16432 new RemoteCallbackList<>(); 16433 16434 public OnPermissionChangeListeners(Looper looper) { 16435 super(looper); 16436 } 16437 16438 @Override 16439 public void handleMessage(Message msg) { 16440 switch (msg.what) { 16441 case MSG_ON_PERMISSIONS_CHANGED: { 16442 final int uid = msg.arg1; 16443 handleOnPermissionsChanged(uid); 16444 } break; 16445 } 16446 } 16447 16448 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16449 mPermissionListeners.register(listener); 16450 16451 } 16452 16453 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16454 mPermissionListeners.unregister(listener); 16455 } 16456 16457 public void onPermissionsChanged(int uid) { 16458 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16459 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16460 } 16461 } 16462 16463 private void handleOnPermissionsChanged(int uid) { 16464 final int count = mPermissionListeners.beginBroadcast(); 16465 try { 16466 for (int i = 0; i < count; i++) { 16467 IOnPermissionsChangeListener callback = mPermissionListeners 16468 .getBroadcastItem(i); 16469 try { 16470 callback.onPermissionsChanged(uid); 16471 } catch (RemoteException e) { 16472 Log.e(TAG, "Permission listener is dead", e); 16473 } 16474 } 16475 } finally { 16476 mPermissionListeners.finishBroadcast(); 16477 } 16478 } 16479 } 16480 16481 private class PackageManagerInternalImpl extends PackageManagerInternal { 16482 @Override 16483 public void setLocationPackagesProvider(PackagesProvider provider) { 16484 synchronized (mPackages) { 16485 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16486 } 16487 } 16488 16489 @Override 16490 public void setImePackagesProvider(PackagesProvider provider) { 16491 synchronized (mPackages) { 16492 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16493 } 16494 } 16495 16496 @Override 16497 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16498 synchronized (mPackages) { 16499 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16500 } 16501 } 16502 16503 @Override 16504 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16505 synchronized (mPackages) { 16506 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16507 } 16508 } 16509 16510 @Override 16511 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16512 synchronized (mPackages) { 16513 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16514 } 16515 } 16516 16517 @Override 16518 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16519 synchronized (mPackages) { 16520 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16521 } 16522 } 16523 16524 @Override 16525 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16526 synchronized (mPackages) { 16527 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16528 } 16529 } 16530 16531 @Override 16532 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16533 synchronized (mPackages) { 16534 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16535 packageName, userId); 16536 } 16537 } 16538 16539 @Override 16540 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16541 synchronized (mPackages) { 16542 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16543 packageName, userId); 16544 } 16545 } 16546 @Override 16547 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16548 synchronized (mPackages) { 16549 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16550 packageName, userId); 16551 } 16552 } 16553 } 16554 16555 @Override 16556 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16557 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16558 synchronized (mPackages) { 16559 final long identity = Binder.clearCallingIdentity(); 16560 try { 16561 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16562 packageNames, userId); 16563 } finally { 16564 Binder.restoreCallingIdentity(identity); 16565 } 16566 } 16567 } 16568 16569 private static void enforceSystemOrPhoneCaller(String tag) { 16570 int callingUid = Binder.getCallingUid(); 16571 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16572 throw new SecurityException( 16573 "Cannot call " + tag + " from UID " + callingUid); 16574 } 16575 } 16576} 16577