PackageManagerService.java revision b92b05bb4bcaa6f7869128e925d0331eee62e4da
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_REVIEW_REQUIRED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 34import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 63import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 64import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 65import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 66import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 67import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 68import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 69import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 70import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 71import static android.content.pm.PackageManager.PERMISSION_DENIED; 72import static android.content.pm.PackageManager.PERMISSION_GRANTED; 73import static android.content.pm.PackageParser.isApkFile; 74import static android.os.Process.PACKAGE_INFO_GID; 75import static android.os.Process.SYSTEM_UID; 76import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 77import static android.system.OsConstants.O_CREAT; 78import static android.system.OsConstants.O_RDWR; 79 80import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 81import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 82import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 83import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 84import static com.android.internal.util.ArrayUtils.appendInt; 85import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 86import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 87import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 88import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 89import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 90import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 92import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 94 95import android.Manifest; 96import android.annotation.NonNull; 97import android.annotation.Nullable; 98import android.app.ActivityManager; 99import android.app.ActivityManagerNative; 100import android.app.AppGlobals; 101import android.app.IActivityManager; 102import android.app.admin.IDevicePolicyManager; 103import android.app.backup.IBackupManager; 104import android.content.BroadcastReceiver; 105import android.content.ComponentName; 106import android.content.Context; 107import android.content.IIntentReceiver; 108import android.content.Intent; 109import android.content.IntentFilter; 110import android.content.IntentSender; 111import android.content.IntentSender.SendIntentException; 112import android.content.ServiceConnection; 113import android.content.pm.ActivityInfo; 114import android.content.pm.ApplicationInfo; 115import android.content.pm.AppsQueryHelper; 116import android.content.pm.ComponentInfo; 117import android.content.pm.EphemeralApplicationInfo; 118import android.content.pm.EphemeralResolveInfo; 119import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 120import android.content.pm.FeatureInfo; 121import android.content.pm.IOnPermissionsChangeListener; 122import android.content.pm.IPackageDataObserver; 123import android.content.pm.IPackageDeleteObserver; 124import android.content.pm.IPackageDeleteObserver2; 125import android.content.pm.IPackageInstallObserver2; 126import android.content.pm.IPackageInstaller; 127import android.content.pm.IPackageManager; 128import android.content.pm.IPackageMoveObserver; 129import android.content.pm.IPackageStatsObserver; 130import android.content.pm.InstrumentationInfo; 131import android.content.pm.IntentFilterVerificationInfo; 132import android.content.pm.KeySet; 133import android.content.pm.PackageCleanItem; 134import android.content.pm.PackageInfo; 135import android.content.pm.PackageInfoLite; 136import android.content.pm.PackageInstaller; 137import android.content.pm.PackageManager; 138import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 139import android.content.pm.PackageManagerInternal; 140import android.content.pm.PackageParser; 141import android.content.pm.PackageParser.ActivityIntentInfo; 142import android.content.pm.PackageParser.PackageLite; 143import android.content.pm.PackageParser.PackageParserException; 144import android.content.pm.PackageStats; 145import android.content.pm.PackageUserState; 146import android.content.pm.ParceledListSlice; 147import android.content.pm.PermissionGroupInfo; 148import android.content.pm.PermissionInfo; 149import android.content.pm.ProviderInfo; 150import android.content.pm.ResolveInfo; 151import android.content.pm.ServiceInfo; 152import android.content.pm.Signature; 153import android.content.pm.UserInfo; 154import android.content.pm.VerificationParams; 155import android.content.pm.VerifierDeviceIdentity; 156import android.content.pm.VerifierInfo; 157import android.content.res.Resources; 158import android.graphics.Bitmap; 159import android.hardware.display.DisplayManager; 160import android.net.Uri; 161import android.os.Binder; 162import android.os.Build; 163import android.os.Bundle; 164import android.os.Debug; 165import android.os.Environment; 166import android.os.Environment.UserEnvironment; 167import android.os.FileUtils; 168import android.os.Handler; 169import android.os.IBinder; 170import android.os.Looper; 171import android.os.Message; 172import android.os.Parcel; 173import android.os.ParcelFileDescriptor; 174import android.os.Process; 175import android.os.RemoteCallbackList; 176import android.os.RemoteException; 177import android.os.ResultReceiver; 178import android.os.SELinux; 179import android.os.ServiceManager; 180import android.os.SystemClock; 181import android.os.SystemProperties; 182import android.os.Trace; 183import android.os.UserHandle; 184import android.os.UserManager; 185import android.os.storage.IMountService; 186import android.os.storage.MountServiceInternal; 187import android.os.storage.StorageEventListener; 188import android.os.storage.StorageManager; 189import android.os.storage.VolumeInfo; 190import android.os.storage.VolumeRecord; 191import android.security.KeyStore; 192import android.security.SystemKeyStore; 193import android.system.ErrnoException; 194import android.system.Os; 195import android.text.TextUtils; 196import android.text.format.DateUtils; 197import android.util.ArrayMap; 198import android.util.ArraySet; 199import android.util.AtomicFile; 200import android.util.DisplayMetrics; 201import android.util.EventLog; 202import android.util.ExceptionUtils; 203import android.util.Log; 204import android.util.LogPrinter; 205import android.util.MathUtils; 206import android.util.PrintStreamPrinter; 207import android.util.Slog; 208import android.util.SparseArray; 209import android.util.SparseBooleanArray; 210import android.util.SparseIntArray; 211import android.util.Xml; 212import android.view.Display; 213 214import com.android.internal.R; 215import com.android.internal.annotations.GuardedBy; 216import com.android.internal.app.IMediaContainerService; 217import com.android.internal.app.ResolverActivity; 218import com.android.internal.content.NativeLibraryHelper; 219import com.android.internal.content.PackageHelper; 220import com.android.internal.os.IParcelFileDescriptorFactory; 221import com.android.internal.os.InstallerConnection.InstallerException; 222import com.android.internal.os.SomeArgs; 223import com.android.internal.os.Zygote; 224import com.android.internal.util.ArrayUtils; 225import com.android.internal.util.FastPrintWriter; 226import com.android.internal.util.FastXmlSerializer; 227import com.android.internal.util.IndentingPrintWriter; 228import com.android.internal.util.Preconditions; 229import com.android.internal.util.XmlUtils; 230import com.android.server.EventLogTags; 231import com.android.server.FgThread; 232import com.android.server.IntentResolver; 233import com.android.server.LocalServices; 234import com.android.server.ServiceThread; 235import com.android.server.SystemConfig; 236import com.android.server.Watchdog; 237import com.android.server.pm.Installer.StorageFlags; 238import com.android.server.pm.PermissionsState.PermissionState; 239import com.android.server.pm.Settings.DatabaseVersion; 240import com.android.server.pm.Settings.VersionInfo; 241import com.android.server.storage.DeviceStorageMonitorInternal; 242 243import dalvik.system.DexFile; 244import dalvik.system.VMRuntime; 245 246import libcore.io.IoUtils; 247import libcore.util.EmptyArray; 248 249import org.xmlpull.v1.XmlPullParser; 250import org.xmlpull.v1.XmlPullParserException; 251import org.xmlpull.v1.XmlSerializer; 252 253import java.io.BufferedInputStream; 254import java.io.BufferedOutputStream; 255import java.io.BufferedReader; 256import java.io.ByteArrayInputStream; 257import java.io.ByteArrayOutputStream; 258import java.io.File; 259import java.io.FileDescriptor; 260import java.io.FileNotFoundException; 261import java.io.FileOutputStream; 262import java.io.FileReader; 263import java.io.FilenameFilter; 264import java.io.IOException; 265import java.io.InputStream; 266import java.io.PrintWriter; 267import java.nio.charset.StandardCharsets; 268import java.security.MessageDigest; 269import java.security.NoSuchAlgorithmException; 270import java.security.PublicKey; 271import java.security.cert.CertificateEncodingException; 272import java.security.cert.CertificateException; 273import java.text.SimpleDateFormat; 274import java.util.ArrayList; 275import java.util.Arrays; 276import java.util.Collection; 277import java.util.Collections; 278import java.util.Comparator; 279import java.util.Date; 280import java.util.Iterator; 281import java.util.List; 282import java.util.Map; 283import java.util.Objects; 284import java.util.Set; 285import java.util.concurrent.CountDownLatch; 286import java.util.concurrent.TimeUnit; 287import java.util.concurrent.atomic.AtomicBoolean; 288import java.util.concurrent.atomic.AtomicInteger; 289import java.util.concurrent.atomic.AtomicLong; 290 291/** 292 * Keep track of all those .apks everywhere. 293 * 294 * This is very central to the platform's security; please run the unit 295 * tests whenever making modifications here: 296 * 297runtest -c android.content.pm.PackageManagerTests frameworks-core 298 * 299 * {@hide} 300 */ 301public class PackageManagerService extends IPackageManager.Stub { 302 static final String TAG = "PackageManager"; 303 static final boolean DEBUG_SETTINGS = false; 304 static final boolean DEBUG_PREFERRED = false; 305 static final boolean DEBUG_UPGRADE = false; 306 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 307 private static final boolean DEBUG_BACKUP = false; 308 private static final boolean DEBUG_INSTALL = false; 309 private static final boolean DEBUG_REMOVE = false; 310 private static final boolean DEBUG_BROADCASTS = false; 311 private static final boolean DEBUG_SHOW_INFO = false; 312 private static final boolean DEBUG_PACKAGE_INFO = false; 313 private static final boolean DEBUG_INTENT_MATCHING = false; 314 private static final boolean DEBUG_PACKAGE_SCANNING = false; 315 private static final boolean DEBUG_VERIFY = false; 316 private static final boolean DEBUG_DEXOPT = false; 317 private static final boolean DEBUG_ABI_SELECTION = false; 318 private static final boolean DEBUG_EPHEMERAL = false; 319 private static final boolean DEBUG_TRIAGED_MISSING = false; 320 private static final boolean DEBUG_APP_DATA = false; 321 322 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 323 324 private static final boolean DISABLE_EPHEMERAL_APPS = true; 325 326 private static final int RADIO_UID = Process.PHONE_UID; 327 private static final int LOG_UID = Process.LOG_UID; 328 private static final int NFC_UID = Process.NFC_UID; 329 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 330 private static final int SHELL_UID = Process.SHELL_UID; 331 332 // Cap the size of permission trees that 3rd party apps can define 333 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 334 335 // Suffix used during package installation when copying/moving 336 // package apks to install directory. 337 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 338 339 static final int SCAN_NO_DEX = 1<<1; 340 static final int SCAN_FORCE_DEX = 1<<2; 341 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 342 static final int SCAN_NEW_INSTALL = 1<<4; 343 static final int SCAN_NO_PATHS = 1<<5; 344 static final int SCAN_UPDATE_TIME = 1<<6; 345 static final int SCAN_DEFER_DEX = 1<<7; 346 static final int SCAN_BOOTING = 1<<8; 347 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 348 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 349 static final int SCAN_REPLACING = 1<<11; 350 static final int SCAN_REQUIRE_KNOWN = 1<<12; 351 static final int SCAN_MOVE = 1<<13; 352 static final int SCAN_INITIAL = 1<<14; 353 354 static final int REMOVE_CHATTY = 1<<16; 355 356 private static final int[] EMPTY_INT_ARRAY = new int[0]; 357 358 /** 359 * Timeout (in milliseconds) after which the watchdog should declare that 360 * our handler thread is wedged. The usual default for such things is one 361 * minute but we sometimes do very lengthy I/O operations on this thread, 362 * such as installing multi-gigabyte applications, so ours needs to be longer. 363 */ 364 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 365 366 /** 367 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 368 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 369 * settings entry if available, otherwise we use the hardcoded default. If it's been 370 * more than this long since the last fstrim, we force one during the boot sequence. 371 * 372 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 373 * one gets run at the next available charging+idle time. This final mandatory 374 * no-fstrim check kicks in only of the other scheduling criteria is never met. 375 */ 376 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 377 378 /** 379 * Whether verification is enabled by default. 380 */ 381 private static final boolean DEFAULT_VERIFY_ENABLE = true; 382 383 /** 384 * The default maximum time to wait for the verification agent to return in 385 * milliseconds. 386 */ 387 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 388 389 /** 390 * The default response for package verification timeout. 391 * 392 * This can be either PackageManager.VERIFICATION_ALLOW or 393 * PackageManager.VERIFICATION_REJECT. 394 */ 395 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 396 397 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 398 399 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 400 DEFAULT_CONTAINER_PACKAGE, 401 "com.android.defcontainer.DefaultContainerService"); 402 403 private static final String KILL_APP_REASON_GIDS_CHANGED = 404 "permission grant or revoke changed gids"; 405 406 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 407 "permissions revoked"; 408 409 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 410 411 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 412 413 /** Permission grant: not grant the permission. */ 414 private static final int GRANT_DENIED = 1; 415 416 /** Permission grant: grant the permission as an install permission. */ 417 private static final int GRANT_INSTALL = 2; 418 419 /** Permission grant: grant the permission as a runtime one. */ 420 private static final int GRANT_RUNTIME = 3; 421 422 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 423 private static final int GRANT_UPGRADE = 4; 424 425 /** Canonical intent used to identify what counts as a "web browser" app */ 426 private static final Intent sBrowserIntent; 427 static { 428 sBrowserIntent = new Intent(); 429 sBrowserIntent.setAction(Intent.ACTION_VIEW); 430 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 431 sBrowserIntent.setData(Uri.parse("http:")); 432 } 433 434 final ServiceThread mHandlerThread; 435 436 final PackageHandler mHandler; 437 438 /** 439 * Messages for {@link #mHandler} that need to wait for system ready before 440 * being dispatched. 441 */ 442 private ArrayList<Message> mPostSystemReadyMessages; 443 444 final int mSdkVersion = Build.VERSION.SDK_INT; 445 446 final Context mContext; 447 final boolean mFactoryTest; 448 final boolean mOnlyCore; 449 final DisplayMetrics mMetrics; 450 final int mDefParseFlags; 451 final String[] mSeparateProcesses; 452 final boolean mIsUpgrade; 453 454 /** The location for ASEC container files on internal storage. */ 455 final String mAsecInternalPath; 456 457 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 458 // LOCK HELD. Can be called with mInstallLock held. 459 @GuardedBy("mInstallLock") 460 final Installer mInstaller; 461 462 /** Directory where installed third-party apps stored */ 463 final File mAppInstallDir; 464 final File mEphemeralInstallDir; 465 466 /** 467 * Directory to which applications installed internally have their 468 * 32 bit native libraries copied. 469 */ 470 private File mAppLib32InstallDir; 471 472 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 473 // apps. 474 final File mDrmAppPrivateInstallDir; 475 476 // ---------------------------------------------------------------- 477 478 // Lock for state used when installing and doing other long running 479 // operations. Methods that must be called with this lock held have 480 // the suffix "LI". 481 final Object mInstallLock = new Object(); 482 483 // ---------------------------------------------------------------- 484 485 // Keys are String (package name), values are Package. This also serves 486 // as the lock for the global state. Methods that must be called with 487 // this lock held have the prefix "LP". 488 @GuardedBy("mPackages") 489 final ArrayMap<String, PackageParser.Package> mPackages = 490 new ArrayMap<String, PackageParser.Package>(); 491 492 // Tracks available target package names -> overlay package paths. 493 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 494 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 495 496 /** 497 * Tracks new system packages [received in an OTA] that we expect to 498 * find updated user-installed versions. Keys are package name, values 499 * are package location. 500 */ 501 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 502 503 /** 504 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 505 */ 506 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 507 /** 508 * Whether or not system app permissions should be promoted from install to runtime. 509 */ 510 boolean mPromoteSystemApps; 511 512 final Settings mSettings; 513 boolean mRestoredSettings; 514 515 // System configuration read by SystemConfig. 516 final int[] mGlobalGids; 517 final SparseArray<ArraySet<String>> mSystemPermissions; 518 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 519 520 // If mac_permissions.xml was found for seinfo labeling. 521 boolean mFoundPolicyFile; 522 523 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 524 525 public static final class SharedLibraryEntry { 526 public final String path; 527 public final String apk; 528 529 SharedLibraryEntry(String _path, String _apk) { 530 path = _path; 531 apk = _apk; 532 } 533 } 534 535 // Currently known shared libraries. 536 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 537 new ArrayMap<String, SharedLibraryEntry>(); 538 539 // All available activities, for your resolving pleasure. 540 final ActivityIntentResolver mActivities = 541 new ActivityIntentResolver(); 542 543 // All available receivers, for your resolving pleasure. 544 final ActivityIntentResolver mReceivers = 545 new ActivityIntentResolver(); 546 547 // All available services, for your resolving pleasure. 548 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 549 550 // All available providers, for your resolving pleasure. 551 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 552 553 // Mapping from provider base names (first directory in content URI codePath) 554 // to the provider information. 555 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 556 new ArrayMap<String, PackageParser.Provider>(); 557 558 // Mapping from instrumentation class names to info about them. 559 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 560 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 561 562 // Mapping from permission names to info about them. 563 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 564 new ArrayMap<String, PackageParser.PermissionGroup>(); 565 566 // Packages whose data we have transfered into another package, thus 567 // should no longer exist. 568 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 569 570 // Broadcast actions that are only available to the system. 571 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 572 573 /** List of packages waiting for verification. */ 574 final SparseArray<PackageVerificationState> mPendingVerification 575 = new SparseArray<PackageVerificationState>(); 576 577 /** Set of packages associated with each app op permission. */ 578 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 579 580 final PackageInstallerService mInstallerService; 581 582 private final PackageDexOptimizer mPackageDexOptimizer; 583 584 private AtomicInteger mNextMoveId = new AtomicInteger(); 585 private final MoveCallbacks mMoveCallbacks; 586 587 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 588 589 // Cache of users who need badging. 590 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 591 592 /** Token for keys in mPendingVerification. */ 593 private int mPendingVerificationToken = 0; 594 595 volatile boolean mSystemReady; 596 volatile boolean mSafeMode; 597 volatile boolean mHasSystemUidErrors; 598 599 ApplicationInfo mAndroidApplication; 600 final ActivityInfo mResolveActivity = new ActivityInfo(); 601 final ResolveInfo mResolveInfo = new ResolveInfo(); 602 ComponentName mResolveComponentName; 603 PackageParser.Package mPlatformPackage; 604 ComponentName mCustomResolverComponentName; 605 606 boolean mResolverReplaced = false; 607 608 private final @Nullable ComponentName mIntentFilterVerifierComponent; 609 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 610 611 private int mIntentFilterVerificationToken = 0; 612 613 /** Component that knows whether or not an ephemeral application exists */ 614 final ComponentName mEphemeralResolverComponent; 615 /** The service connection to the ephemeral resolver */ 616 final EphemeralResolverConnection mEphemeralResolverConnection; 617 618 /** Component used to install ephemeral applications */ 619 final ComponentName mEphemeralInstallerComponent; 620 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 621 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 622 623 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 624 = new SparseArray<IntentFilterVerificationState>(); 625 626 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 627 new DefaultPermissionGrantPolicy(this); 628 629 // List of packages names to keep cached, even if they are uninstalled for all users 630 private List<String> mKeepUninstalledPackages; 631 632 private boolean mUseJitProfiles = 633 SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false); 634 635 private static class IFVerificationParams { 636 PackageParser.Package pkg; 637 boolean replacing; 638 int userId; 639 int verifierUid; 640 641 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 642 int _userId, int _verifierUid) { 643 pkg = _pkg; 644 replacing = _replacing; 645 userId = _userId; 646 replacing = _replacing; 647 verifierUid = _verifierUid; 648 } 649 } 650 651 private interface IntentFilterVerifier<T extends IntentFilter> { 652 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 653 T filter, String packageName); 654 void startVerifications(int userId); 655 void receiveVerificationResponse(int verificationId); 656 } 657 658 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 659 private Context mContext; 660 private ComponentName mIntentFilterVerifierComponent; 661 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 662 663 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 664 mContext = context; 665 mIntentFilterVerifierComponent = verifierComponent; 666 } 667 668 private String getDefaultScheme() { 669 return IntentFilter.SCHEME_HTTPS; 670 } 671 672 @Override 673 public void startVerifications(int userId) { 674 // Launch verifications requests 675 int count = mCurrentIntentFilterVerifications.size(); 676 for (int n=0; n<count; n++) { 677 int verificationId = mCurrentIntentFilterVerifications.get(n); 678 final IntentFilterVerificationState ivs = 679 mIntentFilterVerificationStates.get(verificationId); 680 681 String packageName = ivs.getPackageName(); 682 683 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 684 final int filterCount = filters.size(); 685 ArraySet<String> domainsSet = new ArraySet<>(); 686 for (int m=0; m<filterCount; m++) { 687 PackageParser.ActivityIntentInfo filter = filters.get(m); 688 domainsSet.addAll(filter.getHostsList()); 689 } 690 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 691 synchronized (mPackages) { 692 if (mSettings.createIntentFilterVerificationIfNeededLPw( 693 packageName, domainsList) != null) { 694 scheduleWriteSettingsLocked(); 695 } 696 } 697 sendVerificationRequest(userId, verificationId, ivs); 698 } 699 mCurrentIntentFilterVerifications.clear(); 700 } 701 702 private void sendVerificationRequest(int userId, int verificationId, 703 IntentFilterVerificationState ivs) { 704 705 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 706 verificationIntent.putExtra( 707 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 708 verificationId); 709 verificationIntent.putExtra( 710 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 711 getDefaultScheme()); 712 verificationIntent.putExtra( 713 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 714 ivs.getHostsString()); 715 verificationIntent.putExtra( 716 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 717 ivs.getPackageName()); 718 verificationIntent.setComponent(mIntentFilterVerifierComponent); 719 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 720 721 UserHandle user = new UserHandle(userId); 722 mContext.sendBroadcastAsUser(verificationIntent, user); 723 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 724 "Sending IntentFilter verification broadcast"); 725 } 726 727 public void receiveVerificationResponse(int verificationId) { 728 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 729 730 final boolean verified = ivs.isVerified(); 731 732 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 733 final int count = filters.size(); 734 if (DEBUG_DOMAIN_VERIFICATION) { 735 Slog.i(TAG, "Received verification response " + verificationId 736 + " for " + count + " filters, verified=" + verified); 737 } 738 for (int n=0; n<count; n++) { 739 PackageParser.ActivityIntentInfo filter = filters.get(n); 740 filter.setVerified(verified); 741 742 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 743 + " verified with result:" + verified + " and hosts:" 744 + ivs.getHostsString()); 745 } 746 747 mIntentFilterVerificationStates.remove(verificationId); 748 749 final String packageName = ivs.getPackageName(); 750 IntentFilterVerificationInfo ivi = null; 751 752 synchronized (mPackages) { 753 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 754 } 755 if (ivi == null) { 756 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 757 + verificationId + " packageName:" + packageName); 758 return; 759 } 760 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 761 "Updating IntentFilterVerificationInfo for package " + packageName 762 +" verificationId:" + verificationId); 763 764 synchronized (mPackages) { 765 if (verified) { 766 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 767 } else { 768 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 769 } 770 scheduleWriteSettingsLocked(); 771 772 final int userId = ivs.getUserId(); 773 if (userId != UserHandle.USER_ALL) { 774 final int userStatus = 775 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 776 777 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 778 boolean needUpdate = false; 779 780 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 781 // already been set by the User thru the Disambiguation dialog 782 switch (userStatus) { 783 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 784 if (verified) { 785 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 786 } else { 787 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 788 } 789 needUpdate = true; 790 break; 791 792 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 793 if (verified) { 794 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 795 needUpdate = true; 796 } 797 break; 798 799 default: 800 // Nothing to do 801 } 802 803 if (needUpdate) { 804 mSettings.updateIntentFilterVerificationStatusLPw( 805 packageName, updatedStatus, userId); 806 scheduleWritePackageRestrictionsLocked(userId); 807 } 808 } 809 } 810 } 811 812 @Override 813 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 814 ActivityIntentInfo filter, String packageName) { 815 if (!hasValidDomains(filter)) { 816 return false; 817 } 818 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 819 if (ivs == null) { 820 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 821 packageName); 822 } 823 if (DEBUG_DOMAIN_VERIFICATION) { 824 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 825 } 826 ivs.addFilter(filter); 827 return true; 828 } 829 830 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 831 int userId, int verificationId, String packageName) { 832 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 833 verifierUid, userId, packageName); 834 ivs.setPendingState(); 835 synchronized (mPackages) { 836 mIntentFilterVerificationStates.append(verificationId, ivs); 837 mCurrentIntentFilterVerifications.add(verificationId); 838 } 839 return ivs; 840 } 841 } 842 843 private static boolean hasValidDomains(ActivityIntentInfo filter) { 844 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 845 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 846 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 847 } 848 849 // Set of pending broadcasts for aggregating enable/disable of components. 850 static class PendingPackageBroadcasts { 851 // for each user id, a map of <package name -> components within that package> 852 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 853 854 public PendingPackageBroadcasts() { 855 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 856 } 857 858 public ArrayList<String> get(int userId, String packageName) { 859 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 860 return packages.get(packageName); 861 } 862 863 public void put(int userId, String packageName, ArrayList<String> components) { 864 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 865 packages.put(packageName, components); 866 } 867 868 public void remove(int userId, String packageName) { 869 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 870 if (packages != null) { 871 packages.remove(packageName); 872 } 873 } 874 875 public void remove(int userId) { 876 mUidMap.remove(userId); 877 } 878 879 public int userIdCount() { 880 return mUidMap.size(); 881 } 882 883 public int userIdAt(int n) { 884 return mUidMap.keyAt(n); 885 } 886 887 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 888 return mUidMap.get(userId); 889 } 890 891 public int size() { 892 // total number of pending broadcast entries across all userIds 893 int num = 0; 894 for (int i = 0; i< mUidMap.size(); i++) { 895 num += mUidMap.valueAt(i).size(); 896 } 897 return num; 898 } 899 900 public void clear() { 901 mUidMap.clear(); 902 } 903 904 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 905 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 906 if (map == null) { 907 map = new ArrayMap<String, ArrayList<String>>(); 908 mUidMap.put(userId, map); 909 } 910 return map; 911 } 912 } 913 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 914 915 // Service Connection to remote media container service to copy 916 // package uri's from external media onto secure containers 917 // or internal storage. 918 private IMediaContainerService mContainerService = null; 919 920 static final int SEND_PENDING_BROADCAST = 1; 921 static final int MCS_BOUND = 3; 922 static final int END_COPY = 4; 923 static final int INIT_COPY = 5; 924 static final int MCS_UNBIND = 6; 925 static final int START_CLEANING_PACKAGE = 7; 926 static final int FIND_INSTALL_LOC = 8; 927 static final int POST_INSTALL = 9; 928 static final int MCS_RECONNECT = 10; 929 static final int MCS_GIVE_UP = 11; 930 static final int UPDATED_MEDIA_STATUS = 12; 931 static final int WRITE_SETTINGS = 13; 932 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 933 static final int PACKAGE_VERIFIED = 15; 934 static final int CHECK_PENDING_VERIFICATION = 16; 935 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 936 static final int INTENT_FILTER_VERIFIED = 18; 937 938 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 939 940 // Delay time in millisecs 941 static final int BROADCAST_DELAY = 10 * 1000; 942 943 static UserManagerService sUserManager; 944 945 // Stores a list of users whose package restrictions file needs to be updated 946 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 947 948 final private DefaultContainerConnection mDefContainerConn = 949 new DefaultContainerConnection(); 950 class DefaultContainerConnection implements ServiceConnection { 951 public void onServiceConnected(ComponentName name, IBinder service) { 952 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 953 IMediaContainerService imcs = 954 IMediaContainerService.Stub.asInterface(service); 955 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 956 } 957 958 public void onServiceDisconnected(ComponentName name) { 959 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 960 } 961 } 962 963 // Recordkeeping of restore-after-install operations that are currently in flight 964 // between the Package Manager and the Backup Manager 965 static class PostInstallData { 966 public InstallArgs args; 967 public PackageInstalledInfo res; 968 969 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 970 args = _a; 971 res = _r; 972 } 973 } 974 975 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 976 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 977 978 // XML tags for backup/restore of various bits of state 979 private static final String TAG_PREFERRED_BACKUP = "pa"; 980 private static final String TAG_DEFAULT_APPS = "da"; 981 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 982 983 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 984 private static final String TAG_ALL_GRANTS = "rt-grants"; 985 private static final String TAG_GRANT = "grant"; 986 private static final String ATTR_PACKAGE_NAME = "pkg"; 987 988 private static final String TAG_PERMISSION = "perm"; 989 private static final String ATTR_PERMISSION_NAME = "name"; 990 private static final String ATTR_IS_GRANTED = "g"; 991 private static final String ATTR_USER_SET = "set"; 992 private static final String ATTR_USER_FIXED = "fixed"; 993 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 994 995 // System/policy permission grants are not backed up 996 private static final int SYSTEM_RUNTIME_GRANT_MASK = 997 FLAG_PERMISSION_POLICY_FIXED 998 | FLAG_PERMISSION_SYSTEM_FIXED 999 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1000 1001 // And we back up these user-adjusted states 1002 private static final int USER_RUNTIME_GRANT_MASK = 1003 FLAG_PERMISSION_USER_SET 1004 | FLAG_PERMISSION_USER_FIXED 1005 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1006 1007 final @Nullable String mRequiredVerifierPackage; 1008 final @Nullable String mRequiredInstallerPackage; 1009 1010 private final PackageUsage mPackageUsage = new PackageUsage(); 1011 1012 private class PackageUsage { 1013 private static final int WRITE_INTERVAL 1014 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1015 1016 private final Object mFileLock = new Object(); 1017 private final AtomicLong mLastWritten = new AtomicLong(0); 1018 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1019 1020 private boolean mIsHistoricalPackageUsageAvailable = true; 1021 1022 boolean isHistoricalPackageUsageAvailable() { 1023 return mIsHistoricalPackageUsageAvailable; 1024 } 1025 1026 void write(boolean force) { 1027 if (force) { 1028 writeInternal(); 1029 return; 1030 } 1031 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1032 && !DEBUG_DEXOPT) { 1033 return; 1034 } 1035 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1036 new Thread("PackageUsage_DiskWriter") { 1037 @Override 1038 public void run() { 1039 try { 1040 writeInternal(); 1041 } finally { 1042 mBackgroundWriteRunning.set(false); 1043 } 1044 } 1045 }.start(); 1046 } 1047 } 1048 1049 private void writeInternal() { 1050 synchronized (mPackages) { 1051 synchronized (mFileLock) { 1052 AtomicFile file = getFile(); 1053 FileOutputStream f = null; 1054 try { 1055 f = file.startWrite(); 1056 BufferedOutputStream out = new BufferedOutputStream(f); 1057 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1058 StringBuilder sb = new StringBuilder(); 1059 for (PackageParser.Package pkg : mPackages.values()) { 1060 if (pkg.mLastPackageUsageTimeInMills == 0) { 1061 continue; 1062 } 1063 sb.setLength(0); 1064 sb.append(pkg.packageName); 1065 sb.append(' '); 1066 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1067 sb.append('\n'); 1068 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1069 } 1070 out.flush(); 1071 file.finishWrite(f); 1072 } catch (IOException e) { 1073 if (f != null) { 1074 file.failWrite(f); 1075 } 1076 Log.e(TAG, "Failed to write package usage times", e); 1077 } 1078 } 1079 } 1080 mLastWritten.set(SystemClock.elapsedRealtime()); 1081 } 1082 1083 void readLP() { 1084 synchronized (mFileLock) { 1085 AtomicFile file = getFile(); 1086 BufferedInputStream in = null; 1087 try { 1088 in = new BufferedInputStream(file.openRead()); 1089 StringBuffer sb = new StringBuffer(); 1090 while (true) { 1091 String packageName = readToken(in, sb, ' '); 1092 if (packageName == null) { 1093 break; 1094 } 1095 String timeInMillisString = readToken(in, sb, '\n'); 1096 if (timeInMillisString == null) { 1097 throw new IOException("Failed to find last usage time for package " 1098 + packageName); 1099 } 1100 PackageParser.Package pkg = mPackages.get(packageName); 1101 if (pkg == null) { 1102 continue; 1103 } 1104 long timeInMillis; 1105 try { 1106 timeInMillis = Long.parseLong(timeInMillisString); 1107 } catch (NumberFormatException e) { 1108 throw new IOException("Failed to parse " + timeInMillisString 1109 + " as a long.", e); 1110 } 1111 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1112 } 1113 } catch (FileNotFoundException expected) { 1114 mIsHistoricalPackageUsageAvailable = false; 1115 } catch (IOException e) { 1116 Log.w(TAG, "Failed to read package usage times", e); 1117 } finally { 1118 IoUtils.closeQuietly(in); 1119 } 1120 } 1121 mLastWritten.set(SystemClock.elapsedRealtime()); 1122 } 1123 1124 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1125 throws IOException { 1126 sb.setLength(0); 1127 while (true) { 1128 int ch = in.read(); 1129 if (ch == -1) { 1130 if (sb.length() == 0) { 1131 return null; 1132 } 1133 throw new IOException("Unexpected EOF"); 1134 } 1135 if (ch == endOfToken) { 1136 return sb.toString(); 1137 } 1138 sb.append((char)ch); 1139 } 1140 } 1141 1142 private AtomicFile getFile() { 1143 File dataDir = Environment.getDataDirectory(); 1144 File systemDir = new File(dataDir, "system"); 1145 File fname = new File(systemDir, "package-usage.list"); 1146 return new AtomicFile(fname); 1147 } 1148 } 1149 1150 class PackageHandler extends Handler { 1151 private boolean mBound = false; 1152 final ArrayList<HandlerParams> mPendingInstalls = 1153 new ArrayList<HandlerParams>(); 1154 1155 private boolean connectToService() { 1156 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1157 " DefaultContainerService"); 1158 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1159 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1160 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1161 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1162 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1163 mBound = true; 1164 return true; 1165 } 1166 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1167 return false; 1168 } 1169 1170 private void disconnectService() { 1171 mContainerService = null; 1172 mBound = false; 1173 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1174 mContext.unbindService(mDefContainerConn); 1175 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1176 } 1177 1178 PackageHandler(Looper looper) { 1179 super(looper); 1180 } 1181 1182 public void handleMessage(Message msg) { 1183 try { 1184 doHandleMessage(msg); 1185 } finally { 1186 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1187 } 1188 } 1189 1190 void doHandleMessage(Message msg) { 1191 switch (msg.what) { 1192 case INIT_COPY: { 1193 HandlerParams params = (HandlerParams) msg.obj; 1194 int idx = mPendingInstalls.size(); 1195 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1196 // If a bind was already initiated we dont really 1197 // need to do anything. The pending install 1198 // will be processed later on. 1199 if (!mBound) { 1200 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1201 System.identityHashCode(mHandler)); 1202 // If this is the only one pending we might 1203 // have to bind to the service again. 1204 if (!connectToService()) { 1205 Slog.e(TAG, "Failed to bind to media container service"); 1206 params.serviceError(); 1207 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1208 System.identityHashCode(mHandler)); 1209 if (params.traceMethod != null) { 1210 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1211 params.traceCookie); 1212 } 1213 return; 1214 } else { 1215 // Once we bind to the service, the first 1216 // pending request will be processed. 1217 mPendingInstalls.add(idx, params); 1218 } 1219 } else { 1220 mPendingInstalls.add(idx, params); 1221 // Already bound to the service. Just make 1222 // sure we trigger off processing the first request. 1223 if (idx == 0) { 1224 mHandler.sendEmptyMessage(MCS_BOUND); 1225 } 1226 } 1227 break; 1228 } 1229 case MCS_BOUND: { 1230 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1231 if (msg.obj != null) { 1232 mContainerService = (IMediaContainerService) msg.obj; 1233 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1234 System.identityHashCode(mHandler)); 1235 } 1236 if (mContainerService == null) { 1237 if (!mBound) { 1238 // Something seriously wrong since we are not bound and we are not 1239 // waiting for connection. Bail out. 1240 Slog.e(TAG, "Cannot bind to media container service"); 1241 for (HandlerParams params : mPendingInstalls) { 1242 // Indicate service bind error 1243 params.serviceError(); 1244 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1245 System.identityHashCode(params)); 1246 if (params.traceMethod != null) { 1247 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1248 params.traceMethod, params.traceCookie); 1249 } 1250 return; 1251 } 1252 mPendingInstalls.clear(); 1253 } else { 1254 Slog.w(TAG, "Waiting to connect to media container service"); 1255 } 1256 } else if (mPendingInstalls.size() > 0) { 1257 HandlerParams params = mPendingInstalls.get(0); 1258 if (params != null) { 1259 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1260 System.identityHashCode(params)); 1261 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1262 if (params.startCopy()) { 1263 // We are done... look for more work or to 1264 // go idle. 1265 if (DEBUG_SD_INSTALL) Log.i(TAG, 1266 "Checking for more work or unbind..."); 1267 // Delete pending install 1268 if (mPendingInstalls.size() > 0) { 1269 mPendingInstalls.remove(0); 1270 } 1271 if (mPendingInstalls.size() == 0) { 1272 if (mBound) { 1273 if (DEBUG_SD_INSTALL) Log.i(TAG, 1274 "Posting delayed MCS_UNBIND"); 1275 removeMessages(MCS_UNBIND); 1276 Message ubmsg = obtainMessage(MCS_UNBIND); 1277 // Unbind after a little delay, to avoid 1278 // continual thrashing. 1279 sendMessageDelayed(ubmsg, 10000); 1280 } 1281 } else { 1282 // There are more pending requests in queue. 1283 // Just post MCS_BOUND message to trigger processing 1284 // of next pending install. 1285 if (DEBUG_SD_INSTALL) Log.i(TAG, 1286 "Posting MCS_BOUND for next work"); 1287 mHandler.sendEmptyMessage(MCS_BOUND); 1288 } 1289 } 1290 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1291 } 1292 } else { 1293 // Should never happen ideally. 1294 Slog.w(TAG, "Empty queue"); 1295 } 1296 break; 1297 } 1298 case MCS_RECONNECT: { 1299 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1300 if (mPendingInstalls.size() > 0) { 1301 if (mBound) { 1302 disconnectService(); 1303 } 1304 if (!connectToService()) { 1305 Slog.e(TAG, "Failed to bind to media container service"); 1306 for (HandlerParams params : mPendingInstalls) { 1307 // Indicate service bind error 1308 params.serviceError(); 1309 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1310 System.identityHashCode(params)); 1311 } 1312 mPendingInstalls.clear(); 1313 } 1314 } 1315 break; 1316 } 1317 case MCS_UNBIND: { 1318 // If there is no actual work left, then time to unbind. 1319 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1320 1321 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1322 if (mBound) { 1323 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1324 1325 disconnectService(); 1326 } 1327 } else if (mPendingInstalls.size() > 0) { 1328 // There are more pending requests in queue. 1329 // Just post MCS_BOUND message to trigger processing 1330 // of next pending install. 1331 mHandler.sendEmptyMessage(MCS_BOUND); 1332 } 1333 1334 break; 1335 } 1336 case MCS_GIVE_UP: { 1337 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1338 HandlerParams params = mPendingInstalls.remove(0); 1339 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1340 System.identityHashCode(params)); 1341 break; 1342 } 1343 case SEND_PENDING_BROADCAST: { 1344 String packages[]; 1345 ArrayList<String> components[]; 1346 int size = 0; 1347 int uids[]; 1348 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1349 synchronized (mPackages) { 1350 if (mPendingBroadcasts == null) { 1351 return; 1352 } 1353 size = mPendingBroadcasts.size(); 1354 if (size <= 0) { 1355 // Nothing to be done. Just return 1356 return; 1357 } 1358 packages = new String[size]; 1359 components = new ArrayList[size]; 1360 uids = new int[size]; 1361 int i = 0; // filling out the above arrays 1362 1363 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1364 int packageUserId = mPendingBroadcasts.userIdAt(n); 1365 Iterator<Map.Entry<String, ArrayList<String>>> it 1366 = mPendingBroadcasts.packagesForUserId(packageUserId) 1367 .entrySet().iterator(); 1368 while (it.hasNext() && i < size) { 1369 Map.Entry<String, ArrayList<String>> ent = it.next(); 1370 packages[i] = ent.getKey(); 1371 components[i] = ent.getValue(); 1372 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1373 uids[i] = (ps != null) 1374 ? UserHandle.getUid(packageUserId, ps.appId) 1375 : -1; 1376 i++; 1377 } 1378 } 1379 size = i; 1380 mPendingBroadcasts.clear(); 1381 } 1382 // Send broadcasts 1383 for (int i = 0; i < size; i++) { 1384 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1385 } 1386 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1387 break; 1388 } 1389 case START_CLEANING_PACKAGE: { 1390 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1391 final String packageName = (String)msg.obj; 1392 final int userId = msg.arg1; 1393 final boolean andCode = msg.arg2 != 0; 1394 synchronized (mPackages) { 1395 if (userId == UserHandle.USER_ALL) { 1396 int[] users = sUserManager.getUserIds(); 1397 for (int user : users) { 1398 mSettings.addPackageToCleanLPw( 1399 new PackageCleanItem(user, packageName, andCode)); 1400 } 1401 } else { 1402 mSettings.addPackageToCleanLPw( 1403 new PackageCleanItem(userId, packageName, andCode)); 1404 } 1405 } 1406 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1407 startCleaningPackages(); 1408 } break; 1409 case POST_INSTALL: { 1410 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1411 1412 PostInstallData data = mRunningInstalls.get(msg.arg1); 1413 mRunningInstalls.delete(msg.arg1); 1414 boolean deleteOld = false; 1415 1416 if (data != null) { 1417 InstallArgs args = data.args; 1418 PackageInstalledInfo res = data.res; 1419 1420 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1421 final String packageName = res.pkg.applicationInfo.packageName; 1422 res.removedInfo.sendBroadcast(false, true, false); 1423 Bundle extras = new Bundle(1); 1424 extras.putInt(Intent.EXTRA_UID, res.uid); 1425 1426 // Now that we successfully installed the package, grant runtime 1427 // permissions if requested before broadcasting the install. 1428 if ((args.installFlags 1429 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1430 && res.pkg.applicationInfo.targetSdkVersion 1431 >= Build.VERSION_CODES.M) { 1432 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1433 args.installGrantPermissions); 1434 } 1435 1436 synchronized (mPackages) { 1437 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1438 } 1439 1440 // Determine the set of users who are adding this 1441 // package for the first time vs. those who are seeing 1442 // an update. 1443 int[] firstUsers; 1444 int[] updateUsers = new int[0]; 1445 if (res.origUsers == null || res.origUsers.length == 0) { 1446 firstUsers = res.newUsers; 1447 } else { 1448 firstUsers = new int[0]; 1449 for (int i=0; i<res.newUsers.length; i++) { 1450 int user = res.newUsers[i]; 1451 boolean isNew = true; 1452 for (int j=0; j<res.origUsers.length; j++) { 1453 if (res.origUsers[j] == user) { 1454 isNew = false; 1455 break; 1456 } 1457 } 1458 if (isNew) { 1459 int[] newFirst = new int[firstUsers.length+1]; 1460 System.arraycopy(firstUsers, 0, newFirst, 0, 1461 firstUsers.length); 1462 newFirst[firstUsers.length] = user; 1463 firstUsers = newFirst; 1464 } else { 1465 int[] newUpdate = new int[updateUsers.length+1]; 1466 System.arraycopy(updateUsers, 0, newUpdate, 0, 1467 updateUsers.length); 1468 newUpdate[updateUsers.length] = user; 1469 updateUsers = newUpdate; 1470 } 1471 } 1472 } 1473 // don't broadcast for ephemeral installs/updates 1474 final boolean isEphemeral = isEphemeral(res.pkg); 1475 if (!isEphemeral) { 1476 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1477 extras, 0 /*flags*/, null /*targetPackage*/, 1478 null /*finishedReceiver*/, firstUsers); 1479 } 1480 final boolean update = res.removedInfo.removedPackage != null; 1481 if (update) { 1482 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1483 } 1484 if (!isEphemeral) { 1485 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1486 extras, 0 /*flags*/, null /*targetPackage*/, 1487 null /*finishedReceiver*/, updateUsers); 1488 } 1489 if (update) { 1490 if (!isEphemeral) { 1491 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1492 packageName, extras, 0 /*flags*/, 1493 null /*targetPackage*/, null /*finishedReceiver*/, 1494 updateUsers); 1495 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1496 null /*package*/, null /*extras*/, 0 /*flags*/, 1497 packageName /*targetPackage*/, 1498 null /*finishedReceiver*/, updateUsers); 1499 } 1500 1501 // treat asec-hosted packages like removable media on upgrade 1502 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1503 if (DEBUG_INSTALL) { 1504 Slog.i(TAG, "upgrading pkg " + res.pkg 1505 + " is ASEC-hosted -> AVAILABLE"); 1506 } 1507 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1508 ArrayList<String> pkgList = new ArrayList<String>(1); 1509 pkgList.add(packageName); 1510 sendResourcesChangedBroadcast(true, true, 1511 pkgList,uidArray, null); 1512 } 1513 } 1514 if (res.removedInfo.args != null) { 1515 // Remove the replaced package's older resources safely now 1516 deleteOld = true; 1517 } 1518 1519 1520 // Work that needs to happen on first install within each user 1521 if (firstUsers.length > 0) { 1522 for (int userId : firstUsers) { 1523 synchronized (mPackages) { 1524 // If this app is a browser and it's newly-installed for 1525 // some users, clear any default-browser state in those 1526 // users. The app's nature doesn't depend on the user, 1527 // so we can just check its browser nature in any user 1528 // and generalize. 1529 if (packageIsBrowser(packageName, firstUsers[0])) { 1530 mSettings.setDefaultBrowserPackageNameLPw( 1531 null, userId); 1532 } 1533 1534 // We may also need to apply pending (restored) runtime 1535 // permission grants within these users. 1536 mSettings.applyPendingPermissionGrantsLPw( 1537 packageName, userId); 1538 } 1539 } 1540 } 1541 // Log current value of "unknown sources" setting 1542 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1543 getUnknownSourcesSettings()); 1544 } 1545 // Force a gc to clear up things 1546 Runtime.getRuntime().gc(); 1547 // We delete after a gc for applications on sdcard. 1548 if (deleteOld) { 1549 synchronized (mInstallLock) { 1550 res.removedInfo.args.doPostDeleteLI(true); 1551 } 1552 } 1553 if (args.observer != null) { 1554 try { 1555 Bundle extras = extrasForInstallResult(res); 1556 args.observer.onPackageInstalled(res.name, res.returnCode, 1557 res.returnMsg, extras); 1558 } catch (RemoteException e) { 1559 Slog.i(TAG, "Observer no longer exists."); 1560 } 1561 } 1562 if (args.traceMethod != null) { 1563 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1564 args.traceCookie); 1565 } 1566 return; 1567 } else { 1568 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1569 } 1570 1571 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1572 } break; 1573 case UPDATED_MEDIA_STATUS: { 1574 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1575 boolean reportStatus = msg.arg1 == 1; 1576 boolean doGc = msg.arg2 == 1; 1577 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1578 if (doGc) { 1579 // Force a gc to clear up stale containers. 1580 Runtime.getRuntime().gc(); 1581 } 1582 if (msg.obj != null) { 1583 @SuppressWarnings("unchecked") 1584 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1585 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1586 // Unload containers 1587 unloadAllContainers(args); 1588 } 1589 if (reportStatus) { 1590 try { 1591 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1592 PackageHelper.getMountService().finishMediaUpdate(); 1593 } catch (RemoteException e) { 1594 Log.e(TAG, "MountService not running?"); 1595 } 1596 } 1597 } break; 1598 case WRITE_SETTINGS: { 1599 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1600 synchronized (mPackages) { 1601 removeMessages(WRITE_SETTINGS); 1602 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1603 mSettings.writeLPr(); 1604 mDirtyUsers.clear(); 1605 } 1606 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1607 } break; 1608 case WRITE_PACKAGE_RESTRICTIONS: { 1609 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1610 synchronized (mPackages) { 1611 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1612 for (int userId : mDirtyUsers) { 1613 mSettings.writePackageRestrictionsLPr(userId); 1614 } 1615 mDirtyUsers.clear(); 1616 } 1617 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1618 } break; 1619 case CHECK_PENDING_VERIFICATION: { 1620 final int verificationId = msg.arg1; 1621 final PackageVerificationState state = mPendingVerification.get(verificationId); 1622 1623 if ((state != null) && !state.timeoutExtended()) { 1624 final InstallArgs args = state.getInstallArgs(); 1625 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1626 1627 Slog.i(TAG, "Verification timed out for " + originUri); 1628 mPendingVerification.remove(verificationId); 1629 1630 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1631 1632 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1633 Slog.i(TAG, "Continuing with installation of " + originUri); 1634 state.setVerifierResponse(Binder.getCallingUid(), 1635 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1636 broadcastPackageVerified(verificationId, originUri, 1637 PackageManager.VERIFICATION_ALLOW, 1638 state.getInstallArgs().getUser()); 1639 try { 1640 ret = args.copyApk(mContainerService, true); 1641 } catch (RemoteException e) { 1642 Slog.e(TAG, "Could not contact the ContainerService"); 1643 } 1644 } else { 1645 broadcastPackageVerified(verificationId, originUri, 1646 PackageManager.VERIFICATION_REJECT, 1647 state.getInstallArgs().getUser()); 1648 } 1649 1650 Trace.asyncTraceEnd( 1651 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1652 1653 processPendingInstall(args, ret); 1654 mHandler.sendEmptyMessage(MCS_UNBIND); 1655 } 1656 break; 1657 } 1658 case PACKAGE_VERIFIED: { 1659 final int verificationId = msg.arg1; 1660 1661 final PackageVerificationState state = mPendingVerification.get(verificationId); 1662 if (state == null) { 1663 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1664 break; 1665 } 1666 1667 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1668 1669 state.setVerifierResponse(response.callerUid, response.code); 1670 1671 if (state.isVerificationComplete()) { 1672 mPendingVerification.remove(verificationId); 1673 1674 final InstallArgs args = state.getInstallArgs(); 1675 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1676 1677 int ret; 1678 if (state.isInstallAllowed()) { 1679 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1680 broadcastPackageVerified(verificationId, originUri, 1681 response.code, state.getInstallArgs().getUser()); 1682 try { 1683 ret = args.copyApk(mContainerService, true); 1684 } catch (RemoteException e) { 1685 Slog.e(TAG, "Could not contact the ContainerService"); 1686 } 1687 } else { 1688 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1689 } 1690 1691 Trace.asyncTraceEnd( 1692 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1693 1694 processPendingInstall(args, ret); 1695 mHandler.sendEmptyMessage(MCS_UNBIND); 1696 } 1697 1698 break; 1699 } 1700 case START_INTENT_FILTER_VERIFICATIONS: { 1701 IFVerificationParams params = (IFVerificationParams) msg.obj; 1702 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1703 params.replacing, params.pkg); 1704 break; 1705 } 1706 case INTENT_FILTER_VERIFIED: { 1707 final int verificationId = msg.arg1; 1708 1709 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1710 verificationId); 1711 if (state == null) { 1712 Slog.w(TAG, "Invalid IntentFilter verification token " 1713 + verificationId + " received"); 1714 break; 1715 } 1716 1717 final int userId = state.getUserId(); 1718 1719 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1720 "Processing IntentFilter verification with token:" 1721 + verificationId + " and userId:" + userId); 1722 1723 final IntentFilterVerificationResponse response = 1724 (IntentFilterVerificationResponse) msg.obj; 1725 1726 state.setVerifierResponse(response.callerUid, response.code); 1727 1728 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1729 "IntentFilter verification with token:" + verificationId 1730 + " and userId:" + userId 1731 + " is settings verifier response with response code:" 1732 + response.code); 1733 1734 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1735 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1736 + response.getFailedDomainsString()); 1737 } 1738 1739 if (state.isVerificationComplete()) { 1740 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1741 } else { 1742 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1743 "IntentFilter verification with token:" + verificationId 1744 + " was not said to be complete"); 1745 } 1746 1747 break; 1748 } 1749 } 1750 } 1751 } 1752 1753 private StorageEventListener mStorageListener = new StorageEventListener() { 1754 @Override 1755 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1756 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1757 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1758 final String volumeUuid = vol.getFsUuid(); 1759 1760 // Clean up any users or apps that were removed or recreated 1761 // while this volume was missing 1762 reconcileUsers(volumeUuid); 1763 reconcileApps(volumeUuid); 1764 1765 // Clean up any install sessions that expired or were 1766 // cancelled while this volume was missing 1767 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1768 1769 loadPrivatePackages(vol); 1770 1771 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1772 unloadPrivatePackages(vol); 1773 } 1774 } 1775 1776 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1777 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1778 updateExternalMediaStatus(true, false); 1779 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1780 updateExternalMediaStatus(false, false); 1781 } 1782 } 1783 } 1784 1785 @Override 1786 public void onVolumeForgotten(String fsUuid) { 1787 if (TextUtils.isEmpty(fsUuid)) { 1788 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1789 return; 1790 } 1791 1792 // Remove any apps installed on the forgotten volume 1793 synchronized (mPackages) { 1794 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1795 for (PackageSetting ps : packages) { 1796 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1797 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1798 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1799 } 1800 1801 mSettings.onVolumeForgotten(fsUuid); 1802 mSettings.writeLPr(); 1803 } 1804 } 1805 }; 1806 1807 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1808 String[] grantedPermissions) { 1809 if (userId >= UserHandle.USER_SYSTEM) { 1810 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1811 } else if (userId == UserHandle.USER_ALL) { 1812 final int[] userIds; 1813 synchronized (mPackages) { 1814 userIds = UserManagerService.getInstance().getUserIds(); 1815 } 1816 for (int someUserId : userIds) { 1817 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1818 } 1819 } 1820 1821 // We could have touched GID membership, so flush out packages.list 1822 synchronized (mPackages) { 1823 mSettings.writePackageListLPr(); 1824 } 1825 } 1826 1827 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1828 String[] grantedPermissions) { 1829 SettingBase sb = (SettingBase) pkg.mExtras; 1830 if (sb == null) { 1831 return; 1832 } 1833 1834 PermissionsState permissionsState = sb.getPermissionsState(); 1835 1836 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1837 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1838 1839 synchronized (mPackages) { 1840 for (String permission : pkg.requestedPermissions) { 1841 BasePermission bp = mSettings.mPermissions.get(permission); 1842 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1843 && (grantedPermissions == null 1844 || ArrayUtils.contains(grantedPermissions, permission))) { 1845 final int flags = permissionsState.getPermissionFlags(permission, userId); 1846 // Installer cannot change immutable permissions. 1847 if ((flags & immutableFlags) == 0) { 1848 grantRuntimePermission(pkg.packageName, permission, userId); 1849 } 1850 } 1851 } 1852 } 1853 } 1854 1855 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1856 Bundle extras = null; 1857 switch (res.returnCode) { 1858 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1859 extras = new Bundle(); 1860 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1861 res.origPermission); 1862 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1863 res.origPackage); 1864 break; 1865 } 1866 case PackageManager.INSTALL_SUCCEEDED: { 1867 extras = new Bundle(); 1868 extras.putBoolean(Intent.EXTRA_REPLACING, 1869 res.removedInfo != null && res.removedInfo.removedPackage != null); 1870 break; 1871 } 1872 } 1873 return extras; 1874 } 1875 1876 void scheduleWriteSettingsLocked() { 1877 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1878 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1879 } 1880 } 1881 1882 void scheduleWritePackageRestrictionsLocked(int userId) { 1883 if (!sUserManager.exists(userId)) return; 1884 mDirtyUsers.add(userId); 1885 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1886 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1887 } 1888 } 1889 1890 public static PackageManagerService main(Context context, Installer installer, 1891 boolean factoryTest, boolean onlyCore) { 1892 PackageManagerService m = new PackageManagerService(context, installer, 1893 factoryTest, onlyCore); 1894 m.enableSystemUserPackages(); 1895 ServiceManager.addService("package", m); 1896 return m; 1897 } 1898 1899 private void enableSystemUserPackages() { 1900 if (!UserManager.isSplitSystemUser()) { 1901 return; 1902 } 1903 // For system user, enable apps based on the following conditions: 1904 // - app is whitelisted or belong to one of these groups: 1905 // -- system app which has no launcher icons 1906 // -- system app which has INTERACT_ACROSS_USERS permission 1907 // -- system IME app 1908 // - app is not in the blacklist 1909 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1910 Set<String> enableApps = new ArraySet<>(); 1911 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1912 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1913 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1914 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1915 enableApps.addAll(wlApps); 1916 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1917 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1918 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1919 enableApps.removeAll(blApps); 1920 Log.i(TAG, "Applications installed for system user: " + enableApps); 1921 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1922 UserHandle.SYSTEM); 1923 final int allAppsSize = allAps.size(); 1924 synchronized (mPackages) { 1925 for (int i = 0; i < allAppsSize; i++) { 1926 String pName = allAps.get(i); 1927 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1928 // Should not happen, but we shouldn't be failing if it does 1929 if (pkgSetting == null) { 1930 continue; 1931 } 1932 boolean install = enableApps.contains(pName); 1933 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1934 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1935 + " for system user"); 1936 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1937 } 1938 } 1939 } 1940 } 1941 1942 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1943 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1944 Context.DISPLAY_SERVICE); 1945 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1946 } 1947 1948 public PackageManagerService(Context context, Installer installer, 1949 boolean factoryTest, boolean onlyCore) { 1950 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1951 SystemClock.uptimeMillis()); 1952 1953 if (mSdkVersion <= 0) { 1954 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1955 } 1956 1957 mContext = context; 1958 mFactoryTest = factoryTest; 1959 mOnlyCore = onlyCore; 1960 mMetrics = new DisplayMetrics(); 1961 mSettings = new Settings(mPackages); 1962 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1963 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1964 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1965 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1966 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1967 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1968 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1969 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1970 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1971 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1972 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1973 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1974 1975 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1976 if (separateProcesses != null && separateProcesses.length() > 0) { 1977 if ("*".equals(separateProcesses)) { 1978 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1979 mSeparateProcesses = null; 1980 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1981 } else { 1982 mDefParseFlags = 0; 1983 mSeparateProcesses = separateProcesses.split(","); 1984 Slog.w(TAG, "Running with debug.separate_processes: " 1985 + separateProcesses); 1986 } 1987 } else { 1988 mDefParseFlags = 0; 1989 mSeparateProcesses = null; 1990 } 1991 1992 mInstaller = installer; 1993 mPackageDexOptimizer = new PackageDexOptimizer(this); 1994 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1995 1996 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1997 FgThread.get().getLooper()); 1998 1999 getDefaultDisplayMetrics(context, mMetrics); 2000 2001 SystemConfig systemConfig = SystemConfig.getInstance(); 2002 mGlobalGids = systemConfig.getGlobalGids(); 2003 mSystemPermissions = systemConfig.getSystemPermissions(); 2004 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2005 2006 synchronized (mInstallLock) { 2007 // writer 2008 synchronized (mPackages) { 2009 mHandlerThread = new ServiceThread(TAG, 2010 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2011 mHandlerThread.start(); 2012 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2013 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2014 2015 File dataDir = Environment.getDataDirectory(); 2016 mAppInstallDir = new File(dataDir, "app"); 2017 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2018 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2019 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2020 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2021 2022 sUserManager = new UserManagerService(context, this, mPackages); 2023 2024 // Propagate permission configuration in to package manager. 2025 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2026 = systemConfig.getPermissions(); 2027 for (int i=0; i<permConfig.size(); i++) { 2028 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2029 BasePermission bp = mSettings.mPermissions.get(perm.name); 2030 if (bp == null) { 2031 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2032 mSettings.mPermissions.put(perm.name, bp); 2033 } 2034 if (perm.gids != null) { 2035 bp.setGids(perm.gids, perm.perUser); 2036 } 2037 } 2038 2039 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2040 for (int i=0; i<libConfig.size(); i++) { 2041 mSharedLibraries.put(libConfig.keyAt(i), 2042 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2043 } 2044 2045 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2046 2047 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2048 2049 String customResolverActivity = Resources.getSystem().getString( 2050 R.string.config_customResolverActivity); 2051 if (TextUtils.isEmpty(customResolverActivity)) { 2052 customResolverActivity = null; 2053 } else { 2054 mCustomResolverComponentName = ComponentName.unflattenFromString( 2055 customResolverActivity); 2056 } 2057 2058 long startTime = SystemClock.uptimeMillis(); 2059 2060 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2061 startTime); 2062 2063 // Set flag to monitor and not change apk file paths when 2064 // scanning install directories. 2065 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2066 2067 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2068 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2069 2070 if (bootClassPath == null) { 2071 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2072 } 2073 2074 if (systemServerClassPath == null) { 2075 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2076 } 2077 2078 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2079 final String[] dexCodeInstructionSets = 2080 getDexCodeInstructionSets( 2081 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2082 2083 /** 2084 * Ensure all external libraries have had dexopt run on them. 2085 */ 2086 if (mSharedLibraries.size() > 0) { 2087 // NOTE: For now, we're compiling these system "shared libraries" 2088 // (and framework jars) into all available architectures. It's possible 2089 // to compile them only when we come across an app that uses them (there's 2090 // already logic for that in scanPackageLI) but that adds some complexity. 2091 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2092 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2093 final String lib = libEntry.path; 2094 if (lib == null) { 2095 continue; 2096 } 2097 2098 try { 2099 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2100 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2101 // Shared libraries do not have profiles so we perform a full 2102 // AOT compilation. 2103 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2104 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2105 StorageManager.UUID_PRIVATE_INTERNAL, 2106 false /*useProfiles*/); 2107 } 2108 } catch (FileNotFoundException e) { 2109 Slog.w(TAG, "Library not found: " + lib); 2110 } catch (IOException | InstallerException e) { 2111 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2112 + e.getMessage()); 2113 } 2114 } 2115 } 2116 } 2117 2118 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2119 2120 final VersionInfo ver = mSettings.getInternalVersion(); 2121 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2122 // when upgrading from pre-M, promote system app permissions from install to runtime 2123 mPromoteSystemApps = 2124 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2125 2126 // save off the names of pre-existing system packages prior to scanning; we don't 2127 // want to automatically grant runtime permissions for new system apps 2128 if (mPromoteSystemApps) { 2129 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2130 while (pkgSettingIter.hasNext()) { 2131 PackageSetting ps = pkgSettingIter.next(); 2132 if (isSystemApp(ps)) { 2133 mExistingSystemPackages.add(ps.name); 2134 } 2135 } 2136 } 2137 2138 // Collect vendor overlay packages. 2139 // (Do this before scanning any apps.) 2140 // For security and version matching reason, only consider 2141 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2142 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2143 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2144 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2145 2146 // Find base frameworks (resource packages without code). 2147 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2148 | PackageParser.PARSE_IS_SYSTEM_DIR 2149 | PackageParser.PARSE_IS_PRIVILEGED, 2150 scanFlags | SCAN_NO_DEX, 0); 2151 2152 // Collected privileged system packages. 2153 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2154 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2155 | PackageParser.PARSE_IS_SYSTEM_DIR 2156 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2157 2158 // Collect ordinary system packages. 2159 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2160 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2161 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2162 2163 // Collect all vendor packages. 2164 File vendorAppDir = new File("/vendor/app"); 2165 try { 2166 vendorAppDir = vendorAppDir.getCanonicalFile(); 2167 } catch (IOException e) { 2168 // failed to look up canonical path, continue with original one 2169 } 2170 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2171 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2172 2173 // Collect all OEM packages. 2174 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2175 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2176 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2177 2178 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2179 try { 2180 mInstaller.moveFiles(); 2181 } catch (InstallerException e) { 2182 logCriticalInfo(Log.WARN, "Update commands failed: " + e); 2183 } 2184 2185 // Prune any system packages that no longer exist. 2186 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2187 if (!mOnlyCore) { 2188 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2189 while (psit.hasNext()) { 2190 PackageSetting ps = psit.next(); 2191 2192 /* 2193 * If this is not a system app, it can't be a 2194 * disable system app. 2195 */ 2196 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2197 continue; 2198 } 2199 2200 /* 2201 * If the package is scanned, it's not erased. 2202 */ 2203 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2204 if (scannedPkg != null) { 2205 /* 2206 * If the system app is both scanned and in the 2207 * disabled packages list, then it must have been 2208 * added via OTA. Remove it from the currently 2209 * scanned package so the previously user-installed 2210 * application can be scanned. 2211 */ 2212 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2213 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2214 + ps.name + "; removing system app. Last known codePath=" 2215 + ps.codePathString + ", installStatus=" + ps.installStatus 2216 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2217 + scannedPkg.mVersionCode); 2218 removePackageLI(ps, true); 2219 mExpectingBetter.put(ps.name, ps.codePath); 2220 } 2221 2222 continue; 2223 } 2224 2225 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2226 psit.remove(); 2227 logCriticalInfo(Log.WARN, "System package " + ps.name 2228 + " no longer exists; wiping its data"); 2229 removeDataDirsLI(null, ps.name); 2230 } else { 2231 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2232 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2233 possiblyDeletedUpdatedSystemApps.add(ps.name); 2234 } 2235 } 2236 } 2237 } 2238 2239 //look for any incomplete package installations 2240 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2241 //clean up list 2242 for(int i = 0; i < deletePkgsList.size(); i++) { 2243 //clean up here 2244 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2245 } 2246 //delete tmp files 2247 deleteTempPackageFiles(); 2248 2249 // Remove any shared userIDs that have no associated packages 2250 mSettings.pruneSharedUsersLPw(); 2251 2252 if (!mOnlyCore) { 2253 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2254 SystemClock.uptimeMillis()); 2255 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2256 2257 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2258 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2259 2260 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2261 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2262 2263 /** 2264 * Remove disable package settings for any updated system 2265 * apps that were removed via an OTA. If they're not a 2266 * previously-updated app, remove them completely. 2267 * Otherwise, just revoke their system-level permissions. 2268 */ 2269 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2270 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2271 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2272 2273 String msg; 2274 if (deletedPkg == null) { 2275 msg = "Updated system package " + deletedAppName 2276 + " no longer exists; wiping its data"; 2277 removeDataDirsLI(null, deletedAppName); 2278 } else { 2279 msg = "Updated system app + " + deletedAppName 2280 + " no longer present; removing system privileges for " 2281 + deletedAppName; 2282 2283 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2284 2285 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2286 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2287 } 2288 logCriticalInfo(Log.WARN, msg); 2289 } 2290 2291 /** 2292 * Make sure all system apps that we expected to appear on 2293 * the userdata partition actually showed up. If they never 2294 * appeared, crawl back and revive the system version. 2295 */ 2296 for (int i = 0; i < mExpectingBetter.size(); i++) { 2297 final String packageName = mExpectingBetter.keyAt(i); 2298 if (!mPackages.containsKey(packageName)) { 2299 final File scanFile = mExpectingBetter.valueAt(i); 2300 2301 logCriticalInfo(Log.WARN, "Expected better " + packageName 2302 + " but never showed up; reverting to system"); 2303 2304 final int reparseFlags; 2305 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2306 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2307 | PackageParser.PARSE_IS_SYSTEM_DIR 2308 | PackageParser.PARSE_IS_PRIVILEGED; 2309 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2310 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2311 | PackageParser.PARSE_IS_SYSTEM_DIR; 2312 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2313 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2314 | PackageParser.PARSE_IS_SYSTEM_DIR; 2315 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2316 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2317 | PackageParser.PARSE_IS_SYSTEM_DIR; 2318 } else { 2319 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2320 continue; 2321 } 2322 2323 mSettings.enableSystemPackageLPw(packageName); 2324 2325 try { 2326 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2327 } catch (PackageManagerException e) { 2328 Slog.e(TAG, "Failed to parse original system package: " 2329 + e.getMessage()); 2330 } 2331 } 2332 } 2333 } 2334 mExpectingBetter.clear(); 2335 2336 // Now that we know all of the shared libraries, update all clients to have 2337 // the correct library paths. 2338 updateAllSharedLibrariesLPw(); 2339 2340 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2341 // NOTE: We ignore potential failures here during a system scan (like 2342 // the rest of the commands above) because there's precious little we 2343 // can do about it. A settings error is reported, though. 2344 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2345 false /* boot complete */); 2346 } 2347 2348 // Now that we know all the packages we are keeping, 2349 // read and update their last usage times. 2350 mPackageUsage.readLP(); 2351 2352 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2353 SystemClock.uptimeMillis()); 2354 Slog.i(TAG, "Time to scan packages: " 2355 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2356 + " seconds"); 2357 2358 // If the platform SDK has changed since the last time we booted, 2359 // we need to re-grant app permission to catch any new ones that 2360 // appear. This is really a hack, and means that apps can in some 2361 // cases get permissions that the user didn't initially explicitly 2362 // allow... it would be nice to have some better way to handle 2363 // this situation. 2364 int updateFlags = UPDATE_PERMISSIONS_ALL; 2365 if (ver.sdkVersion != mSdkVersion) { 2366 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2367 + mSdkVersion + "; regranting permissions for internal storage"); 2368 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2369 } 2370 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2371 ver.sdkVersion = mSdkVersion; 2372 2373 // If this is the first boot or an update from pre-M, and it is a normal 2374 // boot, then we need to initialize the default preferred apps across 2375 // all defined users. 2376 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2377 for (UserInfo user : sUserManager.getUsers(true)) { 2378 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2379 applyFactoryDefaultBrowserLPw(user.id); 2380 primeDomainVerificationsLPw(user.id); 2381 } 2382 } 2383 2384 // Prepare storage for system user really early during boot, 2385 // since core system apps like SettingsProvider and SystemUI 2386 // can't wait for user to start 2387 final int flags; 2388 if (StorageManager.isFileBasedEncryptionEnabled()) { 2389 flags = Installer.FLAG_DE_STORAGE; 2390 } else { 2391 flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE; 2392 } 2393 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, flags); 2394 2395 // If this is first boot after an OTA, and a normal boot, then 2396 // we need to clear code cache directories. 2397 if (mIsUpgrade && !onlyCore) { 2398 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2399 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2400 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2401 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2402 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2403 } 2404 } 2405 ver.fingerprint = Build.FINGERPRINT; 2406 } 2407 2408 checkDefaultBrowser(); 2409 2410 // clear only after permissions and other defaults have been updated 2411 mExistingSystemPackages.clear(); 2412 mPromoteSystemApps = false; 2413 2414 // All the changes are done during package scanning. 2415 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2416 2417 // can downgrade to reader 2418 mSettings.writeLPr(); 2419 2420 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2421 SystemClock.uptimeMillis()); 2422 2423 if (!mOnlyCore) { 2424 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2425 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2426 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2427 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2428 mIntentFilterVerifierComponent); 2429 } else { 2430 mRequiredVerifierPackage = null; 2431 mRequiredInstallerPackage = null; 2432 mIntentFilterVerifierComponent = null; 2433 mIntentFilterVerifier = null; 2434 } 2435 2436 mInstallerService = new PackageInstallerService(context, this); 2437 2438 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2439 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2440 // both the installer and resolver must be present to enable ephemeral 2441 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2442 if (DEBUG_EPHEMERAL) { 2443 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2444 + " installer:" + ephemeralInstallerComponent); 2445 } 2446 mEphemeralResolverComponent = ephemeralResolverComponent; 2447 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2448 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2449 mEphemeralResolverConnection = 2450 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2451 } else { 2452 if (DEBUG_EPHEMERAL) { 2453 final String missingComponent = 2454 (ephemeralResolverComponent == null) 2455 ? (ephemeralInstallerComponent == null) 2456 ? "resolver and installer" 2457 : "resolver" 2458 : "installer"; 2459 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2460 } 2461 mEphemeralResolverComponent = null; 2462 mEphemeralInstallerComponent = null; 2463 mEphemeralResolverConnection = null; 2464 } 2465 2466 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2467 } // synchronized (mPackages) 2468 } // synchronized (mInstallLock) 2469 2470 // Now after opening every single application zip, make sure they 2471 // are all flushed. Not really needed, but keeps things nice and 2472 // tidy. 2473 Runtime.getRuntime().gc(); 2474 2475 // The initial scanning above does many calls into installd while 2476 // holding the mPackages lock, but we're mostly interested in yelling 2477 // once we have a booted system. 2478 mInstaller.setWarnIfHeld(mPackages); 2479 2480 // Expose private service for system components to use. 2481 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2482 } 2483 2484 @Override 2485 public boolean isFirstBoot() { 2486 return !mRestoredSettings; 2487 } 2488 2489 @Override 2490 public boolean isOnlyCoreApps() { 2491 return mOnlyCore; 2492 } 2493 2494 @Override 2495 public boolean isUpgrade() { 2496 return mIsUpgrade; 2497 } 2498 2499 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2500 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2501 2502 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2503 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2504 if (matches.size() == 1) { 2505 return matches.get(0).getComponentInfo().packageName; 2506 } else { 2507 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2508 return null; 2509 } 2510 } 2511 2512 private @NonNull String getRequiredInstallerLPr() { 2513 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2514 intent.addCategory(Intent.CATEGORY_DEFAULT); 2515 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2516 2517 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2518 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2519 if (matches.size() == 1) { 2520 return matches.get(0).getComponentInfo().packageName; 2521 } else { 2522 throw new RuntimeException("There must be exactly one installer; found " + matches); 2523 } 2524 } 2525 2526 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2527 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2528 2529 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2530 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2531 ResolveInfo best = null; 2532 final int N = matches.size(); 2533 for (int i = 0; i < N; i++) { 2534 final ResolveInfo cur = matches.get(i); 2535 final String packageName = cur.getComponentInfo().packageName; 2536 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2537 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2538 continue; 2539 } 2540 2541 if (best == null || cur.priority > best.priority) { 2542 best = cur; 2543 } 2544 } 2545 2546 if (best != null) { 2547 return best.getComponentInfo().getComponentName(); 2548 } else { 2549 throw new RuntimeException("There must be at least one intent filter verifier"); 2550 } 2551 } 2552 2553 private @Nullable ComponentName getEphemeralResolverLPr() { 2554 final String[] packageArray = 2555 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2556 if (packageArray.length == 0) { 2557 if (DEBUG_EPHEMERAL) { 2558 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2559 } 2560 return null; 2561 } 2562 2563 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2564 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2565 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2566 2567 final int N = resolvers.size(); 2568 if (N == 0) { 2569 if (DEBUG_EPHEMERAL) { 2570 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2571 } 2572 return null; 2573 } 2574 2575 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2576 for (int i = 0; i < N; i++) { 2577 final ResolveInfo info = resolvers.get(i); 2578 2579 if (info.serviceInfo == null) { 2580 continue; 2581 } 2582 2583 final String packageName = info.serviceInfo.packageName; 2584 if (!possiblePackages.contains(packageName)) { 2585 if (DEBUG_EPHEMERAL) { 2586 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2587 + " pkg: " + packageName + ", info:" + info); 2588 } 2589 continue; 2590 } 2591 2592 if (DEBUG_EPHEMERAL) { 2593 Slog.v(TAG, "Ephemeral resolver found;" 2594 + " pkg: " + packageName + ", info:" + info); 2595 } 2596 return new ComponentName(packageName, info.serviceInfo.name); 2597 } 2598 if (DEBUG_EPHEMERAL) { 2599 Slog.v(TAG, "Ephemeral resolver NOT found"); 2600 } 2601 return null; 2602 } 2603 2604 private @Nullable ComponentName getEphemeralInstallerLPr() { 2605 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2606 intent.addCategory(Intent.CATEGORY_DEFAULT); 2607 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2608 2609 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2610 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2611 if (matches.size() == 0) { 2612 return null; 2613 } else if (matches.size() == 1) { 2614 return matches.get(0).getComponentInfo().getComponentName(); 2615 } else { 2616 throw new RuntimeException( 2617 "There must be at most one ephemeral installer; found " + matches); 2618 } 2619 } 2620 2621 private void primeDomainVerificationsLPw(int userId) { 2622 if (DEBUG_DOMAIN_VERIFICATION) { 2623 Slog.d(TAG, "Priming domain verifications in user " + userId); 2624 } 2625 2626 SystemConfig systemConfig = SystemConfig.getInstance(); 2627 ArraySet<String> packages = systemConfig.getLinkedApps(); 2628 ArraySet<String> domains = new ArraySet<String>(); 2629 2630 for (String packageName : packages) { 2631 PackageParser.Package pkg = mPackages.get(packageName); 2632 if (pkg != null) { 2633 if (!pkg.isSystemApp()) { 2634 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2635 continue; 2636 } 2637 2638 domains.clear(); 2639 for (PackageParser.Activity a : pkg.activities) { 2640 for (ActivityIntentInfo filter : a.intents) { 2641 if (hasValidDomains(filter)) { 2642 domains.addAll(filter.getHostsList()); 2643 } 2644 } 2645 } 2646 2647 if (domains.size() > 0) { 2648 if (DEBUG_DOMAIN_VERIFICATION) { 2649 Slog.v(TAG, " + " + packageName); 2650 } 2651 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2652 // state w.r.t. the formal app-linkage "no verification attempted" state; 2653 // and then 'always' in the per-user state actually used for intent resolution. 2654 final IntentFilterVerificationInfo ivi; 2655 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2656 new ArrayList<String>(domains)); 2657 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2658 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2659 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2660 } else { 2661 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2662 + "' does not handle web links"); 2663 } 2664 } else { 2665 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2666 } 2667 } 2668 2669 scheduleWritePackageRestrictionsLocked(userId); 2670 scheduleWriteSettingsLocked(); 2671 } 2672 2673 private void applyFactoryDefaultBrowserLPw(int userId) { 2674 // The default browser app's package name is stored in a string resource, 2675 // with a product-specific overlay used for vendor customization. 2676 String browserPkg = mContext.getResources().getString( 2677 com.android.internal.R.string.default_browser); 2678 if (!TextUtils.isEmpty(browserPkg)) { 2679 // non-empty string => required to be a known package 2680 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2681 if (ps == null) { 2682 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2683 browserPkg = null; 2684 } else { 2685 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2686 } 2687 } 2688 2689 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2690 // default. If there's more than one, just leave everything alone. 2691 if (browserPkg == null) { 2692 calculateDefaultBrowserLPw(userId); 2693 } 2694 } 2695 2696 private void calculateDefaultBrowserLPw(int userId) { 2697 List<String> allBrowsers = resolveAllBrowserApps(userId); 2698 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2699 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2700 } 2701 2702 private List<String> resolveAllBrowserApps(int userId) { 2703 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2704 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2705 PackageManager.MATCH_ALL, userId); 2706 2707 final int count = list.size(); 2708 List<String> result = new ArrayList<String>(count); 2709 for (int i=0; i<count; i++) { 2710 ResolveInfo info = list.get(i); 2711 if (info.activityInfo == null 2712 || !info.handleAllWebDataURI 2713 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2714 || result.contains(info.activityInfo.packageName)) { 2715 continue; 2716 } 2717 result.add(info.activityInfo.packageName); 2718 } 2719 2720 return result; 2721 } 2722 2723 private boolean packageIsBrowser(String packageName, int userId) { 2724 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2725 PackageManager.MATCH_ALL, userId); 2726 final int N = list.size(); 2727 for (int i = 0; i < N; i++) { 2728 ResolveInfo info = list.get(i); 2729 if (packageName.equals(info.activityInfo.packageName)) { 2730 return true; 2731 } 2732 } 2733 return false; 2734 } 2735 2736 private void checkDefaultBrowser() { 2737 final int myUserId = UserHandle.myUserId(); 2738 final String packageName = getDefaultBrowserPackageName(myUserId); 2739 if (packageName != null) { 2740 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2741 if (info == null) { 2742 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2743 synchronized (mPackages) { 2744 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2745 } 2746 } 2747 } 2748 } 2749 2750 @Override 2751 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2752 throws RemoteException { 2753 try { 2754 return super.onTransact(code, data, reply, flags); 2755 } catch (RuntimeException e) { 2756 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2757 Slog.wtf(TAG, "Package Manager Crash", e); 2758 } 2759 throw e; 2760 } 2761 } 2762 2763 void cleanupInstallFailedPackage(PackageSetting ps) { 2764 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2765 2766 removeDataDirsLI(ps.volumeUuid, ps.name); 2767 if (ps.codePath != null) { 2768 removeCodePathLI(ps.codePath); 2769 } 2770 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2771 if (ps.resourcePath.isDirectory()) { 2772 FileUtils.deleteContents(ps.resourcePath); 2773 } 2774 ps.resourcePath.delete(); 2775 } 2776 mSettings.removePackageLPw(ps.name); 2777 } 2778 2779 static int[] appendInts(int[] cur, int[] add) { 2780 if (add == null) return cur; 2781 if (cur == null) return add; 2782 final int N = add.length; 2783 for (int i=0; i<N; i++) { 2784 cur = appendInt(cur, add[i]); 2785 } 2786 return cur; 2787 } 2788 2789 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2790 if (!sUserManager.exists(userId)) return null; 2791 final PackageSetting ps = (PackageSetting) p.mExtras; 2792 if (ps == null) { 2793 return null; 2794 } 2795 2796 final PermissionsState permissionsState = ps.getPermissionsState(); 2797 2798 final int[] gids = permissionsState.computeGids(userId); 2799 final Set<String> permissions = permissionsState.getPermissions(userId); 2800 final PackageUserState state = ps.readUserState(userId); 2801 2802 return PackageParser.generatePackageInfo(p, gids, flags, 2803 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2804 } 2805 2806 @Override 2807 public void checkPackageStartable(String packageName, int userId) { 2808 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2809 2810 synchronized (mPackages) { 2811 final PackageSetting ps = mSettings.mPackages.get(packageName); 2812 if (ps == null) { 2813 throw new SecurityException("Package " + packageName + " was not found!"); 2814 } 2815 2816 if (ps.frozen) { 2817 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2818 } 2819 2820 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2821 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2822 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2823 } 2824 } 2825 } 2826 2827 @Override 2828 public boolean isPackageAvailable(String packageName, int userId) { 2829 if (!sUserManager.exists(userId)) return false; 2830 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2831 synchronized (mPackages) { 2832 PackageParser.Package p = mPackages.get(packageName); 2833 if (p != null) { 2834 final PackageSetting ps = (PackageSetting) p.mExtras; 2835 if (ps != null) { 2836 final PackageUserState state = ps.readUserState(userId); 2837 if (state != null) { 2838 return PackageParser.isAvailable(state); 2839 } 2840 } 2841 } 2842 } 2843 return false; 2844 } 2845 2846 @Override 2847 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2848 if (!sUserManager.exists(userId)) return null; 2849 flags = updateFlagsForPackage(flags, userId, packageName); 2850 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2851 // reader 2852 synchronized (mPackages) { 2853 PackageParser.Package p = mPackages.get(packageName); 2854 if (DEBUG_PACKAGE_INFO) 2855 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2856 if (p != null) { 2857 return generatePackageInfo(p, flags, userId); 2858 } 2859 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2860 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2861 } 2862 } 2863 return null; 2864 } 2865 2866 @Override 2867 public String[] currentToCanonicalPackageNames(String[] names) { 2868 String[] out = new String[names.length]; 2869 // reader 2870 synchronized (mPackages) { 2871 for (int i=names.length-1; i>=0; i--) { 2872 PackageSetting ps = mSettings.mPackages.get(names[i]); 2873 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2874 } 2875 } 2876 return out; 2877 } 2878 2879 @Override 2880 public String[] canonicalToCurrentPackageNames(String[] names) { 2881 String[] out = new String[names.length]; 2882 // reader 2883 synchronized (mPackages) { 2884 for (int i=names.length-1; i>=0; i--) { 2885 String cur = mSettings.mRenamedPackages.get(names[i]); 2886 out[i] = cur != null ? cur : names[i]; 2887 } 2888 } 2889 return out; 2890 } 2891 2892 @Override 2893 public int getPackageUid(String packageName, int flags, int userId) { 2894 if (!sUserManager.exists(userId)) return -1; 2895 flags = updateFlagsForPackage(flags, userId, packageName); 2896 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2897 2898 // reader 2899 synchronized (mPackages) { 2900 final PackageParser.Package p = mPackages.get(packageName); 2901 if (p != null && p.isMatch(flags)) { 2902 return UserHandle.getUid(userId, p.applicationInfo.uid); 2903 } 2904 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2905 final PackageSetting ps = mSettings.mPackages.get(packageName); 2906 if (ps != null && ps.isMatch(flags)) { 2907 return UserHandle.getUid(userId, ps.appId); 2908 } 2909 } 2910 } 2911 2912 return -1; 2913 } 2914 2915 @Override 2916 public int[] getPackageGids(String packageName, int flags, int userId) { 2917 if (!sUserManager.exists(userId)) return null; 2918 flags = updateFlagsForPackage(flags, userId, packageName); 2919 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2920 "getPackageGids"); 2921 2922 // reader 2923 synchronized (mPackages) { 2924 final PackageParser.Package p = mPackages.get(packageName); 2925 if (p != null && p.isMatch(flags)) { 2926 PackageSetting ps = (PackageSetting) p.mExtras; 2927 return ps.getPermissionsState().computeGids(userId); 2928 } 2929 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2930 final PackageSetting ps = mSettings.mPackages.get(packageName); 2931 if (ps != null && ps.isMatch(flags)) { 2932 return ps.getPermissionsState().computeGids(userId); 2933 } 2934 } 2935 } 2936 2937 return null; 2938 } 2939 2940 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 2941 if (bp.perm != null) { 2942 return PackageParser.generatePermissionInfo(bp.perm, flags); 2943 } 2944 PermissionInfo pi = new PermissionInfo(); 2945 pi.name = bp.name; 2946 pi.packageName = bp.sourcePackage; 2947 pi.nonLocalizedLabel = bp.name; 2948 pi.protectionLevel = bp.protectionLevel; 2949 return pi; 2950 } 2951 2952 @Override 2953 public PermissionInfo getPermissionInfo(String name, int flags) { 2954 // reader 2955 synchronized (mPackages) { 2956 final BasePermission p = mSettings.mPermissions.get(name); 2957 if (p != null) { 2958 return generatePermissionInfo(p, flags); 2959 } 2960 return null; 2961 } 2962 } 2963 2964 @Override 2965 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2966 // reader 2967 synchronized (mPackages) { 2968 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2969 for (BasePermission p : mSettings.mPermissions.values()) { 2970 if (group == null) { 2971 if (p.perm == null || p.perm.info.group == null) { 2972 out.add(generatePermissionInfo(p, flags)); 2973 } 2974 } else { 2975 if (p.perm != null && group.equals(p.perm.info.group)) { 2976 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2977 } 2978 } 2979 } 2980 2981 if (out.size() > 0) { 2982 return out; 2983 } 2984 return mPermissionGroups.containsKey(group) ? out : null; 2985 } 2986 } 2987 2988 @Override 2989 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2990 // reader 2991 synchronized (mPackages) { 2992 return PackageParser.generatePermissionGroupInfo( 2993 mPermissionGroups.get(name), flags); 2994 } 2995 } 2996 2997 @Override 2998 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2999 // reader 3000 synchronized (mPackages) { 3001 final int N = mPermissionGroups.size(); 3002 ArrayList<PermissionGroupInfo> out 3003 = new ArrayList<PermissionGroupInfo>(N); 3004 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3005 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3006 } 3007 return out; 3008 } 3009 } 3010 3011 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3012 int userId) { 3013 if (!sUserManager.exists(userId)) return null; 3014 PackageSetting ps = mSettings.mPackages.get(packageName); 3015 if (ps != null) { 3016 if (ps.pkg == null) { 3017 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3018 flags, userId); 3019 if (pInfo != null) { 3020 return pInfo.applicationInfo; 3021 } 3022 return null; 3023 } 3024 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3025 ps.readUserState(userId), userId); 3026 } 3027 return null; 3028 } 3029 3030 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3031 int userId) { 3032 if (!sUserManager.exists(userId)) return null; 3033 PackageSetting ps = mSettings.mPackages.get(packageName); 3034 if (ps != null) { 3035 PackageParser.Package pkg = ps.pkg; 3036 if (pkg == null) { 3037 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3038 return null; 3039 } 3040 // Only data remains, so we aren't worried about code paths 3041 pkg = new PackageParser.Package(packageName); 3042 pkg.applicationInfo.packageName = packageName; 3043 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3044 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3045 pkg.applicationInfo.uid = ps.appId; 3046 pkg.applicationInfo.initForUser(userId); 3047 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3048 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3049 } 3050 return generatePackageInfo(pkg, flags, userId); 3051 } 3052 return null; 3053 } 3054 3055 @Override 3056 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3057 if (!sUserManager.exists(userId)) return null; 3058 flags = updateFlagsForApplication(flags, userId, packageName); 3059 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3060 // writer 3061 synchronized (mPackages) { 3062 PackageParser.Package p = mPackages.get(packageName); 3063 if (DEBUG_PACKAGE_INFO) Log.v( 3064 TAG, "getApplicationInfo " + packageName 3065 + ": " + p); 3066 if (p != null) { 3067 PackageSetting ps = mSettings.mPackages.get(packageName); 3068 if (ps == null) return null; 3069 // Note: isEnabledLP() does not apply here - always return info 3070 return PackageParser.generateApplicationInfo( 3071 p, flags, ps.readUserState(userId), userId); 3072 } 3073 if ("android".equals(packageName)||"system".equals(packageName)) { 3074 return mAndroidApplication; 3075 } 3076 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3077 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3078 } 3079 } 3080 return null; 3081 } 3082 3083 @Override 3084 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3085 final IPackageDataObserver observer) { 3086 mContext.enforceCallingOrSelfPermission( 3087 android.Manifest.permission.CLEAR_APP_CACHE, null); 3088 // Queue up an async operation since clearing cache may take a little while. 3089 mHandler.post(new Runnable() { 3090 public void run() { 3091 mHandler.removeCallbacks(this); 3092 boolean success = true; 3093 synchronized (mInstallLock) { 3094 try { 3095 mInstaller.freeCache(volumeUuid, freeStorageSize); 3096 } catch (InstallerException e) { 3097 Slog.w(TAG, "Couldn't clear application caches: " + e); 3098 success = false; 3099 } 3100 } 3101 if (observer != null) { 3102 try { 3103 observer.onRemoveCompleted(null, success); 3104 } catch (RemoteException e) { 3105 Slog.w(TAG, "RemoveException when invoking call back"); 3106 } 3107 } 3108 } 3109 }); 3110 } 3111 3112 @Override 3113 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3114 final IntentSender pi) { 3115 mContext.enforceCallingOrSelfPermission( 3116 android.Manifest.permission.CLEAR_APP_CACHE, null); 3117 // Queue up an async operation since clearing cache may take a little while. 3118 mHandler.post(new Runnable() { 3119 public void run() { 3120 mHandler.removeCallbacks(this); 3121 boolean success = true; 3122 synchronized (mInstallLock) { 3123 try { 3124 mInstaller.freeCache(volumeUuid, freeStorageSize); 3125 } catch (InstallerException e) { 3126 Slog.w(TAG, "Couldn't clear application caches: " + e); 3127 success = false; 3128 } 3129 } 3130 if(pi != null) { 3131 try { 3132 // Callback via pending intent 3133 int code = success ? 1 : 0; 3134 pi.sendIntent(null, code, null, 3135 null, null); 3136 } catch (SendIntentException e1) { 3137 Slog.i(TAG, "Failed to send pending intent"); 3138 } 3139 } 3140 } 3141 }); 3142 } 3143 3144 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3145 synchronized (mInstallLock) { 3146 try { 3147 mInstaller.freeCache(volumeUuid, freeStorageSize); 3148 } catch (InstallerException e) { 3149 throw new IOException("Failed to free enough space", e); 3150 } 3151 } 3152 } 3153 3154 /** 3155 * Return if the user key is currently unlocked. 3156 */ 3157 private boolean isUserKeyUnlocked(int userId) { 3158 if (StorageManager.isFileBasedEncryptionEnabled()) { 3159 final IMountService mount = IMountService.Stub 3160 .asInterface(ServiceManager.getService("mount")); 3161 if (mount == null) { 3162 Slog.w(TAG, "Early during boot, assuming locked"); 3163 return false; 3164 } 3165 final long token = Binder.clearCallingIdentity(); 3166 try { 3167 return mount.isUserKeyUnlocked(userId); 3168 } catch (RemoteException e) { 3169 throw e.rethrowAsRuntimeException(); 3170 } finally { 3171 Binder.restoreCallingIdentity(token); 3172 } 3173 } else { 3174 return true; 3175 } 3176 } 3177 3178 /** 3179 * Update given flags based on encryption status of current user. 3180 */ 3181 private int updateFlags(int flags, int userId) { 3182 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3183 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3184 // Caller expressed an explicit opinion about what encryption 3185 // aware/unaware components they want to see, so fall through and 3186 // give them what they want 3187 } else { 3188 // Caller expressed no opinion, so match based on user state 3189 if (isUserKeyUnlocked(userId)) { 3190 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3191 } else { 3192 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3193 } 3194 } 3195 3196 // Safe mode means we should ignore any third-party apps 3197 if (mSafeMode) { 3198 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3199 } 3200 3201 return flags; 3202 } 3203 3204 /** 3205 * Update given flags when being used to request {@link PackageInfo}. 3206 */ 3207 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3208 boolean triaged = true; 3209 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3210 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3211 // Caller is asking for component details, so they'd better be 3212 // asking for specific encryption matching behavior, or be triaged 3213 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3214 | PackageManager.MATCH_ENCRYPTION_AWARE 3215 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3216 triaged = false; 3217 } 3218 } 3219 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3220 | PackageManager.MATCH_SYSTEM_ONLY 3221 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3222 triaged = false; 3223 } 3224 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3225 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3226 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3227 } 3228 return updateFlags(flags, userId); 3229 } 3230 3231 /** 3232 * Update given flags when being used to request {@link ApplicationInfo}. 3233 */ 3234 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3235 return updateFlagsForPackage(flags, userId, cookie); 3236 } 3237 3238 /** 3239 * Update given flags when being used to request {@link ComponentInfo}. 3240 */ 3241 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3242 if (cookie instanceof Intent) { 3243 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3244 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3245 } 3246 } 3247 3248 boolean triaged = true; 3249 // Caller is asking for component details, so they'd better be 3250 // asking for specific encryption matching behavior, or be triaged 3251 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3252 | PackageManager.MATCH_ENCRYPTION_AWARE 3253 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3254 triaged = false; 3255 } 3256 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3257 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3258 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3259 } 3260 return updateFlags(flags, userId); 3261 } 3262 3263 /** 3264 * Update given flags when being used to request {@link ResolveInfo}. 3265 */ 3266 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3267 return updateFlagsForComponent(flags, userId, cookie); 3268 } 3269 3270 @Override 3271 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3272 if (!sUserManager.exists(userId)) return null; 3273 flags = updateFlagsForComponent(flags, userId, component); 3274 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3275 synchronized (mPackages) { 3276 PackageParser.Activity a = mActivities.mActivities.get(component); 3277 3278 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3279 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3280 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3281 if (ps == null) return null; 3282 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3283 userId); 3284 } 3285 if (mResolveComponentName.equals(component)) { 3286 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3287 new PackageUserState(), userId); 3288 } 3289 } 3290 return null; 3291 } 3292 3293 @Override 3294 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3295 String resolvedType) { 3296 synchronized (mPackages) { 3297 if (component.equals(mResolveComponentName)) { 3298 // The resolver supports EVERYTHING! 3299 return true; 3300 } 3301 PackageParser.Activity a = mActivities.mActivities.get(component); 3302 if (a == null) { 3303 return false; 3304 } 3305 for (int i=0; i<a.intents.size(); i++) { 3306 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3307 intent.getData(), intent.getCategories(), TAG) >= 0) { 3308 return true; 3309 } 3310 } 3311 return false; 3312 } 3313 } 3314 3315 @Override 3316 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3317 if (!sUserManager.exists(userId)) return null; 3318 flags = updateFlagsForComponent(flags, userId, component); 3319 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3320 synchronized (mPackages) { 3321 PackageParser.Activity a = mReceivers.mActivities.get(component); 3322 if (DEBUG_PACKAGE_INFO) Log.v( 3323 TAG, "getReceiverInfo " + component + ": " + a); 3324 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3325 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3326 if (ps == null) return null; 3327 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3328 userId); 3329 } 3330 } 3331 return null; 3332 } 3333 3334 @Override 3335 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3336 if (!sUserManager.exists(userId)) return null; 3337 flags = updateFlagsForComponent(flags, userId, component); 3338 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3339 synchronized (mPackages) { 3340 PackageParser.Service s = mServices.mServices.get(component); 3341 if (DEBUG_PACKAGE_INFO) Log.v( 3342 TAG, "getServiceInfo " + component + ": " + s); 3343 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3344 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3345 if (ps == null) return null; 3346 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3347 userId); 3348 } 3349 } 3350 return null; 3351 } 3352 3353 @Override 3354 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3355 if (!sUserManager.exists(userId)) return null; 3356 flags = updateFlagsForComponent(flags, userId, component); 3357 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3358 synchronized (mPackages) { 3359 PackageParser.Provider p = mProviders.mProviders.get(component); 3360 if (DEBUG_PACKAGE_INFO) Log.v( 3361 TAG, "getProviderInfo " + component + ": " + p); 3362 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3363 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3364 if (ps == null) return null; 3365 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3366 userId); 3367 } 3368 } 3369 return null; 3370 } 3371 3372 @Override 3373 public String[] getSystemSharedLibraryNames() { 3374 Set<String> libSet; 3375 synchronized (mPackages) { 3376 libSet = mSharedLibraries.keySet(); 3377 int size = libSet.size(); 3378 if (size > 0) { 3379 String[] libs = new String[size]; 3380 libSet.toArray(libs); 3381 return libs; 3382 } 3383 } 3384 return null; 3385 } 3386 3387 /** 3388 * @hide 3389 */ 3390 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3391 synchronized (mPackages) { 3392 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3393 if (lib != null && lib.apk != null) { 3394 return mPackages.get(lib.apk); 3395 } 3396 } 3397 return null; 3398 } 3399 3400 @Override 3401 public FeatureInfo[] getSystemAvailableFeatures() { 3402 Collection<FeatureInfo> featSet; 3403 synchronized (mPackages) { 3404 featSet = mAvailableFeatures.values(); 3405 int size = featSet.size(); 3406 if (size > 0) { 3407 FeatureInfo[] features = new FeatureInfo[size+1]; 3408 featSet.toArray(features); 3409 FeatureInfo fi = new FeatureInfo(); 3410 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3411 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3412 features[size] = fi; 3413 return features; 3414 } 3415 } 3416 return null; 3417 } 3418 3419 @Override 3420 public boolean hasSystemFeature(String name) { 3421 synchronized (mPackages) { 3422 return mAvailableFeatures.containsKey(name); 3423 } 3424 } 3425 3426 @Override 3427 public int checkPermission(String permName, String pkgName, int userId) { 3428 if (!sUserManager.exists(userId)) { 3429 return PackageManager.PERMISSION_DENIED; 3430 } 3431 3432 synchronized (mPackages) { 3433 final PackageParser.Package p = mPackages.get(pkgName); 3434 if (p != null && p.mExtras != null) { 3435 final PackageSetting ps = (PackageSetting) p.mExtras; 3436 final PermissionsState permissionsState = ps.getPermissionsState(); 3437 if (permissionsState.hasPermission(permName, userId)) { 3438 return PackageManager.PERMISSION_GRANTED; 3439 } 3440 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3441 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3442 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3443 return PackageManager.PERMISSION_GRANTED; 3444 } 3445 } 3446 } 3447 3448 return PackageManager.PERMISSION_DENIED; 3449 } 3450 3451 @Override 3452 public int checkUidPermission(String permName, int uid) { 3453 final int userId = UserHandle.getUserId(uid); 3454 3455 if (!sUserManager.exists(userId)) { 3456 return PackageManager.PERMISSION_DENIED; 3457 } 3458 3459 synchronized (mPackages) { 3460 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3461 if (obj != null) { 3462 final SettingBase ps = (SettingBase) obj; 3463 final PermissionsState permissionsState = ps.getPermissionsState(); 3464 if (permissionsState.hasPermission(permName, userId)) { 3465 return PackageManager.PERMISSION_GRANTED; 3466 } 3467 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3468 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3469 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3470 return PackageManager.PERMISSION_GRANTED; 3471 } 3472 } else { 3473 ArraySet<String> perms = mSystemPermissions.get(uid); 3474 if (perms != null) { 3475 if (perms.contains(permName)) { 3476 return PackageManager.PERMISSION_GRANTED; 3477 } 3478 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3479 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3480 return PackageManager.PERMISSION_GRANTED; 3481 } 3482 } 3483 } 3484 } 3485 3486 return PackageManager.PERMISSION_DENIED; 3487 } 3488 3489 @Override 3490 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3491 if (UserHandle.getCallingUserId() != userId) { 3492 mContext.enforceCallingPermission( 3493 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3494 "isPermissionRevokedByPolicy for user " + userId); 3495 } 3496 3497 if (checkPermission(permission, packageName, userId) 3498 == PackageManager.PERMISSION_GRANTED) { 3499 return false; 3500 } 3501 3502 final long identity = Binder.clearCallingIdentity(); 3503 try { 3504 final int flags = getPermissionFlags(permission, packageName, userId); 3505 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3506 } finally { 3507 Binder.restoreCallingIdentity(identity); 3508 } 3509 } 3510 3511 @Override 3512 public String getPermissionControllerPackageName() { 3513 synchronized (mPackages) { 3514 return mRequiredInstallerPackage; 3515 } 3516 } 3517 3518 /** 3519 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3520 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3521 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3522 * @param message the message to log on security exception 3523 */ 3524 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3525 boolean checkShell, String message) { 3526 if (userId < 0) { 3527 throw new IllegalArgumentException("Invalid userId " + userId); 3528 } 3529 if (checkShell) { 3530 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3531 } 3532 if (userId == UserHandle.getUserId(callingUid)) return; 3533 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3534 if (requireFullPermission) { 3535 mContext.enforceCallingOrSelfPermission( 3536 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3537 } else { 3538 try { 3539 mContext.enforceCallingOrSelfPermission( 3540 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3541 } catch (SecurityException se) { 3542 mContext.enforceCallingOrSelfPermission( 3543 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3544 } 3545 } 3546 } 3547 } 3548 3549 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3550 if (callingUid == Process.SHELL_UID) { 3551 if (userHandle >= 0 3552 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3553 throw new SecurityException("Shell does not have permission to access user " 3554 + userHandle); 3555 } else if (userHandle < 0) { 3556 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3557 + Debug.getCallers(3)); 3558 } 3559 } 3560 } 3561 3562 private BasePermission findPermissionTreeLP(String permName) { 3563 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3564 if (permName.startsWith(bp.name) && 3565 permName.length() > bp.name.length() && 3566 permName.charAt(bp.name.length()) == '.') { 3567 return bp; 3568 } 3569 } 3570 return null; 3571 } 3572 3573 private BasePermission checkPermissionTreeLP(String permName) { 3574 if (permName != null) { 3575 BasePermission bp = findPermissionTreeLP(permName); 3576 if (bp != null) { 3577 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3578 return bp; 3579 } 3580 throw new SecurityException("Calling uid " 3581 + Binder.getCallingUid() 3582 + " is not allowed to add to permission tree " 3583 + bp.name + " owned by uid " + bp.uid); 3584 } 3585 } 3586 throw new SecurityException("No permission tree found for " + permName); 3587 } 3588 3589 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3590 if (s1 == null) { 3591 return s2 == null; 3592 } 3593 if (s2 == null) { 3594 return false; 3595 } 3596 if (s1.getClass() != s2.getClass()) { 3597 return false; 3598 } 3599 return s1.equals(s2); 3600 } 3601 3602 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3603 if (pi1.icon != pi2.icon) return false; 3604 if (pi1.logo != pi2.logo) return false; 3605 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3606 if (!compareStrings(pi1.name, pi2.name)) return false; 3607 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3608 // We'll take care of setting this one. 3609 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3610 // These are not currently stored in settings. 3611 //if (!compareStrings(pi1.group, pi2.group)) return false; 3612 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3613 //if (pi1.labelRes != pi2.labelRes) return false; 3614 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3615 return true; 3616 } 3617 3618 int permissionInfoFootprint(PermissionInfo info) { 3619 int size = info.name.length(); 3620 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3621 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3622 return size; 3623 } 3624 3625 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3626 int size = 0; 3627 for (BasePermission perm : mSettings.mPermissions.values()) { 3628 if (perm.uid == tree.uid) { 3629 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3630 } 3631 } 3632 return size; 3633 } 3634 3635 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3636 // We calculate the max size of permissions defined by this uid and throw 3637 // if that plus the size of 'info' would exceed our stated maximum. 3638 if (tree.uid != Process.SYSTEM_UID) { 3639 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3640 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3641 throw new SecurityException("Permission tree size cap exceeded"); 3642 } 3643 } 3644 } 3645 3646 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3647 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3648 throw new SecurityException("Label must be specified in permission"); 3649 } 3650 BasePermission tree = checkPermissionTreeLP(info.name); 3651 BasePermission bp = mSettings.mPermissions.get(info.name); 3652 boolean added = bp == null; 3653 boolean changed = true; 3654 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3655 if (added) { 3656 enforcePermissionCapLocked(info, tree); 3657 bp = new BasePermission(info.name, tree.sourcePackage, 3658 BasePermission.TYPE_DYNAMIC); 3659 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3660 throw new SecurityException( 3661 "Not allowed to modify non-dynamic permission " 3662 + info.name); 3663 } else { 3664 if (bp.protectionLevel == fixedLevel 3665 && bp.perm.owner.equals(tree.perm.owner) 3666 && bp.uid == tree.uid 3667 && comparePermissionInfos(bp.perm.info, info)) { 3668 changed = false; 3669 } 3670 } 3671 bp.protectionLevel = fixedLevel; 3672 info = new PermissionInfo(info); 3673 info.protectionLevel = fixedLevel; 3674 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3675 bp.perm.info.packageName = tree.perm.info.packageName; 3676 bp.uid = tree.uid; 3677 if (added) { 3678 mSettings.mPermissions.put(info.name, bp); 3679 } 3680 if (changed) { 3681 if (!async) { 3682 mSettings.writeLPr(); 3683 } else { 3684 scheduleWriteSettingsLocked(); 3685 } 3686 } 3687 return added; 3688 } 3689 3690 @Override 3691 public boolean addPermission(PermissionInfo info) { 3692 synchronized (mPackages) { 3693 return addPermissionLocked(info, false); 3694 } 3695 } 3696 3697 @Override 3698 public boolean addPermissionAsync(PermissionInfo info) { 3699 synchronized (mPackages) { 3700 return addPermissionLocked(info, true); 3701 } 3702 } 3703 3704 @Override 3705 public void removePermission(String name) { 3706 synchronized (mPackages) { 3707 checkPermissionTreeLP(name); 3708 BasePermission bp = mSettings.mPermissions.get(name); 3709 if (bp != null) { 3710 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3711 throw new SecurityException( 3712 "Not allowed to modify non-dynamic permission " 3713 + name); 3714 } 3715 mSettings.mPermissions.remove(name); 3716 mSettings.writeLPr(); 3717 } 3718 } 3719 } 3720 3721 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3722 BasePermission bp) { 3723 int index = pkg.requestedPermissions.indexOf(bp.name); 3724 if (index == -1) { 3725 throw new SecurityException("Package " + pkg.packageName 3726 + " has not requested permission " + bp.name); 3727 } 3728 if (!bp.isRuntime() && !bp.isDevelopment()) { 3729 throw new SecurityException("Permission " + bp.name 3730 + " is not a changeable permission type"); 3731 } 3732 } 3733 3734 @Override 3735 public void grantRuntimePermission(String packageName, String name, final int userId) { 3736 if (!sUserManager.exists(userId)) { 3737 Log.e(TAG, "No such user:" + userId); 3738 return; 3739 } 3740 3741 mContext.enforceCallingOrSelfPermission( 3742 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3743 "grantRuntimePermission"); 3744 3745 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3746 "grantRuntimePermission"); 3747 3748 final int uid; 3749 final SettingBase sb; 3750 3751 synchronized (mPackages) { 3752 final PackageParser.Package pkg = mPackages.get(packageName); 3753 if (pkg == null) { 3754 throw new IllegalArgumentException("Unknown package: " + packageName); 3755 } 3756 3757 final BasePermission bp = mSettings.mPermissions.get(name); 3758 if (bp == null) { 3759 throw new IllegalArgumentException("Unknown permission: " + name); 3760 } 3761 3762 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3763 3764 // If a permission review is required for legacy apps we represent 3765 // their permissions as always granted runtime ones since we need 3766 // to keep the review required permission flag per user while an 3767 // install permission's state is shared across all users. 3768 if (Build.PERMISSIONS_REVIEW_REQUIRED 3769 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3770 && bp.isRuntime()) { 3771 return; 3772 } 3773 3774 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3775 sb = (SettingBase) pkg.mExtras; 3776 if (sb == null) { 3777 throw new IllegalArgumentException("Unknown package: " + packageName); 3778 } 3779 3780 final PermissionsState permissionsState = sb.getPermissionsState(); 3781 3782 final int flags = permissionsState.getPermissionFlags(name, userId); 3783 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3784 throw new SecurityException("Cannot grant system fixed permission " 3785 + name + " for package " + packageName); 3786 } 3787 3788 if (bp.isDevelopment()) { 3789 // Development permissions must be handled specially, since they are not 3790 // normal runtime permissions. For now they apply to all users. 3791 if (permissionsState.grantInstallPermission(bp) != 3792 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3793 scheduleWriteSettingsLocked(); 3794 } 3795 return; 3796 } 3797 3798 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3799 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3800 return; 3801 } 3802 3803 final int result = permissionsState.grantRuntimePermission(bp, userId); 3804 switch (result) { 3805 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3806 return; 3807 } 3808 3809 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3810 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3811 mHandler.post(new Runnable() { 3812 @Override 3813 public void run() { 3814 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3815 } 3816 }); 3817 } 3818 break; 3819 } 3820 3821 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3822 3823 // Not critical if that is lost - app has to request again. 3824 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3825 } 3826 3827 // Only need to do this if user is initialized. Otherwise it's a new user 3828 // and there are no processes running as the user yet and there's no need 3829 // to make an expensive call to remount processes for the changed permissions. 3830 if (READ_EXTERNAL_STORAGE.equals(name) 3831 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3832 final long token = Binder.clearCallingIdentity(); 3833 try { 3834 if (sUserManager.isInitialized(userId)) { 3835 MountServiceInternal mountServiceInternal = LocalServices.getService( 3836 MountServiceInternal.class); 3837 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3838 } 3839 } finally { 3840 Binder.restoreCallingIdentity(token); 3841 } 3842 } 3843 } 3844 3845 @Override 3846 public void revokeRuntimePermission(String packageName, String name, int userId) { 3847 if (!sUserManager.exists(userId)) { 3848 Log.e(TAG, "No such user:" + userId); 3849 return; 3850 } 3851 3852 mContext.enforceCallingOrSelfPermission( 3853 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3854 "revokeRuntimePermission"); 3855 3856 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3857 "revokeRuntimePermission"); 3858 3859 final int appId; 3860 3861 synchronized (mPackages) { 3862 final PackageParser.Package pkg = mPackages.get(packageName); 3863 if (pkg == null) { 3864 throw new IllegalArgumentException("Unknown package: " + packageName); 3865 } 3866 3867 final BasePermission bp = mSettings.mPermissions.get(name); 3868 if (bp == null) { 3869 throw new IllegalArgumentException("Unknown permission: " + name); 3870 } 3871 3872 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3873 3874 // If a permission review is required for legacy apps we represent 3875 // their permissions as always granted runtime ones since we need 3876 // to keep the review required permission flag per user while an 3877 // install permission's state is shared across all users. 3878 if (Build.PERMISSIONS_REVIEW_REQUIRED 3879 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3880 && bp.isRuntime()) { 3881 return; 3882 } 3883 3884 SettingBase sb = (SettingBase) pkg.mExtras; 3885 if (sb == null) { 3886 throw new IllegalArgumentException("Unknown package: " + packageName); 3887 } 3888 3889 final PermissionsState permissionsState = sb.getPermissionsState(); 3890 3891 final int flags = permissionsState.getPermissionFlags(name, userId); 3892 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3893 throw new SecurityException("Cannot revoke system fixed permission " 3894 + name + " for package " + packageName); 3895 } 3896 3897 if (bp.isDevelopment()) { 3898 // Development permissions must be handled specially, since they are not 3899 // normal runtime permissions. For now they apply to all users. 3900 if (permissionsState.revokeInstallPermission(bp) != 3901 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3902 scheduleWriteSettingsLocked(); 3903 } 3904 return; 3905 } 3906 3907 if (permissionsState.revokeRuntimePermission(bp, userId) == 3908 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3909 return; 3910 } 3911 3912 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3913 3914 // Critical, after this call app should never have the permission. 3915 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3916 3917 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3918 } 3919 3920 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3921 } 3922 3923 @Override 3924 public void resetRuntimePermissions() { 3925 mContext.enforceCallingOrSelfPermission( 3926 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3927 "revokeRuntimePermission"); 3928 3929 int callingUid = Binder.getCallingUid(); 3930 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3931 mContext.enforceCallingOrSelfPermission( 3932 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3933 "resetRuntimePermissions"); 3934 } 3935 3936 synchronized (mPackages) { 3937 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3938 for (int userId : UserManagerService.getInstance().getUserIds()) { 3939 final int packageCount = mPackages.size(); 3940 for (int i = 0; i < packageCount; i++) { 3941 PackageParser.Package pkg = mPackages.valueAt(i); 3942 if (!(pkg.mExtras instanceof PackageSetting)) { 3943 continue; 3944 } 3945 PackageSetting ps = (PackageSetting) pkg.mExtras; 3946 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3947 } 3948 } 3949 } 3950 } 3951 3952 @Override 3953 public int getPermissionFlags(String name, String packageName, int userId) { 3954 if (!sUserManager.exists(userId)) { 3955 return 0; 3956 } 3957 3958 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3959 3960 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3961 "getPermissionFlags"); 3962 3963 synchronized (mPackages) { 3964 final PackageParser.Package pkg = mPackages.get(packageName); 3965 if (pkg == null) { 3966 throw new IllegalArgumentException("Unknown package: " + packageName); 3967 } 3968 3969 final BasePermission bp = mSettings.mPermissions.get(name); 3970 if (bp == null) { 3971 throw new IllegalArgumentException("Unknown permission: " + name); 3972 } 3973 3974 SettingBase sb = (SettingBase) pkg.mExtras; 3975 if (sb == null) { 3976 throw new IllegalArgumentException("Unknown package: " + packageName); 3977 } 3978 3979 PermissionsState permissionsState = sb.getPermissionsState(); 3980 return permissionsState.getPermissionFlags(name, userId); 3981 } 3982 } 3983 3984 @Override 3985 public void updatePermissionFlags(String name, String packageName, int flagMask, 3986 int flagValues, int userId) { 3987 if (!sUserManager.exists(userId)) { 3988 return; 3989 } 3990 3991 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3992 3993 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3994 "updatePermissionFlags"); 3995 3996 // Only the system can change these flags and nothing else. 3997 if (getCallingUid() != Process.SYSTEM_UID) { 3998 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3999 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4000 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4001 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4002 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4003 } 4004 4005 synchronized (mPackages) { 4006 final PackageParser.Package pkg = mPackages.get(packageName); 4007 if (pkg == null) { 4008 throw new IllegalArgumentException("Unknown package: " + packageName); 4009 } 4010 4011 final BasePermission bp = mSettings.mPermissions.get(name); 4012 if (bp == null) { 4013 throw new IllegalArgumentException("Unknown permission: " + name); 4014 } 4015 4016 SettingBase sb = (SettingBase) pkg.mExtras; 4017 if (sb == null) { 4018 throw new IllegalArgumentException("Unknown package: " + packageName); 4019 } 4020 4021 PermissionsState permissionsState = sb.getPermissionsState(); 4022 4023 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4024 4025 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4026 // Install and runtime permissions are stored in different places, 4027 // so figure out what permission changed and persist the change. 4028 if (permissionsState.getInstallPermissionState(name) != null) { 4029 scheduleWriteSettingsLocked(); 4030 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4031 || hadState) { 4032 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4033 } 4034 } 4035 } 4036 } 4037 4038 /** 4039 * Update the permission flags for all packages and runtime permissions of a user in order 4040 * to allow device or profile owner to remove POLICY_FIXED. 4041 */ 4042 @Override 4043 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4044 if (!sUserManager.exists(userId)) { 4045 return; 4046 } 4047 4048 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4049 4050 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4051 "updatePermissionFlagsForAllApps"); 4052 4053 // Only the system can change system fixed flags. 4054 if (getCallingUid() != Process.SYSTEM_UID) { 4055 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4056 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4057 } 4058 4059 synchronized (mPackages) { 4060 boolean changed = false; 4061 final int packageCount = mPackages.size(); 4062 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4063 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4064 SettingBase sb = (SettingBase) pkg.mExtras; 4065 if (sb == null) { 4066 continue; 4067 } 4068 PermissionsState permissionsState = sb.getPermissionsState(); 4069 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4070 userId, flagMask, flagValues); 4071 } 4072 if (changed) { 4073 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4074 } 4075 } 4076 } 4077 4078 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4079 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4080 != PackageManager.PERMISSION_GRANTED 4081 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4082 != PackageManager.PERMISSION_GRANTED) { 4083 throw new SecurityException(message + " requires " 4084 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4085 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4086 } 4087 } 4088 4089 @Override 4090 public boolean shouldShowRequestPermissionRationale(String permissionName, 4091 String packageName, int userId) { 4092 if (UserHandle.getCallingUserId() != userId) { 4093 mContext.enforceCallingPermission( 4094 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4095 "canShowRequestPermissionRationale for user " + userId); 4096 } 4097 4098 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4099 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4100 return false; 4101 } 4102 4103 if (checkPermission(permissionName, packageName, userId) 4104 == PackageManager.PERMISSION_GRANTED) { 4105 return false; 4106 } 4107 4108 final int flags; 4109 4110 final long identity = Binder.clearCallingIdentity(); 4111 try { 4112 flags = getPermissionFlags(permissionName, 4113 packageName, userId); 4114 } finally { 4115 Binder.restoreCallingIdentity(identity); 4116 } 4117 4118 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4119 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4120 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4121 4122 if ((flags & fixedFlags) != 0) { 4123 return false; 4124 } 4125 4126 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4127 } 4128 4129 @Override 4130 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4131 mContext.enforceCallingOrSelfPermission( 4132 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4133 "addOnPermissionsChangeListener"); 4134 4135 synchronized (mPackages) { 4136 mOnPermissionChangeListeners.addListenerLocked(listener); 4137 } 4138 } 4139 4140 @Override 4141 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4142 synchronized (mPackages) { 4143 mOnPermissionChangeListeners.removeListenerLocked(listener); 4144 } 4145 } 4146 4147 @Override 4148 public boolean isProtectedBroadcast(String actionName) { 4149 synchronized (mPackages) { 4150 if (mProtectedBroadcasts.contains(actionName)) { 4151 return true; 4152 } else if (actionName != null) { 4153 // TODO: remove these terrible hacks 4154 if (actionName.startsWith("android.net.netmon.lingerExpired") 4155 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) { 4156 return true; 4157 } 4158 } 4159 } 4160 return false; 4161 } 4162 4163 @Override 4164 public int checkSignatures(String pkg1, String pkg2) { 4165 synchronized (mPackages) { 4166 final PackageParser.Package p1 = mPackages.get(pkg1); 4167 final PackageParser.Package p2 = mPackages.get(pkg2); 4168 if (p1 == null || p1.mExtras == null 4169 || p2 == null || p2.mExtras == null) { 4170 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4171 } 4172 return compareSignatures(p1.mSignatures, p2.mSignatures); 4173 } 4174 } 4175 4176 @Override 4177 public int checkUidSignatures(int uid1, int uid2) { 4178 // Map to base uids. 4179 uid1 = UserHandle.getAppId(uid1); 4180 uid2 = UserHandle.getAppId(uid2); 4181 // reader 4182 synchronized (mPackages) { 4183 Signature[] s1; 4184 Signature[] s2; 4185 Object obj = mSettings.getUserIdLPr(uid1); 4186 if (obj != null) { 4187 if (obj instanceof SharedUserSetting) { 4188 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4189 } else if (obj instanceof PackageSetting) { 4190 s1 = ((PackageSetting)obj).signatures.mSignatures; 4191 } else { 4192 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4193 } 4194 } else { 4195 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4196 } 4197 obj = mSettings.getUserIdLPr(uid2); 4198 if (obj != null) { 4199 if (obj instanceof SharedUserSetting) { 4200 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4201 } else if (obj instanceof PackageSetting) { 4202 s2 = ((PackageSetting)obj).signatures.mSignatures; 4203 } else { 4204 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4205 } 4206 } else { 4207 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4208 } 4209 return compareSignatures(s1, s2); 4210 } 4211 } 4212 4213 private void killUid(int appId, int userId, String reason) { 4214 final long identity = Binder.clearCallingIdentity(); 4215 try { 4216 IActivityManager am = ActivityManagerNative.getDefault(); 4217 if (am != null) { 4218 try { 4219 am.killUid(appId, userId, reason); 4220 } catch (RemoteException e) { 4221 /* ignore - same process */ 4222 } 4223 } 4224 } finally { 4225 Binder.restoreCallingIdentity(identity); 4226 } 4227 } 4228 4229 /** 4230 * Compares two sets of signatures. Returns: 4231 * <br /> 4232 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4233 * <br /> 4234 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4235 * <br /> 4236 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4237 * <br /> 4238 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4239 * <br /> 4240 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4241 */ 4242 static int compareSignatures(Signature[] s1, Signature[] s2) { 4243 if (s1 == null) { 4244 return s2 == null 4245 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4246 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4247 } 4248 4249 if (s2 == null) { 4250 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4251 } 4252 4253 if (s1.length != s2.length) { 4254 return PackageManager.SIGNATURE_NO_MATCH; 4255 } 4256 4257 // Since both signature sets are of size 1, we can compare without HashSets. 4258 if (s1.length == 1) { 4259 return s1[0].equals(s2[0]) ? 4260 PackageManager.SIGNATURE_MATCH : 4261 PackageManager.SIGNATURE_NO_MATCH; 4262 } 4263 4264 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4265 for (Signature sig : s1) { 4266 set1.add(sig); 4267 } 4268 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4269 for (Signature sig : s2) { 4270 set2.add(sig); 4271 } 4272 // Make sure s2 contains all signatures in s1. 4273 if (set1.equals(set2)) { 4274 return PackageManager.SIGNATURE_MATCH; 4275 } 4276 return PackageManager.SIGNATURE_NO_MATCH; 4277 } 4278 4279 /** 4280 * If the database version for this type of package (internal storage or 4281 * external storage) is less than the version where package signatures 4282 * were updated, return true. 4283 */ 4284 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4285 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4286 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4287 } 4288 4289 /** 4290 * Used for backward compatibility to make sure any packages with 4291 * certificate chains get upgraded to the new style. {@code existingSigs} 4292 * will be in the old format (since they were stored on disk from before the 4293 * system upgrade) and {@code scannedSigs} will be in the newer format. 4294 */ 4295 private int compareSignaturesCompat(PackageSignatures existingSigs, 4296 PackageParser.Package scannedPkg) { 4297 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4298 return PackageManager.SIGNATURE_NO_MATCH; 4299 } 4300 4301 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4302 for (Signature sig : existingSigs.mSignatures) { 4303 existingSet.add(sig); 4304 } 4305 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4306 for (Signature sig : scannedPkg.mSignatures) { 4307 try { 4308 Signature[] chainSignatures = sig.getChainSignatures(); 4309 for (Signature chainSig : chainSignatures) { 4310 scannedCompatSet.add(chainSig); 4311 } 4312 } catch (CertificateEncodingException e) { 4313 scannedCompatSet.add(sig); 4314 } 4315 } 4316 /* 4317 * Make sure the expanded scanned set contains all signatures in the 4318 * existing one. 4319 */ 4320 if (scannedCompatSet.equals(existingSet)) { 4321 // Migrate the old signatures to the new scheme. 4322 existingSigs.assignSignatures(scannedPkg.mSignatures); 4323 // The new KeySets will be re-added later in the scanning process. 4324 synchronized (mPackages) { 4325 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4326 } 4327 return PackageManager.SIGNATURE_MATCH; 4328 } 4329 return PackageManager.SIGNATURE_NO_MATCH; 4330 } 4331 4332 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4333 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4334 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4335 } 4336 4337 private int compareSignaturesRecover(PackageSignatures existingSigs, 4338 PackageParser.Package scannedPkg) { 4339 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4340 return PackageManager.SIGNATURE_NO_MATCH; 4341 } 4342 4343 String msg = null; 4344 try { 4345 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4346 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4347 + scannedPkg.packageName); 4348 return PackageManager.SIGNATURE_MATCH; 4349 } 4350 } catch (CertificateException e) { 4351 msg = e.getMessage(); 4352 } 4353 4354 logCriticalInfo(Log.INFO, 4355 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4356 return PackageManager.SIGNATURE_NO_MATCH; 4357 } 4358 4359 @Override 4360 public String[] getPackagesForUid(int uid) { 4361 uid = UserHandle.getAppId(uid); 4362 // reader 4363 synchronized (mPackages) { 4364 Object obj = mSettings.getUserIdLPr(uid); 4365 if (obj instanceof SharedUserSetting) { 4366 final SharedUserSetting sus = (SharedUserSetting) obj; 4367 final int N = sus.packages.size(); 4368 final String[] res = new String[N]; 4369 final Iterator<PackageSetting> it = sus.packages.iterator(); 4370 int i = 0; 4371 while (it.hasNext()) { 4372 res[i++] = it.next().name; 4373 } 4374 return res; 4375 } else if (obj instanceof PackageSetting) { 4376 final PackageSetting ps = (PackageSetting) obj; 4377 return new String[] { ps.name }; 4378 } 4379 } 4380 return null; 4381 } 4382 4383 @Override 4384 public String getNameForUid(int uid) { 4385 // reader 4386 synchronized (mPackages) { 4387 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4388 if (obj instanceof SharedUserSetting) { 4389 final SharedUserSetting sus = (SharedUserSetting) obj; 4390 return sus.name + ":" + sus.userId; 4391 } else if (obj instanceof PackageSetting) { 4392 final PackageSetting ps = (PackageSetting) obj; 4393 return ps.name; 4394 } 4395 } 4396 return null; 4397 } 4398 4399 @Override 4400 public int getUidForSharedUser(String sharedUserName) { 4401 if(sharedUserName == null) { 4402 return -1; 4403 } 4404 // reader 4405 synchronized (mPackages) { 4406 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4407 if (suid == null) { 4408 return -1; 4409 } 4410 return suid.userId; 4411 } 4412 } 4413 4414 @Override 4415 public int getFlagsForUid(int uid) { 4416 synchronized (mPackages) { 4417 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4418 if (obj instanceof SharedUserSetting) { 4419 final SharedUserSetting sus = (SharedUserSetting) obj; 4420 return sus.pkgFlags; 4421 } else if (obj instanceof PackageSetting) { 4422 final PackageSetting ps = (PackageSetting) obj; 4423 return ps.pkgFlags; 4424 } 4425 } 4426 return 0; 4427 } 4428 4429 @Override 4430 public int getPrivateFlagsForUid(int uid) { 4431 synchronized (mPackages) { 4432 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4433 if (obj instanceof SharedUserSetting) { 4434 final SharedUserSetting sus = (SharedUserSetting) obj; 4435 return sus.pkgPrivateFlags; 4436 } else if (obj instanceof PackageSetting) { 4437 final PackageSetting ps = (PackageSetting) obj; 4438 return ps.pkgPrivateFlags; 4439 } 4440 } 4441 return 0; 4442 } 4443 4444 @Override 4445 public boolean isUidPrivileged(int uid) { 4446 uid = UserHandle.getAppId(uid); 4447 // reader 4448 synchronized (mPackages) { 4449 Object obj = mSettings.getUserIdLPr(uid); 4450 if (obj instanceof SharedUserSetting) { 4451 final SharedUserSetting sus = (SharedUserSetting) obj; 4452 final Iterator<PackageSetting> it = sus.packages.iterator(); 4453 while (it.hasNext()) { 4454 if (it.next().isPrivileged()) { 4455 return true; 4456 } 4457 } 4458 } else if (obj instanceof PackageSetting) { 4459 final PackageSetting ps = (PackageSetting) obj; 4460 return ps.isPrivileged(); 4461 } 4462 } 4463 return false; 4464 } 4465 4466 @Override 4467 public String[] getAppOpPermissionPackages(String permissionName) { 4468 synchronized (mPackages) { 4469 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4470 if (pkgs == null) { 4471 return null; 4472 } 4473 return pkgs.toArray(new String[pkgs.size()]); 4474 } 4475 } 4476 4477 @Override 4478 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4479 int flags, int userId) { 4480 if (!sUserManager.exists(userId)) return null; 4481 flags = updateFlagsForResolve(flags, userId, intent); 4482 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4483 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4484 final ResolveInfo bestChoice = 4485 chooseBestActivity(intent, resolvedType, flags, query, userId); 4486 4487 if (isEphemeralAllowed(intent, query, userId)) { 4488 final EphemeralResolveInfo ai = 4489 getEphemeralResolveInfo(intent, resolvedType, userId); 4490 if (ai != null) { 4491 if (DEBUG_EPHEMERAL) { 4492 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4493 } 4494 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4495 bestChoice.ephemeralResolveInfo = ai; 4496 } 4497 } 4498 return bestChoice; 4499 } 4500 4501 @Override 4502 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4503 IntentFilter filter, int match, ComponentName activity) { 4504 final int userId = UserHandle.getCallingUserId(); 4505 if (DEBUG_PREFERRED) { 4506 Log.v(TAG, "setLastChosenActivity intent=" + intent 4507 + " resolvedType=" + resolvedType 4508 + " flags=" + flags 4509 + " filter=" + filter 4510 + " match=" + match 4511 + " activity=" + activity); 4512 filter.dump(new PrintStreamPrinter(System.out), " "); 4513 } 4514 intent.setComponent(null); 4515 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4516 // Find any earlier preferred or last chosen entries and nuke them 4517 findPreferredActivity(intent, resolvedType, 4518 flags, query, 0, false, true, false, userId); 4519 // Add the new activity as the last chosen for this filter 4520 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4521 "Setting last chosen"); 4522 } 4523 4524 @Override 4525 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4526 final int userId = UserHandle.getCallingUserId(); 4527 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4528 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4529 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4530 false, false, false, userId); 4531 } 4532 4533 4534 private boolean isEphemeralAllowed( 4535 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4536 // Short circuit and return early if possible. 4537 if (DISABLE_EPHEMERAL_APPS) { 4538 return false; 4539 } 4540 final int callingUser = UserHandle.getCallingUserId(); 4541 if (callingUser != UserHandle.USER_SYSTEM) { 4542 return false; 4543 } 4544 if (mEphemeralResolverConnection == null) { 4545 return false; 4546 } 4547 if (intent.getComponent() != null) { 4548 return false; 4549 } 4550 if (intent.getPackage() != null) { 4551 return false; 4552 } 4553 final boolean isWebUri = hasWebURI(intent); 4554 if (!isWebUri) { 4555 return false; 4556 } 4557 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4558 synchronized (mPackages) { 4559 final int count = resolvedActivites.size(); 4560 for (int n = 0; n < count; n++) { 4561 ResolveInfo info = resolvedActivites.get(n); 4562 String packageName = info.activityInfo.packageName; 4563 PackageSetting ps = mSettings.mPackages.get(packageName); 4564 if (ps != null) { 4565 // Try to get the status from User settings first 4566 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4567 int status = (int) (packedStatus >> 32); 4568 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4569 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4570 if (DEBUG_EPHEMERAL) { 4571 Slog.v(TAG, "DENY ephemeral apps;" 4572 + " pkg: " + packageName + ", status: " + status); 4573 } 4574 return false; 4575 } 4576 } 4577 } 4578 } 4579 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4580 return true; 4581 } 4582 4583 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4584 int userId) { 4585 MessageDigest digest = null; 4586 try { 4587 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4588 } catch (NoSuchAlgorithmException e) { 4589 // If we can't create a digest, ignore ephemeral apps. 4590 return null; 4591 } 4592 4593 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4594 final byte[] digestBytes = digest.digest(hostBytes); 4595 int shaPrefix = 4596 digestBytes[0] << 24 4597 | digestBytes[1] << 16 4598 | digestBytes[2] << 8 4599 | digestBytes[3] << 0; 4600 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4601 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4602 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4603 // No hash prefix match; there are no ephemeral apps for this domain. 4604 return null; 4605 } 4606 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4607 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4608 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4609 continue; 4610 } 4611 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4612 // No filters; this should never happen. 4613 if (filters.isEmpty()) { 4614 continue; 4615 } 4616 // We have a domain match; resolve the filters to see if anything matches. 4617 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4618 for (int j = filters.size() - 1; j >= 0; --j) { 4619 final EphemeralResolveIntentInfo intentInfo = 4620 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4621 ephemeralResolver.addFilter(intentInfo); 4622 } 4623 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4624 intent, resolvedType, false /*defaultOnly*/, userId); 4625 if (!matchedResolveInfoList.isEmpty()) { 4626 return matchedResolveInfoList.get(0); 4627 } 4628 } 4629 // Hash or filter mis-match; no ephemeral apps for this domain. 4630 return null; 4631 } 4632 4633 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4634 int flags, List<ResolveInfo> query, int userId) { 4635 if (query != null) { 4636 final int N = query.size(); 4637 if (N == 1) { 4638 return query.get(0); 4639 } else if (N > 1) { 4640 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4641 // If there is more than one activity with the same priority, 4642 // then let the user decide between them. 4643 ResolveInfo r0 = query.get(0); 4644 ResolveInfo r1 = query.get(1); 4645 if (DEBUG_INTENT_MATCHING || debug) { 4646 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4647 + r1.activityInfo.name + "=" + r1.priority); 4648 } 4649 // If the first activity has a higher priority, or a different 4650 // default, then it is always desirable to pick it. 4651 if (r0.priority != r1.priority 4652 || r0.preferredOrder != r1.preferredOrder 4653 || r0.isDefault != r1.isDefault) { 4654 return query.get(0); 4655 } 4656 // If we have saved a preference for a preferred activity for 4657 // this Intent, use that. 4658 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4659 flags, query, r0.priority, true, false, debug, userId); 4660 if (ri != null) { 4661 return ri; 4662 } 4663 ri = new ResolveInfo(mResolveInfo); 4664 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4665 ri.activityInfo.applicationInfo = new ApplicationInfo( 4666 ri.activityInfo.applicationInfo); 4667 if (userId != 0) { 4668 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4669 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4670 } 4671 // Make sure that the resolver is displayable in car mode 4672 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4673 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4674 return ri; 4675 } 4676 } 4677 return null; 4678 } 4679 4680 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4681 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4682 final int N = query.size(); 4683 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4684 .get(userId); 4685 // Get the list of persistent preferred activities that handle the intent 4686 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4687 List<PersistentPreferredActivity> pprefs = ppir != null 4688 ? ppir.queryIntent(intent, resolvedType, 4689 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4690 : null; 4691 if (pprefs != null && pprefs.size() > 0) { 4692 final int M = pprefs.size(); 4693 for (int i=0; i<M; i++) { 4694 final PersistentPreferredActivity ppa = pprefs.get(i); 4695 if (DEBUG_PREFERRED || debug) { 4696 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4697 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4698 + "\n component=" + ppa.mComponent); 4699 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4700 } 4701 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4702 flags | MATCH_DISABLED_COMPONENTS, userId); 4703 if (DEBUG_PREFERRED || debug) { 4704 Slog.v(TAG, "Found persistent preferred activity:"); 4705 if (ai != null) { 4706 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4707 } else { 4708 Slog.v(TAG, " null"); 4709 } 4710 } 4711 if (ai == null) { 4712 // This previously registered persistent preferred activity 4713 // component is no longer known. Ignore it and do NOT remove it. 4714 continue; 4715 } 4716 for (int j=0; j<N; j++) { 4717 final ResolveInfo ri = query.get(j); 4718 if (!ri.activityInfo.applicationInfo.packageName 4719 .equals(ai.applicationInfo.packageName)) { 4720 continue; 4721 } 4722 if (!ri.activityInfo.name.equals(ai.name)) { 4723 continue; 4724 } 4725 // Found a persistent preference that can handle the intent. 4726 if (DEBUG_PREFERRED || debug) { 4727 Slog.v(TAG, "Returning persistent preferred activity: " + 4728 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4729 } 4730 return ri; 4731 } 4732 } 4733 } 4734 return null; 4735 } 4736 4737 // TODO: handle preferred activities missing while user has amnesia 4738 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4739 List<ResolveInfo> query, int priority, boolean always, 4740 boolean removeMatches, boolean debug, int userId) { 4741 if (!sUserManager.exists(userId)) return null; 4742 flags = updateFlagsForResolve(flags, userId, intent); 4743 // writer 4744 synchronized (mPackages) { 4745 if (intent.getSelector() != null) { 4746 intent = intent.getSelector(); 4747 } 4748 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4749 4750 // Try to find a matching persistent preferred activity. 4751 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4752 debug, userId); 4753 4754 // If a persistent preferred activity matched, use it. 4755 if (pri != null) { 4756 return pri; 4757 } 4758 4759 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4760 // Get the list of preferred activities that handle the intent 4761 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4762 List<PreferredActivity> prefs = pir != null 4763 ? pir.queryIntent(intent, resolvedType, 4764 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4765 : null; 4766 if (prefs != null && prefs.size() > 0) { 4767 boolean changed = false; 4768 try { 4769 // First figure out how good the original match set is. 4770 // We will only allow preferred activities that came 4771 // from the same match quality. 4772 int match = 0; 4773 4774 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4775 4776 final int N = query.size(); 4777 for (int j=0; j<N; j++) { 4778 final ResolveInfo ri = query.get(j); 4779 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4780 + ": 0x" + Integer.toHexString(match)); 4781 if (ri.match > match) { 4782 match = ri.match; 4783 } 4784 } 4785 4786 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4787 + Integer.toHexString(match)); 4788 4789 match &= IntentFilter.MATCH_CATEGORY_MASK; 4790 final int M = prefs.size(); 4791 for (int i=0; i<M; i++) { 4792 final PreferredActivity pa = prefs.get(i); 4793 if (DEBUG_PREFERRED || debug) { 4794 Slog.v(TAG, "Checking PreferredActivity ds=" 4795 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4796 + "\n component=" + pa.mPref.mComponent); 4797 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4798 } 4799 if (pa.mPref.mMatch != match) { 4800 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4801 + Integer.toHexString(pa.mPref.mMatch)); 4802 continue; 4803 } 4804 // If it's not an "always" type preferred activity and that's what we're 4805 // looking for, skip it. 4806 if (always && !pa.mPref.mAlways) { 4807 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4808 continue; 4809 } 4810 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4811 flags | MATCH_DISABLED_COMPONENTS, userId); 4812 if (DEBUG_PREFERRED || debug) { 4813 Slog.v(TAG, "Found preferred activity:"); 4814 if (ai != null) { 4815 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4816 } else { 4817 Slog.v(TAG, " null"); 4818 } 4819 } 4820 if (ai == null) { 4821 // This previously registered preferred activity 4822 // component is no longer known. Most likely an update 4823 // to the app was installed and in the new version this 4824 // component no longer exists. Clean it up by removing 4825 // it from the preferred activities list, and skip it. 4826 Slog.w(TAG, "Removing dangling preferred activity: " 4827 + pa.mPref.mComponent); 4828 pir.removeFilter(pa); 4829 changed = true; 4830 continue; 4831 } 4832 for (int j=0; j<N; j++) { 4833 final ResolveInfo ri = query.get(j); 4834 if (!ri.activityInfo.applicationInfo.packageName 4835 .equals(ai.applicationInfo.packageName)) { 4836 continue; 4837 } 4838 if (!ri.activityInfo.name.equals(ai.name)) { 4839 continue; 4840 } 4841 4842 if (removeMatches) { 4843 pir.removeFilter(pa); 4844 changed = true; 4845 if (DEBUG_PREFERRED) { 4846 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4847 } 4848 break; 4849 } 4850 4851 // Okay we found a previously set preferred or last chosen app. 4852 // If the result set is different from when this 4853 // was created, we need to clear it and re-ask the 4854 // user their preference, if we're looking for an "always" type entry. 4855 if (always && !pa.mPref.sameSet(query)) { 4856 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4857 + intent + " type " + resolvedType); 4858 if (DEBUG_PREFERRED) { 4859 Slog.v(TAG, "Removing preferred activity since set changed " 4860 + pa.mPref.mComponent); 4861 } 4862 pir.removeFilter(pa); 4863 // Re-add the filter as a "last chosen" entry (!always) 4864 PreferredActivity lastChosen = new PreferredActivity( 4865 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4866 pir.addFilter(lastChosen); 4867 changed = true; 4868 return null; 4869 } 4870 4871 // Yay! Either the set matched or we're looking for the last chosen 4872 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4873 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4874 return ri; 4875 } 4876 } 4877 } finally { 4878 if (changed) { 4879 if (DEBUG_PREFERRED) { 4880 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4881 } 4882 scheduleWritePackageRestrictionsLocked(userId); 4883 } 4884 } 4885 } 4886 } 4887 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4888 return null; 4889 } 4890 4891 /* 4892 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4893 */ 4894 @Override 4895 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4896 int targetUserId) { 4897 mContext.enforceCallingOrSelfPermission( 4898 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4899 List<CrossProfileIntentFilter> matches = 4900 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4901 if (matches != null) { 4902 int size = matches.size(); 4903 for (int i = 0; i < size; i++) { 4904 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4905 } 4906 } 4907 if (hasWebURI(intent)) { 4908 // cross-profile app linking works only towards the parent. 4909 final UserInfo parent = getProfileParent(sourceUserId); 4910 synchronized(mPackages) { 4911 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4912 intent, resolvedType, 0, sourceUserId, parent.id); 4913 return xpDomainInfo != null; 4914 } 4915 } 4916 return false; 4917 } 4918 4919 private UserInfo getProfileParent(int userId) { 4920 final long identity = Binder.clearCallingIdentity(); 4921 try { 4922 return sUserManager.getProfileParent(userId); 4923 } finally { 4924 Binder.restoreCallingIdentity(identity); 4925 } 4926 } 4927 4928 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4929 String resolvedType, int userId) { 4930 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4931 if (resolver != null) { 4932 return resolver.queryIntent(intent, resolvedType, false, userId); 4933 } 4934 return null; 4935 } 4936 4937 @Override 4938 public List<ResolveInfo> queryIntentActivities(Intent intent, 4939 String resolvedType, int flags, int userId) { 4940 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4941 flags = updateFlagsForResolve(flags, userId, intent); 4942 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4943 ComponentName comp = intent.getComponent(); 4944 if (comp == null) { 4945 if (intent.getSelector() != null) { 4946 intent = intent.getSelector(); 4947 comp = intent.getComponent(); 4948 } 4949 } 4950 4951 if (comp != null) { 4952 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4953 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4954 if (ai != null) { 4955 final ResolveInfo ri = new ResolveInfo(); 4956 ri.activityInfo = ai; 4957 list.add(ri); 4958 } 4959 return list; 4960 } 4961 4962 // reader 4963 synchronized (mPackages) { 4964 final String pkgName = intent.getPackage(); 4965 if (pkgName == null) { 4966 List<CrossProfileIntentFilter> matchingFilters = 4967 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4968 // Check for results that need to skip the current profile. 4969 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4970 resolvedType, flags, userId); 4971 if (xpResolveInfo != null) { 4972 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4973 result.add(xpResolveInfo); 4974 return filterIfNotSystemUser(result, userId); 4975 } 4976 4977 // Check for results in the current profile. 4978 List<ResolveInfo> result = mActivities.queryIntent( 4979 intent, resolvedType, flags, userId); 4980 result = filterIfNotSystemUser(result, userId); 4981 4982 // Check for cross profile results. 4983 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 4984 xpResolveInfo = queryCrossProfileIntents( 4985 matchingFilters, intent, resolvedType, flags, userId, 4986 hasNonNegativePriorityResult); 4987 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4988 boolean isVisibleToUser = filterIfNotSystemUser( 4989 Collections.singletonList(xpResolveInfo), userId).size() > 0; 4990 if (isVisibleToUser) { 4991 result.add(xpResolveInfo); 4992 Collections.sort(result, mResolvePrioritySorter); 4993 } 4994 } 4995 if (hasWebURI(intent)) { 4996 CrossProfileDomainInfo xpDomainInfo = null; 4997 final UserInfo parent = getProfileParent(userId); 4998 if (parent != null) { 4999 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5000 flags, userId, parent.id); 5001 } 5002 if (xpDomainInfo != null) { 5003 if (xpResolveInfo != null) { 5004 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5005 // in the result. 5006 result.remove(xpResolveInfo); 5007 } 5008 if (result.size() == 0) { 5009 result.add(xpDomainInfo.resolveInfo); 5010 return result; 5011 } 5012 } else if (result.size() <= 1) { 5013 return result; 5014 } 5015 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5016 xpDomainInfo, userId); 5017 Collections.sort(result, mResolvePrioritySorter); 5018 } 5019 return result; 5020 } 5021 final PackageParser.Package pkg = mPackages.get(pkgName); 5022 if (pkg != null) { 5023 return filterIfNotSystemUser( 5024 mActivities.queryIntentForPackage( 5025 intent, resolvedType, flags, pkg.activities, userId), 5026 userId); 5027 } 5028 return new ArrayList<ResolveInfo>(); 5029 } 5030 } 5031 5032 private static class CrossProfileDomainInfo { 5033 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5034 ResolveInfo resolveInfo; 5035 /* Best domain verification status of the activities found in the other profile */ 5036 int bestDomainVerificationStatus; 5037 } 5038 5039 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5040 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5041 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5042 sourceUserId)) { 5043 return null; 5044 } 5045 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5046 resolvedType, flags, parentUserId); 5047 5048 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5049 return null; 5050 } 5051 CrossProfileDomainInfo result = null; 5052 int size = resultTargetUser.size(); 5053 for (int i = 0; i < size; i++) { 5054 ResolveInfo riTargetUser = resultTargetUser.get(i); 5055 // Intent filter verification is only for filters that specify a host. So don't return 5056 // those that handle all web uris. 5057 if (riTargetUser.handleAllWebDataURI) { 5058 continue; 5059 } 5060 String packageName = riTargetUser.activityInfo.packageName; 5061 PackageSetting ps = mSettings.mPackages.get(packageName); 5062 if (ps == null) { 5063 continue; 5064 } 5065 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5066 int status = (int)(verificationState >> 32); 5067 if (result == null) { 5068 result = new CrossProfileDomainInfo(); 5069 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5070 sourceUserId, parentUserId); 5071 result.bestDomainVerificationStatus = status; 5072 } else { 5073 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5074 result.bestDomainVerificationStatus); 5075 } 5076 } 5077 // Don't consider matches with status NEVER across profiles. 5078 if (result != null && result.bestDomainVerificationStatus 5079 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5080 return null; 5081 } 5082 return result; 5083 } 5084 5085 /** 5086 * Verification statuses are ordered from the worse to the best, except for 5087 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5088 */ 5089 private int bestDomainVerificationStatus(int status1, int status2) { 5090 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5091 return status2; 5092 } 5093 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5094 return status1; 5095 } 5096 return (int) MathUtils.max(status1, status2); 5097 } 5098 5099 private boolean isUserEnabled(int userId) { 5100 long callingId = Binder.clearCallingIdentity(); 5101 try { 5102 UserInfo userInfo = sUserManager.getUserInfo(userId); 5103 return userInfo != null && userInfo.isEnabled(); 5104 } finally { 5105 Binder.restoreCallingIdentity(callingId); 5106 } 5107 } 5108 5109 /** 5110 * Filter out activities with systemUserOnly flag set, when current user is not System. 5111 * 5112 * @return filtered list 5113 */ 5114 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5115 if (userId == UserHandle.USER_SYSTEM) { 5116 return resolveInfos; 5117 } 5118 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5119 ResolveInfo info = resolveInfos.get(i); 5120 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5121 resolveInfos.remove(i); 5122 } 5123 } 5124 return resolveInfos; 5125 } 5126 5127 /** 5128 * @param resolveInfos list of resolve infos in descending priority order 5129 * @return if the list contains a resolve info with non-negative priority 5130 */ 5131 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5132 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5133 } 5134 5135 private static boolean hasWebURI(Intent intent) { 5136 if (intent.getData() == null) { 5137 return false; 5138 } 5139 final String scheme = intent.getScheme(); 5140 if (TextUtils.isEmpty(scheme)) { 5141 return false; 5142 } 5143 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5144 } 5145 5146 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5147 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5148 int userId) { 5149 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5150 5151 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5152 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5153 candidates.size()); 5154 } 5155 5156 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5157 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5158 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5159 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5160 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5161 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5162 5163 synchronized (mPackages) { 5164 final int count = candidates.size(); 5165 // First, try to use linked apps. Partition the candidates into four lists: 5166 // one for the final results, one for the "do not use ever", one for "undefined status" 5167 // and finally one for "browser app type". 5168 for (int n=0; n<count; n++) { 5169 ResolveInfo info = candidates.get(n); 5170 String packageName = info.activityInfo.packageName; 5171 PackageSetting ps = mSettings.mPackages.get(packageName); 5172 if (ps != null) { 5173 // Add to the special match all list (Browser use case) 5174 if (info.handleAllWebDataURI) { 5175 matchAllList.add(info); 5176 continue; 5177 } 5178 // Try to get the status from User settings first 5179 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5180 int status = (int)(packedStatus >> 32); 5181 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5182 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5183 if (DEBUG_DOMAIN_VERIFICATION) { 5184 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5185 + " : linkgen=" + linkGeneration); 5186 } 5187 // Use link-enabled generation as preferredOrder, i.e. 5188 // prefer newly-enabled over earlier-enabled. 5189 info.preferredOrder = linkGeneration; 5190 alwaysList.add(info); 5191 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5192 if (DEBUG_DOMAIN_VERIFICATION) { 5193 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5194 } 5195 neverList.add(info); 5196 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5197 if (DEBUG_DOMAIN_VERIFICATION) { 5198 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5199 } 5200 alwaysAskList.add(info); 5201 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5202 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5203 if (DEBUG_DOMAIN_VERIFICATION) { 5204 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5205 } 5206 undefinedList.add(info); 5207 } 5208 } 5209 } 5210 5211 // We'll want to include browser possibilities in a few cases 5212 boolean includeBrowser = false; 5213 5214 // First try to add the "always" resolution(s) for the current user, if any 5215 if (alwaysList.size() > 0) { 5216 result.addAll(alwaysList); 5217 } else { 5218 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5219 result.addAll(undefinedList); 5220 // Maybe add one for the other profile. 5221 if (xpDomainInfo != null && ( 5222 xpDomainInfo.bestDomainVerificationStatus 5223 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5224 result.add(xpDomainInfo.resolveInfo); 5225 } 5226 includeBrowser = true; 5227 } 5228 5229 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5230 // If there were 'always' entries their preferred order has been set, so we also 5231 // back that off to make the alternatives equivalent 5232 if (alwaysAskList.size() > 0) { 5233 for (ResolveInfo i : result) { 5234 i.preferredOrder = 0; 5235 } 5236 result.addAll(alwaysAskList); 5237 includeBrowser = true; 5238 } 5239 5240 if (includeBrowser) { 5241 // Also add browsers (all of them or only the default one) 5242 if (DEBUG_DOMAIN_VERIFICATION) { 5243 Slog.v(TAG, " ...including browsers in candidate set"); 5244 } 5245 if ((matchFlags & MATCH_ALL) != 0) { 5246 result.addAll(matchAllList); 5247 } else { 5248 // Browser/generic handling case. If there's a default browser, go straight 5249 // to that (but only if there is no other higher-priority match). 5250 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5251 int maxMatchPrio = 0; 5252 ResolveInfo defaultBrowserMatch = null; 5253 final int numCandidates = matchAllList.size(); 5254 for (int n = 0; n < numCandidates; n++) { 5255 ResolveInfo info = matchAllList.get(n); 5256 // track the highest overall match priority... 5257 if (info.priority > maxMatchPrio) { 5258 maxMatchPrio = info.priority; 5259 } 5260 // ...and the highest-priority default browser match 5261 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5262 if (defaultBrowserMatch == null 5263 || (defaultBrowserMatch.priority < info.priority)) { 5264 if (debug) { 5265 Slog.v(TAG, "Considering default browser match " + info); 5266 } 5267 defaultBrowserMatch = info; 5268 } 5269 } 5270 } 5271 if (defaultBrowserMatch != null 5272 && defaultBrowserMatch.priority >= maxMatchPrio 5273 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5274 { 5275 if (debug) { 5276 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5277 } 5278 result.add(defaultBrowserMatch); 5279 } else { 5280 result.addAll(matchAllList); 5281 } 5282 } 5283 5284 // If there is nothing selected, add all candidates and remove the ones that the user 5285 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5286 if (result.size() == 0) { 5287 result.addAll(candidates); 5288 result.removeAll(neverList); 5289 } 5290 } 5291 } 5292 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5293 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5294 result.size()); 5295 for (ResolveInfo info : result) { 5296 Slog.v(TAG, " + " + info.activityInfo); 5297 } 5298 } 5299 return result; 5300 } 5301 5302 // Returns a packed value as a long: 5303 // 5304 // high 'int'-sized word: link status: undefined/ask/never/always. 5305 // low 'int'-sized word: relative priority among 'always' results. 5306 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5307 long result = ps.getDomainVerificationStatusForUser(userId); 5308 // if none available, get the master status 5309 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5310 if (ps.getIntentFilterVerificationInfo() != null) { 5311 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5312 } 5313 } 5314 return result; 5315 } 5316 5317 private ResolveInfo querySkipCurrentProfileIntents( 5318 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5319 int flags, int sourceUserId) { 5320 if (matchingFilters != null) { 5321 int size = matchingFilters.size(); 5322 for (int i = 0; i < size; i ++) { 5323 CrossProfileIntentFilter filter = matchingFilters.get(i); 5324 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5325 // Checking if there are activities in the target user that can handle the 5326 // intent. 5327 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5328 resolvedType, flags, sourceUserId); 5329 if (resolveInfo != null) { 5330 return resolveInfo; 5331 } 5332 } 5333 } 5334 } 5335 return null; 5336 } 5337 5338 // Return matching ResolveInfo in target user if any. 5339 private ResolveInfo queryCrossProfileIntents( 5340 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5341 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5342 if (matchingFilters != null) { 5343 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5344 // match the same intent. For performance reasons, it is better not to 5345 // run queryIntent twice for the same userId 5346 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5347 int size = matchingFilters.size(); 5348 for (int i = 0; i < size; i++) { 5349 CrossProfileIntentFilter filter = matchingFilters.get(i); 5350 int targetUserId = filter.getTargetUserId(); 5351 boolean skipCurrentProfile = 5352 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5353 boolean skipCurrentProfileIfNoMatchFound = 5354 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5355 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5356 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5357 // Checking if there are activities in the target user that can handle the 5358 // intent. 5359 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5360 resolvedType, flags, sourceUserId); 5361 if (resolveInfo != null) return resolveInfo; 5362 alreadyTriedUserIds.put(targetUserId, true); 5363 } 5364 } 5365 } 5366 return null; 5367 } 5368 5369 /** 5370 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5371 * will forward the intent to the filter's target user. 5372 * Otherwise, returns null. 5373 */ 5374 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5375 String resolvedType, int flags, int sourceUserId) { 5376 int targetUserId = filter.getTargetUserId(); 5377 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5378 resolvedType, flags, targetUserId); 5379 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5380 && isUserEnabled(targetUserId)) { 5381 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5382 } 5383 return null; 5384 } 5385 5386 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5387 int sourceUserId, int targetUserId) { 5388 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5389 long ident = Binder.clearCallingIdentity(); 5390 boolean targetIsProfile; 5391 try { 5392 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5393 } finally { 5394 Binder.restoreCallingIdentity(ident); 5395 } 5396 String className; 5397 if (targetIsProfile) { 5398 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5399 } else { 5400 className = FORWARD_INTENT_TO_PARENT; 5401 } 5402 ComponentName forwardingActivityComponentName = new ComponentName( 5403 mAndroidApplication.packageName, className); 5404 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5405 sourceUserId); 5406 if (!targetIsProfile) { 5407 forwardingActivityInfo.showUserIcon = targetUserId; 5408 forwardingResolveInfo.noResourceId = true; 5409 } 5410 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5411 forwardingResolveInfo.priority = 0; 5412 forwardingResolveInfo.preferredOrder = 0; 5413 forwardingResolveInfo.match = 0; 5414 forwardingResolveInfo.isDefault = true; 5415 forwardingResolveInfo.filter = filter; 5416 forwardingResolveInfo.targetUserId = targetUserId; 5417 return forwardingResolveInfo; 5418 } 5419 5420 @Override 5421 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5422 Intent[] specifics, String[] specificTypes, Intent intent, 5423 String resolvedType, int flags, int userId) { 5424 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5425 flags = updateFlagsForResolve(flags, userId, intent); 5426 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5427 false, "query intent activity options"); 5428 final String resultsAction = intent.getAction(); 5429 5430 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5431 | PackageManager.GET_RESOLVED_FILTER, userId); 5432 5433 if (DEBUG_INTENT_MATCHING) { 5434 Log.v(TAG, "Query " + intent + ": " + results); 5435 } 5436 5437 int specificsPos = 0; 5438 int N; 5439 5440 // todo: note that the algorithm used here is O(N^2). This 5441 // isn't a problem in our current environment, but if we start running 5442 // into situations where we have more than 5 or 10 matches then this 5443 // should probably be changed to something smarter... 5444 5445 // First we go through and resolve each of the specific items 5446 // that were supplied, taking care of removing any corresponding 5447 // duplicate items in the generic resolve list. 5448 if (specifics != null) { 5449 for (int i=0; i<specifics.length; i++) { 5450 final Intent sintent = specifics[i]; 5451 if (sintent == null) { 5452 continue; 5453 } 5454 5455 if (DEBUG_INTENT_MATCHING) { 5456 Log.v(TAG, "Specific #" + i + ": " + sintent); 5457 } 5458 5459 String action = sintent.getAction(); 5460 if (resultsAction != null && resultsAction.equals(action)) { 5461 // If this action was explicitly requested, then don't 5462 // remove things that have it. 5463 action = null; 5464 } 5465 5466 ResolveInfo ri = null; 5467 ActivityInfo ai = null; 5468 5469 ComponentName comp = sintent.getComponent(); 5470 if (comp == null) { 5471 ri = resolveIntent( 5472 sintent, 5473 specificTypes != null ? specificTypes[i] : null, 5474 flags, userId); 5475 if (ri == null) { 5476 continue; 5477 } 5478 if (ri == mResolveInfo) { 5479 // ACK! Must do something better with this. 5480 } 5481 ai = ri.activityInfo; 5482 comp = new ComponentName(ai.applicationInfo.packageName, 5483 ai.name); 5484 } else { 5485 ai = getActivityInfo(comp, flags, userId); 5486 if (ai == null) { 5487 continue; 5488 } 5489 } 5490 5491 // Look for any generic query activities that are duplicates 5492 // of this specific one, and remove them from the results. 5493 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5494 N = results.size(); 5495 int j; 5496 for (j=specificsPos; j<N; j++) { 5497 ResolveInfo sri = results.get(j); 5498 if ((sri.activityInfo.name.equals(comp.getClassName()) 5499 && sri.activityInfo.applicationInfo.packageName.equals( 5500 comp.getPackageName())) 5501 || (action != null && sri.filter.matchAction(action))) { 5502 results.remove(j); 5503 if (DEBUG_INTENT_MATCHING) Log.v( 5504 TAG, "Removing duplicate item from " + j 5505 + " due to specific " + specificsPos); 5506 if (ri == null) { 5507 ri = sri; 5508 } 5509 j--; 5510 N--; 5511 } 5512 } 5513 5514 // Add this specific item to its proper place. 5515 if (ri == null) { 5516 ri = new ResolveInfo(); 5517 ri.activityInfo = ai; 5518 } 5519 results.add(specificsPos, ri); 5520 ri.specificIndex = i; 5521 specificsPos++; 5522 } 5523 } 5524 5525 // Now we go through the remaining generic results and remove any 5526 // duplicate actions that are found here. 5527 N = results.size(); 5528 for (int i=specificsPos; i<N-1; i++) { 5529 final ResolveInfo rii = results.get(i); 5530 if (rii.filter == null) { 5531 continue; 5532 } 5533 5534 // Iterate over all of the actions of this result's intent 5535 // filter... typically this should be just one. 5536 final Iterator<String> it = rii.filter.actionsIterator(); 5537 if (it == null) { 5538 continue; 5539 } 5540 while (it.hasNext()) { 5541 final String action = it.next(); 5542 if (resultsAction != null && resultsAction.equals(action)) { 5543 // If this action was explicitly requested, then don't 5544 // remove things that have it. 5545 continue; 5546 } 5547 for (int j=i+1; j<N; j++) { 5548 final ResolveInfo rij = results.get(j); 5549 if (rij.filter != null && rij.filter.hasAction(action)) { 5550 results.remove(j); 5551 if (DEBUG_INTENT_MATCHING) Log.v( 5552 TAG, "Removing duplicate item from " + j 5553 + " due to action " + action + " at " + i); 5554 j--; 5555 N--; 5556 } 5557 } 5558 } 5559 5560 // If the caller didn't request filter information, drop it now 5561 // so we don't have to marshall/unmarshall it. 5562 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5563 rii.filter = null; 5564 } 5565 } 5566 5567 // Filter out the caller activity if so requested. 5568 if (caller != null) { 5569 N = results.size(); 5570 for (int i=0; i<N; i++) { 5571 ActivityInfo ainfo = results.get(i).activityInfo; 5572 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5573 && caller.getClassName().equals(ainfo.name)) { 5574 results.remove(i); 5575 break; 5576 } 5577 } 5578 } 5579 5580 // If the caller didn't request filter information, 5581 // drop them now so we don't have to 5582 // marshall/unmarshall it. 5583 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5584 N = results.size(); 5585 for (int i=0; i<N; i++) { 5586 results.get(i).filter = null; 5587 } 5588 } 5589 5590 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5591 return results; 5592 } 5593 5594 @Override 5595 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5596 int userId) { 5597 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5598 flags = updateFlagsForResolve(flags, userId, intent); 5599 ComponentName comp = intent.getComponent(); 5600 if (comp == null) { 5601 if (intent.getSelector() != null) { 5602 intent = intent.getSelector(); 5603 comp = intent.getComponent(); 5604 } 5605 } 5606 if (comp != null) { 5607 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5608 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5609 if (ai != null) { 5610 ResolveInfo ri = new ResolveInfo(); 5611 ri.activityInfo = ai; 5612 list.add(ri); 5613 } 5614 return list; 5615 } 5616 5617 // reader 5618 synchronized (mPackages) { 5619 String pkgName = intent.getPackage(); 5620 if (pkgName == null) { 5621 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5622 } 5623 final PackageParser.Package pkg = mPackages.get(pkgName); 5624 if (pkg != null) { 5625 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5626 userId); 5627 } 5628 return null; 5629 } 5630 } 5631 5632 @Override 5633 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5634 if (!sUserManager.exists(userId)) return null; 5635 flags = updateFlagsForResolve(flags, userId, intent); 5636 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5637 if (query != null) { 5638 if (query.size() >= 1) { 5639 // If there is more than one service with the same priority, 5640 // just arbitrarily pick the first one. 5641 return query.get(0); 5642 } 5643 } 5644 return null; 5645 } 5646 5647 @Override 5648 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5649 int userId) { 5650 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5651 flags = updateFlagsForResolve(flags, userId, intent); 5652 ComponentName comp = intent.getComponent(); 5653 if (comp == null) { 5654 if (intent.getSelector() != null) { 5655 intent = intent.getSelector(); 5656 comp = intent.getComponent(); 5657 } 5658 } 5659 if (comp != null) { 5660 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5661 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5662 if (si != null) { 5663 final ResolveInfo ri = new ResolveInfo(); 5664 ri.serviceInfo = si; 5665 list.add(ri); 5666 } 5667 return list; 5668 } 5669 5670 // reader 5671 synchronized (mPackages) { 5672 String pkgName = intent.getPackage(); 5673 if (pkgName == null) { 5674 return mServices.queryIntent(intent, resolvedType, flags, userId); 5675 } 5676 final PackageParser.Package pkg = mPackages.get(pkgName); 5677 if (pkg != null) { 5678 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5679 userId); 5680 } 5681 return null; 5682 } 5683 } 5684 5685 @Override 5686 public List<ResolveInfo> queryIntentContentProviders( 5687 Intent intent, String resolvedType, int flags, int userId) { 5688 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5689 flags = updateFlagsForResolve(flags, userId, intent); 5690 ComponentName comp = intent.getComponent(); 5691 if (comp == null) { 5692 if (intent.getSelector() != null) { 5693 intent = intent.getSelector(); 5694 comp = intent.getComponent(); 5695 } 5696 } 5697 if (comp != null) { 5698 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5699 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5700 if (pi != null) { 5701 final ResolveInfo ri = new ResolveInfo(); 5702 ri.providerInfo = pi; 5703 list.add(ri); 5704 } 5705 return list; 5706 } 5707 5708 // reader 5709 synchronized (mPackages) { 5710 String pkgName = intent.getPackage(); 5711 if (pkgName == null) { 5712 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5713 } 5714 final PackageParser.Package pkg = mPackages.get(pkgName); 5715 if (pkg != null) { 5716 return mProviders.queryIntentForPackage( 5717 intent, resolvedType, flags, pkg.providers, userId); 5718 } 5719 return null; 5720 } 5721 } 5722 5723 @Override 5724 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5725 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5726 flags = updateFlagsForPackage(flags, userId, null); 5727 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5728 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5729 5730 // writer 5731 synchronized (mPackages) { 5732 ArrayList<PackageInfo> list; 5733 if (listUninstalled) { 5734 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5735 for (PackageSetting ps : mSettings.mPackages.values()) { 5736 PackageInfo pi; 5737 if (ps.pkg != null) { 5738 pi = generatePackageInfo(ps.pkg, flags, userId); 5739 } else { 5740 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5741 } 5742 if (pi != null) { 5743 list.add(pi); 5744 } 5745 } 5746 } else { 5747 list = new ArrayList<PackageInfo>(mPackages.size()); 5748 for (PackageParser.Package p : mPackages.values()) { 5749 PackageInfo pi = generatePackageInfo(p, flags, userId); 5750 if (pi != null) { 5751 list.add(pi); 5752 } 5753 } 5754 } 5755 5756 return new ParceledListSlice<PackageInfo>(list); 5757 } 5758 } 5759 5760 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5761 String[] permissions, boolean[] tmp, int flags, int userId) { 5762 int numMatch = 0; 5763 final PermissionsState permissionsState = ps.getPermissionsState(); 5764 for (int i=0; i<permissions.length; i++) { 5765 final String permission = permissions[i]; 5766 if (permissionsState.hasPermission(permission, userId)) { 5767 tmp[i] = true; 5768 numMatch++; 5769 } else { 5770 tmp[i] = false; 5771 } 5772 } 5773 if (numMatch == 0) { 5774 return; 5775 } 5776 PackageInfo pi; 5777 if (ps.pkg != null) { 5778 pi = generatePackageInfo(ps.pkg, flags, userId); 5779 } else { 5780 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5781 } 5782 // The above might return null in cases of uninstalled apps or install-state 5783 // skew across users/profiles. 5784 if (pi != null) { 5785 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5786 if (numMatch == permissions.length) { 5787 pi.requestedPermissions = permissions; 5788 } else { 5789 pi.requestedPermissions = new String[numMatch]; 5790 numMatch = 0; 5791 for (int i=0; i<permissions.length; i++) { 5792 if (tmp[i]) { 5793 pi.requestedPermissions[numMatch] = permissions[i]; 5794 numMatch++; 5795 } 5796 } 5797 } 5798 } 5799 list.add(pi); 5800 } 5801 } 5802 5803 @Override 5804 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5805 String[] permissions, int flags, int userId) { 5806 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5807 flags = updateFlagsForPackage(flags, userId, permissions); 5808 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5809 5810 // writer 5811 synchronized (mPackages) { 5812 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5813 boolean[] tmpBools = new boolean[permissions.length]; 5814 if (listUninstalled) { 5815 for (PackageSetting ps : mSettings.mPackages.values()) { 5816 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5817 } 5818 } else { 5819 for (PackageParser.Package pkg : mPackages.values()) { 5820 PackageSetting ps = (PackageSetting)pkg.mExtras; 5821 if (ps != null) { 5822 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5823 userId); 5824 } 5825 } 5826 } 5827 5828 return new ParceledListSlice<PackageInfo>(list); 5829 } 5830 } 5831 5832 @Override 5833 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5834 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5835 flags = updateFlagsForApplication(flags, userId, null); 5836 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5837 5838 // writer 5839 synchronized (mPackages) { 5840 ArrayList<ApplicationInfo> list; 5841 if (listUninstalled) { 5842 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5843 for (PackageSetting ps : mSettings.mPackages.values()) { 5844 ApplicationInfo ai; 5845 if (ps.pkg != null) { 5846 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5847 ps.readUserState(userId), userId); 5848 } else { 5849 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5850 } 5851 if (ai != null) { 5852 list.add(ai); 5853 } 5854 } 5855 } else { 5856 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5857 for (PackageParser.Package p : mPackages.values()) { 5858 if (p.mExtras != null) { 5859 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5860 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5861 if (ai != null) { 5862 list.add(ai); 5863 } 5864 } 5865 } 5866 } 5867 5868 return new ParceledListSlice<ApplicationInfo>(list); 5869 } 5870 } 5871 5872 @Override 5873 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5874 if (DISABLE_EPHEMERAL_APPS) { 5875 return null; 5876 } 5877 5878 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5879 "getEphemeralApplications"); 5880 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5881 "getEphemeralApplications"); 5882 synchronized (mPackages) { 5883 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5884 .getEphemeralApplicationsLPw(userId); 5885 if (ephemeralApps != null) { 5886 return new ParceledListSlice<>(ephemeralApps); 5887 } 5888 } 5889 return null; 5890 } 5891 5892 @Override 5893 public boolean isEphemeralApplication(String packageName, int userId) { 5894 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5895 "isEphemeral"); 5896 if (DISABLE_EPHEMERAL_APPS) { 5897 return false; 5898 } 5899 5900 if (!isCallerSameApp(packageName)) { 5901 return false; 5902 } 5903 synchronized (mPackages) { 5904 PackageParser.Package pkg = mPackages.get(packageName); 5905 if (pkg != null) { 5906 return pkg.applicationInfo.isEphemeralApp(); 5907 } 5908 } 5909 return false; 5910 } 5911 5912 @Override 5913 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5914 if (DISABLE_EPHEMERAL_APPS) { 5915 return null; 5916 } 5917 5918 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5919 "getCookie"); 5920 if (!isCallerSameApp(packageName)) { 5921 return null; 5922 } 5923 synchronized (mPackages) { 5924 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5925 packageName, userId); 5926 } 5927 } 5928 5929 @Override 5930 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 5931 if (DISABLE_EPHEMERAL_APPS) { 5932 return true; 5933 } 5934 5935 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5936 "setCookie"); 5937 if (!isCallerSameApp(packageName)) { 5938 return false; 5939 } 5940 synchronized (mPackages) { 5941 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 5942 packageName, cookie, userId); 5943 } 5944 } 5945 5946 @Override 5947 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 5948 if (DISABLE_EPHEMERAL_APPS) { 5949 return null; 5950 } 5951 5952 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5953 "getEphemeralApplicationIcon"); 5954 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5955 "getEphemeralApplicationIcon"); 5956 synchronized (mPackages) { 5957 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 5958 packageName, userId); 5959 } 5960 } 5961 5962 private boolean isCallerSameApp(String packageName) { 5963 PackageParser.Package pkg = mPackages.get(packageName); 5964 return pkg != null 5965 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 5966 } 5967 5968 public List<ApplicationInfo> getPersistentApplications(int flags) { 5969 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5970 5971 // reader 5972 synchronized (mPackages) { 5973 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5974 final int userId = UserHandle.getCallingUserId(); 5975 while (i.hasNext()) { 5976 final PackageParser.Package p = i.next(); 5977 if (p.applicationInfo != null 5978 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5979 && (!mSafeMode || isSystemApp(p))) { 5980 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5981 if (ps != null) { 5982 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5983 ps.readUserState(userId), userId); 5984 if (ai != null) { 5985 finalList.add(ai); 5986 } 5987 } 5988 } 5989 } 5990 } 5991 5992 return finalList; 5993 } 5994 5995 @Override 5996 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5997 if (!sUserManager.exists(userId)) return null; 5998 flags = updateFlagsForComponent(flags, userId, name); 5999 // reader 6000 synchronized (mPackages) { 6001 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6002 PackageSetting ps = provider != null 6003 ? mSettings.mPackages.get(provider.owner.packageName) 6004 : null; 6005 return ps != null 6006 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6007 ? PackageParser.generateProviderInfo(provider, flags, 6008 ps.readUserState(userId), userId) 6009 : null; 6010 } 6011 } 6012 6013 /** 6014 * @deprecated 6015 */ 6016 @Deprecated 6017 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6018 // reader 6019 synchronized (mPackages) { 6020 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6021 .entrySet().iterator(); 6022 final int userId = UserHandle.getCallingUserId(); 6023 while (i.hasNext()) { 6024 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6025 PackageParser.Provider p = entry.getValue(); 6026 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6027 6028 if (ps != null && p.syncable 6029 && (!mSafeMode || (p.info.applicationInfo.flags 6030 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6031 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6032 ps.readUserState(userId), userId); 6033 if (info != null) { 6034 outNames.add(entry.getKey()); 6035 outInfo.add(info); 6036 } 6037 } 6038 } 6039 } 6040 } 6041 6042 @Override 6043 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6044 int uid, int flags) { 6045 final int userId = processName != null ? UserHandle.getUserId(uid) 6046 : UserHandle.getCallingUserId(); 6047 if (!sUserManager.exists(userId)) return null; 6048 flags = updateFlagsForComponent(flags, userId, processName); 6049 6050 ArrayList<ProviderInfo> finalList = null; 6051 // reader 6052 synchronized (mPackages) { 6053 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6054 while (i.hasNext()) { 6055 final PackageParser.Provider p = i.next(); 6056 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6057 if (ps != null && p.info.authority != null 6058 && (processName == null 6059 || (p.info.processName.equals(processName) 6060 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6061 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6062 if (finalList == null) { 6063 finalList = new ArrayList<ProviderInfo>(3); 6064 } 6065 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6066 ps.readUserState(userId), userId); 6067 if (info != null) { 6068 finalList.add(info); 6069 } 6070 } 6071 } 6072 } 6073 6074 if (finalList != null) { 6075 Collections.sort(finalList, mProviderInitOrderSorter); 6076 return new ParceledListSlice<ProviderInfo>(finalList); 6077 } 6078 6079 return null; 6080 } 6081 6082 @Override 6083 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6084 // reader 6085 synchronized (mPackages) { 6086 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6087 return PackageParser.generateInstrumentationInfo(i, flags); 6088 } 6089 } 6090 6091 @Override 6092 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6093 int flags) { 6094 ArrayList<InstrumentationInfo> finalList = 6095 new ArrayList<InstrumentationInfo>(); 6096 6097 // reader 6098 synchronized (mPackages) { 6099 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6100 while (i.hasNext()) { 6101 final PackageParser.Instrumentation p = i.next(); 6102 if (targetPackage == null 6103 || targetPackage.equals(p.info.targetPackage)) { 6104 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6105 flags); 6106 if (ii != null) { 6107 finalList.add(ii); 6108 } 6109 } 6110 } 6111 } 6112 6113 return finalList; 6114 } 6115 6116 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6117 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6118 if (overlays == null) { 6119 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6120 return; 6121 } 6122 for (PackageParser.Package opkg : overlays.values()) { 6123 // Not much to do if idmap fails: we already logged the error 6124 // and we certainly don't want to abort installation of pkg simply 6125 // because an overlay didn't fit properly. For these reasons, 6126 // ignore the return value of createIdmapForPackagePairLI. 6127 createIdmapForPackagePairLI(pkg, opkg); 6128 } 6129 } 6130 6131 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6132 PackageParser.Package opkg) { 6133 if (!opkg.mTrustedOverlay) { 6134 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6135 opkg.baseCodePath + ": overlay not trusted"); 6136 return false; 6137 } 6138 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6139 if (overlaySet == null) { 6140 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6141 opkg.baseCodePath + " but target package has no known overlays"); 6142 return false; 6143 } 6144 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6145 // TODO: generate idmap for split APKs 6146 try { 6147 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6148 } catch (InstallerException e) { 6149 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6150 + opkg.baseCodePath); 6151 return false; 6152 } 6153 PackageParser.Package[] overlayArray = 6154 overlaySet.values().toArray(new PackageParser.Package[0]); 6155 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6156 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6157 return p1.mOverlayPriority - p2.mOverlayPriority; 6158 } 6159 }; 6160 Arrays.sort(overlayArray, cmp); 6161 6162 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6163 int i = 0; 6164 for (PackageParser.Package p : overlayArray) { 6165 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6166 } 6167 return true; 6168 } 6169 6170 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6171 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6172 try { 6173 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6174 } finally { 6175 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6176 } 6177 } 6178 6179 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6180 final File[] files = dir.listFiles(); 6181 if (ArrayUtils.isEmpty(files)) { 6182 Log.d(TAG, "No files in app dir " + dir); 6183 return; 6184 } 6185 6186 if (DEBUG_PACKAGE_SCANNING) { 6187 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6188 + " flags=0x" + Integer.toHexString(parseFlags)); 6189 } 6190 6191 for (File file : files) { 6192 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6193 && !PackageInstallerService.isStageName(file.getName()); 6194 if (!isPackage) { 6195 // Ignore entries which are not packages 6196 continue; 6197 } 6198 try { 6199 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6200 scanFlags, currentTime, null); 6201 } catch (PackageManagerException e) { 6202 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6203 6204 // Delete invalid userdata apps 6205 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6206 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6207 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6208 removeCodePathLI(file); 6209 } 6210 } 6211 } 6212 } 6213 6214 private static File getSettingsProblemFile() { 6215 File dataDir = Environment.getDataDirectory(); 6216 File systemDir = new File(dataDir, "system"); 6217 File fname = new File(systemDir, "uiderrors.txt"); 6218 return fname; 6219 } 6220 6221 static void reportSettingsProblem(int priority, String msg) { 6222 logCriticalInfo(priority, msg); 6223 } 6224 6225 static void logCriticalInfo(int priority, String msg) { 6226 Slog.println(priority, TAG, msg); 6227 EventLogTags.writePmCriticalInfo(msg); 6228 try { 6229 File fname = getSettingsProblemFile(); 6230 FileOutputStream out = new FileOutputStream(fname, true); 6231 PrintWriter pw = new FastPrintWriter(out); 6232 SimpleDateFormat formatter = new SimpleDateFormat(); 6233 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6234 pw.println(dateString + ": " + msg); 6235 pw.close(); 6236 FileUtils.setPermissions( 6237 fname.toString(), 6238 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6239 -1, -1); 6240 } catch (java.io.IOException e) { 6241 } 6242 } 6243 6244 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6245 PackageParser.Package pkg, File srcFile, int parseFlags) 6246 throws PackageManagerException { 6247 if (ps != null 6248 && ps.codePath.equals(srcFile) 6249 && ps.timeStamp == srcFile.lastModified() 6250 && !isCompatSignatureUpdateNeeded(pkg) 6251 && !isRecoverSignatureUpdateNeeded(pkg)) { 6252 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6253 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6254 ArraySet<PublicKey> signingKs; 6255 synchronized (mPackages) { 6256 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6257 } 6258 if (ps.signatures.mSignatures != null 6259 && ps.signatures.mSignatures.length != 0 6260 && signingKs != null) { 6261 // Optimization: reuse the existing cached certificates 6262 // if the package appears to be unchanged. 6263 pkg.mSignatures = ps.signatures.mSignatures; 6264 pkg.mSigningKeys = signingKs; 6265 return; 6266 } 6267 6268 Slog.w(TAG, "PackageSetting for " + ps.name 6269 + " is missing signatures. Collecting certs again to recover them."); 6270 } else { 6271 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6272 } 6273 6274 try { 6275 pp.collectCertificates(pkg, parseFlags); 6276 } catch (PackageParserException e) { 6277 throw PackageManagerException.from(e); 6278 } 6279 } 6280 6281 /** 6282 * Traces a package scan. 6283 * @see #scanPackageLI(File, int, int, long, UserHandle) 6284 */ 6285 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6286 long currentTime, UserHandle user) throws PackageManagerException { 6287 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6288 try { 6289 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6290 } finally { 6291 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6292 } 6293 } 6294 6295 /** 6296 * Scans a package and returns the newly parsed package. 6297 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6298 */ 6299 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6300 long currentTime, UserHandle user) throws PackageManagerException { 6301 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6302 parseFlags |= mDefParseFlags; 6303 PackageParser pp = new PackageParser(); 6304 pp.setSeparateProcesses(mSeparateProcesses); 6305 pp.setOnlyCoreApps(mOnlyCore); 6306 pp.setDisplayMetrics(mMetrics); 6307 6308 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6309 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6310 } 6311 6312 final PackageParser.Package pkg; 6313 try { 6314 pkg = pp.parsePackage(scanFile, parseFlags); 6315 } catch (PackageParserException e) { 6316 throw PackageManagerException.from(e); 6317 } 6318 6319 PackageSetting ps = null; 6320 PackageSetting updatedPkg; 6321 // reader 6322 synchronized (mPackages) { 6323 // Look to see if we already know about this package. 6324 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6325 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6326 // This package has been renamed to its original name. Let's 6327 // use that. 6328 ps = mSettings.peekPackageLPr(oldName); 6329 } 6330 // If there was no original package, see one for the real package name. 6331 if (ps == null) { 6332 ps = mSettings.peekPackageLPr(pkg.packageName); 6333 } 6334 // Check to see if this package could be hiding/updating a system 6335 // package. Must look for it either under the original or real 6336 // package name depending on our state. 6337 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6338 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6339 } 6340 boolean updatedPkgBetter = false; 6341 // First check if this is a system package that may involve an update 6342 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6343 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6344 // it needs to drop FLAG_PRIVILEGED. 6345 if (locationIsPrivileged(scanFile)) { 6346 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6347 } else { 6348 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6349 } 6350 6351 if (ps != null && !ps.codePath.equals(scanFile)) { 6352 // The path has changed from what was last scanned... check the 6353 // version of the new path against what we have stored to determine 6354 // what to do. 6355 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6356 if (pkg.mVersionCode <= ps.versionCode) { 6357 // The system package has been updated and the code path does not match 6358 // Ignore entry. Skip it. 6359 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6360 + " ignored: updated version " + ps.versionCode 6361 + " better than this " + pkg.mVersionCode); 6362 if (!updatedPkg.codePath.equals(scanFile)) { 6363 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6364 + ps.name + " changing from " + updatedPkg.codePathString 6365 + " to " + scanFile); 6366 updatedPkg.codePath = scanFile; 6367 updatedPkg.codePathString = scanFile.toString(); 6368 updatedPkg.resourcePath = scanFile; 6369 updatedPkg.resourcePathString = scanFile.toString(); 6370 } 6371 updatedPkg.pkg = pkg; 6372 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6373 "Package " + ps.name + " at " + scanFile 6374 + " ignored: updated version " + ps.versionCode 6375 + " better than this " + pkg.mVersionCode); 6376 } else { 6377 // The current app on the system partition is better than 6378 // what we have updated to on the data partition; switch 6379 // back to the system partition version. 6380 // At this point, its safely assumed that package installation for 6381 // apps in system partition will go through. If not there won't be a working 6382 // version of the app 6383 // writer 6384 synchronized (mPackages) { 6385 // Just remove the loaded entries from package lists. 6386 mPackages.remove(ps.name); 6387 } 6388 6389 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6390 + " reverting from " + ps.codePathString 6391 + ": new version " + pkg.mVersionCode 6392 + " better than installed " + ps.versionCode); 6393 6394 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6395 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6396 synchronized (mInstallLock) { 6397 args.cleanUpResourcesLI(); 6398 } 6399 synchronized (mPackages) { 6400 mSettings.enableSystemPackageLPw(ps.name); 6401 } 6402 updatedPkgBetter = true; 6403 } 6404 } 6405 } 6406 6407 if (updatedPkg != null) { 6408 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6409 // initially 6410 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6411 6412 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6413 // flag set initially 6414 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6415 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6416 } 6417 } 6418 6419 // Verify certificates against what was last scanned 6420 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6421 6422 /* 6423 * A new system app appeared, but we already had a non-system one of the 6424 * same name installed earlier. 6425 */ 6426 boolean shouldHideSystemApp = false; 6427 if (updatedPkg == null && ps != null 6428 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6429 /* 6430 * Check to make sure the signatures match first. If they don't, 6431 * wipe the installed application and its data. 6432 */ 6433 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6434 != PackageManager.SIGNATURE_MATCH) { 6435 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6436 + " signatures don't match existing userdata copy; removing"); 6437 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6438 ps = null; 6439 } else { 6440 /* 6441 * If the newly-added system app is an older version than the 6442 * already installed version, hide it. It will be scanned later 6443 * and re-added like an update. 6444 */ 6445 if (pkg.mVersionCode <= ps.versionCode) { 6446 shouldHideSystemApp = true; 6447 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6448 + " but new version " + pkg.mVersionCode + " better than installed " 6449 + ps.versionCode + "; hiding system"); 6450 } else { 6451 /* 6452 * The newly found system app is a newer version that the 6453 * one previously installed. Simply remove the 6454 * already-installed application and replace it with our own 6455 * while keeping the application data. 6456 */ 6457 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6458 + " reverting from " + ps.codePathString + ": new version " 6459 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6460 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6461 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6462 synchronized (mInstallLock) { 6463 args.cleanUpResourcesLI(); 6464 } 6465 } 6466 } 6467 } 6468 6469 // The apk is forward locked (not public) if its code and resources 6470 // are kept in different files. (except for app in either system or 6471 // vendor path). 6472 // TODO grab this value from PackageSettings 6473 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6474 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6475 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6476 } 6477 } 6478 6479 // TODO: extend to support forward-locked splits 6480 String resourcePath = null; 6481 String baseResourcePath = null; 6482 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6483 if (ps != null && ps.resourcePathString != null) { 6484 resourcePath = ps.resourcePathString; 6485 baseResourcePath = ps.resourcePathString; 6486 } else { 6487 // Should not happen at all. Just log an error. 6488 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6489 } 6490 } else { 6491 resourcePath = pkg.codePath; 6492 baseResourcePath = pkg.baseCodePath; 6493 } 6494 6495 // Set application objects path explicitly. 6496 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6497 pkg.applicationInfo.setCodePath(pkg.codePath); 6498 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6499 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6500 pkg.applicationInfo.setResourcePath(resourcePath); 6501 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6502 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6503 6504 // Note that we invoke the following method only if we are about to unpack an application 6505 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6506 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6507 6508 /* 6509 * If the system app should be overridden by a previously installed 6510 * data, hide the system app now and let the /data/app scan pick it up 6511 * again. 6512 */ 6513 if (shouldHideSystemApp) { 6514 synchronized (mPackages) { 6515 mSettings.disableSystemPackageLPw(pkg.packageName); 6516 } 6517 } 6518 6519 return scannedPkg; 6520 } 6521 6522 private static String fixProcessName(String defProcessName, 6523 String processName, int uid) { 6524 if (processName == null) { 6525 return defProcessName; 6526 } 6527 return processName; 6528 } 6529 6530 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6531 throws PackageManagerException { 6532 if (pkgSetting.signatures.mSignatures != null) { 6533 // Already existing package. Make sure signatures match 6534 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6535 == PackageManager.SIGNATURE_MATCH; 6536 if (!match) { 6537 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6538 == PackageManager.SIGNATURE_MATCH; 6539 } 6540 if (!match) { 6541 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6542 == PackageManager.SIGNATURE_MATCH; 6543 } 6544 if (!match) { 6545 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6546 + pkg.packageName + " signatures do not match the " 6547 + "previously installed version; ignoring!"); 6548 } 6549 } 6550 6551 // Check for shared user signatures 6552 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6553 // Already existing package. Make sure signatures match 6554 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6555 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6556 if (!match) { 6557 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6558 == PackageManager.SIGNATURE_MATCH; 6559 } 6560 if (!match) { 6561 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6562 == PackageManager.SIGNATURE_MATCH; 6563 } 6564 if (!match) { 6565 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6566 "Package " + pkg.packageName 6567 + " has no signatures that match those in shared user " 6568 + pkgSetting.sharedUser.name + "; ignoring!"); 6569 } 6570 } 6571 } 6572 6573 /** 6574 * Enforces that only the system UID or root's UID can call a method exposed 6575 * via Binder. 6576 * 6577 * @param message used as message if SecurityException is thrown 6578 * @throws SecurityException if the caller is not system or root 6579 */ 6580 private static final void enforceSystemOrRoot(String message) { 6581 final int uid = Binder.getCallingUid(); 6582 if (uid != Process.SYSTEM_UID && uid != 0) { 6583 throw new SecurityException(message); 6584 } 6585 } 6586 6587 @Override 6588 public void performFstrimIfNeeded() { 6589 enforceSystemOrRoot("Only the system can request fstrim"); 6590 6591 // Before everything else, see whether we need to fstrim. 6592 try { 6593 IMountService ms = PackageHelper.getMountService(); 6594 if (ms != null) { 6595 final boolean isUpgrade = isUpgrade(); 6596 boolean doTrim = isUpgrade; 6597 if (doTrim) { 6598 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6599 } else { 6600 final long interval = android.provider.Settings.Global.getLong( 6601 mContext.getContentResolver(), 6602 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6603 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6604 if (interval > 0) { 6605 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6606 if (timeSinceLast > interval) { 6607 doTrim = true; 6608 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6609 + "; running immediately"); 6610 } 6611 } 6612 } 6613 if (doTrim) { 6614 if (!isFirstBoot()) { 6615 try { 6616 ActivityManagerNative.getDefault().showBootMessage( 6617 mContext.getResources().getString( 6618 R.string.android_upgrading_fstrim), true); 6619 } catch (RemoteException e) { 6620 } 6621 } 6622 ms.runMaintenance(); 6623 } 6624 } else { 6625 Slog.e(TAG, "Mount service unavailable!"); 6626 } 6627 } catch (RemoteException e) { 6628 // Can't happen; MountService is local 6629 } 6630 } 6631 6632 @Override 6633 public void extractPackagesIfNeeded() { 6634 enforceSystemOrRoot("Only the system can request package extraction"); 6635 6636 // Extract pacakges only if profile-guided compilation is enabled because 6637 // otherwise BackgroundDexOptService will not dexopt them later. 6638 if (mUseJitProfiles) { 6639 ArraySet<String> pkgs = getOptimizablePackages(); 6640 if (pkgs != null) { 6641 for (String pkg : pkgs) { 6642 performDexOpt(pkg, null /* instructionSet */, false /* useProfiles */, 6643 true /* extractOnly */); 6644 } 6645 } 6646 } 6647 } 6648 6649 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6650 List<ResolveInfo> ris = null; 6651 try { 6652 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6653 intent, null, 0, userId); 6654 } catch (RemoteException e) { 6655 } 6656 ArraySet<String> pkgNames = new ArraySet<String>(); 6657 if (ris != null) { 6658 for (ResolveInfo ri : ris) { 6659 pkgNames.add(ri.activityInfo.packageName); 6660 } 6661 } 6662 return pkgNames; 6663 } 6664 6665 @Override 6666 public void notifyPackageUse(String packageName) { 6667 synchronized (mPackages) { 6668 PackageParser.Package p = mPackages.get(packageName); 6669 if (p == null) { 6670 return; 6671 } 6672 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6673 } 6674 } 6675 6676 // TODO: this is not used nor needed. Delete it. 6677 @Override 6678 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6679 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6680 false /* extractOnly */); 6681 } 6682 6683 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6684 boolean extractOnly) { 6685 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly); 6686 } 6687 6688 private boolean performDexOptTraced(String packageName, String instructionSet, 6689 boolean useProfiles, boolean extractOnly) { 6690 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6691 try { 6692 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly); 6693 } finally { 6694 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6695 } 6696 } 6697 6698 private boolean performDexOptInternal(String packageName, String instructionSet, 6699 boolean useProfiles, boolean extractOnly) { 6700 PackageParser.Package p; 6701 final String targetInstructionSet; 6702 synchronized (mPackages) { 6703 p = mPackages.get(packageName); 6704 if (p == null) { 6705 return false; 6706 } 6707 mPackageUsage.write(false); 6708 6709 targetInstructionSet = instructionSet != null ? instructionSet : 6710 getPrimaryInstructionSet(p.applicationInfo); 6711 if (!useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) { 6712 // Skip only if we do not use profiles since they might trigger a recompilation. 6713 return false; 6714 } 6715 } 6716 long callingId = Binder.clearCallingIdentity(); 6717 try { 6718 synchronized (mInstallLock) { 6719 final String[] instructionSets = new String[] { targetInstructionSet }; 6720 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6721 true /* inclDependencies */, useProfiles, extractOnly); 6722 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6723 } 6724 } finally { 6725 Binder.restoreCallingIdentity(callingId); 6726 } 6727 } 6728 6729 public ArraySet<String> getOptimizablePackages() { 6730 ArraySet<String> pkgs = new ArraySet<String>(); 6731 synchronized (mPackages) { 6732 for (PackageParser.Package p : mPackages.values()) { 6733 if (PackageDexOptimizer.canOptimizePackage(p)) { 6734 pkgs.add(p.packageName); 6735 } 6736 } 6737 } 6738 return pkgs; 6739 } 6740 6741 public void shutdown() { 6742 mPackageUsage.write(true); 6743 } 6744 6745 @Override 6746 public void forceDexOpt(String packageName) { 6747 enforceSystemOrRoot("forceDexOpt"); 6748 6749 PackageParser.Package pkg; 6750 synchronized (mPackages) { 6751 pkg = mPackages.get(packageName); 6752 if (pkg == null) { 6753 throw new IllegalArgumentException("Unknown package: " + packageName); 6754 } 6755 } 6756 6757 synchronized (mInstallLock) { 6758 final String[] instructionSets = new String[] { 6759 getPrimaryInstructionSet(pkg.applicationInfo) }; 6760 6761 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6762 6763 // Whoever is calling forceDexOpt wants a fully compiled package. 6764 // Don't use profiles since that may cause compilation to be skipped. 6765 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6766 true /* inclDependencies */, false /* useProfiles */, 6767 false /* extractOnly */); 6768 6769 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6770 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6771 throw new IllegalStateException("Failed to dexopt: " + res); 6772 } 6773 } 6774 } 6775 6776 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6777 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6778 Slog.w(TAG, "Unable to update from " + oldPkg.name 6779 + " to " + newPkg.packageName 6780 + ": old package not in system partition"); 6781 return false; 6782 } else if (mPackages.get(oldPkg.name) != null) { 6783 Slog.w(TAG, "Unable to update from " + oldPkg.name 6784 + " to " + newPkg.packageName 6785 + ": old package still exists"); 6786 return false; 6787 } 6788 return true; 6789 } 6790 6791 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 6792 // TODO: triage flags as part of 26466827 6793 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 6794 6795 boolean res = true; 6796 final int[] users = sUserManager.getUserIds(); 6797 for (int user : users) { 6798 try { 6799 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 6800 } catch (InstallerException e) { 6801 Slog.w(TAG, "Failed to delete data directory", e); 6802 res = false; 6803 } 6804 } 6805 return res; 6806 } 6807 6808 void removeCodePathLI(File codePath) { 6809 if (codePath.isDirectory()) { 6810 try { 6811 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 6812 } catch (InstallerException e) { 6813 Slog.w(TAG, "Failed to remove code path", e); 6814 } 6815 } else { 6816 codePath.delete(); 6817 } 6818 } 6819 6820 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 6821 try { 6822 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 6823 } catch (InstallerException e) { 6824 Slog.w(TAG, "Failed to destroy app data", e); 6825 } 6826 } 6827 6828 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 6829 int appId, String seinfo) { 6830 try { 6831 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 6832 } catch (InstallerException e) { 6833 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 6834 } 6835 } 6836 6837 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6838 // TODO: triage flags as part of 26466827 6839 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 6840 6841 final int[] users = sUserManager.getUserIds(); 6842 for (int user : users) { 6843 try { 6844 mInstaller.clearAppData(volumeUuid, packageName, user, 6845 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 6846 } catch (InstallerException e) { 6847 Slog.w(TAG, "Failed to delete code cache directory", e); 6848 } 6849 } 6850 } 6851 6852 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6853 PackageParser.Package changingLib) { 6854 if (file.path != null) { 6855 usesLibraryFiles.add(file.path); 6856 return; 6857 } 6858 PackageParser.Package p = mPackages.get(file.apk); 6859 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6860 // If we are doing this while in the middle of updating a library apk, 6861 // then we need to make sure to use that new apk for determining the 6862 // dependencies here. (We haven't yet finished committing the new apk 6863 // to the package manager state.) 6864 if (p == null || p.packageName.equals(changingLib.packageName)) { 6865 p = changingLib; 6866 } 6867 } 6868 if (p != null) { 6869 usesLibraryFiles.addAll(p.getAllCodePaths()); 6870 } 6871 } 6872 6873 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6874 PackageParser.Package changingLib) throws PackageManagerException { 6875 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6876 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6877 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6878 for (int i=0; i<N; i++) { 6879 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6880 if (file == null) { 6881 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6882 "Package " + pkg.packageName + " requires unavailable shared library " 6883 + pkg.usesLibraries.get(i) + "; failing!"); 6884 } 6885 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6886 } 6887 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6888 for (int i=0; i<N; i++) { 6889 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6890 if (file == null) { 6891 Slog.w(TAG, "Package " + pkg.packageName 6892 + " desires unavailable shared library " 6893 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6894 } else { 6895 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6896 } 6897 } 6898 N = usesLibraryFiles.size(); 6899 if (N > 0) { 6900 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6901 } else { 6902 pkg.usesLibraryFiles = null; 6903 } 6904 } 6905 } 6906 6907 private static boolean hasString(List<String> list, List<String> which) { 6908 if (list == null) { 6909 return false; 6910 } 6911 for (int i=list.size()-1; i>=0; i--) { 6912 for (int j=which.size()-1; j>=0; j--) { 6913 if (which.get(j).equals(list.get(i))) { 6914 return true; 6915 } 6916 } 6917 } 6918 return false; 6919 } 6920 6921 private void updateAllSharedLibrariesLPw() { 6922 for (PackageParser.Package pkg : mPackages.values()) { 6923 try { 6924 updateSharedLibrariesLPw(pkg, null); 6925 } catch (PackageManagerException e) { 6926 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6927 } 6928 } 6929 } 6930 6931 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6932 PackageParser.Package changingPkg) { 6933 ArrayList<PackageParser.Package> res = null; 6934 for (PackageParser.Package pkg : mPackages.values()) { 6935 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6936 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6937 if (res == null) { 6938 res = new ArrayList<PackageParser.Package>(); 6939 } 6940 res.add(pkg); 6941 try { 6942 updateSharedLibrariesLPw(pkg, changingPkg); 6943 } catch (PackageManagerException e) { 6944 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6945 } 6946 } 6947 } 6948 return res; 6949 } 6950 6951 /** 6952 * Derive the value of the {@code cpuAbiOverride} based on the provided 6953 * value and an optional stored value from the package settings. 6954 */ 6955 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6956 String cpuAbiOverride = null; 6957 6958 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6959 cpuAbiOverride = null; 6960 } else if (abiOverride != null) { 6961 cpuAbiOverride = abiOverride; 6962 } else if (settings != null) { 6963 cpuAbiOverride = settings.cpuAbiOverrideString; 6964 } 6965 6966 return cpuAbiOverride; 6967 } 6968 6969 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6970 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6971 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6972 try { 6973 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6974 } finally { 6975 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6976 } 6977 } 6978 6979 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6980 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6981 boolean success = false; 6982 try { 6983 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6984 currentTime, user); 6985 success = true; 6986 return res; 6987 } finally { 6988 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6989 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6990 } 6991 } 6992 } 6993 6994 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6995 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6996 final File scanFile = new File(pkg.codePath); 6997 if (pkg.applicationInfo.getCodePath() == null || 6998 pkg.applicationInfo.getResourcePath() == null) { 6999 // Bail out. The resource and code paths haven't been set. 7000 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7001 "Code and resource paths haven't been set correctly"); 7002 } 7003 7004 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7005 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7006 } else { 7007 // Only allow system apps to be flagged as core apps. 7008 pkg.coreApp = false; 7009 } 7010 7011 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7012 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7013 } 7014 7015 if (mCustomResolverComponentName != null && 7016 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7017 setUpCustomResolverActivity(pkg); 7018 } 7019 7020 if (pkg.packageName.equals("android")) { 7021 synchronized (mPackages) { 7022 if (mAndroidApplication != null) { 7023 Slog.w(TAG, "*************************************************"); 7024 Slog.w(TAG, "Core android package being redefined. Skipping."); 7025 Slog.w(TAG, " file=" + scanFile); 7026 Slog.w(TAG, "*************************************************"); 7027 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7028 "Core android package being redefined. Skipping."); 7029 } 7030 7031 // Set up information for our fall-back user intent resolution activity. 7032 mPlatformPackage = pkg; 7033 pkg.mVersionCode = mSdkVersion; 7034 mAndroidApplication = pkg.applicationInfo; 7035 7036 if (!mResolverReplaced) { 7037 mResolveActivity.applicationInfo = mAndroidApplication; 7038 mResolveActivity.name = ResolverActivity.class.getName(); 7039 mResolveActivity.packageName = mAndroidApplication.packageName; 7040 mResolveActivity.processName = "system:ui"; 7041 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7042 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7043 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7044 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7045 mResolveActivity.exported = true; 7046 mResolveActivity.enabled = true; 7047 mResolveInfo.activityInfo = mResolveActivity; 7048 mResolveInfo.priority = 0; 7049 mResolveInfo.preferredOrder = 0; 7050 mResolveInfo.match = 0; 7051 mResolveComponentName = new ComponentName( 7052 mAndroidApplication.packageName, mResolveActivity.name); 7053 } 7054 } 7055 } 7056 7057 if (DEBUG_PACKAGE_SCANNING) { 7058 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7059 Log.d(TAG, "Scanning package " + pkg.packageName); 7060 } 7061 7062 if (mPackages.containsKey(pkg.packageName) 7063 || mSharedLibraries.containsKey(pkg.packageName)) { 7064 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7065 "Application package " + pkg.packageName 7066 + " already installed. Skipping duplicate."); 7067 } 7068 7069 // If we're only installing presumed-existing packages, require that the 7070 // scanned APK is both already known and at the path previously established 7071 // for it. Previously unknown packages we pick up normally, but if we have an 7072 // a priori expectation about this package's install presence, enforce it. 7073 // With a singular exception for new system packages. When an OTA contains 7074 // a new system package, we allow the codepath to change from a system location 7075 // to the user-installed location. If we don't allow this change, any newer, 7076 // user-installed version of the application will be ignored. 7077 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7078 if (mExpectingBetter.containsKey(pkg.packageName)) { 7079 logCriticalInfo(Log.WARN, 7080 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7081 } else { 7082 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7083 if (known != null) { 7084 if (DEBUG_PACKAGE_SCANNING) { 7085 Log.d(TAG, "Examining " + pkg.codePath 7086 + " and requiring known paths " + known.codePathString 7087 + " & " + known.resourcePathString); 7088 } 7089 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7090 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 7091 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7092 "Application package " + pkg.packageName 7093 + " found at " + pkg.applicationInfo.getCodePath() 7094 + " but expected at " + known.codePathString + "; ignoring."); 7095 } 7096 } 7097 } 7098 } 7099 7100 // Initialize package source and resource directories 7101 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7102 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7103 7104 SharedUserSetting suid = null; 7105 PackageSetting pkgSetting = null; 7106 7107 if (!isSystemApp(pkg)) { 7108 // Only system apps can use these features. 7109 pkg.mOriginalPackages = null; 7110 pkg.mRealPackage = null; 7111 pkg.mAdoptPermissions = null; 7112 } 7113 7114 // writer 7115 synchronized (mPackages) { 7116 if (pkg.mSharedUserId != null) { 7117 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7118 if (suid == null) { 7119 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7120 "Creating application package " + pkg.packageName 7121 + " for shared user failed"); 7122 } 7123 if (DEBUG_PACKAGE_SCANNING) { 7124 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7125 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7126 + "): packages=" + suid.packages); 7127 } 7128 } 7129 7130 // Check if we are renaming from an original package name. 7131 PackageSetting origPackage = null; 7132 String realName = null; 7133 if (pkg.mOriginalPackages != null) { 7134 // This package may need to be renamed to a previously 7135 // installed name. Let's check on that... 7136 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7137 if (pkg.mOriginalPackages.contains(renamed)) { 7138 // This package had originally been installed as the 7139 // original name, and we have already taken care of 7140 // transitioning to the new one. Just update the new 7141 // one to continue using the old name. 7142 realName = pkg.mRealPackage; 7143 if (!pkg.packageName.equals(renamed)) { 7144 // Callers into this function may have already taken 7145 // care of renaming the package; only do it here if 7146 // it is not already done. 7147 pkg.setPackageName(renamed); 7148 } 7149 7150 } else { 7151 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7152 if ((origPackage = mSettings.peekPackageLPr( 7153 pkg.mOriginalPackages.get(i))) != null) { 7154 // We do have the package already installed under its 7155 // original name... should we use it? 7156 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7157 // New package is not compatible with original. 7158 origPackage = null; 7159 continue; 7160 } else if (origPackage.sharedUser != null) { 7161 // Make sure uid is compatible between packages. 7162 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7163 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7164 + " to " + pkg.packageName + ": old uid " 7165 + origPackage.sharedUser.name 7166 + " differs from " + pkg.mSharedUserId); 7167 origPackage = null; 7168 continue; 7169 } 7170 } else { 7171 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7172 + pkg.packageName + " to old name " + origPackage.name); 7173 } 7174 break; 7175 } 7176 } 7177 } 7178 } 7179 7180 if (mTransferedPackages.contains(pkg.packageName)) { 7181 Slog.w(TAG, "Package " + pkg.packageName 7182 + " was transferred to another, but its .apk remains"); 7183 } 7184 7185 // Just create the setting, don't add it yet. For already existing packages 7186 // the PkgSetting exists already and doesn't have to be created. 7187 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7188 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7189 pkg.applicationInfo.primaryCpuAbi, 7190 pkg.applicationInfo.secondaryCpuAbi, 7191 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7192 user, false); 7193 if (pkgSetting == null) { 7194 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7195 "Creating application package " + pkg.packageName + " failed"); 7196 } 7197 7198 if (pkgSetting.origPackage != null) { 7199 // If we are first transitioning from an original package, 7200 // fix up the new package's name now. We need to do this after 7201 // looking up the package under its new name, so getPackageLP 7202 // can take care of fiddling things correctly. 7203 pkg.setPackageName(origPackage.name); 7204 7205 // File a report about this. 7206 String msg = "New package " + pkgSetting.realName 7207 + " renamed to replace old package " + pkgSetting.name; 7208 reportSettingsProblem(Log.WARN, msg); 7209 7210 // Make a note of it. 7211 mTransferedPackages.add(origPackage.name); 7212 7213 // No longer need to retain this. 7214 pkgSetting.origPackage = null; 7215 } 7216 7217 if (realName != null) { 7218 // Make a note of it. 7219 mTransferedPackages.add(pkg.packageName); 7220 } 7221 7222 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7223 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7224 } 7225 7226 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7227 // Check all shared libraries and map to their actual file path. 7228 // We only do this here for apps not on a system dir, because those 7229 // are the only ones that can fail an install due to this. We 7230 // will take care of the system apps by updating all of their 7231 // library paths after the scan is done. 7232 updateSharedLibrariesLPw(pkg, null); 7233 } 7234 7235 if (mFoundPolicyFile) { 7236 SELinuxMMAC.assignSeinfoValue(pkg); 7237 } 7238 7239 pkg.applicationInfo.uid = pkgSetting.appId; 7240 pkg.mExtras = pkgSetting; 7241 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7242 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7243 // We just determined the app is signed correctly, so bring 7244 // over the latest parsed certs. 7245 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7246 } else { 7247 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7248 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7249 "Package " + pkg.packageName + " upgrade keys do not match the " 7250 + "previously installed version"); 7251 } else { 7252 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7253 String msg = "System package " + pkg.packageName 7254 + " signature changed; retaining data."; 7255 reportSettingsProblem(Log.WARN, msg); 7256 } 7257 } 7258 } else { 7259 try { 7260 verifySignaturesLP(pkgSetting, pkg); 7261 // We just determined the app is signed correctly, so bring 7262 // over the latest parsed certs. 7263 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7264 } catch (PackageManagerException e) { 7265 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7266 throw e; 7267 } 7268 // The signature has changed, but this package is in the system 7269 // image... let's recover! 7270 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7271 // However... if this package is part of a shared user, but it 7272 // doesn't match the signature of the shared user, let's fail. 7273 // What this means is that you can't change the signatures 7274 // associated with an overall shared user, which doesn't seem all 7275 // that unreasonable. 7276 if (pkgSetting.sharedUser != null) { 7277 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7278 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7279 throw new PackageManagerException( 7280 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7281 "Signature mismatch for shared user: " 7282 + pkgSetting.sharedUser); 7283 } 7284 } 7285 // File a report about this. 7286 String msg = "System package " + pkg.packageName 7287 + " signature changed; retaining data."; 7288 reportSettingsProblem(Log.WARN, msg); 7289 } 7290 } 7291 // Verify that this new package doesn't have any content providers 7292 // that conflict with existing packages. Only do this if the 7293 // package isn't already installed, since we don't want to break 7294 // things that are installed. 7295 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7296 final int N = pkg.providers.size(); 7297 int i; 7298 for (i=0; i<N; i++) { 7299 PackageParser.Provider p = pkg.providers.get(i); 7300 if (p.info.authority != null) { 7301 String names[] = p.info.authority.split(";"); 7302 for (int j = 0; j < names.length; j++) { 7303 if (mProvidersByAuthority.containsKey(names[j])) { 7304 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7305 final String otherPackageName = 7306 ((other != null && other.getComponentName() != null) ? 7307 other.getComponentName().getPackageName() : "?"); 7308 throw new PackageManagerException( 7309 INSTALL_FAILED_CONFLICTING_PROVIDER, 7310 "Can't install because provider name " + names[j] 7311 + " (in package " + pkg.applicationInfo.packageName 7312 + ") is already used by " + otherPackageName); 7313 } 7314 } 7315 } 7316 } 7317 } 7318 7319 if (pkg.mAdoptPermissions != null) { 7320 // This package wants to adopt ownership of permissions from 7321 // another package. 7322 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7323 final String origName = pkg.mAdoptPermissions.get(i); 7324 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7325 if (orig != null) { 7326 if (verifyPackageUpdateLPr(orig, pkg)) { 7327 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7328 + pkg.packageName); 7329 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7330 } 7331 } 7332 } 7333 } 7334 } 7335 7336 final String pkgName = pkg.packageName; 7337 7338 final long scanFileTime = scanFile.lastModified(); 7339 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7340 pkg.applicationInfo.processName = fixProcessName( 7341 pkg.applicationInfo.packageName, 7342 pkg.applicationInfo.processName, 7343 pkg.applicationInfo.uid); 7344 7345 if (pkg != mPlatformPackage) { 7346 // Get all of our default paths setup 7347 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7348 } 7349 7350 final String path = scanFile.getPath(); 7351 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7352 7353 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7354 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7355 7356 // Some system apps still use directory structure for native libraries 7357 // in which case we might end up not detecting abi solely based on apk 7358 // structure. Try to detect abi based on directory structure. 7359 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7360 pkg.applicationInfo.primaryCpuAbi == null) { 7361 setBundledAppAbisAndRoots(pkg, pkgSetting); 7362 setNativeLibraryPaths(pkg); 7363 } 7364 7365 } else { 7366 if ((scanFlags & SCAN_MOVE) != 0) { 7367 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7368 // but we already have this packages package info in the PackageSetting. We just 7369 // use that and derive the native library path based on the new codepath. 7370 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7371 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7372 } 7373 7374 // Set native library paths again. For moves, the path will be updated based on the 7375 // ABIs we've determined above. For non-moves, the path will be updated based on the 7376 // ABIs we determined during compilation, but the path will depend on the final 7377 // package path (after the rename away from the stage path). 7378 setNativeLibraryPaths(pkg); 7379 } 7380 7381 // This is a special case for the "system" package, where the ABI is 7382 // dictated by the zygote configuration (and init.rc). We should keep track 7383 // of this ABI so that we can deal with "normal" applications that run under 7384 // the same UID correctly. 7385 if (mPlatformPackage == pkg) { 7386 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7387 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7388 } 7389 7390 // If there's a mismatch between the abi-override in the package setting 7391 // and the abiOverride specified for the install. Warn about this because we 7392 // would've already compiled the app without taking the package setting into 7393 // account. 7394 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7395 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7396 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7397 " for package " + pkg.packageName); 7398 } 7399 } 7400 7401 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7402 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7403 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7404 7405 // Copy the derived override back to the parsed package, so that we can 7406 // update the package settings accordingly. 7407 pkg.cpuAbiOverride = cpuAbiOverride; 7408 7409 if (DEBUG_ABI_SELECTION) { 7410 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7411 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7412 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7413 } 7414 7415 // Push the derived path down into PackageSettings so we know what to 7416 // clean up at uninstall time. 7417 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7418 7419 if (DEBUG_ABI_SELECTION) { 7420 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7421 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7422 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7423 } 7424 7425 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7426 // We don't do this here during boot because we can do it all 7427 // at once after scanning all existing packages. 7428 // 7429 // We also do this *before* we perform dexopt on this package, so that 7430 // we can avoid redundant dexopts, and also to make sure we've got the 7431 // code and package path correct. 7432 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7433 pkg, true /* boot complete */); 7434 } 7435 7436 if (mFactoryTest && pkg.requestedPermissions.contains( 7437 android.Manifest.permission.FACTORY_TEST)) { 7438 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7439 } 7440 7441 ArrayList<PackageParser.Package> clientLibPkgs = null; 7442 7443 // writer 7444 synchronized (mPackages) { 7445 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7446 // Only system apps can add new shared libraries. 7447 if (pkg.libraryNames != null) { 7448 for (int i=0; i<pkg.libraryNames.size(); i++) { 7449 String name = pkg.libraryNames.get(i); 7450 boolean allowed = false; 7451 if (pkg.isUpdatedSystemApp()) { 7452 // New library entries can only be added through the 7453 // system image. This is important to get rid of a lot 7454 // of nasty edge cases: for example if we allowed a non- 7455 // system update of the app to add a library, then uninstalling 7456 // the update would make the library go away, and assumptions 7457 // we made such as through app install filtering would now 7458 // have allowed apps on the device which aren't compatible 7459 // with it. Better to just have the restriction here, be 7460 // conservative, and create many fewer cases that can negatively 7461 // impact the user experience. 7462 final PackageSetting sysPs = mSettings 7463 .getDisabledSystemPkgLPr(pkg.packageName); 7464 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7465 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7466 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7467 allowed = true; 7468 break; 7469 } 7470 } 7471 } 7472 } else { 7473 allowed = true; 7474 } 7475 if (allowed) { 7476 if (!mSharedLibraries.containsKey(name)) { 7477 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7478 } else if (!name.equals(pkg.packageName)) { 7479 Slog.w(TAG, "Package " + pkg.packageName + " library " 7480 + name + " already exists; skipping"); 7481 } 7482 } else { 7483 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7484 + name + " that is not declared on system image; skipping"); 7485 } 7486 } 7487 if ((scanFlags & SCAN_BOOTING) == 0) { 7488 // If we are not booting, we need to update any applications 7489 // that are clients of our shared library. If we are booting, 7490 // this will all be done once the scan is complete. 7491 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7492 } 7493 } 7494 } 7495 } 7496 7497 // Request the ActivityManager to kill the process(only for existing packages) 7498 // so that we do not end up in a confused state while the user is still using the older 7499 // version of the application while the new one gets installed. 7500 if ((scanFlags & SCAN_REPLACING) != 0) { 7501 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7502 7503 killApplication(pkg.applicationInfo.packageName, 7504 pkg.applicationInfo.uid, "replace pkg"); 7505 7506 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7507 } 7508 7509 // Also need to kill any apps that are dependent on the library. 7510 if (clientLibPkgs != null) { 7511 for (int i=0; i<clientLibPkgs.size(); i++) { 7512 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7513 killApplication(clientPkg.applicationInfo.packageName, 7514 clientPkg.applicationInfo.uid, "update lib"); 7515 } 7516 } 7517 7518 // Make sure we're not adding any bogus keyset info 7519 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7520 ksms.assertScannedPackageValid(pkg); 7521 7522 // writer 7523 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7524 7525 boolean createIdmapFailed = false; 7526 synchronized (mPackages) { 7527 // We don't expect installation to fail beyond this point 7528 7529 // Add the new setting to mSettings 7530 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7531 // Add the new setting to mPackages 7532 mPackages.put(pkg.applicationInfo.packageName, pkg); 7533 // Make sure we don't accidentally delete its data. 7534 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7535 while (iter.hasNext()) { 7536 PackageCleanItem item = iter.next(); 7537 if (pkgName.equals(item.packageName)) { 7538 iter.remove(); 7539 } 7540 } 7541 7542 // Take care of first install / last update times. 7543 if (currentTime != 0) { 7544 if (pkgSetting.firstInstallTime == 0) { 7545 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7546 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7547 pkgSetting.lastUpdateTime = currentTime; 7548 } 7549 } else if (pkgSetting.firstInstallTime == 0) { 7550 // We need *something*. Take time time stamp of the file. 7551 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7552 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7553 if (scanFileTime != pkgSetting.timeStamp) { 7554 // A package on the system image has changed; consider this 7555 // to be an update. 7556 pkgSetting.lastUpdateTime = scanFileTime; 7557 } 7558 } 7559 7560 // Add the package's KeySets to the global KeySetManagerService 7561 ksms.addScannedPackageLPw(pkg); 7562 7563 int N = pkg.providers.size(); 7564 StringBuilder r = null; 7565 int i; 7566 for (i=0; i<N; i++) { 7567 PackageParser.Provider p = pkg.providers.get(i); 7568 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7569 p.info.processName, pkg.applicationInfo.uid); 7570 mProviders.addProvider(p); 7571 p.syncable = p.info.isSyncable; 7572 if (p.info.authority != null) { 7573 String names[] = p.info.authority.split(";"); 7574 p.info.authority = null; 7575 for (int j = 0; j < names.length; j++) { 7576 if (j == 1 && p.syncable) { 7577 // We only want the first authority for a provider to possibly be 7578 // syncable, so if we already added this provider using a different 7579 // authority clear the syncable flag. We copy the provider before 7580 // changing it because the mProviders object contains a reference 7581 // to a provider that we don't want to change. 7582 // Only do this for the second authority since the resulting provider 7583 // object can be the same for all future authorities for this provider. 7584 p = new PackageParser.Provider(p); 7585 p.syncable = false; 7586 } 7587 if (!mProvidersByAuthority.containsKey(names[j])) { 7588 mProvidersByAuthority.put(names[j], p); 7589 if (p.info.authority == null) { 7590 p.info.authority = names[j]; 7591 } else { 7592 p.info.authority = p.info.authority + ";" + names[j]; 7593 } 7594 if (DEBUG_PACKAGE_SCANNING) { 7595 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7596 Log.d(TAG, "Registered content provider: " + names[j] 7597 + ", className = " + p.info.name + ", isSyncable = " 7598 + p.info.isSyncable); 7599 } 7600 } else { 7601 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7602 Slog.w(TAG, "Skipping provider name " + names[j] + 7603 " (in package " + pkg.applicationInfo.packageName + 7604 "): name already used by " 7605 + ((other != null && other.getComponentName() != null) 7606 ? other.getComponentName().getPackageName() : "?")); 7607 } 7608 } 7609 } 7610 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7611 if (r == null) { 7612 r = new StringBuilder(256); 7613 } else { 7614 r.append(' '); 7615 } 7616 r.append(p.info.name); 7617 } 7618 } 7619 if (r != null) { 7620 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7621 } 7622 7623 N = pkg.services.size(); 7624 r = null; 7625 for (i=0; i<N; i++) { 7626 PackageParser.Service s = pkg.services.get(i); 7627 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7628 s.info.processName, pkg.applicationInfo.uid); 7629 mServices.addService(s); 7630 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7631 if (r == null) { 7632 r = new StringBuilder(256); 7633 } else { 7634 r.append(' '); 7635 } 7636 r.append(s.info.name); 7637 } 7638 } 7639 if (r != null) { 7640 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7641 } 7642 7643 N = pkg.receivers.size(); 7644 r = null; 7645 for (i=0; i<N; i++) { 7646 PackageParser.Activity a = pkg.receivers.get(i); 7647 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7648 a.info.processName, pkg.applicationInfo.uid); 7649 mReceivers.addActivity(a, "receiver"); 7650 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7651 if (r == null) { 7652 r = new StringBuilder(256); 7653 } else { 7654 r.append(' '); 7655 } 7656 r.append(a.info.name); 7657 } 7658 } 7659 if (r != null) { 7660 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7661 } 7662 7663 N = pkg.activities.size(); 7664 r = null; 7665 for (i=0; i<N; i++) { 7666 PackageParser.Activity a = pkg.activities.get(i); 7667 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7668 a.info.processName, pkg.applicationInfo.uid); 7669 mActivities.addActivity(a, "activity"); 7670 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7671 if (r == null) { 7672 r = new StringBuilder(256); 7673 } else { 7674 r.append(' '); 7675 } 7676 r.append(a.info.name); 7677 } 7678 } 7679 if (r != null) { 7680 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7681 } 7682 7683 N = pkg.permissionGroups.size(); 7684 r = null; 7685 for (i=0; i<N; i++) { 7686 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7687 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7688 if (cur == null) { 7689 mPermissionGroups.put(pg.info.name, pg); 7690 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7691 if (r == null) { 7692 r = new StringBuilder(256); 7693 } else { 7694 r.append(' '); 7695 } 7696 r.append(pg.info.name); 7697 } 7698 } else { 7699 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7700 + pg.info.packageName + " ignored: original from " 7701 + cur.info.packageName); 7702 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7703 if (r == null) { 7704 r = new StringBuilder(256); 7705 } else { 7706 r.append(' '); 7707 } 7708 r.append("DUP:"); 7709 r.append(pg.info.name); 7710 } 7711 } 7712 } 7713 if (r != null) { 7714 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7715 } 7716 7717 N = pkg.permissions.size(); 7718 r = null; 7719 for (i=0; i<N; i++) { 7720 PackageParser.Permission p = pkg.permissions.get(i); 7721 7722 // Assume by default that we did not install this permission into the system. 7723 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7724 7725 // Now that permission groups have a special meaning, we ignore permission 7726 // groups for legacy apps to prevent unexpected behavior. In particular, 7727 // permissions for one app being granted to someone just becuase they happen 7728 // to be in a group defined by another app (before this had no implications). 7729 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7730 p.group = mPermissionGroups.get(p.info.group); 7731 // Warn for a permission in an unknown group. 7732 if (p.info.group != null && p.group == null) { 7733 Slog.w(TAG, "Permission " + p.info.name + " from package " 7734 + p.info.packageName + " in an unknown group " + p.info.group); 7735 } 7736 } 7737 7738 ArrayMap<String, BasePermission> permissionMap = 7739 p.tree ? mSettings.mPermissionTrees 7740 : mSettings.mPermissions; 7741 BasePermission bp = permissionMap.get(p.info.name); 7742 7743 // Allow system apps to redefine non-system permissions 7744 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7745 final boolean currentOwnerIsSystem = (bp.perm != null 7746 && isSystemApp(bp.perm.owner)); 7747 if (isSystemApp(p.owner)) { 7748 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7749 // It's a built-in permission and no owner, take ownership now 7750 bp.packageSetting = pkgSetting; 7751 bp.perm = p; 7752 bp.uid = pkg.applicationInfo.uid; 7753 bp.sourcePackage = p.info.packageName; 7754 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7755 } else if (!currentOwnerIsSystem) { 7756 String msg = "New decl " + p.owner + " of permission " 7757 + p.info.name + " is system; overriding " + bp.sourcePackage; 7758 reportSettingsProblem(Log.WARN, msg); 7759 bp = null; 7760 } 7761 } 7762 } 7763 7764 if (bp == null) { 7765 bp = new BasePermission(p.info.name, p.info.packageName, 7766 BasePermission.TYPE_NORMAL); 7767 permissionMap.put(p.info.name, bp); 7768 } 7769 7770 if (bp.perm == null) { 7771 if (bp.sourcePackage == null 7772 || bp.sourcePackage.equals(p.info.packageName)) { 7773 BasePermission tree = findPermissionTreeLP(p.info.name); 7774 if (tree == null 7775 || tree.sourcePackage.equals(p.info.packageName)) { 7776 bp.packageSetting = pkgSetting; 7777 bp.perm = p; 7778 bp.uid = pkg.applicationInfo.uid; 7779 bp.sourcePackage = p.info.packageName; 7780 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7781 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7782 if (r == null) { 7783 r = new StringBuilder(256); 7784 } else { 7785 r.append(' '); 7786 } 7787 r.append(p.info.name); 7788 } 7789 } else { 7790 Slog.w(TAG, "Permission " + p.info.name + " from package " 7791 + p.info.packageName + " ignored: base tree " 7792 + tree.name + " is from package " 7793 + tree.sourcePackage); 7794 } 7795 } else { 7796 Slog.w(TAG, "Permission " + p.info.name + " from package " 7797 + p.info.packageName + " ignored: original from " 7798 + bp.sourcePackage); 7799 } 7800 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7801 if (r == null) { 7802 r = new StringBuilder(256); 7803 } else { 7804 r.append(' '); 7805 } 7806 r.append("DUP:"); 7807 r.append(p.info.name); 7808 } 7809 if (bp.perm == p) { 7810 bp.protectionLevel = p.info.protectionLevel; 7811 } 7812 } 7813 7814 if (r != null) { 7815 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7816 } 7817 7818 N = pkg.instrumentation.size(); 7819 r = null; 7820 for (i=0; i<N; i++) { 7821 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7822 a.info.packageName = pkg.applicationInfo.packageName; 7823 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7824 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7825 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7826 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7827 a.info.dataDir = pkg.applicationInfo.dataDir; 7828 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7829 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7830 7831 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7832 // need other information about the application, like the ABI and what not ? 7833 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7834 mInstrumentation.put(a.getComponentName(), a); 7835 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7836 if (r == null) { 7837 r = new StringBuilder(256); 7838 } else { 7839 r.append(' '); 7840 } 7841 r.append(a.info.name); 7842 } 7843 } 7844 if (r != null) { 7845 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7846 } 7847 7848 if (pkg.protectedBroadcasts != null) { 7849 N = pkg.protectedBroadcasts.size(); 7850 for (i=0; i<N; i++) { 7851 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7852 } 7853 } 7854 7855 pkgSetting.setTimeStamp(scanFileTime); 7856 7857 // Create idmap files for pairs of (packages, overlay packages). 7858 // Note: "android", ie framework-res.apk, is handled by native layers. 7859 if (pkg.mOverlayTarget != null) { 7860 // This is an overlay package. 7861 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7862 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7863 mOverlays.put(pkg.mOverlayTarget, 7864 new ArrayMap<String, PackageParser.Package>()); 7865 } 7866 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7867 map.put(pkg.packageName, pkg); 7868 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7869 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7870 createIdmapFailed = true; 7871 } 7872 } 7873 } else if (mOverlays.containsKey(pkg.packageName) && 7874 !pkg.packageName.equals("android")) { 7875 // This is a regular package, with one or more known overlay packages. 7876 createIdmapsForPackageLI(pkg); 7877 } 7878 } 7879 7880 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7881 7882 if (createIdmapFailed) { 7883 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7884 "scanPackageLI failed to createIdmap"); 7885 } 7886 return pkg; 7887 } 7888 7889 /** 7890 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7891 * is derived purely on the basis of the contents of {@code scanFile} and 7892 * {@code cpuAbiOverride}. 7893 * 7894 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7895 */ 7896 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7897 String cpuAbiOverride, boolean extractLibs) 7898 throws PackageManagerException { 7899 // TODO: We can probably be smarter about this stuff. For installed apps, 7900 // we can calculate this information at install time once and for all. For 7901 // system apps, we can probably assume that this information doesn't change 7902 // after the first boot scan. As things stand, we do lots of unnecessary work. 7903 7904 // Give ourselves some initial paths; we'll come back for another 7905 // pass once we've determined ABI below. 7906 setNativeLibraryPaths(pkg); 7907 7908 // We would never need to extract libs for forward-locked and external packages, 7909 // since the container service will do it for us. We shouldn't attempt to 7910 // extract libs from system app when it was not updated. 7911 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7912 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7913 extractLibs = false; 7914 } 7915 7916 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7917 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7918 7919 NativeLibraryHelper.Handle handle = null; 7920 try { 7921 handle = NativeLibraryHelper.Handle.create(pkg); 7922 // TODO(multiArch): This can be null for apps that didn't go through the 7923 // usual installation process. We can calculate it again, like we 7924 // do during install time. 7925 // 7926 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7927 // unnecessary. 7928 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7929 7930 // Null out the abis so that they can be recalculated. 7931 pkg.applicationInfo.primaryCpuAbi = null; 7932 pkg.applicationInfo.secondaryCpuAbi = null; 7933 if (isMultiArch(pkg.applicationInfo)) { 7934 // Warn if we've set an abiOverride for multi-lib packages.. 7935 // By definition, we need to copy both 32 and 64 bit libraries for 7936 // such packages. 7937 if (pkg.cpuAbiOverride != null 7938 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7939 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7940 } 7941 7942 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7943 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7944 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7945 if (extractLibs) { 7946 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7947 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7948 useIsaSpecificSubdirs); 7949 } else { 7950 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7951 } 7952 } 7953 7954 maybeThrowExceptionForMultiArchCopy( 7955 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7956 7957 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7958 if (extractLibs) { 7959 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7960 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7961 useIsaSpecificSubdirs); 7962 } else { 7963 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7964 } 7965 } 7966 7967 maybeThrowExceptionForMultiArchCopy( 7968 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7969 7970 if (abi64 >= 0) { 7971 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7972 } 7973 7974 if (abi32 >= 0) { 7975 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7976 if (abi64 >= 0) { 7977 pkg.applicationInfo.secondaryCpuAbi = abi; 7978 } else { 7979 pkg.applicationInfo.primaryCpuAbi = abi; 7980 } 7981 } 7982 } else { 7983 String[] abiList = (cpuAbiOverride != null) ? 7984 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7985 7986 // Enable gross and lame hacks for apps that are built with old 7987 // SDK tools. We must scan their APKs for renderscript bitcode and 7988 // not launch them if it's present. Don't bother checking on devices 7989 // that don't have 64 bit support. 7990 boolean needsRenderScriptOverride = false; 7991 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7992 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7993 abiList = Build.SUPPORTED_32_BIT_ABIS; 7994 needsRenderScriptOverride = true; 7995 } 7996 7997 final int copyRet; 7998 if (extractLibs) { 7999 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8000 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8001 } else { 8002 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8003 } 8004 8005 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8006 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8007 "Error unpackaging native libs for app, errorCode=" + copyRet); 8008 } 8009 8010 if (copyRet >= 0) { 8011 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8012 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8013 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8014 } else if (needsRenderScriptOverride) { 8015 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8016 } 8017 } 8018 } catch (IOException ioe) { 8019 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8020 } finally { 8021 IoUtils.closeQuietly(handle); 8022 } 8023 8024 // Now that we've calculated the ABIs and determined if it's an internal app, 8025 // we will go ahead and populate the nativeLibraryPath. 8026 setNativeLibraryPaths(pkg); 8027 } 8028 8029 /** 8030 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8031 * i.e, so that all packages can be run inside a single process if required. 8032 * 8033 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8034 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8035 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8036 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8037 * updating a package that belongs to a shared user. 8038 * 8039 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8040 * adds unnecessary complexity. 8041 */ 8042 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8043 PackageParser.Package scannedPackage, boolean bootComplete) { 8044 String requiredInstructionSet = null; 8045 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8046 requiredInstructionSet = VMRuntime.getInstructionSet( 8047 scannedPackage.applicationInfo.primaryCpuAbi); 8048 } 8049 8050 PackageSetting requirer = null; 8051 for (PackageSetting ps : packagesForUser) { 8052 // If packagesForUser contains scannedPackage, we skip it. This will happen 8053 // when scannedPackage is an update of an existing package. Without this check, 8054 // we will never be able to change the ABI of any package belonging to a shared 8055 // user, even if it's compatible with other packages. 8056 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8057 if (ps.primaryCpuAbiString == null) { 8058 continue; 8059 } 8060 8061 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8062 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8063 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8064 // this but there's not much we can do. 8065 String errorMessage = "Instruction set mismatch, " 8066 + ((requirer == null) ? "[caller]" : requirer) 8067 + " requires " + requiredInstructionSet + " whereas " + ps 8068 + " requires " + instructionSet; 8069 Slog.w(TAG, errorMessage); 8070 } 8071 8072 if (requiredInstructionSet == null) { 8073 requiredInstructionSet = instructionSet; 8074 requirer = ps; 8075 } 8076 } 8077 } 8078 8079 if (requiredInstructionSet != null) { 8080 String adjustedAbi; 8081 if (requirer != null) { 8082 // requirer != null implies that either scannedPackage was null or that scannedPackage 8083 // did not require an ABI, in which case we have to adjust scannedPackage to match 8084 // the ABI of the set (which is the same as requirer's ABI) 8085 adjustedAbi = requirer.primaryCpuAbiString; 8086 if (scannedPackage != null) { 8087 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8088 } 8089 } else { 8090 // requirer == null implies that we're updating all ABIs in the set to 8091 // match scannedPackage. 8092 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8093 } 8094 8095 for (PackageSetting ps : packagesForUser) { 8096 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8097 if (ps.primaryCpuAbiString != null) { 8098 continue; 8099 } 8100 8101 ps.primaryCpuAbiString = adjustedAbi; 8102 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 8103 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8104 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi); 8105 try { 8106 mInstaller.rmdex(ps.codePathString, 8107 getDexCodeInstructionSet(getPreferredInstructionSet())); 8108 } catch (InstallerException ignored) { 8109 } 8110 } 8111 } 8112 } 8113 } 8114 } 8115 8116 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8117 synchronized (mPackages) { 8118 mResolverReplaced = true; 8119 // Set up information for custom user intent resolution activity. 8120 mResolveActivity.applicationInfo = pkg.applicationInfo; 8121 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8122 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8123 mResolveActivity.processName = pkg.applicationInfo.packageName; 8124 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8125 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8126 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8127 mResolveActivity.theme = 0; 8128 mResolveActivity.exported = true; 8129 mResolveActivity.enabled = true; 8130 mResolveInfo.activityInfo = mResolveActivity; 8131 mResolveInfo.priority = 0; 8132 mResolveInfo.preferredOrder = 0; 8133 mResolveInfo.match = 0; 8134 mResolveComponentName = mCustomResolverComponentName; 8135 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8136 mResolveComponentName); 8137 } 8138 } 8139 8140 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8141 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8142 8143 // Set up information for ephemeral installer activity 8144 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8145 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8146 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8147 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8148 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8149 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8150 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8151 mEphemeralInstallerActivity.theme = 0; 8152 mEphemeralInstallerActivity.exported = true; 8153 mEphemeralInstallerActivity.enabled = true; 8154 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8155 mEphemeralInstallerInfo.priority = 0; 8156 mEphemeralInstallerInfo.preferredOrder = 0; 8157 mEphemeralInstallerInfo.match = 0; 8158 8159 if (DEBUG_EPHEMERAL) { 8160 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8161 } 8162 } 8163 8164 private static String calculateBundledApkRoot(final String codePathString) { 8165 final File codePath = new File(codePathString); 8166 final File codeRoot; 8167 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8168 codeRoot = Environment.getRootDirectory(); 8169 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8170 codeRoot = Environment.getOemDirectory(); 8171 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8172 codeRoot = Environment.getVendorDirectory(); 8173 } else { 8174 // Unrecognized code path; take its top real segment as the apk root: 8175 // e.g. /something/app/blah.apk => /something 8176 try { 8177 File f = codePath.getCanonicalFile(); 8178 File parent = f.getParentFile(); // non-null because codePath is a file 8179 File tmp; 8180 while ((tmp = parent.getParentFile()) != null) { 8181 f = parent; 8182 parent = tmp; 8183 } 8184 codeRoot = f; 8185 Slog.w(TAG, "Unrecognized code path " 8186 + codePath + " - using " + codeRoot); 8187 } catch (IOException e) { 8188 // Can't canonicalize the code path -- shenanigans? 8189 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8190 return Environment.getRootDirectory().getPath(); 8191 } 8192 } 8193 return codeRoot.getPath(); 8194 } 8195 8196 /** 8197 * Derive and set the location of native libraries for the given package, 8198 * which varies depending on where and how the package was installed. 8199 */ 8200 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8201 final ApplicationInfo info = pkg.applicationInfo; 8202 final String codePath = pkg.codePath; 8203 final File codeFile = new File(codePath); 8204 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8205 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8206 8207 info.nativeLibraryRootDir = null; 8208 info.nativeLibraryRootRequiresIsa = false; 8209 info.nativeLibraryDir = null; 8210 info.secondaryNativeLibraryDir = null; 8211 8212 if (isApkFile(codeFile)) { 8213 // Monolithic install 8214 if (bundledApp) { 8215 // If "/system/lib64/apkname" exists, assume that is the per-package 8216 // native library directory to use; otherwise use "/system/lib/apkname". 8217 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8218 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8219 getPrimaryInstructionSet(info)); 8220 8221 // This is a bundled system app so choose the path based on the ABI. 8222 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8223 // is just the default path. 8224 final String apkName = deriveCodePathName(codePath); 8225 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8226 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8227 apkName).getAbsolutePath(); 8228 8229 if (info.secondaryCpuAbi != null) { 8230 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8231 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8232 secondaryLibDir, apkName).getAbsolutePath(); 8233 } 8234 } else if (asecApp) { 8235 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8236 .getAbsolutePath(); 8237 } else { 8238 final String apkName = deriveCodePathName(codePath); 8239 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8240 .getAbsolutePath(); 8241 } 8242 8243 info.nativeLibraryRootRequiresIsa = false; 8244 info.nativeLibraryDir = info.nativeLibraryRootDir; 8245 } else { 8246 // Cluster install 8247 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8248 info.nativeLibraryRootRequiresIsa = true; 8249 8250 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8251 getPrimaryInstructionSet(info)).getAbsolutePath(); 8252 8253 if (info.secondaryCpuAbi != null) { 8254 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8255 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8256 } 8257 } 8258 } 8259 8260 /** 8261 * Calculate the abis and roots for a bundled app. These can uniquely 8262 * be determined from the contents of the system partition, i.e whether 8263 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8264 * of this information, and instead assume that the system was built 8265 * sensibly. 8266 */ 8267 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8268 PackageSetting pkgSetting) { 8269 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8270 8271 // If "/system/lib64/apkname" exists, assume that is the per-package 8272 // native library directory to use; otherwise use "/system/lib/apkname". 8273 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8274 setBundledAppAbi(pkg, apkRoot, apkName); 8275 // pkgSetting might be null during rescan following uninstall of updates 8276 // to a bundled app, so accommodate that possibility. The settings in 8277 // that case will be established later from the parsed package. 8278 // 8279 // If the settings aren't null, sync them up with what we've just derived. 8280 // note that apkRoot isn't stored in the package settings. 8281 if (pkgSetting != null) { 8282 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8283 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8284 } 8285 } 8286 8287 /** 8288 * Deduces the ABI of a bundled app and sets the relevant fields on the 8289 * parsed pkg object. 8290 * 8291 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8292 * under which system libraries are installed. 8293 * @param apkName the name of the installed package. 8294 */ 8295 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8296 final File codeFile = new File(pkg.codePath); 8297 8298 final boolean has64BitLibs; 8299 final boolean has32BitLibs; 8300 if (isApkFile(codeFile)) { 8301 // Monolithic install 8302 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8303 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8304 } else { 8305 // Cluster install 8306 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8307 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8308 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8309 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8310 has64BitLibs = (new File(rootDir, isa)).exists(); 8311 } else { 8312 has64BitLibs = false; 8313 } 8314 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8315 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8316 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8317 has32BitLibs = (new File(rootDir, isa)).exists(); 8318 } else { 8319 has32BitLibs = false; 8320 } 8321 } 8322 8323 if (has64BitLibs && !has32BitLibs) { 8324 // The package has 64 bit libs, but not 32 bit libs. Its primary 8325 // ABI should be 64 bit. We can safely assume here that the bundled 8326 // native libraries correspond to the most preferred ABI in the list. 8327 8328 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8329 pkg.applicationInfo.secondaryCpuAbi = null; 8330 } else if (has32BitLibs && !has64BitLibs) { 8331 // The package has 32 bit libs but not 64 bit libs. Its primary 8332 // ABI should be 32 bit. 8333 8334 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8335 pkg.applicationInfo.secondaryCpuAbi = null; 8336 } else if (has32BitLibs && has64BitLibs) { 8337 // The application has both 64 and 32 bit bundled libraries. We check 8338 // here that the app declares multiArch support, and warn if it doesn't. 8339 // 8340 // We will be lenient here and record both ABIs. The primary will be the 8341 // ABI that's higher on the list, i.e, a device that's configured to prefer 8342 // 64 bit apps will see a 64 bit primary ABI, 8343 8344 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8345 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8346 } 8347 8348 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8349 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8350 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8351 } else { 8352 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8353 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8354 } 8355 } else { 8356 pkg.applicationInfo.primaryCpuAbi = null; 8357 pkg.applicationInfo.secondaryCpuAbi = null; 8358 } 8359 } 8360 8361 private void killApplication(String pkgName, int appId, String reason) { 8362 // Request the ActivityManager to kill the process(only for existing packages) 8363 // so that we do not end up in a confused state while the user is still using the older 8364 // version of the application while the new one gets installed. 8365 IActivityManager am = ActivityManagerNative.getDefault(); 8366 if (am != null) { 8367 try { 8368 am.killApplicationWithAppId(pkgName, appId, reason); 8369 } catch (RemoteException e) { 8370 } 8371 } 8372 } 8373 8374 void removePackageLI(PackageSetting ps, boolean chatty) { 8375 if (DEBUG_INSTALL) { 8376 if (chatty) 8377 Log.d(TAG, "Removing package " + ps.name); 8378 } 8379 8380 // writer 8381 synchronized (mPackages) { 8382 mPackages.remove(ps.name); 8383 final PackageParser.Package pkg = ps.pkg; 8384 if (pkg != null) { 8385 cleanPackageDataStructuresLILPw(pkg, chatty); 8386 } 8387 } 8388 } 8389 8390 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8391 if (DEBUG_INSTALL) { 8392 if (chatty) 8393 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8394 } 8395 8396 // writer 8397 synchronized (mPackages) { 8398 mPackages.remove(pkg.applicationInfo.packageName); 8399 cleanPackageDataStructuresLILPw(pkg, chatty); 8400 } 8401 } 8402 8403 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8404 int N = pkg.providers.size(); 8405 StringBuilder r = null; 8406 int i; 8407 for (i=0; i<N; i++) { 8408 PackageParser.Provider p = pkg.providers.get(i); 8409 mProviders.removeProvider(p); 8410 if (p.info.authority == null) { 8411 8412 /* There was another ContentProvider with this authority when 8413 * this app was installed so this authority is null, 8414 * Ignore it as we don't have to unregister the provider. 8415 */ 8416 continue; 8417 } 8418 String names[] = p.info.authority.split(";"); 8419 for (int j = 0; j < names.length; j++) { 8420 if (mProvidersByAuthority.get(names[j]) == p) { 8421 mProvidersByAuthority.remove(names[j]); 8422 if (DEBUG_REMOVE) { 8423 if (chatty) 8424 Log.d(TAG, "Unregistered content provider: " + names[j] 8425 + ", className = " + p.info.name + ", isSyncable = " 8426 + p.info.isSyncable); 8427 } 8428 } 8429 } 8430 if (DEBUG_REMOVE && chatty) { 8431 if (r == null) { 8432 r = new StringBuilder(256); 8433 } else { 8434 r.append(' '); 8435 } 8436 r.append(p.info.name); 8437 } 8438 } 8439 if (r != null) { 8440 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8441 } 8442 8443 N = pkg.services.size(); 8444 r = null; 8445 for (i=0; i<N; i++) { 8446 PackageParser.Service s = pkg.services.get(i); 8447 mServices.removeService(s); 8448 if (chatty) { 8449 if (r == null) { 8450 r = new StringBuilder(256); 8451 } else { 8452 r.append(' '); 8453 } 8454 r.append(s.info.name); 8455 } 8456 } 8457 if (r != null) { 8458 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8459 } 8460 8461 N = pkg.receivers.size(); 8462 r = null; 8463 for (i=0; i<N; i++) { 8464 PackageParser.Activity a = pkg.receivers.get(i); 8465 mReceivers.removeActivity(a, "receiver"); 8466 if (DEBUG_REMOVE && chatty) { 8467 if (r == null) { 8468 r = new StringBuilder(256); 8469 } else { 8470 r.append(' '); 8471 } 8472 r.append(a.info.name); 8473 } 8474 } 8475 if (r != null) { 8476 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8477 } 8478 8479 N = pkg.activities.size(); 8480 r = null; 8481 for (i=0; i<N; i++) { 8482 PackageParser.Activity a = pkg.activities.get(i); 8483 mActivities.removeActivity(a, "activity"); 8484 if (DEBUG_REMOVE && chatty) { 8485 if (r == null) { 8486 r = new StringBuilder(256); 8487 } else { 8488 r.append(' '); 8489 } 8490 r.append(a.info.name); 8491 } 8492 } 8493 if (r != null) { 8494 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8495 } 8496 8497 N = pkg.permissions.size(); 8498 r = null; 8499 for (i=0; i<N; i++) { 8500 PackageParser.Permission p = pkg.permissions.get(i); 8501 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8502 if (bp == null) { 8503 bp = mSettings.mPermissionTrees.get(p.info.name); 8504 } 8505 if (bp != null && bp.perm == p) { 8506 bp.perm = null; 8507 if (DEBUG_REMOVE && chatty) { 8508 if (r == null) { 8509 r = new StringBuilder(256); 8510 } else { 8511 r.append(' '); 8512 } 8513 r.append(p.info.name); 8514 } 8515 } 8516 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8517 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8518 if (appOpPkgs != null) { 8519 appOpPkgs.remove(pkg.packageName); 8520 } 8521 } 8522 } 8523 if (r != null) { 8524 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8525 } 8526 8527 N = pkg.requestedPermissions.size(); 8528 r = null; 8529 for (i=0; i<N; i++) { 8530 String perm = pkg.requestedPermissions.get(i); 8531 BasePermission bp = mSettings.mPermissions.get(perm); 8532 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8533 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8534 if (appOpPkgs != null) { 8535 appOpPkgs.remove(pkg.packageName); 8536 if (appOpPkgs.isEmpty()) { 8537 mAppOpPermissionPackages.remove(perm); 8538 } 8539 } 8540 } 8541 } 8542 if (r != null) { 8543 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8544 } 8545 8546 N = pkg.instrumentation.size(); 8547 r = null; 8548 for (i=0; i<N; i++) { 8549 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8550 mInstrumentation.remove(a.getComponentName()); 8551 if (DEBUG_REMOVE && chatty) { 8552 if (r == null) { 8553 r = new StringBuilder(256); 8554 } else { 8555 r.append(' '); 8556 } 8557 r.append(a.info.name); 8558 } 8559 } 8560 if (r != null) { 8561 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8562 } 8563 8564 r = null; 8565 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8566 // Only system apps can hold shared libraries. 8567 if (pkg.libraryNames != null) { 8568 for (i=0; i<pkg.libraryNames.size(); i++) { 8569 String name = pkg.libraryNames.get(i); 8570 SharedLibraryEntry cur = mSharedLibraries.get(name); 8571 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8572 mSharedLibraries.remove(name); 8573 if (DEBUG_REMOVE && chatty) { 8574 if (r == null) { 8575 r = new StringBuilder(256); 8576 } else { 8577 r.append(' '); 8578 } 8579 r.append(name); 8580 } 8581 } 8582 } 8583 } 8584 } 8585 if (r != null) { 8586 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8587 } 8588 } 8589 8590 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8591 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8592 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8593 return true; 8594 } 8595 } 8596 return false; 8597 } 8598 8599 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8600 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8601 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8602 8603 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8604 int flags) { 8605 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8606 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8607 } 8608 8609 private void updatePermissionsLPw(String changingPkg, 8610 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8611 // Make sure there are no dangling permission trees. 8612 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8613 while (it.hasNext()) { 8614 final BasePermission bp = it.next(); 8615 if (bp.packageSetting == null) { 8616 // We may not yet have parsed the package, so just see if 8617 // we still know about its settings. 8618 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8619 } 8620 if (bp.packageSetting == null) { 8621 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8622 + " from package " + bp.sourcePackage); 8623 it.remove(); 8624 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8625 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8626 Slog.i(TAG, "Removing old permission tree: " + bp.name 8627 + " from package " + bp.sourcePackage); 8628 flags |= UPDATE_PERMISSIONS_ALL; 8629 it.remove(); 8630 } 8631 } 8632 } 8633 8634 // Make sure all dynamic permissions have been assigned to a package, 8635 // and make sure there are no dangling permissions. 8636 it = mSettings.mPermissions.values().iterator(); 8637 while (it.hasNext()) { 8638 final BasePermission bp = it.next(); 8639 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8640 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8641 + bp.name + " pkg=" + bp.sourcePackage 8642 + " info=" + bp.pendingInfo); 8643 if (bp.packageSetting == null && bp.pendingInfo != null) { 8644 final BasePermission tree = findPermissionTreeLP(bp.name); 8645 if (tree != null && tree.perm != null) { 8646 bp.packageSetting = tree.packageSetting; 8647 bp.perm = new PackageParser.Permission(tree.perm.owner, 8648 new PermissionInfo(bp.pendingInfo)); 8649 bp.perm.info.packageName = tree.perm.info.packageName; 8650 bp.perm.info.name = bp.name; 8651 bp.uid = tree.uid; 8652 } 8653 } 8654 } 8655 if (bp.packageSetting == null) { 8656 // We may not yet have parsed the package, so just see if 8657 // we still know about its settings. 8658 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8659 } 8660 if (bp.packageSetting == null) { 8661 Slog.w(TAG, "Removing dangling permission: " + bp.name 8662 + " from package " + bp.sourcePackage); 8663 it.remove(); 8664 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8665 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8666 Slog.i(TAG, "Removing old permission: " + bp.name 8667 + " from package " + bp.sourcePackage); 8668 flags |= UPDATE_PERMISSIONS_ALL; 8669 it.remove(); 8670 } 8671 } 8672 } 8673 8674 // Now update the permissions for all packages, in particular 8675 // replace the granted permissions of the system packages. 8676 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8677 for (PackageParser.Package pkg : mPackages.values()) { 8678 if (pkg != pkgInfo) { 8679 // Only replace for packages on requested volume 8680 final String volumeUuid = getVolumeUuidForPackage(pkg); 8681 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8682 && Objects.equals(replaceVolumeUuid, volumeUuid); 8683 grantPermissionsLPw(pkg, replace, changingPkg); 8684 } 8685 } 8686 } 8687 8688 if (pkgInfo != null) { 8689 // Only replace for packages on requested volume 8690 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8691 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8692 && Objects.equals(replaceVolumeUuid, volumeUuid); 8693 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8694 } 8695 } 8696 8697 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8698 String packageOfInterest) { 8699 // IMPORTANT: There are two types of permissions: install and runtime. 8700 // Install time permissions are granted when the app is installed to 8701 // all device users and users added in the future. Runtime permissions 8702 // are granted at runtime explicitly to specific users. Normal and signature 8703 // protected permissions are install time permissions. Dangerous permissions 8704 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8705 // otherwise they are runtime permissions. This function does not manage 8706 // runtime permissions except for the case an app targeting Lollipop MR1 8707 // being upgraded to target a newer SDK, in which case dangerous permissions 8708 // are transformed from install time to runtime ones. 8709 8710 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8711 if (ps == null) { 8712 return; 8713 } 8714 8715 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8716 8717 PermissionsState permissionsState = ps.getPermissionsState(); 8718 PermissionsState origPermissions = permissionsState; 8719 8720 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8721 8722 boolean runtimePermissionsRevoked = false; 8723 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8724 8725 boolean changedInstallPermission = false; 8726 8727 if (replace) { 8728 ps.installPermissionsFixed = false; 8729 if (!ps.isSharedUser()) { 8730 origPermissions = new PermissionsState(permissionsState); 8731 permissionsState.reset(); 8732 } else { 8733 // We need to know only about runtime permission changes since the 8734 // calling code always writes the install permissions state but 8735 // the runtime ones are written only if changed. The only cases of 8736 // changed runtime permissions here are promotion of an install to 8737 // runtime and revocation of a runtime from a shared user. 8738 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8739 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8740 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8741 runtimePermissionsRevoked = true; 8742 } 8743 } 8744 } 8745 8746 permissionsState.setGlobalGids(mGlobalGids); 8747 8748 final int N = pkg.requestedPermissions.size(); 8749 for (int i=0; i<N; i++) { 8750 final String name = pkg.requestedPermissions.get(i); 8751 final BasePermission bp = mSettings.mPermissions.get(name); 8752 8753 if (DEBUG_INSTALL) { 8754 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8755 } 8756 8757 if (bp == null || bp.packageSetting == null) { 8758 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8759 Slog.w(TAG, "Unknown permission " + name 8760 + " in package " + pkg.packageName); 8761 } 8762 continue; 8763 } 8764 8765 final String perm = bp.name; 8766 boolean allowedSig = false; 8767 int grant = GRANT_DENIED; 8768 8769 // Keep track of app op permissions. 8770 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8771 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8772 if (pkgs == null) { 8773 pkgs = new ArraySet<>(); 8774 mAppOpPermissionPackages.put(bp.name, pkgs); 8775 } 8776 pkgs.add(pkg.packageName); 8777 } 8778 8779 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8780 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8781 >= Build.VERSION_CODES.M; 8782 switch (level) { 8783 case PermissionInfo.PROTECTION_NORMAL: { 8784 // For all apps normal permissions are install time ones. 8785 grant = GRANT_INSTALL; 8786 } break; 8787 8788 case PermissionInfo.PROTECTION_DANGEROUS: { 8789 // If a permission review is required for legacy apps we represent 8790 // their permissions as always granted runtime ones since we need 8791 // to keep the review required permission flag per user while an 8792 // install permission's state is shared across all users. 8793 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8794 // For legacy apps dangerous permissions are install time ones. 8795 grant = GRANT_INSTALL; 8796 } else if (origPermissions.hasInstallPermission(bp.name)) { 8797 // For legacy apps that became modern, install becomes runtime. 8798 grant = GRANT_UPGRADE; 8799 } else if (mPromoteSystemApps 8800 && isSystemApp(ps) 8801 && mExistingSystemPackages.contains(ps.name)) { 8802 // For legacy system apps, install becomes runtime. 8803 // We cannot check hasInstallPermission() for system apps since those 8804 // permissions were granted implicitly and not persisted pre-M. 8805 grant = GRANT_UPGRADE; 8806 } else { 8807 // For modern apps keep runtime permissions unchanged. 8808 grant = GRANT_RUNTIME; 8809 } 8810 } break; 8811 8812 case PermissionInfo.PROTECTION_SIGNATURE: { 8813 // For all apps signature permissions are install time ones. 8814 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8815 if (allowedSig) { 8816 grant = GRANT_INSTALL; 8817 } 8818 } break; 8819 } 8820 8821 if (DEBUG_INSTALL) { 8822 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8823 } 8824 8825 if (grant != GRANT_DENIED) { 8826 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8827 // If this is an existing, non-system package, then 8828 // we can't add any new permissions to it. 8829 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8830 // Except... if this is a permission that was added 8831 // to the platform (note: need to only do this when 8832 // updating the platform). 8833 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8834 grant = GRANT_DENIED; 8835 } 8836 } 8837 } 8838 8839 switch (grant) { 8840 case GRANT_INSTALL: { 8841 // Revoke this as runtime permission to handle the case of 8842 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8843 for (int userId : UserManagerService.getInstance().getUserIds()) { 8844 if (origPermissions.getRuntimePermissionState( 8845 bp.name, userId) != null) { 8846 // Revoke the runtime permission and clear the flags. 8847 origPermissions.revokeRuntimePermission(bp, userId); 8848 origPermissions.updatePermissionFlags(bp, userId, 8849 PackageManager.MASK_PERMISSION_FLAGS, 0); 8850 // If we revoked a permission permission, we have to write. 8851 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8852 changedRuntimePermissionUserIds, userId); 8853 } 8854 } 8855 // Grant an install permission. 8856 if (permissionsState.grantInstallPermission(bp) != 8857 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8858 changedInstallPermission = true; 8859 } 8860 } break; 8861 8862 case GRANT_RUNTIME: { 8863 // Grant previously granted runtime permissions. 8864 for (int userId : UserManagerService.getInstance().getUserIds()) { 8865 PermissionState permissionState = origPermissions 8866 .getRuntimePermissionState(bp.name, userId); 8867 int flags = permissionState != null 8868 ? permissionState.getFlags() : 0; 8869 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8870 if (permissionsState.grantRuntimePermission(bp, userId) == 8871 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8872 // If we cannot put the permission as it was, we have to write. 8873 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8874 changedRuntimePermissionUserIds, userId); 8875 } 8876 // If the app supports runtime permissions no need for a review. 8877 if (Build.PERMISSIONS_REVIEW_REQUIRED 8878 && appSupportsRuntimePermissions 8879 && (flags & PackageManager 8880 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8881 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8882 // Since we changed the flags, we have to write. 8883 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8884 changedRuntimePermissionUserIds, userId); 8885 } 8886 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8887 && !appSupportsRuntimePermissions) { 8888 // For legacy apps that need a permission review, every new 8889 // runtime permission is granted but it is pending a review. 8890 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8891 permissionsState.grantRuntimePermission(bp, userId); 8892 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8893 // We changed the permission and flags, hence have to write. 8894 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8895 changedRuntimePermissionUserIds, userId); 8896 } 8897 } 8898 // Propagate the permission flags. 8899 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8900 } 8901 } break; 8902 8903 case GRANT_UPGRADE: { 8904 // Grant runtime permissions for a previously held install permission. 8905 PermissionState permissionState = origPermissions 8906 .getInstallPermissionState(bp.name); 8907 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8908 8909 if (origPermissions.revokeInstallPermission(bp) 8910 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8911 // We will be transferring the permission flags, so clear them. 8912 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8913 PackageManager.MASK_PERMISSION_FLAGS, 0); 8914 changedInstallPermission = true; 8915 } 8916 8917 // If the permission is not to be promoted to runtime we ignore it and 8918 // also its other flags as they are not applicable to install permissions. 8919 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8920 for (int userId : currentUserIds) { 8921 if (permissionsState.grantRuntimePermission(bp, userId) != 8922 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8923 // Transfer the permission flags. 8924 permissionsState.updatePermissionFlags(bp, userId, 8925 flags, flags); 8926 // If we granted the permission, we have to write. 8927 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8928 changedRuntimePermissionUserIds, userId); 8929 } 8930 } 8931 } 8932 } break; 8933 8934 default: { 8935 if (packageOfInterest == null 8936 || packageOfInterest.equals(pkg.packageName)) { 8937 Slog.w(TAG, "Not granting permission " + perm 8938 + " to package " + pkg.packageName 8939 + " because it was previously installed without"); 8940 } 8941 } break; 8942 } 8943 } else { 8944 if (permissionsState.revokeInstallPermission(bp) != 8945 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8946 // Also drop the permission flags. 8947 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8948 PackageManager.MASK_PERMISSION_FLAGS, 0); 8949 changedInstallPermission = true; 8950 Slog.i(TAG, "Un-granting permission " + perm 8951 + " from package " + pkg.packageName 8952 + " (protectionLevel=" + bp.protectionLevel 8953 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8954 + ")"); 8955 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8956 // Don't print warning for app op permissions, since it is fine for them 8957 // not to be granted, there is a UI for the user to decide. 8958 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8959 Slog.w(TAG, "Not granting permission " + perm 8960 + " to package " + pkg.packageName 8961 + " (protectionLevel=" + bp.protectionLevel 8962 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8963 + ")"); 8964 } 8965 } 8966 } 8967 } 8968 8969 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8970 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8971 // This is the first that we have heard about this package, so the 8972 // permissions we have now selected are fixed until explicitly 8973 // changed. 8974 ps.installPermissionsFixed = true; 8975 } 8976 8977 // Persist the runtime permissions state for users with changes. If permissions 8978 // were revoked because no app in the shared user declares them we have to 8979 // write synchronously to avoid losing runtime permissions state. 8980 for (int userId : changedRuntimePermissionUserIds) { 8981 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8982 } 8983 8984 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8985 } 8986 8987 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8988 boolean allowed = false; 8989 final int NP = PackageParser.NEW_PERMISSIONS.length; 8990 for (int ip=0; ip<NP; ip++) { 8991 final PackageParser.NewPermissionInfo npi 8992 = PackageParser.NEW_PERMISSIONS[ip]; 8993 if (npi.name.equals(perm) 8994 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8995 allowed = true; 8996 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8997 + pkg.packageName); 8998 break; 8999 } 9000 } 9001 return allowed; 9002 } 9003 9004 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9005 BasePermission bp, PermissionsState origPermissions) { 9006 boolean allowed; 9007 allowed = (compareSignatures( 9008 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9009 == PackageManager.SIGNATURE_MATCH) 9010 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9011 == PackageManager.SIGNATURE_MATCH); 9012 if (!allowed && (bp.protectionLevel 9013 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9014 if (isSystemApp(pkg)) { 9015 // For updated system applications, a system permission 9016 // is granted only if it had been defined by the original application. 9017 if (pkg.isUpdatedSystemApp()) { 9018 final PackageSetting sysPs = mSettings 9019 .getDisabledSystemPkgLPr(pkg.packageName); 9020 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 9021 // If the original was granted this permission, we take 9022 // that grant decision as read and propagate it to the 9023 // update. 9024 if (sysPs.isPrivileged()) { 9025 allowed = true; 9026 } 9027 } else { 9028 // The system apk may have been updated with an older 9029 // version of the one on the data partition, but which 9030 // granted a new system permission that it didn't have 9031 // before. In this case we do want to allow the app to 9032 // now get the new permission if the ancestral apk is 9033 // privileged to get it. 9034 if (sysPs.pkg != null && sysPs.isPrivileged()) { 9035 for (int j=0; 9036 j<sysPs.pkg.requestedPermissions.size(); j++) { 9037 if (perm.equals( 9038 sysPs.pkg.requestedPermissions.get(j))) { 9039 allowed = true; 9040 break; 9041 } 9042 } 9043 } 9044 } 9045 } else { 9046 allowed = isPrivilegedApp(pkg); 9047 } 9048 } 9049 } 9050 if (!allowed) { 9051 if (!allowed && (bp.protectionLevel 9052 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9053 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9054 // If this was a previously normal/dangerous permission that got moved 9055 // to a system permission as part of the runtime permission redesign, then 9056 // we still want to blindly grant it to old apps. 9057 allowed = true; 9058 } 9059 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9060 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9061 // If this permission is to be granted to the system installer and 9062 // this app is an installer, then it gets the permission. 9063 allowed = true; 9064 } 9065 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9066 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9067 // If this permission is to be granted to the system verifier and 9068 // this app is a verifier, then it gets the permission. 9069 allowed = true; 9070 } 9071 if (!allowed && (bp.protectionLevel 9072 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9073 && isSystemApp(pkg)) { 9074 // Any pre-installed system app is allowed to get this permission. 9075 allowed = true; 9076 } 9077 if (!allowed && (bp.protectionLevel 9078 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9079 // For development permissions, a development permission 9080 // is granted only if it was already granted. 9081 allowed = origPermissions.hasInstallPermission(perm); 9082 } 9083 } 9084 return allowed; 9085 } 9086 9087 final class ActivityIntentResolver 9088 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9089 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9090 boolean defaultOnly, int userId) { 9091 if (!sUserManager.exists(userId)) return null; 9092 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9093 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9094 } 9095 9096 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9097 int userId) { 9098 if (!sUserManager.exists(userId)) return null; 9099 mFlags = flags; 9100 return super.queryIntent(intent, resolvedType, 9101 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9102 } 9103 9104 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9105 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9106 if (!sUserManager.exists(userId)) return null; 9107 if (packageActivities == null) { 9108 return null; 9109 } 9110 mFlags = flags; 9111 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9112 final int N = packageActivities.size(); 9113 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9114 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9115 9116 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9117 for (int i = 0; i < N; ++i) { 9118 intentFilters = packageActivities.get(i).intents; 9119 if (intentFilters != null && intentFilters.size() > 0) { 9120 PackageParser.ActivityIntentInfo[] array = 9121 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9122 intentFilters.toArray(array); 9123 listCut.add(array); 9124 } 9125 } 9126 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9127 } 9128 9129 public final void addActivity(PackageParser.Activity a, String type) { 9130 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9131 mActivities.put(a.getComponentName(), a); 9132 if (DEBUG_SHOW_INFO) 9133 Log.v( 9134 TAG, " " + type + " " + 9135 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9136 if (DEBUG_SHOW_INFO) 9137 Log.v(TAG, " Class=" + a.info.name); 9138 final int NI = a.intents.size(); 9139 for (int j=0; j<NI; j++) { 9140 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9141 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9142 intent.setPriority(0); 9143 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9144 + a.className + " with priority > 0, forcing to 0"); 9145 } 9146 if (DEBUG_SHOW_INFO) { 9147 Log.v(TAG, " IntentFilter:"); 9148 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9149 } 9150 if (!intent.debugCheck()) { 9151 Log.w(TAG, "==> For Activity " + a.info.name); 9152 } 9153 addFilter(intent); 9154 } 9155 } 9156 9157 public final void removeActivity(PackageParser.Activity a, String type) { 9158 mActivities.remove(a.getComponentName()); 9159 if (DEBUG_SHOW_INFO) { 9160 Log.v(TAG, " " + type + " " 9161 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9162 : a.info.name) + ":"); 9163 Log.v(TAG, " Class=" + a.info.name); 9164 } 9165 final int NI = a.intents.size(); 9166 for (int j=0; j<NI; j++) { 9167 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9168 if (DEBUG_SHOW_INFO) { 9169 Log.v(TAG, " IntentFilter:"); 9170 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9171 } 9172 removeFilter(intent); 9173 } 9174 } 9175 9176 @Override 9177 protected boolean allowFilterResult( 9178 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9179 ActivityInfo filterAi = filter.activity.info; 9180 for (int i=dest.size()-1; i>=0; i--) { 9181 ActivityInfo destAi = dest.get(i).activityInfo; 9182 if (destAi.name == filterAi.name 9183 && destAi.packageName == filterAi.packageName) { 9184 return false; 9185 } 9186 } 9187 return true; 9188 } 9189 9190 @Override 9191 protected ActivityIntentInfo[] newArray(int size) { 9192 return new ActivityIntentInfo[size]; 9193 } 9194 9195 @Override 9196 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9197 if (!sUserManager.exists(userId)) return true; 9198 PackageParser.Package p = filter.activity.owner; 9199 if (p != null) { 9200 PackageSetting ps = (PackageSetting)p.mExtras; 9201 if (ps != null) { 9202 // System apps are never considered stopped for purposes of 9203 // filtering, because there may be no way for the user to 9204 // actually re-launch them. 9205 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9206 && ps.getStopped(userId); 9207 } 9208 } 9209 return false; 9210 } 9211 9212 @Override 9213 protected boolean isPackageForFilter(String packageName, 9214 PackageParser.ActivityIntentInfo info) { 9215 return packageName.equals(info.activity.owner.packageName); 9216 } 9217 9218 @Override 9219 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9220 int match, int userId) { 9221 if (!sUserManager.exists(userId)) return null; 9222 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9223 return null; 9224 } 9225 final PackageParser.Activity activity = info.activity; 9226 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9227 if (ps == null) { 9228 return null; 9229 } 9230 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9231 ps.readUserState(userId), userId); 9232 if (ai == null) { 9233 return null; 9234 } 9235 final ResolveInfo res = new ResolveInfo(); 9236 res.activityInfo = ai; 9237 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9238 res.filter = info; 9239 } 9240 if (info != null) { 9241 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9242 } 9243 res.priority = info.getPriority(); 9244 res.preferredOrder = activity.owner.mPreferredOrder; 9245 //System.out.println("Result: " + res.activityInfo.className + 9246 // " = " + res.priority); 9247 res.match = match; 9248 res.isDefault = info.hasDefault; 9249 res.labelRes = info.labelRes; 9250 res.nonLocalizedLabel = info.nonLocalizedLabel; 9251 if (userNeedsBadging(userId)) { 9252 res.noResourceId = true; 9253 } else { 9254 res.icon = info.icon; 9255 } 9256 res.iconResourceId = info.icon; 9257 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9258 return res; 9259 } 9260 9261 @Override 9262 protected void sortResults(List<ResolveInfo> results) { 9263 Collections.sort(results, mResolvePrioritySorter); 9264 } 9265 9266 @Override 9267 protected void dumpFilter(PrintWriter out, String prefix, 9268 PackageParser.ActivityIntentInfo filter) { 9269 out.print(prefix); out.print( 9270 Integer.toHexString(System.identityHashCode(filter.activity))); 9271 out.print(' '); 9272 filter.activity.printComponentShortName(out); 9273 out.print(" filter "); 9274 out.println(Integer.toHexString(System.identityHashCode(filter))); 9275 } 9276 9277 @Override 9278 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9279 return filter.activity; 9280 } 9281 9282 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9283 PackageParser.Activity activity = (PackageParser.Activity)label; 9284 out.print(prefix); out.print( 9285 Integer.toHexString(System.identityHashCode(activity))); 9286 out.print(' '); 9287 activity.printComponentShortName(out); 9288 if (count > 1) { 9289 out.print(" ("); out.print(count); out.print(" filters)"); 9290 } 9291 out.println(); 9292 } 9293 9294// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9295// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9296// final List<ResolveInfo> retList = Lists.newArrayList(); 9297// while (i.hasNext()) { 9298// final ResolveInfo resolveInfo = i.next(); 9299// if (isEnabledLP(resolveInfo.activityInfo)) { 9300// retList.add(resolveInfo); 9301// } 9302// } 9303// return retList; 9304// } 9305 9306 // Keys are String (activity class name), values are Activity. 9307 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9308 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9309 private int mFlags; 9310 } 9311 9312 private final class ServiceIntentResolver 9313 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9314 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9315 boolean defaultOnly, int userId) { 9316 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9317 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9318 } 9319 9320 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9321 int userId) { 9322 if (!sUserManager.exists(userId)) return null; 9323 mFlags = flags; 9324 return super.queryIntent(intent, resolvedType, 9325 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9326 } 9327 9328 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9329 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9330 if (!sUserManager.exists(userId)) return null; 9331 if (packageServices == null) { 9332 return null; 9333 } 9334 mFlags = flags; 9335 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9336 final int N = packageServices.size(); 9337 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9338 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9339 9340 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9341 for (int i = 0; i < N; ++i) { 9342 intentFilters = packageServices.get(i).intents; 9343 if (intentFilters != null && intentFilters.size() > 0) { 9344 PackageParser.ServiceIntentInfo[] array = 9345 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9346 intentFilters.toArray(array); 9347 listCut.add(array); 9348 } 9349 } 9350 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9351 } 9352 9353 public final void addService(PackageParser.Service s) { 9354 mServices.put(s.getComponentName(), s); 9355 if (DEBUG_SHOW_INFO) { 9356 Log.v(TAG, " " 9357 + (s.info.nonLocalizedLabel != null 9358 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9359 Log.v(TAG, " Class=" + s.info.name); 9360 } 9361 final int NI = s.intents.size(); 9362 int j; 9363 for (j=0; j<NI; j++) { 9364 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9365 if (DEBUG_SHOW_INFO) { 9366 Log.v(TAG, " IntentFilter:"); 9367 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9368 } 9369 if (!intent.debugCheck()) { 9370 Log.w(TAG, "==> For Service " + s.info.name); 9371 } 9372 addFilter(intent); 9373 } 9374 } 9375 9376 public final void removeService(PackageParser.Service s) { 9377 mServices.remove(s.getComponentName()); 9378 if (DEBUG_SHOW_INFO) { 9379 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9380 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9381 Log.v(TAG, " Class=" + s.info.name); 9382 } 9383 final int NI = s.intents.size(); 9384 int j; 9385 for (j=0; j<NI; j++) { 9386 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9387 if (DEBUG_SHOW_INFO) { 9388 Log.v(TAG, " IntentFilter:"); 9389 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9390 } 9391 removeFilter(intent); 9392 } 9393 } 9394 9395 @Override 9396 protected boolean allowFilterResult( 9397 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9398 ServiceInfo filterSi = filter.service.info; 9399 for (int i=dest.size()-1; i>=0; i--) { 9400 ServiceInfo destAi = dest.get(i).serviceInfo; 9401 if (destAi.name == filterSi.name 9402 && destAi.packageName == filterSi.packageName) { 9403 return false; 9404 } 9405 } 9406 return true; 9407 } 9408 9409 @Override 9410 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9411 return new PackageParser.ServiceIntentInfo[size]; 9412 } 9413 9414 @Override 9415 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9416 if (!sUserManager.exists(userId)) return true; 9417 PackageParser.Package p = filter.service.owner; 9418 if (p != null) { 9419 PackageSetting ps = (PackageSetting)p.mExtras; 9420 if (ps != null) { 9421 // System apps are never considered stopped for purposes of 9422 // filtering, because there may be no way for the user to 9423 // actually re-launch them. 9424 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9425 && ps.getStopped(userId); 9426 } 9427 } 9428 return false; 9429 } 9430 9431 @Override 9432 protected boolean isPackageForFilter(String packageName, 9433 PackageParser.ServiceIntentInfo info) { 9434 return packageName.equals(info.service.owner.packageName); 9435 } 9436 9437 @Override 9438 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9439 int match, int userId) { 9440 if (!sUserManager.exists(userId)) return null; 9441 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9442 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9443 return null; 9444 } 9445 final PackageParser.Service service = info.service; 9446 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9447 if (ps == null) { 9448 return null; 9449 } 9450 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9451 ps.readUserState(userId), userId); 9452 if (si == null) { 9453 return null; 9454 } 9455 final ResolveInfo res = new ResolveInfo(); 9456 res.serviceInfo = si; 9457 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9458 res.filter = filter; 9459 } 9460 res.priority = info.getPriority(); 9461 res.preferredOrder = service.owner.mPreferredOrder; 9462 res.match = match; 9463 res.isDefault = info.hasDefault; 9464 res.labelRes = info.labelRes; 9465 res.nonLocalizedLabel = info.nonLocalizedLabel; 9466 res.icon = info.icon; 9467 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9468 return res; 9469 } 9470 9471 @Override 9472 protected void sortResults(List<ResolveInfo> results) { 9473 Collections.sort(results, mResolvePrioritySorter); 9474 } 9475 9476 @Override 9477 protected void dumpFilter(PrintWriter out, String prefix, 9478 PackageParser.ServiceIntentInfo filter) { 9479 out.print(prefix); out.print( 9480 Integer.toHexString(System.identityHashCode(filter.service))); 9481 out.print(' '); 9482 filter.service.printComponentShortName(out); 9483 out.print(" filter "); 9484 out.println(Integer.toHexString(System.identityHashCode(filter))); 9485 } 9486 9487 @Override 9488 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9489 return filter.service; 9490 } 9491 9492 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9493 PackageParser.Service service = (PackageParser.Service)label; 9494 out.print(prefix); out.print( 9495 Integer.toHexString(System.identityHashCode(service))); 9496 out.print(' '); 9497 service.printComponentShortName(out); 9498 if (count > 1) { 9499 out.print(" ("); out.print(count); out.print(" filters)"); 9500 } 9501 out.println(); 9502 } 9503 9504// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9505// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9506// final List<ResolveInfo> retList = Lists.newArrayList(); 9507// while (i.hasNext()) { 9508// final ResolveInfo resolveInfo = (ResolveInfo) i; 9509// if (isEnabledLP(resolveInfo.serviceInfo)) { 9510// retList.add(resolveInfo); 9511// } 9512// } 9513// return retList; 9514// } 9515 9516 // Keys are String (activity class name), values are Activity. 9517 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9518 = new ArrayMap<ComponentName, PackageParser.Service>(); 9519 private int mFlags; 9520 }; 9521 9522 private final class ProviderIntentResolver 9523 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9524 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9525 boolean defaultOnly, int userId) { 9526 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9527 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9528 } 9529 9530 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9531 int userId) { 9532 if (!sUserManager.exists(userId)) 9533 return null; 9534 mFlags = flags; 9535 return super.queryIntent(intent, resolvedType, 9536 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9537 } 9538 9539 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9540 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9541 if (!sUserManager.exists(userId)) 9542 return null; 9543 if (packageProviders == null) { 9544 return null; 9545 } 9546 mFlags = flags; 9547 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9548 final int N = packageProviders.size(); 9549 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9550 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9551 9552 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9553 for (int i = 0; i < N; ++i) { 9554 intentFilters = packageProviders.get(i).intents; 9555 if (intentFilters != null && intentFilters.size() > 0) { 9556 PackageParser.ProviderIntentInfo[] array = 9557 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9558 intentFilters.toArray(array); 9559 listCut.add(array); 9560 } 9561 } 9562 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9563 } 9564 9565 public final void addProvider(PackageParser.Provider p) { 9566 if (mProviders.containsKey(p.getComponentName())) { 9567 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9568 return; 9569 } 9570 9571 mProviders.put(p.getComponentName(), p); 9572 if (DEBUG_SHOW_INFO) { 9573 Log.v(TAG, " " 9574 + (p.info.nonLocalizedLabel != null 9575 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9576 Log.v(TAG, " Class=" + p.info.name); 9577 } 9578 final int NI = p.intents.size(); 9579 int j; 9580 for (j = 0; j < NI; j++) { 9581 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9582 if (DEBUG_SHOW_INFO) { 9583 Log.v(TAG, " IntentFilter:"); 9584 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9585 } 9586 if (!intent.debugCheck()) { 9587 Log.w(TAG, "==> For Provider " + p.info.name); 9588 } 9589 addFilter(intent); 9590 } 9591 } 9592 9593 public final void removeProvider(PackageParser.Provider p) { 9594 mProviders.remove(p.getComponentName()); 9595 if (DEBUG_SHOW_INFO) { 9596 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9597 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9598 Log.v(TAG, " Class=" + p.info.name); 9599 } 9600 final int NI = p.intents.size(); 9601 int j; 9602 for (j = 0; j < NI; j++) { 9603 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9604 if (DEBUG_SHOW_INFO) { 9605 Log.v(TAG, " IntentFilter:"); 9606 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9607 } 9608 removeFilter(intent); 9609 } 9610 } 9611 9612 @Override 9613 protected boolean allowFilterResult( 9614 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9615 ProviderInfo filterPi = filter.provider.info; 9616 for (int i = dest.size() - 1; i >= 0; i--) { 9617 ProviderInfo destPi = dest.get(i).providerInfo; 9618 if (destPi.name == filterPi.name 9619 && destPi.packageName == filterPi.packageName) { 9620 return false; 9621 } 9622 } 9623 return true; 9624 } 9625 9626 @Override 9627 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9628 return new PackageParser.ProviderIntentInfo[size]; 9629 } 9630 9631 @Override 9632 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9633 if (!sUserManager.exists(userId)) 9634 return true; 9635 PackageParser.Package p = filter.provider.owner; 9636 if (p != null) { 9637 PackageSetting ps = (PackageSetting) p.mExtras; 9638 if (ps != null) { 9639 // System apps are never considered stopped for purposes of 9640 // filtering, because there may be no way for the user to 9641 // actually re-launch them. 9642 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9643 && ps.getStopped(userId); 9644 } 9645 } 9646 return false; 9647 } 9648 9649 @Override 9650 protected boolean isPackageForFilter(String packageName, 9651 PackageParser.ProviderIntentInfo info) { 9652 return packageName.equals(info.provider.owner.packageName); 9653 } 9654 9655 @Override 9656 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9657 int match, int userId) { 9658 if (!sUserManager.exists(userId)) 9659 return null; 9660 final PackageParser.ProviderIntentInfo info = filter; 9661 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 9662 return null; 9663 } 9664 final PackageParser.Provider provider = info.provider; 9665 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9666 if (ps == null) { 9667 return null; 9668 } 9669 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9670 ps.readUserState(userId), userId); 9671 if (pi == null) { 9672 return null; 9673 } 9674 final ResolveInfo res = new ResolveInfo(); 9675 res.providerInfo = pi; 9676 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9677 res.filter = filter; 9678 } 9679 res.priority = info.getPriority(); 9680 res.preferredOrder = provider.owner.mPreferredOrder; 9681 res.match = match; 9682 res.isDefault = info.hasDefault; 9683 res.labelRes = info.labelRes; 9684 res.nonLocalizedLabel = info.nonLocalizedLabel; 9685 res.icon = info.icon; 9686 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9687 return res; 9688 } 9689 9690 @Override 9691 protected void sortResults(List<ResolveInfo> results) { 9692 Collections.sort(results, mResolvePrioritySorter); 9693 } 9694 9695 @Override 9696 protected void dumpFilter(PrintWriter out, String prefix, 9697 PackageParser.ProviderIntentInfo filter) { 9698 out.print(prefix); 9699 out.print( 9700 Integer.toHexString(System.identityHashCode(filter.provider))); 9701 out.print(' '); 9702 filter.provider.printComponentShortName(out); 9703 out.print(" filter "); 9704 out.println(Integer.toHexString(System.identityHashCode(filter))); 9705 } 9706 9707 @Override 9708 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9709 return filter.provider; 9710 } 9711 9712 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9713 PackageParser.Provider provider = (PackageParser.Provider)label; 9714 out.print(prefix); out.print( 9715 Integer.toHexString(System.identityHashCode(provider))); 9716 out.print(' '); 9717 provider.printComponentShortName(out); 9718 if (count > 1) { 9719 out.print(" ("); out.print(count); out.print(" filters)"); 9720 } 9721 out.println(); 9722 } 9723 9724 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9725 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9726 private int mFlags; 9727 } 9728 9729 private static final class EphemeralIntentResolver 9730 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 9731 @Override 9732 protected EphemeralResolveIntentInfo[] newArray(int size) { 9733 return new EphemeralResolveIntentInfo[size]; 9734 } 9735 9736 @Override 9737 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 9738 return true; 9739 } 9740 9741 @Override 9742 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 9743 int userId) { 9744 if (!sUserManager.exists(userId)) { 9745 return null; 9746 } 9747 return info.getEphemeralResolveInfo(); 9748 } 9749 } 9750 9751 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9752 new Comparator<ResolveInfo>() { 9753 public int compare(ResolveInfo r1, ResolveInfo r2) { 9754 int v1 = r1.priority; 9755 int v2 = r2.priority; 9756 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9757 if (v1 != v2) { 9758 return (v1 > v2) ? -1 : 1; 9759 } 9760 v1 = r1.preferredOrder; 9761 v2 = r2.preferredOrder; 9762 if (v1 != v2) { 9763 return (v1 > v2) ? -1 : 1; 9764 } 9765 if (r1.isDefault != r2.isDefault) { 9766 return r1.isDefault ? -1 : 1; 9767 } 9768 v1 = r1.match; 9769 v2 = r2.match; 9770 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9771 if (v1 != v2) { 9772 return (v1 > v2) ? -1 : 1; 9773 } 9774 if (r1.system != r2.system) { 9775 return r1.system ? -1 : 1; 9776 } 9777 if (r1.activityInfo != null) { 9778 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 9779 } 9780 if (r1.serviceInfo != null) { 9781 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 9782 } 9783 if (r1.providerInfo != null) { 9784 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 9785 } 9786 return 0; 9787 } 9788 }; 9789 9790 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9791 new Comparator<ProviderInfo>() { 9792 public int compare(ProviderInfo p1, ProviderInfo p2) { 9793 final int v1 = p1.initOrder; 9794 final int v2 = p2.initOrder; 9795 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9796 } 9797 }; 9798 9799 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9800 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9801 final int[] userIds) { 9802 mHandler.post(new Runnable() { 9803 @Override 9804 public void run() { 9805 try { 9806 final IActivityManager am = ActivityManagerNative.getDefault(); 9807 if (am == null) return; 9808 final int[] resolvedUserIds; 9809 if (userIds == null) { 9810 resolvedUserIds = am.getRunningUserIds(); 9811 } else { 9812 resolvedUserIds = userIds; 9813 } 9814 for (int id : resolvedUserIds) { 9815 final Intent intent = new Intent(action, 9816 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9817 if (extras != null) { 9818 intent.putExtras(extras); 9819 } 9820 if (targetPkg != null) { 9821 intent.setPackage(targetPkg); 9822 } 9823 // Modify the UID when posting to other users 9824 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9825 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9826 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9827 intent.putExtra(Intent.EXTRA_UID, uid); 9828 } 9829 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9830 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9831 if (DEBUG_BROADCASTS) { 9832 RuntimeException here = new RuntimeException("here"); 9833 here.fillInStackTrace(); 9834 Slog.d(TAG, "Sending to user " + id + ": " 9835 + intent.toShortString(false, true, false, false) 9836 + " " + intent.getExtras(), here); 9837 } 9838 am.broadcastIntent(null, intent, null, finishedReceiver, 9839 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9840 null, finishedReceiver != null, false, id); 9841 } 9842 } catch (RemoteException ex) { 9843 } 9844 } 9845 }); 9846 } 9847 9848 /** 9849 * Check if the external storage media is available. This is true if there 9850 * is a mounted external storage medium or if the external storage is 9851 * emulated. 9852 */ 9853 private boolean isExternalMediaAvailable() { 9854 return mMediaMounted || Environment.isExternalStorageEmulated(); 9855 } 9856 9857 @Override 9858 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9859 // writer 9860 synchronized (mPackages) { 9861 if (!isExternalMediaAvailable()) { 9862 // If the external storage is no longer mounted at this point, 9863 // the caller may not have been able to delete all of this 9864 // packages files and can not delete any more. Bail. 9865 return null; 9866 } 9867 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9868 if (lastPackage != null) { 9869 pkgs.remove(lastPackage); 9870 } 9871 if (pkgs.size() > 0) { 9872 return pkgs.get(0); 9873 } 9874 } 9875 return null; 9876 } 9877 9878 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9879 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9880 userId, andCode ? 1 : 0, packageName); 9881 if (mSystemReady) { 9882 msg.sendToTarget(); 9883 } else { 9884 if (mPostSystemReadyMessages == null) { 9885 mPostSystemReadyMessages = new ArrayList<>(); 9886 } 9887 mPostSystemReadyMessages.add(msg); 9888 } 9889 } 9890 9891 void startCleaningPackages() { 9892 // reader 9893 synchronized (mPackages) { 9894 if (!isExternalMediaAvailable()) { 9895 return; 9896 } 9897 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9898 return; 9899 } 9900 } 9901 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9902 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9903 IActivityManager am = ActivityManagerNative.getDefault(); 9904 if (am != null) { 9905 try { 9906 am.startService(null, intent, null, mContext.getOpPackageName(), 9907 UserHandle.USER_SYSTEM); 9908 } catch (RemoteException e) { 9909 } 9910 } 9911 } 9912 9913 @Override 9914 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9915 int installFlags, String installerPackageName, VerificationParams verificationParams, 9916 String packageAbiOverride) { 9917 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9918 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9919 } 9920 9921 @Override 9922 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9923 int installFlags, String installerPackageName, VerificationParams verificationParams, 9924 String packageAbiOverride, int userId) { 9925 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9926 9927 final int callingUid = Binder.getCallingUid(); 9928 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9929 9930 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9931 try { 9932 if (observer != null) { 9933 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9934 } 9935 } catch (RemoteException re) { 9936 } 9937 return; 9938 } 9939 9940 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9941 installFlags |= PackageManager.INSTALL_FROM_ADB; 9942 9943 } else { 9944 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9945 // about installerPackageName. 9946 9947 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9948 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9949 } 9950 9951 UserHandle user; 9952 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9953 user = UserHandle.ALL; 9954 } else { 9955 user = new UserHandle(userId); 9956 } 9957 9958 // Only system components can circumvent runtime permissions when installing. 9959 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9960 && mContext.checkCallingOrSelfPermission(Manifest.permission 9961 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9962 throw new SecurityException("You need the " 9963 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9964 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9965 } 9966 9967 verificationParams.setInstallerUid(callingUid); 9968 9969 final File originFile = new File(originPath); 9970 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9971 9972 final Message msg = mHandler.obtainMessage(INIT_COPY); 9973 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9974 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9975 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9976 msg.obj = params; 9977 9978 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9979 System.identityHashCode(msg.obj)); 9980 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9981 System.identityHashCode(msg.obj)); 9982 9983 mHandler.sendMessage(msg); 9984 } 9985 9986 void installStage(String packageName, File stagedDir, String stagedCid, 9987 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9988 String installerPackageName, int installerUid, UserHandle user) { 9989 if (DEBUG_EPHEMERAL) { 9990 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 9991 Slog.d(TAG, "Ephemeral install of " + packageName); 9992 } 9993 } 9994 final VerificationParams verifParams = new VerificationParams( 9995 null, sessionParams.originatingUri, sessionParams.referrerUri, 9996 sessionParams.originatingUid); 9997 verifParams.setInstallerUid(installerUid); 9998 9999 final OriginInfo origin; 10000 if (stagedDir != null) { 10001 origin = OriginInfo.fromStagedFile(stagedDir); 10002 } else { 10003 origin = OriginInfo.fromStagedContainer(stagedCid); 10004 } 10005 10006 final Message msg = mHandler.obtainMessage(INIT_COPY); 10007 final InstallParams params = new InstallParams(origin, null, observer, 10008 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10009 verifParams, user, sessionParams.abiOverride, 10010 sessionParams.grantedRuntimePermissions); 10011 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10012 msg.obj = params; 10013 10014 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10015 System.identityHashCode(msg.obj)); 10016 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10017 System.identityHashCode(msg.obj)); 10018 10019 mHandler.sendMessage(msg); 10020 } 10021 10022 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 10023 Bundle extras = new Bundle(1); 10024 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 10025 10026 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10027 packageName, extras, 0, null, null, new int[] {userId}); 10028 try { 10029 IActivityManager am = ActivityManagerNative.getDefault(); 10030 final boolean isSystem = 10031 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10032 if (isSystem && am.isUserRunning(userId, 0)) { 10033 // The just-installed/enabled app is bundled on the system, so presumed 10034 // to be able to run automatically without needing an explicit launch. 10035 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10036 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10037 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10038 .setPackage(packageName); 10039 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10040 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10041 } 10042 } catch (RemoteException e) { 10043 // shouldn't happen 10044 Slog.w(TAG, "Unable to bootstrap installed package", e); 10045 } 10046 } 10047 10048 @Override 10049 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10050 int userId) { 10051 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10052 PackageSetting pkgSetting; 10053 final int uid = Binder.getCallingUid(); 10054 enforceCrossUserPermission(uid, userId, true, true, 10055 "setApplicationHiddenSetting for user " + userId); 10056 10057 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10058 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10059 return false; 10060 } 10061 10062 long callingId = Binder.clearCallingIdentity(); 10063 try { 10064 boolean sendAdded = false; 10065 boolean sendRemoved = false; 10066 // writer 10067 synchronized (mPackages) { 10068 pkgSetting = mSettings.mPackages.get(packageName); 10069 if (pkgSetting == null) { 10070 return false; 10071 } 10072 if (pkgSetting.getHidden(userId) != hidden) { 10073 pkgSetting.setHidden(hidden, userId); 10074 mSettings.writePackageRestrictionsLPr(userId); 10075 if (hidden) { 10076 sendRemoved = true; 10077 } else { 10078 sendAdded = true; 10079 } 10080 } 10081 } 10082 if (sendAdded) { 10083 sendPackageAddedForUser(packageName, pkgSetting, userId); 10084 return true; 10085 } 10086 if (sendRemoved) { 10087 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10088 "hiding pkg"); 10089 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10090 return true; 10091 } 10092 } finally { 10093 Binder.restoreCallingIdentity(callingId); 10094 } 10095 return false; 10096 } 10097 10098 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10099 int userId) { 10100 final PackageRemovedInfo info = new PackageRemovedInfo(); 10101 info.removedPackage = packageName; 10102 info.removedUsers = new int[] {userId}; 10103 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10104 info.sendBroadcast(false, false, false); 10105 } 10106 10107 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10108 if (pkgList.length > 0) { 10109 Bundle extras = new Bundle(1); 10110 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10111 10112 sendPackageBroadcast( 10113 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10114 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10115 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10116 new int[] {userId}); 10117 } 10118 } 10119 10120 /** 10121 * Returns true if application is not found or there was an error. Otherwise it returns 10122 * the hidden state of the package for the given user. 10123 */ 10124 @Override 10125 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10126 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10127 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10128 false, "getApplicationHidden for user " + userId); 10129 PackageSetting pkgSetting; 10130 long callingId = Binder.clearCallingIdentity(); 10131 try { 10132 // writer 10133 synchronized (mPackages) { 10134 pkgSetting = mSettings.mPackages.get(packageName); 10135 if (pkgSetting == null) { 10136 return true; 10137 } 10138 return pkgSetting.getHidden(userId); 10139 } 10140 } finally { 10141 Binder.restoreCallingIdentity(callingId); 10142 } 10143 } 10144 10145 /** 10146 * @hide 10147 */ 10148 @Override 10149 public int installExistingPackageAsUser(String packageName, int userId) { 10150 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10151 null); 10152 PackageSetting pkgSetting; 10153 final int uid = Binder.getCallingUid(); 10154 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10155 + userId); 10156 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10157 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10158 } 10159 10160 long callingId = Binder.clearCallingIdentity(); 10161 try { 10162 boolean installed = false; 10163 10164 // writer 10165 synchronized (mPackages) { 10166 pkgSetting = mSettings.mPackages.get(packageName); 10167 if (pkgSetting == null) { 10168 return PackageManager.INSTALL_FAILED_INVALID_URI; 10169 } 10170 if (!pkgSetting.getInstalled(userId)) { 10171 pkgSetting.setInstalled(true, userId); 10172 pkgSetting.setHidden(false, userId); 10173 mSettings.writePackageRestrictionsLPr(userId); 10174 if (pkgSetting.pkg != null) { 10175 prepareAppDataAfterInstall(pkgSetting.pkg); 10176 } 10177 installed = true; 10178 } 10179 } 10180 10181 if (installed) { 10182 sendPackageAddedForUser(packageName, pkgSetting, userId); 10183 } 10184 } finally { 10185 Binder.restoreCallingIdentity(callingId); 10186 } 10187 10188 return PackageManager.INSTALL_SUCCEEDED; 10189 } 10190 10191 boolean isUserRestricted(int userId, String restrictionKey) { 10192 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10193 if (restrictions.getBoolean(restrictionKey, false)) { 10194 Log.w(TAG, "User is restricted: " + restrictionKey); 10195 return true; 10196 } 10197 return false; 10198 } 10199 10200 @Override 10201 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10202 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10203 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10204 "setPackageSuspended for user " + userId); 10205 10206 // TODO: investigate and add more restrictions for suspending crucial packages. 10207 if (isPackageDeviceAdmin(packageName, userId)) { 10208 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10209 + "\": has active device admin"); 10210 return false; 10211 } 10212 10213 long callingId = Binder.clearCallingIdentity(); 10214 try { 10215 boolean changed = false; 10216 boolean success = false; 10217 int appId = -1; 10218 synchronized (mPackages) { 10219 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10220 if (pkgSetting != null) { 10221 if (pkgSetting.getSuspended(userId) != suspended) { 10222 pkgSetting.setSuspended(suspended, userId); 10223 mSettings.writePackageRestrictionsLPr(userId); 10224 appId = pkgSetting.appId; 10225 changed = true; 10226 } 10227 success = true; 10228 } 10229 } 10230 10231 if (changed) { 10232 sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended); 10233 if (suspended) { 10234 killApplication(packageName, UserHandle.getUid(userId, appId), 10235 "suspending package"); 10236 } 10237 } 10238 return success; 10239 } finally { 10240 Binder.restoreCallingIdentity(callingId); 10241 } 10242 } 10243 10244 @Override 10245 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10246 mContext.enforceCallingOrSelfPermission( 10247 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10248 "Only package verification agents can verify applications"); 10249 10250 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10251 final PackageVerificationResponse response = new PackageVerificationResponse( 10252 verificationCode, Binder.getCallingUid()); 10253 msg.arg1 = id; 10254 msg.obj = response; 10255 mHandler.sendMessage(msg); 10256 } 10257 10258 @Override 10259 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10260 long millisecondsToDelay) { 10261 mContext.enforceCallingOrSelfPermission( 10262 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10263 "Only package verification agents can extend verification timeouts"); 10264 10265 final PackageVerificationState state = mPendingVerification.get(id); 10266 final PackageVerificationResponse response = new PackageVerificationResponse( 10267 verificationCodeAtTimeout, Binder.getCallingUid()); 10268 10269 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10270 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10271 } 10272 if (millisecondsToDelay < 0) { 10273 millisecondsToDelay = 0; 10274 } 10275 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10276 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10277 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10278 } 10279 10280 if ((state != null) && !state.timeoutExtended()) { 10281 state.extendTimeout(); 10282 10283 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10284 msg.arg1 = id; 10285 msg.obj = response; 10286 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10287 } 10288 } 10289 10290 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10291 int verificationCode, UserHandle user) { 10292 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10293 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10294 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10295 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10296 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10297 10298 mContext.sendBroadcastAsUser(intent, user, 10299 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10300 } 10301 10302 private ComponentName matchComponentForVerifier(String packageName, 10303 List<ResolveInfo> receivers) { 10304 ActivityInfo targetReceiver = null; 10305 10306 final int NR = receivers.size(); 10307 for (int i = 0; i < NR; i++) { 10308 final ResolveInfo info = receivers.get(i); 10309 if (info.activityInfo == null) { 10310 continue; 10311 } 10312 10313 if (packageName.equals(info.activityInfo.packageName)) { 10314 targetReceiver = info.activityInfo; 10315 break; 10316 } 10317 } 10318 10319 if (targetReceiver == null) { 10320 return null; 10321 } 10322 10323 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10324 } 10325 10326 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10327 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10328 if (pkgInfo.verifiers.length == 0) { 10329 return null; 10330 } 10331 10332 final int N = pkgInfo.verifiers.length; 10333 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10334 for (int i = 0; i < N; i++) { 10335 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10336 10337 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10338 receivers); 10339 if (comp == null) { 10340 continue; 10341 } 10342 10343 final int verifierUid = getUidForVerifier(verifierInfo); 10344 if (verifierUid == -1) { 10345 continue; 10346 } 10347 10348 if (DEBUG_VERIFY) { 10349 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10350 + " with the correct signature"); 10351 } 10352 sufficientVerifiers.add(comp); 10353 verificationState.addSufficientVerifier(verifierUid); 10354 } 10355 10356 return sufficientVerifiers; 10357 } 10358 10359 private int getUidForVerifier(VerifierInfo verifierInfo) { 10360 synchronized (mPackages) { 10361 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10362 if (pkg == null) { 10363 return -1; 10364 } else if (pkg.mSignatures.length != 1) { 10365 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10366 + " has more than one signature; ignoring"); 10367 return -1; 10368 } 10369 10370 /* 10371 * If the public key of the package's signature does not match 10372 * our expected public key, then this is a different package and 10373 * we should skip. 10374 */ 10375 10376 final byte[] expectedPublicKey; 10377 try { 10378 final Signature verifierSig = pkg.mSignatures[0]; 10379 final PublicKey publicKey = verifierSig.getPublicKey(); 10380 expectedPublicKey = publicKey.getEncoded(); 10381 } catch (CertificateException e) { 10382 return -1; 10383 } 10384 10385 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10386 10387 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10388 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10389 + " does not have the expected public key; ignoring"); 10390 return -1; 10391 } 10392 10393 return pkg.applicationInfo.uid; 10394 } 10395 } 10396 10397 @Override 10398 public void finishPackageInstall(int token) { 10399 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10400 10401 if (DEBUG_INSTALL) { 10402 Slog.v(TAG, "BM finishing package install for " + token); 10403 } 10404 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10405 10406 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10407 mHandler.sendMessage(msg); 10408 } 10409 10410 /** 10411 * Get the verification agent timeout. 10412 * 10413 * @return verification timeout in milliseconds 10414 */ 10415 private long getVerificationTimeout() { 10416 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10417 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10418 DEFAULT_VERIFICATION_TIMEOUT); 10419 } 10420 10421 /** 10422 * Get the default verification agent response code. 10423 * 10424 * @return default verification response code 10425 */ 10426 private int getDefaultVerificationResponse() { 10427 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10428 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10429 DEFAULT_VERIFICATION_RESPONSE); 10430 } 10431 10432 /** 10433 * Check whether or not package verification has been enabled. 10434 * 10435 * @return true if verification should be performed 10436 */ 10437 private boolean isVerificationEnabled(int userId, int installFlags) { 10438 if (!DEFAULT_VERIFY_ENABLE) { 10439 return false; 10440 } 10441 // Ephemeral apps don't get the full verification treatment 10442 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10443 if (DEBUG_EPHEMERAL) { 10444 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10445 } 10446 return false; 10447 } 10448 10449 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10450 10451 // Check if installing from ADB 10452 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10453 // Do not run verification in a test harness environment 10454 if (ActivityManager.isRunningInTestHarness()) { 10455 return false; 10456 } 10457 if (ensureVerifyAppsEnabled) { 10458 return true; 10459 } 10460 // Check if the developer does not want package verification for ADB installs 10461 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10462 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10463 return false; 10464 } 10465 } 10466 10467 if (ensureVerifyAppsEnabled) { 10468 return true; 10469 } 10470 10471 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10472 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10473 } 10474 10475 @Override 10476 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10477 throws RemoteException { 10478 mContext.enforceCallingOrSelfPermission( 10479 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10480 "Only intentfilter verification agents can verify applications"); 10481 10482 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10483 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10484 Binder.getCallingUid(), verificationCode, failedDomains); 10485 msg.arg1 = id; 10486 msg.obj = response; 10487 mHandler.sendMessage(msg); 10488 } 10489 10490 @Override 10491 public int getIntentVerificationStatus(String packageName, int userId) { 10492 synchronized (mPackages) { 10493 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10494 } 10495 } 10496 10497 @Override 10498 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10499 mContext.enforceCallingOrSelfPermission( 10500 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10501 10502 boolean result = false; 10503 synchronized (mPackages) { 10504 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10505 } 10506 if (result) { 10507 scheduleWritePackageRestrictionsLocked(userId); 10508 } 10509 return result; 10510 } 10511 10512 @Override 10513 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10514 synchronized (mPackages) { 10515 return mSettings.getIntentFilterVerificationsLPr(packageName); 10516 } 10517 } 10518 10519 @Override 10520 public List<IntentFilter> getAllIntentFilters(String packageName) { 10521 if (TextUtils.isEmpty(packageName)) { 10522 return Collections.<IntentFilter>emptyList(); 10523 } 10524 synchronized (mPackages) { 10525 PackageParser.Package pkg = mPackages.get(packageName); 10526 if (pkg == null || pkg.activities == null) { 10527 return Collections.<IntentFilter>emptyList(); 10528 } 10529 final int count = pkg.activities.size(); 10530 ArrayList<IntentFilter> result = new ArrayList<>(); 10531 for (int n=0; n<count; n++) { 10532 PackageParser.Activity activity = pkg.activities.get(n); 10533 if (activity.intents != null && activity.intents.size() > 0) { 10534 result.addAll(activity.intents); 10535 } 10536 } 10537 return result; 10538 } 10539 } 10540 10541 @Override 10542 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10543 mContext.enforceCallingOrSelfPermission( 10544 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10545 10546 synchronized (mPackages) { 10547 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10548 if (packageName != null) { 10549 result |= updateIntentVerificationStatus(packageName, 10550 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10551 userId); 10552 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10553 packageName, userId); 10554 } 10555 return result; 10556 } 10557 } 10558 10559 @Override 10560 public String getDefaultBrowserPackageName(int userId) { 10561 synchronized (mPackages) { 10562 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10563 } 10564 } 10565 10566 /** 10567 * Get the "allow unknown sources" setting. 10568 * 10569 * @return the current "allow unknown sources" setting 10570 */ 10571 private int getUnknownSourcesSettings() { 10572 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10573 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10574 -1); 10575 } 10576 10577 @Override 10578 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10579 final int uid = Binder.getCallingUid(); 10580 // writer 10581 synchronized (mPackages) { 10582 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10583 if (targetPackageSetting == null) { 10584 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10585 } 10586 10587 PackageSetting installerPackageSetting; 10588 if (installerPackageName != null) { 10589 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10590 if (installerPackageSetting == null) { 10591 throw new IllegalArgumentException("Unknown installer package: " 10592 + installerPackageName); 10593 } 10594 } else { 10595 installerPackageSetting = null; 10596 } 10597 10598 Signature[] callerSignature; 10599 Object obj = mSettings.getUserIdLPr(uid); 10600 if (obj != null) { 10601 if (obj instanceof SharedUserSetting) { 10602 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10603 } else if (obj instanceof PackageSetting) { 10604 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10605 } else { 10606 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10607 } 10608 } else { 10609 throw new SecurityException("Unknown calling UID: " + uid); 10610 } 10611 10612 // Verify: can't set installerPackageName to a package that is 10613 // not signed with the same cert as the caller. 10614 if (installerPackageSetting != null) { 10615 if (compareSignatures(callerSignature, 10616 installerPackageSetting.signatures.mSignatures) 10617 != PackageManager.SIGNATURE_MATCH) { 10618 throw new SecurityException( 10619 "Caller does not have same cert as new installer package " 10620 + installerPackageName); 10621 } 10622 } 10623 10624 // Verify: if target already has an installer package, it must 10625 // be signed with the same cert as the caller. 10626 if (targetPackageSetting.installerPackageName != null) { 10627 PackageSetting setting = mSettings.mPackages.get( 10628 targetPackageSetting.installerPackageName); 10629 // If the currently set package isn't valid, then it's always 10630 // okay to change it. 10631 if (setting != null) { 10632 if (compareSignatures(callerSignature, 10633 setting.signatures.mSignatures) 10634 != PackageManager.SIGNATURE_MATCH) { 10635 throw new SecurityException( 10636 "Caller does not have same cert as old installer package " 10637 + targetPackageSetting.installerPackageName); 10638 } 10639 } 10640 } 10641 10642 // Okay! 10643 targetPackageSetting.installerPackageName = installerPackageName; 10644 scheduleWriteSettingsLocked(); 10645 } 10646 } 10647 10648 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10649 // Queue up an async operation since the package installation may take a little while. 10650 mHandler.post(new Runnable() { 10651 public void run() { 10652 mHandler.removeCallbacks(this); 10653 // Result object to be returned 10654 PackageInstalledInfo res = new PackageInstalledInfo(); 10655 res.returnCode = currentStatus; 10656 res.uid = -1; 10657 res.pkg = null; 10658 res.removedInfo = new PackageRemovedInfo(); 10659 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10660 args.doPreInstall(res.returnCode); 10661 synchronized (mInstallLock) { 10662 installPackageTracedLI(args, res); 10663 } 10664 args.doPostInstall(res.returnCode, res.uid); 10665 } 10666 10667 // A restore should be performed at this point if (a) the install 10668 // succeeded, (b) the operation is not an update, and (c) the new 10669 // package has not opted out of backup participation. 10670 final boolean update = res.removedInfo.removedPackage != null; 10671 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10672 boolean doRestore = !update 10673 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10674 10675 // Set up the post-install work request bookkeeping. This will be used 10676 // and cleaned up by the post-install event handling regardless of whether 10677 // there's a restore pass performed. Token values are >= 1. 10678 int token; 10679 if (mNextInstallToken < 0) mNextInstallToken = 1; 10680 token = mNextInstallToken++; 10681 10682 PostInstallData data = new PostInstallData(args, res); 10683 mRunningInstalls.put(token, data); 10684 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10685 10686 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10687 // Pass responsibility to the Backup Manager. It will perform a 10688 // restore if appropriate, then pass responsibility back to the 10689 // Package Manager to run the post-install observer callbacks 10690 // and broadcasts. 10691 IBackupManager bm = IBackupManager.Stub.asInterface( 10692 ServiceManager.getService(Context.BACKUP_SERVICE)); 10693 if (bm != null) { 10694 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10695 + " to BM for possible restore"); 10696 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10697 try { 10698 // TODO: http://b/22388012 10699 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10700 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10701 } else { 10702 doRestore = false; 10703 } 10704 } catch (RemoteException e) { 10705 // can't happen; the backup manager is local 10706 } catch (Exception e) { 10707 Slog.e(TAG, "Exception trying to enqueue restore", e); 10708 doRestore = false; 10709 } 10710 } else { 10711 Slog.e(TAG, "Backup Manager not found!"); 10712 doRestore = false; 10713 } 10714 } 10715 10716 if (!doRestore) { 10717 // No restore possible, or the Backup Manager was mysteriously not 10718 // available -- just fire the post-install work request directly. 10719 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10720 10721 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10722 10723 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10724 mHandler.sendMessage(msg); 10725 } 10726 } 10727 }); 10728 } 10729 10730 private abstract class HandlerParams { 10731 private static final int MAX_RETRIES = 4; 10732 10733 /** 10734 * Number of times startCopy() has been attempted and had a non-fatal 10735 * error. 10736 */ 10737 private int mRetries = 0; 10738 10739 /** User handle for the user requesting the information or installation. */ 10740 private final UserHandle mUser; 10741 String traceMethod; 10742 int traceCookie; 10743 10744 HandlerParams(UserHandle user) { 10745 mUser = user; 10746 } 10747 10748 UserHandle getUser() { 10749 return mUser; 10750 } 10751 10752 HandlerParams setTraceMethod(String traceMethod) { 10753 this.traceMethod = traceMethod; 10754 return this; 10755 } 10756 10757 HandlerParams setTraceCookie(int traceCookie) { 10758 this.traceCookie = traceCookie; 10759 return this; 10760 } 10761 10762 final boolean startCopy() { 10763 boolean res; 10764 try { 10765 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10766 10767 if (++mRetries > MAX_RETRIES) { 10768 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10769 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10770 handleServiceError(); 10771 return false; 10772 } else { 10773 handleStartCopy(); 10774 res = true; 10775 } 10776 } catch (RemoteException e) { 10777 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10778 mHandler.sendEmptyMessage(MCS_RECONNECT); 10779 res = false; 10780 } 10781 handleReturnCode(); 10782 return res; 10783 } 10784 10785 final void serviceError() { 10786 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10787 handleServiceError(); 10788 handleReturnCode(); 10789 } 10790 10791 abstract void handleStartCopy() throws RemoteException; 10792 abstract void handleServiceError(); 10793 abstract void handleReturnCode(); 10794 } 10795 10796 class MeasureParams extends HandlerParams { 10797 private final PackageStats mStats; 10798 private boolean mSuccess; 10799 10800 private final IPackageStatsObserver mObserver; 10801 10802 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10803 super(new UserHandle(stats.userHandle)); 10804 mObserver = observer; 10805 mStats = stats; 10806 } 10807 10808 @Override 10809 public String toString() { 10810 return "MeasureParams{" 10811 + Integer.toHexString(System.identityHashCode(this)) 10812 + " " + mStats.packageName + "}"; 10813 } 10814 10815 @Override 10816 void handleStartCopy() throws RemoteException { 10817 synchronized (mInstallLock) { 10818 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10819 } 10820 10821 if (mSuccess) { 10822 final boolean mounted; 10823 if (Environment.isExternalStorageEmulated()) { 10824 mounted = true; 10825 } else { 10826 final String status = Environment.getExternalStorageState(); 10827 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10828 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10829 } 10830 10831 if (mounted) { 10832 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10833 10834 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10835 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10836 10837 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10838 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10839 10840 // Always subtract cache size, since it's a subdirectory 10841 mStats.externalDataSize -= mStats.externalCacheSize; 10842 10843 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10844 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10845 10846 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10847 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10848 } 10849 } 10850 } 10851 10852 @Override 10853 void handleReturnCode() { 10854 if (mObserver != null) { 10855 try { 10856 mObserver.onGetStatsCompleted(mStats, mSuccess); 10857 } catch (RemoteException e) { 10858 Slog.i(TAG, "Observer no longer exists."); 10859 } 10860 } 10861 } 10862 10863 @Override 10864 void handleServiceError() { 10865 Slog.e(TAG, "Could not measure application " + mStats.packageName 10866 + " external storage"); 10867 } 10868 } 10869 10870 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10871 throws RemoteException { 10872 long result = 0; 10873 for (File path : paths) { 10874 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10875 } 10876 return result; 10877 } 10878 10879 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10880 for (File path : paths) { 10881 try { 10882 mcs.clearDirectory(path.getAbsolutePath()); 10883 } catch (RemoteException e) { 10884 } 10885 } 10886 } 10887 10888 static class OriginInfo { 10889 /** 10890 * Location where install is coming from, before it has been 10891 * copied/renamed into place. This could be a single monolithic APK 10892 * file, or a cluster directory. This location may be untrusted. 10893 */ 10894 final File file; 10895 final String cid; 10896 10897 /** 10898 * Flag indicating that {@link #file} or {@link #cid} has already been 10899 * staged, meaning downstream users don't need to defensively copy the 10900 * contents. 10901 */ 10902 final boolean staged; 10903 10904 /** 10905 * Flag indicating that {@link #file} or {@link #cid} is an already 10906 * installed app that is being moved. 10907 */ 10908 final boolean existing; 10909 10910 final String resolvedPath; 10911 final File resolvedFile; 10912 10913 static OriginInfo fromNothing() { 10914 return new OriginInfo(null, null, false, false); 10915 } 10916 10917 static OriginInfo fromUntrustedFile(File file) { 10918 return new OriginInfo(file, null, false, false); 10919 } 10920 10921 static OriginInfo fromExistingFile(File file) { 10922 return new OriginInfo(file, null, false, true); 10923 } 10924 10925 static OriginInfo fromStagedFile(File file) { 10926 return new OriginInfo(file, null, true, false); 10927 } 10928 10929 static OriginInfo fromStagedContainer(String cid) { 10930 return new OriginInfo(null, cid, true, false); 10931 } 10932 10933 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10934 this.file = file; 10935 this.cid = cid; 10936 this.staged = staged; 10937 this.existing = existing; 10938 10939 if (cid != null) { 10940 resolvedPath = PackageHelper.getSdDir(cid); 10941 resolvedFile = new File(resolvedPath); 10942 } else if (file != null) { 10943 resolvedPath = file.getAbsolutePath(); 10944 resolvedFile = file; 10945 } else { 10946 resolvedPath = null; 10947 resolvedFile = null; 10948 } 10949 } 10950 } 10951 10952 static class MoveInfo { 10953 final int moveId; 10954 final String fromUuid; 10955 final String toUuid; 10956 final String packageName; 10957 final String dataAppName; 10958 final int appId; 10959 final String seinfo; 10960 final int targetSdkVersion; 10961 10962 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10963 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 10964 this.moveId = moveId; 10965 this.fromUuid = fromUuid; 10966 this.toUuid = toUuid; 10967 this.packageName = packageName; 10968 this.dataAppName = dataAppName; 10969 this.appId = appId; 10970 this.seinfo = seinfo; 10971 this.targetSdkVersion = targetSdkVersion; 10972 } 10973 } 10974 10975 class InstallParams extends HandlerParams { 10976 final OriginInfo origin; 10977 final MoveInfo move; 10978 final IPackageInstallObserver2 observer; 10979 int installFlags; 10980 final String installerPackageName; 10981 final String volumeUuid; 10982 final VerificationParams verificationParams; 10983 private InstallArgs mArgs; 10984 private int mRet; 10985 final String packageAbiOverride; 10986 final String[] grantedRuntimePermissions; 10987 10988 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10989 int installFlags, String installerPackageName, String volumeUuid, 10990 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10991 String[] grantedPermissions) { 10992 super(user); 10993 this.origin = origin; 10994 this.move = move; 10995 this.observer = observer; 10996 this.installFlags = installFlags; 10997 this.installerPackageName = installerPackageName; 10998 this.volumeUuid = volumeUuid; 10999 this.verificationParams = verificationParams; 11000 this.packageAbiOverride = packageAbiOverride; 11001 this.grantedRuntimePermissions = grantedPermissions; 11002 } 11003 11004 @Override 11005 public String toString() { 11006 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11007 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11008 } 11009 11010 private int installLocationPolicy(PackageInfoLite pkgLite) { 11011 String packageName = pkgLite.packageName; 11012 int installLocation = pkgLite.installLocation; 11013 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11014 // reader 11015 synchronized (mPackages) { 11016 PackageParser.Package pkg = mPackages.get(packageName); 11017 if (pkg != null) { 11018 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11019 // Check for downgrading. 11020 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11021 try { 11022 checkDowngrade(pkg, pkgLite); 11023 } catch (PackageManagerException e) { 11024 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11025 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11026 } 11027 } 11028 // Check for updated system application. 11029 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11030 if (onSd) { 11031 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11032 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11033 } 11034 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11035 } else { 11036 if (onSd) { 11037 // Install flag overrides everything. 11038 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11039 } 11040 // If current upgrade specifies particular preference 11041 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11042 // Application explicitly specified internal. 11043 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11044 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11045 // App explictly prefers external. Let policy decide 11046 } else { 11047 // Prefer previous location 11048 if (isExternal(pkg)) { 11049 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11050 } 11051 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11052 } 11053 } 11054 } else { 11055 // Invalid install. Return error code 11056 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11057 } 11058 } 11059 } 11060 // All the special cases have been taken care of. 11061 // Return result based on recommended install location. 11062 if (onSd) { 11063 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11064 } 11065 return pkgLite.recommendedInstallLocation; 11066 } 11067 11068 /* 11069 * Invoke remote method to get package information and install 11070 * location values. Override install location based on default 11071 * policy if needed and then create install arguments based 11072 * on the install location. 11073 */ 11074 public void handleStartCopy() throws RemoteException { 11075 int ret = PackageManager.INSTALL_SUCCEEDED; 11076 11077 // If we're already staged, we've firmly committed to an install location 11078 if (origin.staged) { 11079 if (origin.file != null) { 11080 installFlags |= PackageManager.INSTALL_INTERNAL; 11081 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11082 } else if (origin.cid != null) { 11083 installFlags |= PackageManager.INSTALL_EXTERNAL; 11084 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11085 } else { 11086 throw new IllegalStateException("Invalid stage location"); 11087 } 11088 } 11089 11090 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11091 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11092 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11093 PackageInfoLite pkgLite = null; 11094 11095 if (onInt && onSd) { 11096 // Check if both bits are set. 11097 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11098 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11099 } else if (onSd && ephemeral) { 11100 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11101 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11102 } else { 11103 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11104 packageAbiOverride); 11105 11106 if (DEBUG_EPHEMERAL && ephemeral) { 11107 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11108 } 11109 11110 /* 11111 * If we have too little free space, try to free cache 11112 * before giving up. 11113 */ 11114 if (!origin.staged && pkgLite.recommendedInstallLocation 11115 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11116 // TODO: focus freeing disk space on the target device 11117 final StorageManager storage = StorageManager.from(mContext); 11118 final long lowThreshold = storage.getStorageLowBytes( 11119 Environment.getDataDirectory()); 11120 11121 final long sizeBytes = mContainerService.calculateInstalledSize( 11122 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11123 11124 try { 11125 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11126 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11127 installFlags, packageAbiOverride); 11128 } catch (InstallerException e) { 11129 Slog.w(TAG, "Failed to free cache", e); 11130 } 11131 11132 /* 11133 * The cache free must have deleted the file we 11134 * downloaded to install. 11135 * 11136 * TODO: fix the "freeCache" call to not delete 11137 * the file we care about. 11138 */ 11139 if (pkgLite.recommendedInstallLocation 11140 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11141 pkgLite.recommendedInstallLocation 11142 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11143 } 11144 } 11145 } 11146 11147 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11148 int loc = pkgLite.recommendedInstallLocation; 11149 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11150 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11151 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11152 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11153 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11154 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11155 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11156 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11157 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11158 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11159 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11160 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11161 } else { 11162 // Override with defaults if needed. 11163 loc = installLocationPolicy(pkgLite); 11164 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11165 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11166 } else if (!onSd && !onInt) { 11167 // Override install location with flags 11168 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11169 // Set the flag to install on external media. 11170 installFlags |= PackageManager.INSTALL_EXTERNAL; 11171 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11172 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11173 if (DEBUG_EPHEMERAL) { 11174 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11175 } 11176 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11177 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11178 |PackageManager.INSTALL_INTERNAL); 11179 } else { 11180 // Make sure the flag for installing on external 11181 // media is unset 11182 installFlags |= PackageManager.INSTALL_INTERNAL; 11183 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11184 } 11185 } 11186 } 11187 } 11188 11189 final InstallArgs args = createInstallArgs(this); 11190 mArgs = args; 11191 11192 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11193 // TODO: http://b/22976637 11194 // Apps installed for "all" users use the device owner to verify the app 11195 UserHandle verifierUser = getUser(); 11196 if (verifierUser == UserHandle.ALL) { 11197 verifierUser = UserHandle.SYSTEM; 11198 } 11199 11200 /* 11201 * Determine if we have any installed package verifiers. If we 11202 * do, then we'll defer to them to verify the packages. 11203 */ 11204 final int requiredUid = mRequiredVerifierPackage == null ? -1 11205 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11206 verifierUser.getIdentifier()); 11207 if (!origin.existing && requiredUid != -1 11208 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11209 final Intent verification = new Intent( 11210 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11211 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11212 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11213 PACKAGE_MIME_TYPE); 11214 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11215 11216 // Query all live verifiers based on current user state 11217 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11218 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11219 11220 if (DEBUG_VERIFY) { 11221 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11222 + verification.toString() + " with " + pkgLite.verifiers.length 11223 + " optional verifiers"); 11224 } 11225 11226 final int verificationId = mPendingVerificationToken++; 11227 11228 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11229 11230 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11231 installerPackageName); 11232 11233 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11234 installFlags); 11235 11236 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11237 pkgLite.packageName); 11238 11239 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11240 pkgLite.versionCode); 11241 11242 if (verificationParams != null) { 11243 if (verificationParams.getVerificationURI() != null) { 11244 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11245 verificationParams.getVerificationURI()); 11246 } 11247 if (verificationParams.getOriginatingURI() != null) { 11248 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11249 verificationParams.getOriginatingURI()); 11250 } 11251 if (verificationParams.getReferrer() != null) { 11252 verification.putExtra(Intent.EXTRA_REFERRER, 11253 verificationParams.getReferrer()); 11254 } 11255 if (verificationParams.getOriginatingUid() >= 0) { 11256 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11257 verificationParams.getOriginatingUid()); 11258 } 11259 if (verificationParams.getInstallerUid() >= 0) { 11260 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11261 verificationParams.getInstallerUid()); 11262 } 11263 } 11264 11265 final PackageVerificationState verificationState = new PackageVerificationState( 11266 requiredUid, args); 11267 11268 mPendingVerification.append(verificationId, verificationState); 11269 11270 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11271 receivers, verificationState); 11272 11273 /* 11274 * If any sufficient verifiers were listed in the package 11275 * manifest, attempt to ask them. 11276 */ 11277 if (sufficientVerifiers != null) { 11278 final int N = sufficientVerifiers.size(); 11279 if (N == 0) { 11280 Slog.i(TAG, "Additional verifiers required, but none installed."); 11281 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11282 } else { 11283 for (int i = 0; i < N; i++) { 11284 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11285 11286 final Intent sufficientIntent = new Intent(verification); 11287 sufficientIntent.setComponent(verifierComponent); 11288 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11289 } 11290 } 11291 } 11292 11293 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11294 mRequiredVerifierPackage, receivers); 11295 if (ret == PackageManager.INSTALL_SUCCEEDED 11296 && mRequiredVerifierPackage != null) { 11297 Trace.asyncTraceBegin( 11298 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11299 /* 11300 * Send the intent to the required verification agent, 11301 * but only start the verification timeout after the 11302 * target BroadcastReceivers have run. 11303 */ 11304 verification.setComponent(requiredVerifierComponent); 11305 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11306 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11307 new BroadcastReceiver() { 11308 @Override 11309 public void onReceive(Context context, Intent intent) { 11310 final Message msg = mHandler 11311 .obtainMessage(CHECK_PENDING_VERIFICATION); 11312 msg.arg1 = verificationId; 11313 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11314 } 11315 }, null, 0, null, null); 11316 11317 /* 11318 * We don't want the copy to proceed until verification 11319 * succeeds, so null out this field. 11320 */ 11321 mArgs = null; 11322 } 11323 } else { 11324 /* 11325 * No package verification is enabled, so immediately start 11326 * the remote call to initiate copy using temporary file. 11327 */ 11328 ret = args.copyApk(mContainerService, true); 11329 } 11330 } 11331 11332 mRet = ret; 11333 } 11334 11335 @Override 11336 void handleReturnCode() { 11337 // If mArgs is null, then MCS couldn't be reached. When it 11338 // reconnects, it will try again to install. At that point, this 11339 // will succeed. 11340 if (mArgs != null) { 11341 processPendingInstall(mArgs, mRet); 11342 } 11343 } 11344 11345 @Override 11346 void handleServiceError() { 11347 mArgs = createInstallArgs(this); 11348 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11349 } 11350 11351 public boolean isForwardLocked() { 11352 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11353 } 11354 } 11355 11356 /** 11357 * Used during creation of InstallArgs 11358 * 11359 * @param installFlags package installation flags 11360 * @return true if should be installed on external storage 11361 */ 11362 private static boolean installOnExternalAsec(int installFlags) { 11363 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11364 return false; 11365 } 11366 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11367 return true; 11368 } 11369 return false; 11370 } 11371 11372 /** 11373 * Used during creation of InstallArgs 11374 * 11375 * @param installFlags package installation flags 11376 * @return true if should be installed as forward locked 11377 */ 11378 private static boolean installForwardLocked(int installFlags) { 11379 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11380 } 11381 11382 private InstallArgs createInstallArgs(InstallParams params) { 11383 if (params.move != null) { 11384 return new MoveInstallArgs(params); 11385 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11386 return new AsecInstallArgs(params); 11387 } else { 11388 return new FileInstallArgs(params); 11389 } 11390 } 11391 11392 /** 11393 * Create args that describe an existing installed package. Typically used 11394 * when cleaning up old installs, or used as a move source. 11395 */ 11396 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11397 String resourcePath, String[] instructionSets) { 11398 final boolean isInAsec; 11399 if (installOnExternalAsec(installFlags)) { 11400 /* Apps on SD card are always in ASEC containers. */ 11401 isInAsec = true; 11402 } else if (installForwardLocked(installFlags) 11403 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11404 /* 11405 * Forward-locked apps are only in ASEC containers if they're the 11406 * new style 11407 */ 11408 isInAsec = true; 11409 } else { 11410 isInAsec = false; 11411 } 11412 11413 if (isInAsec) { 11414 return new AsecInstallArgs(codePath, instructionSets, 11415 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11416 } else { 11417 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11418 } 11419 } 11420 11421 static abstract class InstallArgs { 11422 /** @see InstallParams#origin */ 11423 final OriginInfo origin; 11424 /** @see InstallParams#move */ 11425 final MoveInfo move; 11426 11427 final IPackageInstallObserver2 observer; 11428 // Always refers to PackageManager flags only 11429 final int installFlags; 11430 final String installerPackageName; 11431 final String volumeUuid; 11432 final UserHandle user; 11433 final String abiOverride; 11434 final String[] installGrantPermissions; 11435 /** If non-null, drop an async trace when the install completes */ 11436 final String traceMethod; 11437 final int traceCookie; 11438 11439 // The list of instruction sets supported by this app. This is currently 11440 // only used during the rmdex() phase to clean up resources. We can get rid of this 11441 // if we move dex files under the common app path. 11442 /* nullable */ String[] instructionSets; 11443 11444 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11445 int installFlags, String installerPackageName, String volumeUuid, 11446 UserHandle user, String[] instructionSets, 11447 String abiOverride, String[] installGrantPermissions, 11448 String traceMethod, int traceCookie) { 11449 this.origin = origin; 11450 this.move = move; 11451 this.installFlags = installFlags; 11452 this.observer = observer; 11453 this.installerPackageName = installerPackageName; 11454 this.volumeUuid = volumeUuid; 11455 this.user = user; 11456 this.instructionSets = instructionSets; 11457 this.abiOverride = abiOverride; 11458 this.installGrantPermissions = installGrantPermissions; 11459 this.traceMethod = traceMethod; 11460 this.traceCookie = traceCookie; 11461 } 11462 11463 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11464 abstract int doPreInstall(int status); 11465 11466 /** 11467 * Rename package into final resting place. All paths on the given 11468 * scanned package should be updated to reflect the rename. 11469 */ 11470 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11471 abstract int doPostInstall(int status, int uid); 11472 11473 /** @see PackageSettingBase#codePathString */ 11474 abstract String getCodePath(); 11475 /** @see PackageSettingBase#resourcePathString */ 11476 abstract String getResourcePath(); 11477 11478 // Need installer lock especially for dex file removal. 11479 abstract void cleanUpResourcesLI(); 11480 abstract boolean doPostDeleteLI(boolean delete); 11481 11482 /** 11483 * Called before the source arguments are copied. This is used mostly 11484 * for MoveParams when it needs to read the source file to put it in the 11485 * destination. 11486 */ 11487 int doPreCopy() { 11488 return PackageManager.INSTALL_SUCCEEDED; 11489 } 11490 11491 /** 11492 * Called after the source arguments are copied. This is used mostly for 11493 * MoveParams when it needs to read the source file to put it in the 11494 * destination. 11495 * 11496 * @return 11497 */ 11498 int doPostCopy(int uid) { 11499 return PackageManager.INSTALL_SUCCEEDED; 11500 } 11501 11502 protected boolean isFwdLocked() { 11503 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11504 } 11505 11506 protected boolean isExternalAsec() { 11507 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11508 } 11509 11510 protected boolean isEphemeral() { 11511 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11512 } 11513 11514 UserHandle getUser() { 11515 return user; 11516 } 11517 } 11518 11519 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11520 if (!allCodePaths.isEmpty()) { 11521 if (instructionSets == null) { 11522 throw new IllegalStateException("instructionSet == null"); 11523 } 11524 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11525 for (String codePath : allCodePaths) { 11526 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11527 try { 11528 mInstaller.rmdex(codePath, dexCodeInstructionSet); 11529 } catch (InstallerException ignored) { 11530 } 11531 } 11532 } 11533 } 11534 } 11535 11536 /** 11537 * Logic to handle installation of non-ASEC applications, including copying 11538 * and renaming logic. 11539 */ 11540 class FileInstallArgs extends InstallArgs { 11541 private File codeFile; 11542 private File resourceFile; 11543 11544 // Example topology: 11545 // /data/app/com.example/base.apk 11546 // /data/app/com.example/split_foo.apk 11547 // /data/app/com.example/lib/arm/libfoo.so 11548 // /data/app/com.example/lib/arm64/libfoo.so 11549 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11550 11551 /** New install */ 11552 FileInstallArgs(InstallParams params) { 11553 super(params.origin, params.move, params.observer, params.installFlags, 11554 params.installerPackageName, params.volumeUuid, 11555 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11556 params.grantedRuntimePermissions, 11557 params.traceMethod, params.traceCookie); 11558 if (isFwdLocked()) { 11559 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11560 } 11561 } 11562 11563 /** Existing install */ 11564 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11565 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 11566 null, null, null, 0); 11567 this.codeFile = (codePath != null) ? new File(codePath) : null; 11568 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11569 } 11570 11571 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11572 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11573 try { 11574 return doCopyApk(imcs, temp); 11575 } finally { 11576 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11577 } 11578 } 11579 11580 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11581 if (origin.staged) { 11582 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11583 codeFile = origin.file; 11584 resourceFile = origin.file; 11585 return PackageManager.INSTALL_SUCCEEDED; 11586 } 11587 11588 try { 11589 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11590 final File tempDir = 11591 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11592 codeFile = tempDir; 11593 resourceFile = tempDir; 11594 } catch (IOException e) { 11595 Slog.w(TAG, "Failed to create copy file: " + e); 11596 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11597 } 11598 11599 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11600 @Override 11601 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11602 if (!FileUtils.isValidExtFilename(name)) { 11603 throw new IllegalArgumentException("Invalid filename: " + name); 11604 } 11605 try { 11606 final File file = new File(codeFile, name); 11607 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11608 O_RDWR | O_CREAT, 0644); 11609 Os.chmod(file.getAbsolutePath(), 0644); 11610 return new ParcelFileDescriptor(fd); 11611 } catch (ErrnoException e) { 11612 throw new RemoteException("Failed to open: " + e.getMessage()); 11613 } 11614 } 11615 }; 11616 11617 int ret = PackageManager.INSTALL_SUCCEEDED; 11618 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11619 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11620 Slog.e(TAG, "Failed to copy package"); 11621 return ret; 11622 } 11623 11624 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11625 NativeLibraryHelper.Handle handle = null; 11626 try { 11627 handle = NativeLibraryHelper.Handle.create(codeFile); 11628 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11629 abiOverride); 11630 } catch (IOException e) { 11631 Slog.e(TAG, "Copying native libraries failed", e); 11632 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11633 } finally { 11634 IoUtils.closeQuietly(handle); 11635 } 11636 11637 return ret; 11638 } 11639 11640 int doPreInstall(int status) { 11641 if (status != PackageManager.INSTALL_SUCCEEDED) { 11642 cleanUp(); 11643 } 11644 return status; 11645 } 11646 11647 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11648 if (status != PackageManager.INSTALL_SUCCEEDED) { 11649 cleanUp(); 11650 return false; 11651 } 11652 11653 final File targetDir = codeFile.getParentFile(); 11654 final File beforeCodeFile = codeFile; 11655 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11656 11657 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11658 try { 11659 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11660 } catch (ErrnoException e) { 11661 Slog.w(TAG, "Failed to rename", e); 11662 return false; 11663 } 11664 11665 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11666 Slog.w(TAG, "Failed to restorecon"); 11667 return false; 11668 } 11669 11670 // Reflect the rename internally 11671 codeFile = afterCodeFile; 11672 resourceFile = afterCodeFile; 11673 11674 // Reflect the rename in scanned details 11675 pkg.codePath = afterCodeFile.getAbsolutePath(); 11676 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11677 pkg.baseCodePath); 11678 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11679 pkg.splitCodePaths); 11680 11681 // Reflect the rename in app info 11682 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11683 pkg.applicationInfo.setCodePath(pkg.codePath); 11684 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11685 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11686 pkg.applicationInfo.setResourcePath(pkg.codePath); 11687 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11688 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11689 11690 return true; 11691 } 11692 11693 int doPostInstall(int status, int uid) { 11694 if (status != PackageManager.INSTALL_SUCCEEDED) { 11695 cleanUp(); 11696 } 11697 return status; 11698 } 11699 11700 @Override 11701 String getCodePath() { 11702 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11703 } 11704 11705 @Override 11706 String getResourcePath() { 11707 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11708 } 11709 11710 private boolean cleanUp() { 11711 if (codeFile == null || !codeFile.exists()) { 11712 return false; 11713 } 11714 11715 removeCodePathLI(codeFile); 11716 11717 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11718 resourceFile.delete(); 11719 } 11720 11721 return true; 11722 } 11723 11724 void cleanUpResourcesLI() { 11725 // Try enumerating all code paths before deleting 11726 List<String> allCodePaths = Collections.EMPTY_LIST; 11727 if (codeFile != null && codeFile.exists()) { 11728 try { 11729 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11730 allCodePaths = pkg.getAllCodePaths(); 11731 } catch (PackageParserException e) { 11732 // Ignored; we tried our best 11733 } 11734 } 11735 11736 cleanUp(); 11737 removeDexFiles(allCodePaths, instructionSets); 11738 } 11739 11740 boolean doPostDeleteLI(boolean delete) { 11741 // XXX err, shouldn't we respect the delete flag? 11742 cleanUpResourcesLI(); 11743 return true; 11744 } 11745 } 11746 11747 private boolean isAsecExternal(String cid) { 11748 final String asecPath = PackageHelper.getSdFilesystem(cid); 11749 return !asecPath.startsWith(mAsecInternalPath); 11750 } 11751 11752 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11753 PackageManagerException { 11754 if (copyRet < 0) { 11755 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11756 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11757 throw new PackageManagerException(copyRet, message); 11758 } 11759 } 11760 } 11761 11762 /** 11763 * Extract the MountService "container ID" from the full code path of an 11764 * .apk. 11765 */ 11766 static String cidFromCodePath(String fullCodePath) { 11767 int eidx = fullCodePath.lastIndexOf("/"); 11768 String subStr1 = fullCodePath.substring(0, eidx); 11769 int sidx = subStr1.lastIndexOf("/"); 11770 return subStr1.substring(sidx+1, eidx); 11771 } 11772 11773 /** 11774 * Logic to handle installation of ASEC applications, including copying and 11775 * renaming logic. 11776 */ 11777 class AsecInstallArgs extends InstallArgs { 11778 static final String RES_FILE_NAME = "pkg.apk"; 11779 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11780 11781 String cid; 11782 String packagePath; 11783 String resourcePath; 11784 11785 /** New install */ 11786 AsecInstallArgs(InstallParams params) { 11787 super(params.origin, params.move, params.observer, params.installFlags, 11788 params.installerPackageName, params.volumeUuid, 11789 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11790 params.grantedRuntimePermissions, 11791 params.traceMethod, params.traceCookie); 11792 } 11793 11794 /** Existing install */ 11795 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11796 boolean isExternal, boolean isForwardLocked) { 11797 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11798 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11799 instructionSets, null, null, null, 0); 11800 // Hackily pretend we're still looking at a full code path 11801 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11802 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11803 } 11804 11805 // Extract cid from fullCodePath 11806 int eidx = fullCodePath.lastIndexOf("/"); 11807 String subStr1 = fullCodePath.substring(0, eidx); 11808 int sidx = subStr1.lastIndexOf("/"); 11809 cid = subStr1.substring(sidx+1, eidx); 11810 setMountPath(subStr1); 11811 } 11812 11813 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11814 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11815 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11816 instructionSets, null, null, null, 0); 11817 this.cid = cid; 11818 setMountPath(PackageHelper.getSdDir(cid)); 11819 } 11820 11821 void createCopyFile() { 11822 cid = mInstallerService.allocateExternalStageCidLegacy(); 11823 } 11824 11825 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11826 if (origin.staged && origin.cid != null) { 11827 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11828 cid = origin.cid; 11829 setMountPath(PackageHelper.getSdDir(cid)); 11830 return PackageManager.INSTALL_SUCCEEDED; 11831 } 11832 11833 if (temp) { 11834 createCopyFile(); 11835 } else { 11836 /* 11837 * Pre-emptively destroy the container since it's destroyed if 11838 * copying fails due to it existing anyway. 11839 */ 11840 PackageHelper.destroySdDir(cid); 11841 } 11842 11843 final String newMountPath = imcs.copyPackageToContainer( 11844 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11845 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11846 11847 if (newMountPath != null) { 11848 setMountPath(newMountPath); 11849 return PackageManager.INSTALL_SUCCEEDED; 11850 } else { 11851 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11852 } 11853 } 11854 11855 @Override 11856 String getCodePath() { 11857 return packagePath; 11858 } 11859 11860 @Override 11861 String getResourcePath() { 11862 return resourcePath; 11863 } 11864 11865 int doPreInstall(int status) { 11866 if (status != PackageManager.INSTALL_SUCCEEDED) { 11867 // Destroy container 11868 PackageHelper.destroySdDir(cid); 11869 } else { 11870 boolean mounted = PackageHelper.isContainerMounted(cid); 11871 if (!mounted) { 11872 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11873 Process.SYSTEM_UID); 11874 if (newMountPath != null) { 11875 setMountPath(newMountPath); 11876 } else { 11877 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11878 } 11879 } 11880 } 11881 return status; 11882 } 11883 11884 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11885 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11886 String newMountPath = null; 11887 if (PackageHelper.isContainerMounted(cid)) { 11888 // Unmount the container 11889 if (!PackageHelper.unMountSdDir(cid)) { 11890 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11891 return false; 11892 } 11893 } 11894 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11895 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11896 " which might be stale. Will try to clean up."); 11897 // Clean up the stale container and proceed to recreate. 11898 if (!PackageHelper.destroySdDir(newCacheId)) { 11899 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11900 return false; 11901 } 11902 // Successfully cleaned up stale container. Try to rename again. 11903 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11904 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11905 + " inspite of cleaning it up."); 11906 return false; 11907 } 11908 } 11909 if (!PackageHelper.isContainerMounted(newCacheId)) { 11910 Slog.w(TAG, "Mounting container " + newCacheId); 11911 newMountPath = PackageHelper.mountSdDir(newCacheId, 11912 getEncryptKey(), Process.SYSTEM_UID); 11913 } else { 11914 newMountPath = PackageHelper.getSdDir(newCacheId); 11915 } 11916 if (newMountPath == null) { 11917 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11918 return false; 11919 } 11920 Log.i(TAG, "Succesfully renamed " + cid + 11921 " to " + newCacheId + 11922 " at new path: " + newMountPath); 11923 cid = newCacheId; 11924 11925 final File beforeCodeFile = new File(packagePath); 11926 setMountPath(newMountPath); 11927 final File afterCodeFile = new File(packagePath); 11928 11929 // Reflect the rename in scanned details 11930 pkg.codePath = afterCodeFile.getAbsolutePath(); 11931 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11932 pkg.baseCodePath); 11933 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11934 pkg.splitCodePaths); 11935 11936 // Reflect the rename in app info 11937 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11938 pkg.applicationInfo.setCodePath(pkg.codePath); 11939 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11940 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11941 pkg.applicationInfo.setResourcePath(pkg.codePath); 11942 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11943 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11944 11945 return true; 11946 } 11947 11948 private void setMountPath(String mountPath) { 11949 final File mountFile = new File(mountPath); 11950 11951 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11952 if (monolithicFile.exists()) { 11953 packagePath = monolithicFile.getAbsolutePath(); 11954 if (isFwdLocked()) { 11955 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11956 } else { 11957 resourcePath = packagePath; 11958 } 11959 } else { 11960 packagePath = mountFile.getAbsolutePath(); 11961 resourcePath = packagePath; 11962 } 11963 } 11964 11965 int doPostInstall(int status, int uid) { 11966 if (status != PackageManager.INSTALL_SUCCEEDED) { 11967 cleanUp(); 11968 } else { 11969 final int groupOwner; 11970 final String protectedFile; 11971 if (isFwdLocked()) { 11972 groupOwner = UserHandle.getSharedAppGid(uid); 11973 protectedFile = RES_FILE_NAME; 11974 } else { 11975 groupOwner = -1; 11976 protectedFile = null; 11977 } 11978 11979 if (uid < Process.FIRST_APPLICATION_UID 11980 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11981 Slog.e(TAG, "Failed to finalize " + cid); 11982 PackageHelper.destroySdDir(cid); 11983 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11984 } 11985 11986 boolean mounted = PackageHelper.isContainerMounted(cid); 11987 if (!mounted) { 11988 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11989 } 11990 } 11991 return status; 11992 } 11993 11994 private void cleanUp() { 11995 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11996 11997 // Destroy secure container 11998 PackageHelper.destroySdDir(cid); 11999 } 12000 12001 private List<String> getAllCodePaths() { 12002 final File codeFile = new File(getCodePath()); 12003 if (codeFile != null && codeFile.exists()) { 12004 try { 12005 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12006 return pkg.getAllCodePaths(); 12007 } catch (PackageParserException e) { 12008 // Ignored; we tried our best 12009 } 12010 } 12011 return Collections.EMPTY_LIST; 12012 } 12013 12014 void cleanUpResourcesLI() { 12015 // Enumerate all code paths before deleting 12016 cleanUpResourcesLI(getAllCodePaths()); 12017 } 12018 12019 private void cleanUpResourcesLI(List<String> allCodePaths) { 12020 cleanUp(); 12021 removeDexFiles(allCodePaths, instructionSets); 12022 } 12023 12024 String getPackageName() { 12025 return getAsecPackageName(cid); 12026 } 12027 12028 boolean doPostDeleteLI(boolean delete) { 12029 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12030 final List<String> allCodePaths = getAllCodePaths(); 12031 boolean mounted = PackageHelper.isContainerMounted(cid); 12032 if (mounted) { 12033 // Unmount first 12034 if (PackageHelper.unMountSdDir(cid)) { 12035 mounted = false; 12036 } 12037 } 12038 if (!mounted && delete) { 12039 cleanUpResourcesLI(allCodePaths); 12040 } 12041 return !mounted; 12042 } 12043 12044 @Override 12045 int doPreCopy() { 12046 if (isFwdLocked()) { 12047 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12048 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12049 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12050 } 12051 } 12052 12053 return PackageManager.INSTALL_SUCCEEDED; 12054 } 12055 12056 @Override 12057 int doPostCopy(int uid) { 12058 if (isFwdLocked()) { 12059 if (uid < Process.FIRST_APPLICATION_UID 12060 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12061 RES_FILE_NAME)) { 12062 Slog.e(TAG, "Failed to finalize " + cid); 12063 PackageHelper.destroySdDir(cid); 12064 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12065 } 12066 } 12067 12068 return PackageManager.INSTALL_SUCCEEDED; 12069 } 12070 } 12071 12072 /** 12073 * Logic to handle movement of existing installed applications. 12074 */ 12075 class MoveInstallArgs extends InstallArgs { 12076 private File codeFile; 12077 private File resourceFile; 12078 12079 /** New install */ 12080 MoveInstallArgs(InstallParams params) { 12081 super(params.origin, params.move, params.observer, params.installFlags, 12082 params.installerPackageName, params.volumeUuid, 12083 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12084 params.grantedRuntimePermissions, 12085 params.traceMethod, params.traceCookie); 12086 } 12087 12088 int copyApk(IMediaContainerService imcs, boolean temp) { 12089 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12090 + move.fromUuid + " to " + move.toUuid); 12091 synchronized (mInstaller) { 12092 try { 12093 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12094 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12095 } catch (InstallerException e) { 12096 Slog.w(TAG, "Failed to move app", e); 12097 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12098 } 12099 } 12100 12101 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12102 resourceFile = codeFile; 12103 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12104 12105 return PackageManager.INSTALL_SUCCEEDED; 12106 } 12107 12108 int doPreInstall(int status) { 12109 if (status != PackageManager.INSTALL_SUCCEEDED) { 12110 cleanUp(move.toUuid); 12111 } 12112 return status; 12113 } 12114 12115 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12116 if (status != PackageManager.INSTALL_SUCCEEDED) { 12117 cleanUp(move.toUuid); 12118 return false; 12119 } 12120 12121 // Reflect the move in app info 12122 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12123 pkg.applicationInfo.setCodePath(pkg.codePath); 12124 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12125 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12126 pkg.applicationInfo.setResourcePath(pkg.codePath); 12127 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12128 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12129 12130 return true; 12131 } 12132 12133 int doPostInstall(int status, int uid) { 12134 if (status == PackageManager.INSTALL_SUCCEEDED) { 12135 cleanUp(move.fromUuid); 12136 } else { 12137 cleanUp(move.toUuid); 12138 } 12139 return status; 12140 } 12141 12142 @Override 12143 String getCodePath() { 12144 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12145 } 12146 12147 @Override 12148 String getResourcePath() { 12149 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12150 } 12151 12152 private boolean cleanUp(String volumeUuid) { 12153 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12154 move.dataAppName); 12155 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12156 synchronized (mInstallLock) { 12157 // Clean up both app data and code 12158 removeDataDirsLI(volumeUuid, move.packageName); 12159 removeCodePathLI(codeFile); 12160 } 12161 return true; 12162 } 12163 12164 void cleanUpResourcesLI() { 12165 throw new UnsupportedOperationException(); 12166 } 12167 12168 boolean doPostDeleteLI(boolean delete) { 12169 throw new UnsupportedOperationException(); 12170 } 12171 } 12172 12173 static String getAsecPackageName(String packageCid) { 12174 int idx = packageCid.lastIndexOf("-"); 12175 if (idx == -1) { 12176 return packageCid; 12177 } 12178 return packageCid.substring(0, idx); 12179 } 12180 12181 // Utility method used to create code paths based on package name and available index. 12182 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12183 String idxStr = ""; 12184 int idx = 1; 12185 // Fall back to default value of idx=1 if prefix is not 12186 // part of oldCodePath 12187 if (oldCodePath != null) { 12188 String subStr = oldCodePath; 12189 // Drop the suffix right away 12190 if (suffix != null && subStr.endsWith(suffix)) { 12191 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12192 } 12193 // If oldCodePath already contains prefix find out the 12194 // ending index to either increment or decrement. 12195 int sidx = subStr.lastIndexOf(prefix); 12196 if (sidx != -1) { 12197 subStr = subStr.substring(sidx + prefix.length()); 12198 if (subStr != null) { 12199 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12200 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12201 } 12202 try { 12203 idx = Integer.parseInt(subStr); 12204 if (idx <= 1) { 12205 idx++; 12206 } else { 12207 idx--; 12208 } 12209 } catch(NumberFormatException e) { 12210 } 12211 } 12212 } 12213 } 12214 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12215 return prefix + idxStr; 12216 } 12217 12218 private File getNextCodePath(File targetDir, String packageName) { 12219 int suffix = 1; 12220 File result; 12221 do { 12222 result = new File(targetDir, packageName + "-" + suffix); 12223 suffix++; 12224 } while (result.exists()); 12225 return result; 12226 } 12227 12228 // Utility method that returns the relative package path with respect 12229 // to the installation directory. Like say for /data/data/com.test-1.apk 12230 // string com.test-1 is returned. 12231 static String deriveCodePathName(String codePath) { 12232 if (codePath == null) { 12233 return null; 12234 } 12235 final File codeFile = new File(codePath); 12236 final String name = codeFile.getName(); 12237 if (codeFile.isDirectory()) { 12238 return name; 12239 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12240 final int lastDot = name.lastIndexOf('.'); 12241 return name.substring(0, lastDot); 12242 } else { 12243 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12244 return null; 12245 } 12246 } 12247 12248 static class PackageInstalledInfo { 12249 String name; 12250 int uid; 12251 // The set of users that originally had this package installed. 12252 int[] origUsers; 12253 // The set of users that now have this package installed. 12254 int[] newUsers; 12255 PackageParser.Package pkg; 12256 int returnCode; 12257 String returnMsg; 12258 PackageRemovedInfo removedInfo; 12259 12260 public void setError(int code, String msg) { 12261 returnCode = code; 12262 returnMsg = msg; 12263 Slog.w(TAG, msg); 12264 } 12265 12266 public void setError(String msg, PackageParserException e) { 12267 returnCode = e.error; 12268 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12269 Slog.w(TAG, msg, e); 12270 } 12271 12272 public void setError(String msg, PackageManagerException e) { 12273 returnCode = e.error; 12274 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12275 Slog.w(TAG, msg, e); 12276 } 12277 12278 // In some error cases we want to convey more info back to the observer 12279 String origPackage; 12280 String origPermission; 12281 } 12282 12283 /* 12284 * Install a non-existing package. 12285 */ 12286 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12287 UserHandle user, String installerPackageName, String volumeUuid, 12288 PackageInstalledInfo res) { 12289 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12290 12291 // Remember this for later, in case we need to rollback this install 12292 String pkgName = pkg.packageName; 12293 12294 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12295 // TODO: b/23350563 12296 final boolean dataDirExists = Environment 12297 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12298 12299 synchronized(mPackages) { 12300 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12301 // A package with the same name is already installed, though 12302 // it has been renamed to an older name. The package we 12303 // are trying to install should be installed as an update to 12304 // the existing one, but that has not been requested, so bail. 12305 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12306 + " without first uninstalling package running as " 12307 + mSettings.mRenamedPackages.get(pkgName)); 12308 return; 12309 } 12310 if (mPackages.containsKey(pkgName)) { 12311 // Don't allow installation over an existing package with the same name. 12312 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12313 + " without first uninstalling."); 12314 return; 12315 } 12316 } 12317 12318 try { 12319 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12320 System.currentTimeMillis(), user); 12321 12322 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12323 prepareAppDataAfterInstall(newPackage); 12324 12325 // delete the partially installed application. the data directory will have to be 12326 // restored if it was already existing 12327 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12328 // remove package from internal structures. Note that we want deletePackageX to 12329 // delete the package data and cache directories that it created in 12330 // scanPackageLocked, unless those directories existed before we even tried to 12331 // install. 12332 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12333 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12334 res.removedInfo, true); 12335 } 12336 12337 } catch (PackageManagerException e) { 12338 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12339 } 12340 12341 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12342 } 12343 12344 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12345 // Can't rotate keys during boot or if sharedUser. 12346 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12347 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12348 return false; 12349 } 12350 // app is using upgradeKeySets; make sure all are valid 12351 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12352 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12353 for (int i = 0; i < upgradeKeySets.length; i++) { 12354 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12355 Slog.wtf(TAG, "Package " 12356 + (oldPs.name != null ? oldPs.name : "<null>") 12357 + " contains upgrade-key-set reference to unknown key-set: " 12358 + upgradeKeySets[i] 12359 + " reverting to signatures check."); 12360 return false; 12361 } 12362 } 12363 return true; 12364 } 12365 12366 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12367 // Upgrade keysets are being used. Determine if new package has a superset of the 12368 // required keys. 12369 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12370 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12371 for (int i = 0; i < upgradeKeySets.length; i++) { 12372 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12373 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12374 return true; 12375 } 12376 } 12377 return false; 12378 } 12379 12380 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12381 UserHandle user, String installerPackageName, String volumeUuid, 12382 PackageInstalledInfo res) { 12383 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12384 12385 final PackageParser.Package oldPackage; 12386 final String pkgName = pkg.packageName; 12387 final int[] allUsers; 12388 final boolean[] perUserInstalled; 12389 12390 // First find the old package info and check signatures 12391 synchronized(mPackages) { 12392 oldPackage = mPackages.get(pkgName); 12393 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12394 if (isEphemeral && !oldIsEphemeral) { 12395 // can't downgrade from full to ephemeral 12396 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12397 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12398 return; 12399 } 12400 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12401 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12402 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12403 if(!checkUpgradeKeySetLP(ps, pkg)) { 12404 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12405 "New package not signed by keys specified by upgrade-keysets: " 12406 + pkgName); 12407 return; 12408 } 12409 } else { 12410 // default to original signature matching 12411 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12412 != PackageManager.SIGNATURE_MATCH) { 12413 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12414 "New package has a different signature: " + pkgName); 12415 return; 12416 } 12417 } 12418 12419 // In case of rollback, remember per-user/profile install state 12420 allUsers = sUserManager.getUserIds(); 12421 perUserInstalled = new boolean[allUsers.length]; 12422 for (int i = 0; i < allUsers.length; i++) { 12423 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12424 } 12425 } 12426 12427 boolean sysPkg = (isSystemApp(oldPackage)); 12428 if (sysPkg) { 12429 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12430 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12431 } else { 12432 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12433 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12434 } 12435 } 12436 12437 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12438 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12439 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12440 String volumeUuid, PackageInstalledInfo res) { 12441 String pkgName = deletedPackage.packageName; 12442 boolean deletedPkg = true; 12443 boolean updatedSettings = false; 12444 12445 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12446 + deletedPackage); 12447 long origUpdateTime; 12448 if (pkg.mExtras != null) { 12449 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12450 } else { 12451 origUpdateTime = 0; 12452 } 12453 12454 // First delete the existing package while retaining the data directory 12455 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12456 res.removedInfo, true)) { 12457 // If the existing package wasn't successfully deleted 12458 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12459 deletedPkg = false; 12460 } else { 12461 // Successfully deleted the old package; proceed with replace. 12462 12463 // If deleted package lived in a container, give users a chance to 12464 // relinquish resources before killing. 12465 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12466 if (DEBUG_INSTALL) { 12467 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12468 } 12469 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12470 final ArrayList<String> pkgList = new ArrayList<String>(1); 12471 pkgList.add(deletedPackage.applicationInfo.packageName); 12472 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12473 } 12474 12475 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12476 try { 12477 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12478 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12479 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12480 perUserInstalled, res, user); 12481 prepareAppDataAfterInstall(newPackage); 12482 updatedSettings = true; 12483 } catch (PackageManagerException e) { 12484 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12485 } 12486 } 12487 12488 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12489 // remove package from internal structures. Note that we want deletePackageX to 12490 // delete the package data and cache directories that it created in 12491 // scanPackageLocked, unless those directories existed before we even tried to 12492 // install. 12493 if(updatedSettings) { 12494 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12495 deletePackageLI( 12496 pkgName, null, true, allUsers, perUserInstalled, 12497 PackageManager.DELETE_KEEP_DATA, 12498 res.removedInfo, true); 12499 } 12500 // Since we failed to install the new package we need to restore the old 12501 // package that we deleted. 12502 if (deletedPkg) { 12503 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12504 File restoreFile = new File(deletedPackage.codePath); 12505 // Parse old package 12506 boolean oldExternal = isExternal(deletedPackage); 12507 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12508 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12509 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12510 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12511 try { 12512 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12513 null); 12514 } catch (PackageManagerException e) { 12515 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12516 + e.getMessage()); 12517 return; 12518 } 12519 // Restore of old package succeeded. Update permissions. 12520 // writer 12521 synchronized (mPackages) { 12522 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12523 UPDATE_PERMISSIONS_ALL); 12524 // can downgrade to reader 12525 mSettings.writeLPr(); 12526 } 12527 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12528 } 12529 } 12530 } 12531 12532 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12533 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12534 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12535 String volumeUuid, PackageInstalledInfo res) { 12536 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12537 + ", old=" + deletedPackage); 12538 boolean disabledSystem = false; 12539 boolean updatedSettings = false; 12540 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12541 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12542 != 0) { 12543 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12544 } 12545 String packageName = deletedPackage.packageName; 12546 if (packageName == null) { 12547 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12548 "Attempt to delete null packageName."); 12549 return; 12550 } 12551 PackageParser.Package oldPkg; 12552 PackageSetting oldPkgSetting; 12553 // reader 12554 synchronized (mPackages) { 12555 oldPkg = mPackages.get(packageName); 12556 oldPkgSetting = mSettings.mPackages.get(packageName); 12557 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12558 (oldPkgSetting == null)) { 12559 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12560 "Couldn't find package " + packageName + " information"); 12561 return; 12562 } 12563 } 12564 12565 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12566 12567 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12568 res.removedInfo.removedPackage = packageName; 12569 // Remove existing system package 12570 removePackageLI(oldPkgSetting, true); 12571 // writer 12572 synchronized (mPackages) { 12573 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12574 if (!disabledSystem && deletedPackage != null) { 12575 // We didn't need to disable the .apk as a current system package, 12576 // which means we are replacing another update that is already 12577 // installed. We need to make sure to delete the older one's .apk. 12578 res.removedInfo.args = createInstallArgsForExisting(0, 12579 deletedPackage.applicationInfo.getCodePath(), 12580 deletedPackage.applicationInfo.getResourcePath(), 12581 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12582 } else { 12583 res.removedInfo.args = null; 12584 } 12585 } 12586 12587 // Successfully disabled the old package. Now proceed with re-installation 12588 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12589 12590 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12591 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12592 12593 PackageParser.Package newPackage = null; 12594 try { 12595 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12596 if (newPackage.mExtras != null) { 12597 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12598 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12599 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12600 12601 // is the update attempting to change shared user? that isn't going to work... 12602 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12603 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12604 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12605 + " to " + newPkgSetting.sharedUser); 12606 updatedSettings = true; 12607 } 12608 } 12609 12610 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12611 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12612 perUserInstalled, res, user); 12613 prepareAppDataAfterInstall(newPackage); 12614 updatedSettings = true; 12615 } 12616 12617 } catch (PackageManagerException e) { 12618 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12619 } 12620 12621 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12622 // Re installation failed. Restore old information 12623 // Remove new pkg information 12624 if (newPackage != null) { 12625 removeInstalledPackageLI(newPackage, true); 12626 } 12627 // Add back the old system package 12628 try { 12629 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12630 } catch (PackageManagerException e) { 12631 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12632 } 12633 // Restore the old system information in Settings 12634 synchronized (mPackages) { 12635 if (disabledSystem) { 12636 mSettings.enableSystemPackageLPw(packageName); 12637 } 12638 if (updatedSettings) { 12639 mSettings.setInstallerPackageName(packageName, 12640 oldPkgSetting.installerPackageName); 12641 } 12642 mSettings.writeLPr(); 12643 } 12644 } 12645 } 12646 12647 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12648 // Collect all used permissions in the UID 12649 ArraySet<String> usedPermissions = new ArraySet<>(); 12650 final int packageCount = su.packages.size(); 12651 for (int i = 0; i < packageCount; i++) { 12652 PackageSetting ps = su.packages.valueAt(i); 12653 if (ps.pkg == null) { 12654 continue; 12655 } 12656 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12657 for (int j = 0; j < requestedPermCount; j++) { 12658 String permission = ps.pkg.requestedPermissions.get(j); 12659 BasePermission bp = mSettings.mPermissions.get(permission); 12660 if (bp != null) { 12661 usedPermissions.add(permission); 12662 } 12663 } 12664 } 12665 12666 PermissionsState permissionsState = su.getPermissionsState(); 12667 // Prune install permissions 12668 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12669 final int installPermCount = installPermStates.size(); 12670 for (int i = installPermCount - 1; i >= 0; i--) { 12671 PermissionState permissionState = installPermStates.get(i); 12672 if (!usedPermissions.contains(permissionState.getName())) { 12673 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12674 if (bp != null) { 12675 permissionsState.revokeInstallPermission(bp); 12676 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12677 PackageManager.MASK_PERMISSION_FLAGS, 0); 12678 } 12679 } 12680 } 12681 12682 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12683 12684 // Prune runtime permissions 12685 for (int userId : allUserIds) { 12686 List<PermissionState> runtimePermStates = permissionsState 12687 .getRuntimePermissionStates(userId); 12688 final int runtimePermCount = runtimePermStates.size(); 12689 for (int i = runtimePermCount - 1; i >= 0; i--) { 12690 PermissionState permissionState = runtimePermStates.get(i); 12691 if (!usedPermissions.contains(permissionState.getName())) { 12692 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12693 if (bp != null) { 12694 permissionsState.revokeRuntimePermission(bp, userId); 12695 permissionsState.updatePermissionFlags(bp, userId, 12696 PackageManager.MASK_PERMISSION_FLAGS, 0); 12697 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12698 runtimePermissionChangedUserIds, userId); 12699 } 12700 } 12701 } 12702 } 12703 12704 return runtimePermissionChangedUserIds; 12705 } 12706 12707 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12708 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12709 UserHandle user) { 12710 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12711 12712 String pkgName = newPackage.packageName; 12713 synchronized (mPackages) { 12714 //write settings. the installStatus will be incomplete at this stage. 12715 //note that the new package setting would have already been 12716 //added to mPackages. It hasn't been persisted yet. 12717 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12718 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12719 mSettings.writeLPr(); 12720 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12721 } 12722 12723 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12724 synchronized (mPackages) { 12725 updatePermissionsLPw(newPackage.packageName, newPackage, 12726 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12727 ? UPDATE_PERMISSIONS_ALL : 0)); 12728 // For system-bundled packages, we assume that installing an upgraded version 12729 // of the package implies that the user actually wants to run that new code, 12730 // so we enable the package. 12731 PackageSetting ps = mSettings.mPackages.get(pkgName); 12732 if (ps != null) { 12733 if (isSystemApp(newPackage)) { 12734 // NB: implicit assumption that system package upgrades apply to all users 12735 if (DEBUG_INSTALL) { 12736 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12737 } 12738 if (res.origUsers != null) { 12739 for (int userHandle : res.origUsers) { 12740 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12741 userHandle, installerPackageName); 12742 } 12743 } 12744 // Also convey the prior install/uninstall state 12745 if (allUsers != null && perUserInstalled != null) { 12746 for (int i = 0; i < allUsers.length; i++) { 12747 if (DEBUG_INSTALL) { 12748 Slog.d(TAG, " user " + allUsers[i] 12749 + " => " + perUserInstalled[i]); 12750 } 12751 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12752 } 12753 // these install state changes will be persisted in the 12754 // upcoming call to mSettings.writeLPr(). 12755 } 12756 } 12757 // It's implied that when a user requests installation, they want the app to be 12758 // installed and enabled. 12759 int userId = user.getIdentifier(); 12760 if (userId != UserHandle.USER_ALL) { 12761 ps.setInstalled(true, userId); 12762 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12763 } 12764 } 12765 res.name = pkgName; 12766 res.uid = newPackage.applicationInfo.uid; 12767 res.pkg = newPackage; 12768 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12769 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12770 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12771 //to update install status 12772 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12773 mSettings.writeLPr(); 12774 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12775 } 12776 12777 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12778 } 12779 12780 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12781 try { 12782 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12783 installPackageLI(args, res); 12784 } finally { 12785 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12786 } 12787 } 12788 12789 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12790 final int installFlags = args.installFlags; 12791 final String installerPackageName = args.installerPackageName; 12792 final String volumeUuid = args.volumeUuid; 12793 final File tmpPackageFile = new File(args.getCodePath()); 12794 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12795 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12796 || (args.volumeUuid != null)); 12797 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12798 boolean replace = false; 12799 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12800 if (args.move != null) { 12801 // moving a complete application; perfom an initial scan on the new install location 12802 scanFlags |= SCAN_INITIAL; 12803 } 12804 // Result object to be returned 12805 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12806 12807 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12808 12809 // Sanity check 12810 if (ephemeral && (forwardLocked || onExternal)) { 12811 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12812 + " external=" + onExternal); 12813 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12814 return; 12815 } 12816 12817 // Retrieve PackageSettings and parse package 12818 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12819 | PackageParser.PARSE_ENFORCE_CODE 12820 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12821 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12822 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12823 PackageParser pp = new PackageParser(); 12824 pp.setSeparateProcesses(mSeparateProcesses); 12825 pp.setDisplayMetrics(mMetrics); 12826 12827 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12828 final PackageParser.Package pkg; 12829 try { 12830 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12831 } catch (PackageParserException e) { 12832 res.setError("Failed parse during installPackageLI", e); 12833 return; 12834 } finally { 12835 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12836 } 12837 12838 // Mark that we have an install time CPU ABI override. 12839 pkg.cpuAbiOverride = args.abiOverride; 12840 12841 String pkgName = res.name = pkg.packageName; 12842 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12843 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12844 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12845 return; 12846 } 12847 } 12848 12849 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12850 try { 12851 pp.collectCertificates(pkg, parseFlags); 12852 } catch (PackageParserException e) { 12853 res.setError("Failed collect during installPackageLI", e); 12854 return; 12855 } finally { 12856 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12857 } 12858 12859 // Get rid of all references to package scan path via parser. 12860 pp = null; 12861 String oldCodePath = null; 12862 boolean systemApp = false; 12863 synchronized (mPackages) { 12864 // Check if installing already existing package 12865 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12866 String oldName = mSettings.mRenamedPackages.get(pkgName); 12867 if (pkg.mOriginalPackages != null 12868 && pkg.mOriginalPackages.contains(oldName) 12869 && mPackages.containsKey(oldName)) { 12870 // This package is derived from an original package, 12871 // and this device has been updating from that original 12872 // name. We must continue using the original name, so 12873 // rename the new package here. 12874 pkg.setPackageName(oldName); 12875 pkgName = pkg.packageName; 12876 replace = true; 12877 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12878 + oldName + " pkgName=" + pkgName); 12879 } else if (mPackages.containsKey(pkgName)) { 12880 // This package, under its official name, already exists 12881 // on the device; we should replace it. 12882 replace = true; 12883 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12884 } 12885 12886 // Prevent apps opting out from runtime permissions 12887 if (replace) { 12888 PackageParser.Package oldPackage = mPackages.get(pkgName); 12889 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12890 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12891 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12892 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12893 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12894 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12895 + " doesn't support runtime permissions but the old" 12896 + " target SDK " + oldTargetSdk + " does."); 12897 return; 12898 } 12899 } 12900 } 12901 12902 PackageSetting ps = mSettings.mPackages.get(pkgName); 12903 if (ps != null) { 12904 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12905 12906 // Quick sanity check that we're signed correctly if updating; 12907 // we'll check this again later when scanning, but we want to 12908 // bail early here before tripping over redefined permissions. 12909 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12910 if (!checkUpgradeKeySetLP(ps, pkg)) { 12911 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12912 + pkg.packageName + " upgrade keys do not match the " 12913 + "previously installed version"); 12914 return; 12915 } 12916 } else { 12917 try { 12918 verifySignaturesLP(ps, pkg); 12919 } catch (PackageManagerException e) { 12920 res.setError(e.error, e.getMessage()); 12921 return; 12922 } 12923 } 12924 12925 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12926 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12927 systemApp = (ps.pkg.applicationInfo.flags & 12928 ApplicationInfo.FLAG_SYSTEM) != 0; 12929 } 12930 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12931 } 12932 12933 // Check whether the newly-scanned package wants to define an already-defined perm 12934 int N = pkg.permissions.size(); 12935 for (int i = N-1; i >= 0; i--) { 12936 PackageParser.Permission perm = pkg.permissions.get(i); 12937 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12938 if (bp != null) { 12939 // If the defining package is signed with our cert, it's okay. This 12940 // also includes the "updating the same package" case, of course. 12941 // "updating same package" could also involve key-rotation. 12942 final boolean sigsOk; 12943 if (bp.sourcePackage.equals(pkg.packageName) 12944 && (bp.packageSetting instanceof PackageSetting) 12945 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12946 scanFlags))) { 12947 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12948 } else { 12949 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12950 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12951 } 12952 if (!sigsOk) { 12953 // If the owning package is the system itself, we log but allow 12954 // install to proceed; we fail the install on all other permission 12955 // redefinitions. 12956 if (!bp.sourcePackage.equals("android")) { 12957 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12958 + pkg.packageName + " attempting to redeclare permission " 12959 + perm.info.name + " already owned by " + bp.sourcePackage); 12960 res.origPermission = perm.info.name; 12961 res.origPackage = bp.sourcePackage; 12962 return; 12963 } else { 12964 Slog.w(TAG, "Package " + pkg.packageName 12965 + " attempting to redeclare system permission " 12966 + perm.info.name + "; ignoring new declaration"); 12967 pkg.permissions.remove(i); 12968 } 12969 } 12970 } 12971 } 12972 12973 } 12974 12975 if (systemApp) { 12976 if (onExternal) { 12977 // Abort update; system app can't be replaced with app on sdcard 12978 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12979 "Cannot install updates to system apps on sdcard"); 12980 return; 12981 } else if (ephemeral) { 12982 // Abort update; system app can't be replaced with an ephemeral app 12983 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 12984 "Cannot update a system app with an ephemeral app"); 12985 return; 12986 } 12987 } 12988 12989 if (args.move != null) { 12990 // We did an in-place move, so dex is ready to roll 12991 scanFlags |= SCAN_NO_DEX; 12992 scanFlags |= SCAN_MOVE; 12993 12994 synchronized (mPackages) { 12995 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12996 if (ps == null) { 12997 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12998 "Missing settings for moved package " + pkgName); 12999 } 13000 13001 // We moved the entire application as-is, so bring over the 13002 // previously derived ABI information. 13003 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13004 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13005 } 13006 13007 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13008 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13009 scanFlags |= SCAN_NO_DEX; 13010 13011 try { 13012 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 13013 true /* extract libs */); 13014 } catch (PackageManagerException pme) { 13015 Slog.e(TAG, "Error deriving application ABI", pme); 13016 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13017 return; 13018 } 13019 13020 // Extract package to save the VM unzipping the APK in memory during 13021 // launch. Only do this if profile-guided compilation is enabled because 13022 // otherwise BackgroundDexOptService will not dexopt the package later. 13023 if (mUseJitProfiles) { 13024 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13025 // Do not run PackageDexOptimizer through the local performDexOpt 13026 // method because `pkg` is not in `mPackages` yet. 13027 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13028 false /* inclDependencies */, false /* useProfiles */, 13029 true /* extractOnly */); 13030 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13031 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13032 String msg = "Extracking package failed for " + pkgName; 13033 res.setError(INSTALL_FAILED_DEXOPT, msg); 13034 return; 13035 } 13036 } 13037 } 13038 13039 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13040 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13041 return; 13042 } 13043 13044 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13045 13046 if (replace) { 13047 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13048 installerPackageName, volumeUuid, res); 13049 } else { 13050 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13051 args.user, installerPackageName, volumeUuid, res); 13052 } 13053 synchronized (mPackages) { 13054 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13055 if (ps != null) { 13056 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13057 } 13058 } 13059 } 13060 13061 private void startIntentFilterVerifications(int userId, boolean replacing, 13062 PackageParser.Package pkg) { 13063 if (mIntentFilterVerifierComponent == null) { 13064 Slog.w(TAG, "No IntentFilter verification will not be done as " 13065 + "there is no IntentFilterVerifier available!"); 13066 return; 13067 } 13068 13069 final int verifierUid = getPackageUid( 13070 mIntentFilterVerifierComponent.getPackageName(), 13071 MATCH_DEBUG_TRIAGED_MISSING, 13072 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13073 13074 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13075 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13076 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13077 mHandler.sendMessage(msg); 13078 } 13079 13080 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13081 PackageParser.Package pkg) { 13082 int size = pkg.activities.size(); 13083 if (size == 0) { 13084 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13085 "No activity, so no need to verify any IntentFilter!"); 13086 return; 13087 } 13088 13089 final boolean hasDomainURLs = hasDomainURLs(pkg); 13090 if (!hasDomainURLs) { 13091 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13092 "No domain URLs, so no need to verify any IntentFilter!"); 13093 return; 13094 } 13095 13096 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13097 + " if any IntentFilter from the " + size 13098 + " Activities needs verification ..."); 13099 13100 int count = 0; 13101 final String packageName = pkg.packageName; 13102 13103 synchronized (mPackages) { 13104 // If this is a new install and we see that we've already run verification for this 13105 // package, we have nothing to do: it means the state was restored from backup. 13106 if (!replacing) { 13107 IntentFilterVerificationInfo ivi = 13108 mSettings.getIntentFilterVerificationLPr(packageName); 13109 if (ivi != null) { 13110 if (DEBUG_DOMAIN_VERIFICATION) { 13111 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13112 + ivi.getStatusString()); 13113 } 13114 return; 13115 } 13116 } 13117 13118 // If any filters need to be verified, then all need to be. 13119 boolean needToVerify = false; 13120 for (PackageParser.Activity a : pkg.activities) { 13121 for (ActivityIntentInfo filter : a.intents) { 13122 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13123 if (DEBUG_DOMAIN_VERIFICATION) { 13124 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13125 } 13126 needToVerify = true; 13127 break; 13128 } 13129 } 13130 } 13131 13132 if (needToVerify) { 13133 final int verificationId = mIntentFilterVerificationToken++; 13134 for (PackageParser.Activity a : pkg.activities) { 13135 for (ActivityIntentInfo filter : a.intents) { 13136 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13137 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13138 "Verification needed for IntentFilter:" + filter.toString()); 13139 mIntentFilterVerifier.addOneIntentFilterVerification( 13140 verifierUid, userId, verificationId, filter, packageName); 13141 count++; 13142 } 13143 } 13144 } 13145 } 13146 } 13147 13148 if (count > 0) { 13149 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13150 + " IntentFilter verification" + (count > 1 ? "s" : "") 13151 + " for userId:" + userId); 13152 mIntentFilterVerifier.startVerifications(userId); 13153 } else { 13154 if (DEBUG_DOMAIN_VERIFICATION) { 13155 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13156 } 13157 } 13158 } 13159 13160 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13161 final ComponentName cn = filter.activity.getComponentName(); 13162 final String packageName = cn.getPackageName(); 13163 13164 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13165 packageName); 13166 if (ivi == null) { 13167 return true; 13168 } 13169 int status = ivi.getStatus(); 13170 switch (status) { 13171 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13172 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13173 return true; 13174 13175 default: 13176 // Nothing to do 13177 return false; 13178 } 13179 } 13180 13181 private static boolean isMultiArch(ApplicationInfo info) { 13182 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13183 } 13184 13185 private static boolean isExternal(PackageParser.Package pkg) { 13186 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13187 } 13188 13189 private static boolean isExternal(PackageSetting ps) { 13190 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13191 } 13192 13193 private static boolean isEphemeral(PackageParser.Package pkg) { 13194 return pkg.applicationInfo.isEphemeralApp(); 13195 } 13196 13197 private static boolean isEphemeral(PackageSetting ps) { 13198 return ps.pkg != null && isEphemeral(ps.pkg); 13199 } 13200 13201 private static boolean isSystemApp(PackageParser.Package pkg) { 13202 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13203 } 13204 13205 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13206 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13207 } 13208 13209 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13210 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13211 } 13212 13213 private static boolean isSystemApp(PackageSetting ps) { 13214 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13215 } 13216 13217 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13218 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13219 } 13220 13221 private int packageFlagsToInstallFlags(PackageSetting ps) { 13222 int installFlags = 0; 13223 if (isEphemeral(ps)) { 13224 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13225 } 13226 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13227 // This existing package was an external ASEC install when we have 13228 // the external flag without a UUID 13229 installFlags |= PackageManager.INSTALL_EXTERNAL; 13230 } 13231 if (ps.isForwardLocked()) { 13232 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13233 } 13234 return installFlags; 13235 } 13236 13237 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13238 if (isExternal(pkg)) { 13239 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13240 return StorageManager.UUID_PRIMARY_PHYSICAL; 13241 } else { 13242 return pkg.volumeUuid; 13243 } 13244 } else { 13245 return StorageManager.UUID_PRIVATE_INTERNAL; 13246 } 13247 } 13248 13249 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13250 if (isExternal(pkg)) { 13251 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13252 return mSettings.getExternalVersion(); 13253 } else { 13254 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13255 } 13256 } else { 13257 return mSettings.getInternalVersion(); 13258 } 13259 } 13260 13261 private void deleteTempPackageFiles() { 13262 final FilenameFilter filter = new FilenameFilter() { 13263 public boolean accept(File dir, String name) { 13264 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13265 } 13266 }; 13267 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13268 file.delete(); 13269 } 13270 } 13271 13272 @Override 13273 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13274 int flags) { 13275 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13276 flags); 13277 } 13278 13279 @Override 13280 public void deletePackage(final String packageName, 13281 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13282 mContext.enforceCallingOrSelfPermission( 13283 android.Manifest.permission.DELETE_PACKAGES, null); 13284 Preconditions.checkNotNull(packageName); 13285 Preconditions.checkNotNull(observer); 13286 final int uid = Binder.getCallingUid(); 13287 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13288 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13289 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13290 mContext.enforceCallingOrSelfPermission( 13291 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13292 "deletePackage for user " + userId); 13293 } 13294 13295 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13296 try { 13297 observer.onPackageDeleted(packageName, 13298 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13299 } catch (RemoteException re) { 13300 } 13301 return; 13302 } 13303 13304 for (int currentUserId : users) { 13305 if (getBlockUninstallForUser(packageName, currentUserId)) { 13306 try { 13307 observer.onPackageDeleted(packageName, 13308 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13309 } catch (RemoteException re) { 13310 } 13311 return; 13312 } 13313 } 13314 13315 if (DEBUG_REMOVE) { 13316 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13317 } 13318 // Queue up an async operation since the package deletion may take a little while. 13319 mHandler.post(new Runnable() { 13320 public void run() { 13321 mHandler.removeCallbacks(this); 13322 final int returnCode = deletePackageX(packageName, userId, flags); 13323 try { 13324 observer.onPackageDeleted(packageName, returnCode, null); 13325 } catch (RemoteException e) { 13326 Log.i(TAG, "Observer no longer exists."); 13327 } //end catch 13328 } //end run 13329 }); 13330 } 13331 13332 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13333 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13334 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13335 try { 13336 if (dpm != null) { 13337 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13338 /* callingUserOnly =*/ false); 13339 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13340 : deviceOwnerComponentName.getPackageName(); 13341 // Does the package contains the device owner? 13342 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13343 // this check is probably not needed, since DO should be registered as a device 13344 // admin on some user too. (Original bug for this: b/17657954) 13345 if (packageName.equals(deviceOwnerPackageName)) { 13346 return true; 13347 } 13348 // Does it contain a device admin for any user? 13349 int[] users; 13350 if (userId == UserHandle.USER_ALL) { 13351 users = sUserManager.getUserIds(); 13352 } else { 13353 users = new int[]{userId}; 13354 } 13355 for (int i = 0; i < users.length; ++i) { 13356 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13357 return true; 13358 } 13359 } 13360 } 13361 } catch (RemoteException e) { 13362 } 13363 return false; 13364 } 13365 13366 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13367 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13368 } 13369 13370 /** 13371 * This method is an internal method that could be get invoked either 13372 * to delete an installed package or to clean up a failed installation. 13373 * After deleting an installed package, a broadcast is sent to notify any 13374 * listeners that the package has been installed. For cleaning up a failed 13375 * installation, the broadcast is not necessary since the package's 13376 * installation wouldn't have sent the initial broadcast either 13377 * The key steps in deleting a package are 13378 * deleting the package information in internal structures like mPackages, 13379 * deleting the packages base directories through installd 13380 * updating mSettings to reflect current status 13381 * persisting settings for later use 13382 * sending a broadcast if necessary 13383 */ 13384 private int deletePackageX(String packageName, int userId, int flags) { 13385 final PackageRemovedInfo info = new PackageRemovedInfo(); 13386 final boolean res; 13387 13388 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13389 ? UserHandle.ALL : new UserHandle(userId); 13390 13391 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13392 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13393 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13394 } 13395 13396 boolean removedForAllUsers = false; 13397 boolean systemUpdate = false; 13398 13399 PackageParser.Package uninstalledPkg; 13400 13401 // for the uninstall-updates case and restricted profiles, remember the per- 13402 // userhandle installed state 13403 int[] allUsers; 13404 boolean[] perUserInstalled; 13405 synchronized (mPackages) { 13406 uninstalledPkg = mPackages.get(packageName); 13407 PackageSetting ps = mSettings.mPackages.get(packageName); 13408 allUsers = sUserManager.getUserIds(); 13409 perUserInstalled = new boolean[allUsers.length]; 13410 for (int i = 0; i < allUsers.length; i++) { 13411 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13412 } 13413 } 13414 13415 synchronized (mInstallLock) { 13416 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13417 res = deletePackageLI(packageName, removeForUser, 13418 true, allUsers, perUserInstalled, 13419 flags | REMOVE_CHATTY, info, true); 13420 systemUpdate = info.isRemovedPackageSystemUpdate; 13421 synchronized (mPackages) { 13422 if (res) { 13423 if (!systemUpdate && mPackages.get(packageName) == null) { 13424 removedForAllUsers = true; 13425 } 13426 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13427 } 13428 } 13429 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13430 + " removedForAllUsers=" + removedForAllUsers); 13431 } 13432 13433 if (res) { 13434 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13435 13436 // If the removed package was a system update, the old system package 13437 // was re-enabled; we need to broadcast this information 13438 if (systemUpdate) { 13439 Bundle extras = new Bundle(1); 13440 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13441 ? info.removedAppId : info.uid); 13442 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13443 13444 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13445 extras, 0, null, null, null); 13446 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13447 extras, 0, null, null, null); 13448 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13449 null, 0, packageName, null, null); 13450 } 13451 } 13452 // Force a gc here. 13453 Runtime.getRuntime().gc(); 13454 // Delete the resources here after sending the broadcast to let 13455 // other processes clean up before deleting resources. 13456 if (info.args != null) { 13457 synchronized (mInstallLock) { 13458 info.args.doPostDeleteLI(true); 13459 } 13460 } 13461 13462 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13463 } 13464 13465 class PackageRemovedInfo { 13466 String removedPackage; 13467 int uid = -1; 13468 int removedAppId = -1; 13469 int[] removedUsers = null; 13470 boolean isRemovedPackageSystemUpdate = false; 13471 // Clean up resources deleted packages. 13472 InstallArgs args = null; 13473 13474 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13475 Bundle extras = new Bundle(1); 13476 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13477 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13478 if (replacing) { 13479 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13480 } 13481 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13482 if (removedPackage != null) { 13483 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13484 extras, 0, null, null, removedUsers); 13485 if (fullRemove && !replacing) { 13486 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13487 extras, 0, null, null, removedUsers); 13488 } 13489 } 13490 if (removedAppId >= 0) { 13491 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13492 removedUsers); 13493 } 13494 } 13495 } 13496 13497 /* 13498 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13499 * flag is not set, the data directory is removed as well. 13500 * make sure this flag is set for partially installed apps. If not its meaningless to 13501 * delete a partially installed application. 13502 */ 13503 private void removePackageDataLI(PackageSetting ps, 13504 int[] allUserHandles, boolean[] perUserInstalled, 13505 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13506 String packageName = ps.name; 13507 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13508 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13509 // Retrieve object to delete permissions for shared user later on 13510 final PackageSetting deletedPs; 13511 // reader 13512 synchronized (mPackages) { 13513 deletedPs = mSettings.mPackages.get(packageName); 13514 if (outInfo != null) { 13515 outInfo.removedPackage = packageName; 13516 outInfo.removedUsers = deletedPs != null 13517 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13518 : null; 13519 } 13520 } 13521 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13522 removeDataDirsLI(ps.volumeUuid, packageName); 13523 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13524 } 13525 // writer 13526 synchronized (mPackages) { 13527 if (deletedPs != null) { 13528 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13529 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13530 clearDefaultBrowserIfNeeded(packageName); 13531 if (outInfo != null) { 13532 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13533 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13534 } 13535 updatePermissionsLPw(deletedPs.name, null, 0); 13536 if (deletedPs.sharedUser != null) { 13537 // Remove permissions associated with package. Since runtime 13538 // permissions are per user we have to kill the removed package 13539 // or packages running under the shared user of the removed 13540 // package if revoking the permissions requested only by the removed 13541 // package is successful and this causes a change in gids. 13542 for (int userId : UserManagerService.getInstance().getUserIds()) { 13543 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13544 userId); 13545 if (userIdToKill == UserHandle.USER_ALL 13546 || userIdToKill >= UserHandle.USER_SYSTEM) { 13547 // If gids changed for this user, kill all affected packages. 13548 mHandler.post(new Runnable() { 13549 @Override 13550 public void run() { 13551 // This has to happen with no lock held. 13552 killApplication(deletedPs.name, deletedPs.appId, 13553 KILL_APP_REASON_GIDS_CHANGED); 13554 } 13555 }); 13556 break; 13557 } 13558 } 13559 } 13560 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13561 } 13562 // make sure to preserve per-user disabled state if this removal was just 13563 // a downgrade of a system app to the factory package 13564 if (allUserHandles != null && perUserInstalled != null) { 13565 if (DEBUG_REMOVE) { 13566 Slog.d(TAG, "Propagating install state across downgrade"); 13567 } 13568 for (int i = 0; i < allUserHandles.length; i++) { 13569 if (DEBUG_REMOVE) { 13570 Slog.d(TAG, " user " + allUserHandles[i] 13571 + " => " + perUserInstalled[i]); 13572 } 13573 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13574 } 13575 } 13576 } 13577 // can downgrade to reader 13578 if (writeSettings) { 13579 // Save settings now 13580 mSettings.writeLPr(); 13581 } 13582 } 13583 if (outInfo != null) { 13584 // A user ID was deleted here. Go through all users and remove it 13585 // from KeyStore. 13586 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13587 } 13588 } 13589 13590 static boolean locationIsPrivileged(File path) { 13591 try { 13592 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13593 .getCanonicalPath(); 13594 return path.getCanonicalPath().startsWith(privilegedAppDir); 13595 } catch (IOException e) { 13596 Slog.e(TAG, "Unable to access code path " + path); 13597 } 13598 return false; 13599 } 13600 13601 /* 13602 * Tries to delete system package. 13603 */ 13604 private boolean deleteSystemPackageLI(PackageSetting newPs, 13605 int[] allUserHandles, boolean[] perUserInstalled, 13606 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13607 final boolean applyUserRestrictions 13608 = (allUserHandles != null) && (perUserInstalled != null); 13609 PackageSetting disabledPs = null; 13610 // Confirm if the system package has been updated 13611 // An updated system app can be deleted. This will also have to restore 13612 // the system pkg from system partition 13613 // reader 13614 synchronized (mPackages) { 13615 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13616 } 13617 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13618 + " disabledPs=" + disabledPs); 13619 if (disabledPs == null) { 13620 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13621 return false; 13622 } else if (DEBUG_REMOVE) { 13623 Slog.d(TAG, "Deleting system pkg from data partition"); 13624 } 13625 if (DEBUG_REMOVE) { 13626 if (applyUserRestrictions) { 13627 Slog.d(TAG, "Remembering install states:"); 13628 for (int i = 0; i < allUserHandles.length; i++) { 13629 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13630 } 13631 } 13632 } 13633 // Delete the updated package 13634 outInfo.isRemovedPackageSystemUpdate = true; 13635 if (disabledPs.versionCode < newPs.versionCode) { 13636 // Delete data for downgrades 13637 flags &= ~PackageManager.DELETE_KEEP_DATA; 13638 } else { 13639 // Preserve data by setting flag 13640 flags |= PackageManager.DELETE_KEEP_DATA; 13641 } 13642 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13643 allUserHandles, perUserInstalled, outInfo, writeSettings); 13644 if (!ret) { 13645 return false; 13646 } 13647 // writer 13648 synchronized (mPackages) { 13649 // Reinstate the old system package 13650 mSettings.enableSystemPackageLPw(newPs.name); 13651 // Remove any native libraries from the upgraded package. 13652 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13653 } 13654 // Install the system package 13655 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13656 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13657 if (locationIsPrivileged(disabledPs.codePath)) { 13658 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13659 } 13660 13661 final PackageParser.Package newPkg; 13662 try { 13663 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13664 } catch (PackageManagerException e) { 13665 Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage()); 13666 return false; 13667 } 13668 13669 prepareAppDataAfterInstall(newPkg); 13670 13671 // writer 13672 synchronized (mPackages) { 13673 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13674 13675 // Propagate the permissions state as we do not want to drop on the floor 13676 // runtime permissions. The update permissions method below will take 13677 // care of removing obsolete permissions and grant install permissions. 13678 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13679 updatePermissionsLPw(newPkg.packageName, newPkg, 13680 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13681 13682 if (applyUserRestrictions) { 13683 if (DEBUG_REMOVE) { 13684 Slog.d(TAG, "Propagating install state across reinstall"); 13685 } 13686 for (int i = 0; i < allUserHandles.length; i++) { 13687 if (DEBUG_REMOVE) { 13688 Slog.d(TAG, " user " + allUserHandles[i] 13689 + " => " + perUserInstalled[i]); 13690 } 13691 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13692 13693 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13694 } 13695 // Regardless of writeSettings we need to ensure that this restriction 13696 // state propagation is persisted 13697 mSettings.writeAllUsersPackageRestrictionsLPr(); 13698 } 13699 // can downgrade to reader here 13700 if (writeSettings) { 13701 mSettings.writeLPr(); 13702 } 13703 } 13704 return true; 13705 } 13706 13707 private boolean deleteInstalledPackageLI(PackageSetting ps, 13708 boolean deleteCodeAndResources, int flags, 13709 int[] allUserHandles, boolean[] perUserInstalled, 13710 PackageRemovedInfo outInfo, boolean writeSettings) { 13711 if (outInfo != null) { 13712 outInfo.uid = ps.appId; 13713 } 13714 13715 // Delete package data from internal structures and also remove data if flag is set 13716 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13717 13718 // Delete application code and resources 13719 if (deleteCodeAndResources && (outInfo != null)) { 13720 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13721 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13722 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13723 } 13724 return true; 13725 } 13726 13727 @Override 13728 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13729 int userId) { 13730 mContext.enforceCallingOrSelfPermission( 13731 android.Manifest.permission.DELETE_PACKAGES, null); 13732 synchronized (mPackages) { 13733 PackageSetting ps = mSettings.mPackages.get(packageName); 13734 if (ps == null) { 13735 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13736 return false; 13737 } 13738 if (!ps.getInstalled(userId)) { 13739 // Can't block uninstall for an app that is not installed or enabled. 13740 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13741 return false; 13742 } 13743 ps.setBlockUninstall(blockUninstall, userId); 13744 mSettings.writePackageRestrictionsLPr(userId); 13745 } 13746 return true; 13747 } 13748 13749 @Override 13750 public boolean getBlockUninstallForUser(String packageName, int userId) { 13751 synchronized (mPackages) { 13752 PackageSetting ps = mSettings.mPackages.get(packageName); 13753 if (ps == null) { 13754 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13755 return false; 13756 } 13757 return ps.getBlockUninstall(userId); 13758 } 13759 } 13760 13761 @Override 13762 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 13763 int callingUid = Binder.getCallingUid(); 13764 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 13765 throw new SecurityException( 13766 "setRequiredForSystemUser can only be run by the system or root"); 13767 } 13768 synchronized (mPackages) { 13769 PackageSetting ps = mSettings.mPackages.get(packageName); 13770 if (ps == null) { 13771 Log.w(TAG, "Package doesn't exist: " + packageName); 13772 return false; 13773 } 13774 if (systemUserApp) { 13775 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13776 } else { 13777 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13778 } 13779 mSettings.writeLPr(); 13780 } 13781 return true; 13782 } 13783 13784 /* 13785 * This method handles package deletion in general 13786 */ 13787 private boolean deletePackageLI(String packageName, UserHandle user, 13788 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13789 int flags, PackageRemovedInfo outInfo, 13790 boolean writeSettings) { 13791 if (packageName == null) { 13792 Slog.w(TAG, "Attempt to delete null packageName."); 13793 return false; 13794 } 13795 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13796 PackageSetting ps; 13797 boolean dataOnly = false; 13798 int removeUser = -1; 13799 int appId = -1; 13800 synchronized (mPackages) { 13801 ps = mSettings.mPackages.get(packageName); 13802 if (ps == null) { 13803 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13804 return false; 13805 } 13806 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13807 && user.getIdentifier() != UserHandle.USER_ALL) { 13808 // The caller is asking that the package only be deleted for a single 13809 // user. To do this, we just mark its uninstalled state and delete 13810 // its data. If this is a system app, we only allow this to happen if 13811 // they have set the special DELETE_SYSTEM_APP which requests different 13812 // semantics than normal for uninstalling system apps. 13813 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13814 final int userId = user.getIdentifier(); 13815 ps.setUserState(userId, 13816 COMPONENT_ENABLED_STATE_DEFAULT, 13817 false, //installed 13818 true, //stopped 13819 true, //notLaunched 13820 false, //hidden 13821 false, //suspended 13822 null, null, null, 13823 false, // blockUninstall 13824 ps.readUserState(userId).domainVerificationStatus, 0); 13825 if (!isSystemApp(ps)) { 13826 // Do not uninstall the APK if an app should be cached 13827 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13828 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13829 // Other user still have this package installed, so all 13830 // we need to do is clear this user's data and save that 13831 // it is uninstalled. 13832 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13833 removeUser = user.getIdentifier(); 13834 appId = ps.appId; 13835 scheduleWritePackageRestrictionsLocked(removeUser); 13836 } else { 13837 // We need to set it back to 'installed' so the uninstall 13838 // broadcasts will be sent correctly. 13839 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13840 ps.setInstalled(true, user.getIdentifier()); 13841 } 13842 } else { 13843 // This is a system app, so we assume that the 13844 // other users still have this package installed, so all 13845 // we need to do is clear this user's data and save that 13846 // it is uninstalled. 13847 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13848 removeUser = user.getIdentifier(); 13849 appId = ps.appId; 13850 scheduleWritePackageRestrictionsLocked(removeUser); 13851 } 13852 } 13853 } 13854 13855 if (removeUser >= 0) { 13856 // From above, we determined that we are deleting this only 13857 // for a single user. Continue the work here. 13858 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13859 if (outInfo != null) { 13860 outInfo.removedPackage = packageName; 13861 outInfo.removedAppId = appId; 13862 outInfo.removedUsers = new int[] {removeUser}; 13863 } 13864 // TODO: triage flags as part of 26466827 13865 final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 13866 try { 13867 mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags); 13868 } catch (InstallerException e) { 13869 Slog.w(TAG, "Failed to delete app data", e); 13870 } 13871 removeKeystoreDataIfNeeded(removeUser, appId); 13872 schedulePackageCleaning(packageName, removeUser, false); 13873 synchronized (mPackages) { 13874 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13875 scheduleWritePackageRestrictionsLocked(removeUser); 13876 } 13877 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13878 } 13879 return true; 13880 } 13881 13882 if (dataOnly) { 13883 // Delete application data first 13884 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13885 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13886 return true; 13887 } 13888 13889 boolean ret = false; 13890 if (isSystemApp(ps)) { 13891 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 13892 // When an updated system application is deleted we delete the existing resources as well and 13893 // fall back to existing code in system partition 13894 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13895 flags, outInfo, writeSettings); 13896 } else { 13897 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 13898 // Kill application pre-emptively especially for apps on sd. 13899 killApplication(packageName, ps.appId, "uninstall pkg"); 13900 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13901 allUserHandles, perUserInstalled, 13902 outInfo, writeSettings); 13903 } 13904 13905 return ret; 13906 } 13907 13908 private final static class ClearStorageConnection implements ServiceConnection { 13909 IMediaContainerService mContainerService; 13910 13911 @Override 13912 public void onServiceConnected(ComponentName name, IBinder service) { 13913 synchronized (this) { 13914 mContainerService = IMediaContainerService.Stub.asInterface(service); 13915 notifyAll(); 13916 } 13917 } 13918 13919 @Override 13920 public void onServiceDisconnected(ComponentName name) { 13921 } 13922 } 13923 13924 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13925 final boolean mounted; 13926 if (Environment.isExternalStorageEmulated()) { 13927 mounted = true; 13928 } else { 13929 final String status = Environment.getExternalStorageState(); 13930 13931 mounted = status.equals(Environment.MEDIA_MOUNTED) 13932 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13933 } 13934 13935 if (!mounted) { 13936 return; 13937 } 13938 13939 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13940 int[] users; 13941 if (userId == UserHandle.USER_ALL) { 13942 users = sUserManager.getUserIds(); 13943 } else { 13944 users = new int[] { userId }; 13945 } 13946 final ClearStorageConnection conn = new ClearStorageConnection(); 13947 if (mContext.bindServiceAsUser( 13948 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13949 try { 13950 for (int curUser : users) { 13951 long timeout = SystemClock.uptimeMillis() + 5000; 13952 synchronized (conn) { 13953 long now = SystemClock.uptimeMillis(); 13954 while (conn.mContainerService == null && now < timeout) { 13955 try { 13956 conn.wait(timeout - now); 13957 } catch (InterruptedException e) { 13958 } 13959 } 13960 } 13961 if (conn.mContainerService == null) { 13962 return; 13963 } 13964 13965 final UserEnvironment userEnv = new UserEnvironment(curUser); 13966 clearDirectory(conn.mContainerService, 13967 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13968 if (allData) { 13969 clearDirectory(conn.mContainerService, 13970 userEnv.buildExternalStorageAppDataDirs(packageName)); 13971 clearDirectory(conn.mContainerService, 13972 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13973 } 13974 } 13975 } finally { 13976 mContext.unbindService(conn); 13977 } 13978 } 13979 } 13980 13981 @Override 13982 public void clearApplicationUserData(final String packageName, 13983 final IPackageDataObserver observer, final int userId) { 13984 mContext.enforceCallingOrSelfPermission( 13985 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13986 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13987 // Queue up an async operation since the package deletion may take a little while. 13988 mHandler.post(new Runnable() { 13989 public void run() { 13990 mHandler.removeCallbacks(this); 13991 final boolean succeeded; 13992 synchronized (mInstallLock) { 13993 succeeded = clearApplicationUserDataLI(packageName, userId); 13994 } 13995 clearExternalStorageDataSync(packageName, userId, true); 13996 if (succeeded) { 13997 // invoke DeviceStorageMonitor's update method to clear any notifications 13998 DeviceStorageMonitorInternal 13999 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14000 if (dsm != null) { 14001 dsm.checkMemory(); 14002 } 14003 } 14004 if(observer != null) { 14005 try { 14006 observer.onRemoveCompleted(packageName, succeeded); 14007 } catch (RemoteException e) { 14008 Log.i(TAG, "Observer no longer exists."); 14009 } 14010 } //end if observer 14011 } //end run 14012 }); 14013 } 14014 14015 private boolean clearApplicationUserDataLI(String packageName, int userId) { 14016 if (packageName == null) { 14017 Slog.w(TAG, "Attempt to delete null packageName."); 14018 return false; 14019 } 14020 14021 // Try finding details about the requested package 14022 PackageParser.Package pkg; 14023 synchronized (mPackages) { 14024 pkg = mPackages.get(packageName); 14025 if (pkg == null) { 14026 final PackageSetting ps = mSettings.mPackages.get(packageName); 14027 if (ps != null) { 14028 pkg = ps.pkg; 14029 } 14030 } 14031 14032 if (pkg == null) { 14033 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14034 return false; 14035 } 14036 14037 PackageSetting ps = (PackageSetting) pkg.mExtras; 14038 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14039 } 14040 14041 // Always delete data directories for package, even if we found no other 14042 // record of app. This helps users recover from UID mismatches without 14043 // resorting to a full data wipe. 14044 // TODO: triage flags as part of 26466827 14045 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14046 try { 14047 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 14048 } catch (InstallerException e) { 14049 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 14050 return false; 14051 } 14052 14053 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14054 removeKeystoreDataIfNeeded(userId, appId); 14055 14056 // Create a native library symlink only if we have native libraries 14057 // and if the native libraries are 32 bit libraries. We do not provide 14058 // this symlink for 64 bit libraries. 14059 if (pkg.applicationInfo.primaryCpuAbi != null && 14060 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14061 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14062 try { 14063 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14064 nativeLibPath, userId); 14065 } catch (InstallerException e) { 14066 Slog.w(TAG, "Failed linking native library dir", e); 14067 return false; 14068 } 14069 } 14070 14071 return true; 14072 } 14073 14074 /** 14075 * Reverts user permission state changes (permissions and flags) in 14076 * all packages for a given user. 14077 * 14078 * @param userId The device user for which to do a reset. 14079 */ 14080 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14081 final int packageCount = mPackages.size(); 14082 for (int i = 0; i < packageCount; i++) { 14083 PackageParser.Package pkg = mPackages.valueAt(i); 14084 PackageSetting ps = (PackageSetting) pkg.mExtras; 14085 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14086 } 14087 } 14088 14089 /** 14090 * Reverts user permission state changes (permissions and flags). 14091 * 14092 * @param ps The package for which to reset. 14093 * @param userId The device user for which to do a reset. 14094 */ 14095 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14096 final PackageSetting ps, final int userId) { 14097 if (ps.pkg == null) { 14098 return; 14099 } 14100 14101 // These are flags that can change base on user actions. 14102 final int userSettableMask = FLAG_PERMISSION_USER_SET 14103 | FLAG_PERMISSION_USER_FIXED 14104 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14105 | FLAG_PERMISSION_REVIEW_REQUIRED; 14106 14107 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14108 | FLAG_PERMISSION_POLICY_FIXED; 14109 14110 boolean writeInstallPermissions = false; 14111 boolean writeRuntimePermissions = false; 14112 14113 final int permissionCount = ps.pkg.requestedPermissions.size(); 14114 for (int i = 0; i < permissionCount; i++) { 14115 String permission = ps.pkg.requestedPermissions.get(i); 14116 14117 BasePermission bp = mSettings.mPermissions.get(permission); 14118 if (bp == null) { 14119 continue; 14120 } 14121 14122 // If shared user we just reset the state to which only this app contributed. 14123 if (ps.sharedUser != null) { 14124 boolean used = false; 14125 final int packageCount = ps.sharedUser.packages.size(); 14126 for (int j = 0; j < packageCount; j++) { 14127 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14128 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14129 && pkg.pkg.requestedPermissions.contains(permission)) { 14130 used = true; 14131 break; 14132 } 14133 } 14134 if (used) { 14135 continue; 14136 } 14137 } 14138 14139 PermissionsState permissionsState = ps.getPermissionsState(); 14140 14141 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14142 14143 // Always clear the user settable flags. 14144 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14145 bp.name) != null; 14146 // If permission review is enabled and this is a legacy app, mark the 14147 // permission as requiring a review as this is the initial state. 14148 int flags = 0; 14149 if (Build.PERMISSIONS_REVIEW_REQUIRED 14150 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14151 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14152 } 14153 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14154 if (hasInstallState) { 14155 writeInstallPermissions = true; 14156 } else { 14157 writeRuntimePermissions = true; 14158 } 14159 } 14160 14161 // Below is only runtime permission handling. 14162 if (!bp.isRuntime()) { 14163 continue; 14164 } 14165 14166 // Never clobber system or policy. 14167 if ((oldFlags & policyOrSystemFlags) != 0) { 14168 continue; 14169 } 14170 14171 // If this permission was granted by default, make sure it is. 14172 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14173 if (permissionsState.grantRuntimePermission(bp, userId) 14174 != PERMISSION_OPERATION_FAILURE) { 14175 writeRuntimePermissions = true; 14176 } 14177 // If permission review is enabled the permissions for a legacy apps 14178 // are represented as constantly granted runtime ones, so don't revoke. 14179 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14180 // Otherwise, reset the permission. 14181 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14182 switch (revokeResult) { 14183 case PERMISSION_OPERATION_SUCCESS: { 14184 writeRuntimePermissions = true; 14185 } break; 14186 14187 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14188 writeRuntimePermissions = true; 14189 final int appId = ps.appId; 14190 mHandler.post(new Runnable() { 14191 @Override 14192 public void run() { 14193 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14194 } 14195 }); 14196 } break; 14197 } 14198 } 14199 } 14200 14201 // Synchronously write as we are taking permissions away. 14202 if (writeRuntimePermissions) { 14203 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14204 } 14205 14206 // Synchronously write as we are taking permissions away. 14207 if (writeInstallPermissions) { 14208 mSettings.writeLPr(); 14209 } 14210 } 14211 14212 /** 14213 * Remove entries from the keystore daemon. Will only remove it if the 14214 * {@code appId} is valid. 14215 */ 14216 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14217 if (appId < 0) { 14218 return; 14219 } 14220 14221 final KeyStore keyStore = KeyStore.getInstance(); 14222 if (keyStore != null) { 14223 if (userId == UserHandle.USER_ALL) { 14224 for (final int individual : sUserManager.getUserIds()) { 14225 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14226 } 14227 } else { 14228 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14229 } 14230 } else { 14231 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14232 } 14233 } 14234 14235 @Override 14236 public void deleteApplicationCacheFiles(final String packageName, 14237 final IPackageDataObserver observer) { 14238 mContext.enforceCallingOrSelfPermission( 14239 android.Manifest.permission.DELETE_CACHE_FILES, null); 14240 // Queue up an async operation since the package deletion may take a little while. 14241 final int userId = UserHandle.getCallingUserId(); 14242 mHandler.post(new Runnable() { 14243 public void run() { 14244 mHandler.removeCallbacks(this); 14245 final boolean succeded; 14246 synchronized (mInstallLock) { 14247 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14248 } 14249 clearExternalStorageDataSync(packageName, userId, false); 14250 if (observer != null) { 14251 try { 14252 observer.onRemoveCompleted(packageName, succeded); 14253 } catch (RemoteException e) { 14254 Log.i(TAG, "Observer no longer exists."); 14255 } 14256 } //end if observer 14257 } //end run 14258 }); 14259 } 14260 14261 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14262 if (packageName == null) { 14263 Slog.w(TAG, "Attempt to delete null packageName."); 14264 return false; 14265 } 14266 PackageParser.Package p; 14267 synchronized (mPackages) { 14268 p = mPackages.get(packageName); 14269 } 14270 if (p == null) { 14271 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14272 return false; 14273 } 14274 final ApplicationInfo applicationInfo = p.applicationInfo; 14275 if (applicationInfo == null) { 14276 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14277 return false; 14278 } 14279 // TODO: triage flags as part of 26466827 14280 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14281 try { 14282 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 14283 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 14284 } catch (InstallerException e) { 14285 Slog.w(TAG, "Couldn't remove cache files for package " 14286 + packageName + " u" + userId, e); 14287 return false; 14288 } 14289 return true; 14290 } 14291 14292 @Override 14293 public void getPackageSizeInfo(final String packageName, int userHandle, 14294 final IPackageStatsObserver observer) { 14295 mContext.enforceCallingOrSelfPermission( 14296 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14297 if (packageName == null) { 14298 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14299 } 14300 14301 PackageStats stats = new PackageStats(packageName, userHandle); 14302 14303 /* 14304 * Queue up an async operation since the package measurement may take a 14305 * little while. 14306 */ 14307 Message msg = mHandler.obtainMessage(INIT_COPY); 14308 msg.obj = new MeasureParams(stats, observer); 14309 mHandler.sendMessage(msg); 14310 } 14311 14312 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14313 PackageStats pStats) { 14314 if (packageName == null) { 14315 Slog.w(TAG, "Attempt to get size of null packageName."); 14316 return false; 14317 } 14318 PackageParser.Package p; 14319 boolean dataOnly = false; 14320 String libDirRoot = null; 14321 String asecPath = null; 14322 PackageSetting ps = null; 14323 synchronized (mPackages) { 14324 p = mPackages.get(packageName); 14325 ps = mSettings.mPackages.get(packageName); 14326 if(p == null) { 14327 dataOnly = true; 14328 if((ps == null) || (ps.pkg == null)) { 14329 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14330 return false; 14331 } 14332 p = ps.pkg; 14333 } 14334 if (ps != null) { 14335 libDirRoot = ps.legacyNativeLibraryPathString; 14336 } 14337 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14338 final long token = Binder.clearCallingIdentity(); 14339 try { 14340 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14341 if (secureContainerId != null) { 14342 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14343 } 14344 } finally { 14345 Binder.restoreCallingIdentity(token); 14346 } 14347 } 14348 } 14349 String publicSrcDir = null; 14350 if(!dataOnly) { 14351 final ApplicationInfo applicationInfo = p.applicationInfo; 14352 if (applicationInfo == null) { 14353 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14354 return false; 14355 } 14356 if (p.isForwardLocked()) { 14357 publicSrcDir = applicationInfo.getBaseResourcePath(); 14358 } 14359 } 14360 // TODO: extend to measure size of split APKs 14361 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14362 // not just the first level. 14363 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14364 // just the primary. 14365 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14366 14367 String apkPath; 14368 File packageDir = new File(p.codePath); 14369 14370 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14371 apkPath = packageDir.getAbsolutePath(); 14372 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14373 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14374 libDirRoot = null; 14375 } 14376 } else { 14377 apkPath = p.baseCodePath; 14378 } 14379 14380 // TODO: triage flags as part of 26466827 14381 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14382 try { 14383 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 14384 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14385 } catch (InstallerException e) { 14386 return false; 14387 } 14388 14389 // Fix-up for forward-locked applications in ASEC containers. 14390 if (!isExternal(p)) { 14391 pStats.codeSize += pStats.externalCodeSize; 14392 pStats.externalCodeSize = 0L; 14393 } 14394 14395 return true; 14396 } 14397 14398 14399 @Override 14400 public void addPackageToPreferred(String packageName) { 14401 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14402 } 14403 14404 @Override 14405 public void removePackageFromPreferred(String packageName) { 14406 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14407 } 14408 14409 @Override 14410 public List<PackageInfo> getPreferredPackages(int flags) { 14411 return new ArrayList<PackageInfo>(); 14412 } 14413 14414 private int getUidTargetSdkVersionLockedLPr(int uid) { 14415 Object obj = mSettings.getUserIdLPr(uid); 14416 if (obj instanceof SharedUserSetting) { 14417 final SharedUserSetting sus = (SharedUserSetting) obj; 14418 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14419 final Iterator<PackageSetting> it = sus.packages.iterator(); 14420 while (it.hasNext()) { 14421 final PackageSetting ps = it.next(); 14422 if (ps.pkg != null) { 14423 int v = ps.pkg.applicationInfo.targetSdkVersion; 14424 if (v < vers) vers = v; 14425 } 14426 } 14427 return vers; 14428 } else if (obj instanceof PackageSetting) { 14429 final PackageSetting ps = (PackageSetting) obj; 14430 if (ps.pkg != null) { 14431 return ps.pkg.applicationInfo.targetSdkVersion; 14432 } 14433 } 14434 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14435 } 14436 14437 @Override 14438 public void addPreferredActivity(IntentFilter filter, int match, 14439 ComponentName[] set, ComponentName activity, int userId) { 14440 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14441 "Adding preferred"); 14442 } 14443 14444 private void addPreferredActivityInternal(IntentFilter filter, int match, 14445 ComponentName[] set, ComponentName activity, boolean always, int userId, 14446 String opname) { 14447 // writer 14448 int callingUid = Binder.getCallingUid(); 14449 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14450 if (filter.countActions() == 0) { 14451 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14452 return; 14453 } 14454 synchronized (mPackages) { 14455 if (mContext.checkCallingOrSelfPermission( 14456 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14457 != PackageManager.PERMISSION_GRANTED) { 14458 if (getUidTargetSdkVersionLockedLPr(callingUid) 14459 < Build.VERSION_CODES.FROYO) { 14460 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14461 + callingUid); 14462 return; 14463 } 14464 mContext.enforceCallingOrSelfPermission( 14465 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14466 } 14467 14468 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14469 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14470 + userId + ":"); 14471 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14472 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14473 scheduleWritePackageRestrictionsLocked(userId); 14474 } 14475 } 14476 14477 @Override 14478 public void replacePreferredActivity(IntentFilter filter, int match, 14479 ComponentName[] set, ComponentName activity, int userId) { 14480 if (filter.countActions() != 1) { 14481 throw new IllegalArgumentException( 14482 "replacePreferredActivity expects filter to have only 1 action."); 14483 } 14484 if (filter.countDataAuthorities() != 0 14485 || filter.countDataPaths() != 0 14486 || filter.countDataSchemes() > 1 14487 || filter.countDataTypes() != 0) { 14488 throw new IllegalArgumentException( 14489 "replacePreferredActivity expects filter to have no data authorities, " + 14490 "paths, or types; and at most one scheme."); 14491 } 14492 14493 final int callingUid = Binder.getCallingUid(); 14494 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14495 synchronized (mPackages) { 14496 if (mContext.checkCallingOrSelfPermission( 14497 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14498 != PackageManager.PERMISSION_GRANTED) { 14499 if (getUidTargetSdkVersionLockedLPr(callingUid) 14500 < Build.VERSION_CODES.FROYO) { 14501 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14502 + Binder.getCallingUid()); 14503 return; 14504 } 14505 mContext.enforceCallingOrSelfPermission( 14506 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14507 } 14508 14509 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14510 if (pir != null) { 14511 // Get all of the existing entries that exactly match this filter. 14512 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14513 if (existing != null && existing.size() == 1) { 14514 PreferredActivity cur = existing.get(0); 14515 if (DEBUG_PREFERRED) { 14516 Slog.i(TAG, "Checking replace of preferred:"); 14517 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14518 if (!cur.mPref.mAlways) { 14519 Slog.i(TAG, " -- CUR; not mAlways!"); 14520 } else { 14521 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14522 Slog.i(TAG, " -- CUR: mSet=" 14523 + Arrays.toString(cur.mPref.mSetComponents)); 14524 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14525 Slog.i(TAG, " -- NEW: mMatch=" 14526 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14527 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14528 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14529 } 14530 } 14531 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14532 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14533 && cur.mPref.sameSet(set)) { 14534 // Setting the preferred activity to what it happens to be already 14535 if (DEBUG_PREFERRED) { 14536 Slog.i(TAG, "Replacing with same preferred activity " 14537 + cur.mPref.mShortComponent + " for user " 14538 + userId + ":"); 14539 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14540 } 14541 return; 14542 } 14543 } 14544 14545 if (existing != null) { 14546 if (DEBUG_PREFERRED) { 14547 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14548 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14549 } 14550 for (int i = 0; i < existing.size(); i++) { 14551 PreferredActivity pa = existing.get(i); 14552 if (DEBUG_PREFERRED) { 14553 Slog.i(TAG, "Removing existing preferred activity " 14554 + pa.mPref.mComponent + ":"); 14555 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14556 } 14557 pir.removeFilter(pa); 14558 } 14559 } 14560 } 14561 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14562 "Replacing preferred"); 14563 } 14564 } 14565 14566 @Override 14567 public void clearPackagePreferredActivities(String packageName) { 14568 final int uid = Binder.getCallingUid(); 14569 // writer 14570 synchronized (mPackages) { 14571 PackageParser.Package pkg = mPackages.get(packageName); 14572 if (pkg == null || pkg.applicationInfo.uid != uid) { 14573 if (mContext.checkCallingOrSelfPermission( 14574 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14575 != PackageManager.PERMISSION_GRANTED) { 14576 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14577 < Build.VERSION_CODES.FROYO) { 14578 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14579 + Binder.getCallingUid()); 14580 return; 14581 } 14582 mContext.enforceCallingOrSelfPermission( 14583 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14584 } 14585 } 14586 14587 int user = UserHandle.getCallingUserId(); 14588 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14589 scheduleWritePackageRestrictionsLocked(user); 14590 } 14591 } 14592 } 14593 14594 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14595 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14596 ArrayList<PreferredActivity> removed = null; 14597 boolean changed = false; 14598 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14599 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14600 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14601 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14602 continue; 14603 } 14604 Iterator<PreferredActivity> it = pir.filterIterator(); 14605 while (it.hasNext()) { 14606 PreferredActivity pa = it.next(); 14607 // Mark entry for removal only if it matches the package name 14608 // and the entry is of type "always". 14609 if (packageName == null || 14610 (pa.mPref.mComponent.getPackageName().equals(packageName) 14611 && pa.mPref.mAlways)) { 14612 if (removed == null) { 14613 removed = new ArrayList<PreferredActivity>(); 14614 } 14615 removed.add(pa); 14616 } 14617 } 14618 if (removed != null) { 14619 for (int j=0; j<removed.size(); j++) { 14620 PreferredActivity pa = removed.get(j); 14621 pir.removeFilter(pa); 14622 } 14623 changed = true; 14624 } 14625 } 14626 return changed; 14627 } 14628 14629 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14630 private void clearIntentFilterVerificationsLPw(int userId) { 14631 final int packageCount = mPackages.size(); 14632 for (int i = 0; i < packageCount; i++) { 14633 PackageParser.Package pkg = mPackages.valueAt(i); 14634 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14635 } 14636 } 14637 14638 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14639 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14640 if (userId == UserHandle.USER_ALL) { 14641 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14642 sUserManager.getUserIds())) { 14643 for (int oneUserId : sUserManager.getUserIds()) { 14644 scheduleWritePackageRestrictionsLocked(oneUserId); 14645 } 14646 } 14647 } else { 14648 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14649 scheduleWritePackageRestrictionsLocked(userId); 14650 } 14651 } 14652 } 14653 14654 void clearDefaultBrowserIfNeeded(String packageName) { 14655 for (int oneUserId : sUserManager.getUserIds()) { 14656 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14657 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14658 if (packageName.equals(defaultBrowserPackageName)) { 14659 setDefaultBrowserPackageName(null, oneUserId); 14660 } 14661 } 14662 } 14663 14664 @Override 14665 public void resetApplicationPreferences(int userId) { 14666 mContext.enforceCallingOrSelfPermission( 14667 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14668 // writer 14669 synchronized (mPackages) { 14670 final long identity = Binder.clearCallingIdentity(); 14671 try { 14672 clearPackagePreferredActivitiesLPw(null, userId); 14673 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14674 // TODO: We have to reset the default SMS and Phone. This requires 14675 // significant refactoring to keep all default apps in the package 14676 // manager (cleaner but more work) or have the services provide 14677 // callbacks to the package manager to request a default app reset. 14678 applyFactoryDefaultBrowserLPw(userId); 14679 clearIntentFilterVerificationsLPw(userId); 14680 primeDomainVerificationsLPw(userId); 14681 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14682 scheduleWritePackageRestrictionsLocked(userId); 14683 } finally { 14684 Binder.restoreCallingIdentity(identity); 14685 } 14686 } 14687 } 14688 14689 @Override 14690 public int getPreferredActivities(List<IntentFilter> outFilters, 14691 List<ComponentName> outActivities, String packageName) { 14692 14693 int num = 0; 14694 final int userId = UserHandle.getCallingUserId(); 14695 // reader 14696 synchronized (mPackages) { 14697 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14698 if (pir != null) { 14699 final Iterator<PreferredActivity> it = pir.filterIterator(); 14700 while (it.hasNext()) { 14701 final PreferredActivity pa = it.next(); 14702 if (packageName == null 14703 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14704 && pa.mPref.mAlways)) { 14705 if (outFilters != null) { 14706 outFilters.add(new IntentFilter(pa)); 14707 } 14708 if (outActivities != null) { 14709 outActivities.add(pa.mPref.mComponent); 14710 } 14711 } 14712 } 14713 } 14714 } 14715 14716 return num; 14717 } 14718 14719 @Override 14720 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14721 int userId) { 14722 int callingUid = Binder.getCallingUid(); 14723 if (callingUid != Process.SYSTEM_UID) { 14724 throw new SecurityException( 14725 "addPersistentPreferredActivity can only be run by the system"); 14726 } 14727 if (filter.countActions() == 0) { 14728 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14729 return; 14730 } 14731 synchronized (mPackages) { 14732 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14733 ":"); 14734 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14735 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14736 new PersistentPreferredActivity(filter, activity)); 14737 scheduleWritePackageRestrictionsLocked(userId); 14738 } 14739 } 14740 14741 @Override 14742 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14743 int callingUid = Binder.getCallingUid(); 14744 if (callingUid != Process.SYSTEM_UID) { 14745 throw new SecurityException( 14746 "clearPackagePersistentPreferredActivities can only be run by the system"); 14747 } 14748 ArrayList<PersistentPreferredActivity> removed = null; 14749 boolean changed = false; 14750 synchronized (mPackages) { 14751 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14752 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14753 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14754 .valueAt(i); 14755 if (userId != thisUserId) { 14756 continue; 14757 } 14758 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14759 while (it.hasNext()) { 14760 PersistentPreferredActivity ppa = it.next(); 14761 // Mark entry for removal only if it matches the package name. 14762 if (ppa.mComponent.getPackageName().equals(packageName)) { 14763 if (removed == null) { 14764 removed = new ArrayList<PersistentPreferredActivity>(); 14765 } 14766 removed.add(ppa); 14767 } 14768 } 14769 if (removed != null) { 14770 for (int j=0; j<removed.size(); j++) { 14771 PersistentPreferredActivity ppa = removed.get(j); 14772 ppir.removeFilter(ppa); 14773 } 14774 changed = true; 14775 } 14776 } 14777 14778 if (changed) { 14779 scheduleWritePackageRestrictionsLocked(userId); 14780 } 14781 } 14782 } 14783 14784 /** 14785 * Common machinery for picking apart a restored XML blob and passing 14786 * it to a caller-supplied functor to be applied to the running system. 14787 */ 14788 private void restoreFromXml(XmlPullParser parser, int userId, 14789 String expectedStartTag, BlobXmlRestorer functor) 14790 throws IOException, XmlPullParserException { 14791 int type; 14792 while ((type = parser.next()) != XmlPullParser.START_TAG 14793 && type != XmlPullParser.END_DOCUMENT) { 14794 } 14795 if (type != XmlPullParser.START_TAG) { 14796 // oops didn't find a start tag?! 14797 if (DEBUG_BACKUP) { 14798 Slog.e(TAG, "Didn't find start tag during restore"); 14799 } 14800 return; 14801 } 14802Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 14803 // this is supposed to be TAG_PREFERRED_BACKUP 14804 if (!expectedStartTag.equals(parser.getName())) { 14805 if (DEBUG_BACKUP) { 14806 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14807 } 14808 return; 14809 } 14810 14811 // skip interfering stuff, then we're aligned with the backing implementation 14812 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14813Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 14814 functor.apply(parser, userId); 14815 } 14816 14817 private interface BlobXmlRestorer { 14818 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14819 } 14820 14821 /** 14822 * Non-Binder method, support for the backup/restore mechanism: write the 14823 * full set of preferred activities in its canonical XML format. Returns the 14824 * XML output as a byte array, or null if there is none. 14825 */ 14826 @Override 14827 public byte[] getPreferredActivityBackup(int userId) { 14828 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14829 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14830 } 14831 14832 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14833 try { 14834 final XmlSerializer serializer = new FastXmlSerializer(); 14835 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14836 serializer.startDocument(null, true); 14837 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14838 14839 synchronized (mPackages) { 14840 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14841 } 14842 14843 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14844 serializer.endDocument(); 14845 serializer.flush(); 14846 } catch (Exception e) { 14847 if (DEBUG_BACKUP) { 14848 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14849 } 14850 return null; 14851 } 14852 14853 return dataStream.toByteArray(); 14854 } 14855 14856 @Override 14857 public void restorePreferredActivities(byte[] backup, int userId) { 14858 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14859 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14860 } 14861 14862 try { 14863 final XmlPullParser parser = Xml.newPullParser(); 14864 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14865 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14866 new BlobXmlRestorer() { 14867 @Override 14868 public void apply(XmlPullParser parser, int userId) 14869 throws XmlPullParserException, IOException { 14870 synchronized (mPackages) { 14871 mSettings.readPreferredActivitiesLPw(parser, userId); 14872 } 14873 } 14874 } ); 14875 } catch (Exception e) { 14876 if (DEBUG_BACKUP) { 14877 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14878 } 14879 } 14880 } 14881 14882 /** 14883 * Non-Binder method, support for the backup/restore mechanism: write the 14884 * default browser (etc) settings in its canonical XML format. Returns the default 14885 * browser XML representation as a byte array, or null if there is none. 14886 */ 14887 @Override 14888 public byte[] getDefaultAppsBackup(int userId) { 14889 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14890 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14891 } 14892 14893 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14894 try { 14895 final XmlSerializer serializer = new FastXmlSerializer(); 14896 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14897 serializer.startDocument(null, true); 14898 serializer.startTag(null, TAG_DEFAULT_APPS); 14899 14900 synchronized (mPackages) { 14901 mSettings.writeDefaultAppsLPr(serializer, userId); 14902 } 14903 14904 serializer.endTag(null, TAG_DEFAULT_APPS); 14905 serializer.endDocument(); 14906 serializer.flush(); 14907 } catch (Exception e) { 14908 if (DEBUG_BACKUP) { 14909 Slog.e(TAG, "Unable to write default apps for backup", e); 14910 } 14911 return null; 14912 } 14913 14914 return dataStream.toByteArray(); 14915 } 14916 14917 @Override 14918 public void restoreDefaultApps(byte[] backup, int userId) { 14919 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14920 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14921 } 14922 14923 try { 14924 final XmlPullParser parser = Xml.newPullParser(); 14925 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14926 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14927 new BlobXmlRestorer() { 14928 @Override 14929 public void apply(XmlPullParser parser, int userId) 14930 throws XmlPullParserException, IOException { 14931 synchronized (mPackages) { 14932 mSettings.readDefaultAppsLPw(parser, userId); 14933 } 14934 } 14935 } ); 14936 } catch (Exception e) { 14937 if (DEBUG_BACKUP) { 14938 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14939 } 14940 } 14941 } 14942 14943 @Override 14944 public byte[] getIntentFilterVerificationBackup(int userId) { 14945 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14946 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14947 } 14948 14949 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14950 try { 14951 final XmlSerializer serializer = new FastXmlSerializer(); 14952 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14953 serializer.startDocument(null, true); 14954 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14955 14956 synchronized (mPackages) { 14957 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14958 } 14959 14960 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14961 serializer.endDocument(); 14962 serializer.flush(); 14963 } catch (Exception e) { 14964 if (DEBUG_BACKUP) { 14965 Slog.e(TAG, "Unable to write default apps for backup", e); 14966 } 14967 return null; 14968 } 14969 14970 return dataStream.toByteArray(); 14971 } 14972 14973 @Override 14974 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14975 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14976 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14977 } 14978 14979 try { 14980 final XmlPullParser parser = Xml.newPullParser(); 14981 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14982 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14983 new BlobXmlRestorer() { 14984 @Override 14985 public void apply(XmlPullParser parser, int userId) 14986 throws XmlPullParserException, IOException { 14987 synchronized (mPackages) { 14988 mSettings.readAllDomainVerificationsLPr(parser, userId); 14989 mSettings.writeLPr(); 14990 } 14991 } 14992 } ); 14993 } catch (Exception e) { 14994 if (DEBUG_BACKUP) { 14995 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14996 } 14997 } 14998 } 14999 15000 @Override 15001 public byte[] getPermissionGrantBackup(int userId) { 15002 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15003 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 15004 } 15005 15006 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15007 try { 15008 final XmlSerializer serializer = new FastXmlSerializer(); 15009 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15010 serializer.startDocument(null, true); 15011 serializer.startTag(null, TAG_PERMISSION_BACKUP); 15012 15013 synchronized (mPackages) { 15014 serializeRuntimePermissionGrantsLPr(serializer, userId); 15015 } 15016 15017 serializer.endTag(null, TAG_PERMISSION_BACKUP); 15018 serializer.endDocument(); 15019 serializer.flush(); 15020 } catch (Exception e) { 15021 if (DEBUG_BACKUP) { 15022 Slog.e(TAG, "Unable to write default apps for backup", e); 15023 } 15024 return null; 15025 } 15026 15027 return dataStream.toByteArray(); 15028 } 15029 15030 @Override 15031 public void restorePermissionGrants(byte[] backup, int userId) { 15032 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15033 throw new SecurityException("Only the system may call restorePermissionGrants()"); 15034 } 15035 15036 try { 15037 final XmlPullParser parser = Xml.newPullParser(); 15038 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15039 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 15040 new BlobXmlRestorer() { 15041 @Override 15042 public void apply(XmlPullParser parser, int userId) 15043 throws XmlPullParserException, IOException { 15044 synchronized (mPackages) { 15045 processRestoredPermissionGrantsLPr(parser, userId); 15046 } 15047 } 15048 } ); 15049 } catch (Exception e) { 15050 if (DEBUG_BACKUP) { 15051 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15052 } 15053 } 15054 } 15055 15056 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 15057 throws IOException { 15058 serializer.startTag(null, TAG_ALL_GRANTS); 15059 15060 final int N = mSettings.mPackages.size(); 15061 for (int i = 0; i < N; i++) { 15062 final PackageSetting ps = mSettings.mPackages.valueAt(i); 15063 boolean pkgGrantsKnown = false; 15064 15065 PermissionsState packagePerms = ps.getPermissionsState(); 15066 15067 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 15068 final int grantFlags = state.getFlags(); 15069 // only look at grants that are not system/policy fixed 15070 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 15071 final boolean isGranted = state.isGranted(); 15072 // And only back up the user-twiddled state bits 15073 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 15074 final String packageName = mSettings.mPackages.keyAt(i); 15075 if (!pkgGrantsKnown) { 15076 serializer.startTag(null, TAG_GRANT); 15077 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 15078 pkgGrantsKnown = true; 15079 } 15080 15081 final boolean userSet = 15082 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 15083 final boolean userFixed = 15084 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 15085 final boolean revoke = 15086 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 15087 15088 serializer.startTag(null, TAG_PERMISSION); 15089 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 15090 if (isGranted) { 15091 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 15092 } 15093 if (userSet) { 15094 serializer.attribute(null, ATTR_USER_SET, "true"); 15095 } 15096 if (userFixed) { 15097 serializer.attribute(null, ATTR_USER_FIXED, "true"); 15098 } 15099 if (revoke) { 15100 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 15101 } 15102 serializer.endTag(null, TAG_PERMISSION); 15103 } 15104 } 15105 } 15106 15107 if (pkgGrantsKnown) { 15108 serializer.endTag(null, TAG_GRANT); 15109 } 15110 } 15111 15112 serializer.endTag(null, TAG_ALL_GRANTS); 15113 } 15114 15115 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 15116 throws XmlPullParserException, IOException { 15117 String pkgName = null; 15118 int outerDepth = parser.getDepth(); 15119 int type; 15120 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 15121 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 15122 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 15123 continue; 15124 } 15125 15126 final String tagName = parser.getName(); 15127 if (tagName.equals(TAG_GRANT)) { 15128 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 15129 if (DEBUG_BACKUP) { 15130 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 15131 } 15132 } else if (tagName.equals(TAG_PERMISSION)) { 15133 15134 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 15135 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 15136 15137 int newFlagSet = 0; 15138 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 15139 newFlagSet |= FLAG_PERMISSION_USER_SET; 15140 } 15141 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 15142 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 15143 } 15144 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 15145 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 15146 } 15147 if (DEBUG_BACKUP) { 15148 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 15149 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 15150 } 15151 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15152 if (ps != null) { 15153 // Already installed so we apply the grant immediately 15154 if (DEBUG_BACKUP) { 15155 Slog.v(TAG, " + already installed; applying"); 15156 } 15157 PermissionsState perms = ps.getPermissionsState(); 15158 BasePermission bp = mSettings.mPermissions.get(permName); 15159 if (bp != null) { 15160 if (isGranted) { 15161 perms.grantRuntimePermission(bp, userId); 15162 } 15163 if (newFlagSet != 0) { 15164 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 15165 } 15166 } 15167 } else { 15168 // Need to wait for post-restore install to apply the grant 15169 if (DEBUG_BACKUP) { 15170 Slog.v(TAG, " - not yet installed; saving for later"); 15171 } 15172 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 15173 isGranted, newFlagSet, userId); 15174 } 15175 } else { 15176 PackageManagerService.reportSettingsProblem(Log.WARN, 15177 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 15178 XmlUtils.skipCurrentTag(parser); 15179 } 15180 } 15181 15182 scheduleWriteSettingsLocked(); 15183 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15184 } 15185 15186 @Override 15187 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 15188 int sourceUserId, int targetUserId, int flags) { 15189 mContext.enforceCallingOrSelfPermission( 15190 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15191 int callingUid = Binder.getCallingUid(); 15192 enforceOwnerRights(ownerPackage, callingUid); 15193 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15194 if (intentFilter.countActions() == 0) { 15195 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 15196 return; 15197 } 15198 synchronized (mPackages) { 15199 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 15200 ownerPackage, targetUserId, flags); 15201 CrossProfileIntentResolver resolver = 15202 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15203 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 15204 // We have all those whose filter is equal. Now checking if the rest is equal as well. 15205 if (existing != null) { 15206 int size = existing.size(); 15207 for (int i = 0; i < size; i++) { 15208 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 15209 return; 15210 } 15211 } 15212 } 15213 resolver.addFilter(newFilter); 15214 scheduleWritePackageRestrictionsLocked(sourceUserId); 15215 } 15216 } 15217 15218 @Override 15219 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 15220 mContext.enforceCallingOrSelfPermission( 15221 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15222 int callingUid = Binder.getCallingUid(); 15223 enforceOwnerRights(ownerPackage, callingUid); 15224 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15225 synchronized (mPackages) { 15226 CrossProfileIntentResolver resolver = 15227 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15228 ArraySet<CrossProfileIntentFilter> set = 15229 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 15230 for (CrossProfileIntentFilter filter : set) { 15231 if (filter.getOwnerPackage().equals(ownerPackage)) { 15232 resolver.removeFilter(filter); 15233 } 15234 } 15235 scheduleWritePackageRestrictionsLocked(sourceUserId); 15236 } 15237 } 15238 15239 // Enforcing that callingUid is owning pkg on userId 15240 private void enforceOwnerRights(String pkg, int callingUid) { 15241 // The system owns everything. 15242 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15243 return; 15244 } 15245 int callingUserId = UserHandle.getUserId(callingUid); 15246 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15247 if (pi == null) { 15248 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15249 + callingUserId); 15250 } 15251 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15252 throw new SecurityException("Calling uid " + callingUid 15253 + " does not own package " + pkg); 15254 } 15255 } 15256 15257 @Override 15258 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15259 Intent intent = new Intent(Intent.ACTION_MAIN); 15260 intent.addCategory(Intent.CATEGORY_HOME); 15261 15262 final int callingUserId = UserHandle.getCallingUserId(); 15263 List<ResolveInfo> list = queryIntentActivities(intent, null, 15264 PackageManager.GET_META_DATA, callingUserId); 15265 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15266 true, false, false, callingUserId); 15267 15268 allHomeCandidates.clear(); 15269 if (list != null) { 15270 for (ResolveInfo ri : list) { 15271 allHomeCandidates.add(ri); 15272 } 15273 } 15274 return (preferred == null || preferred.activityInfo == null) 15275 ? null 15276 : new ComponentName(preferred.activityInfo.packageName, 15277 preferred.activityInfo.name); 15278 } 15279 15280 @Override 15281 public void setApplicationEnabledSetting(String appPackageName, 15282 int newState, int flags, int userId, String callingPackage) { 15283 if (!sUserManager.exists(userId)) return; 15284 if (callingPackage == null) { 15285 callingPackage = Integer.toString(Binder.getCallingUid()); 15286 } 15287 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15288 } 15289 15290 @Override 15291 public void setComponentEnabledSetting(ComponentName componentName, 15292 int newState, int flags, int userId) { 15293 if (!sUserManager.exists(userId)) return; 15294 setEnabledSetting(componentName.getPackageName(), 15295 componentName.getClassName(), newState, flags, userId, null); 15296 } 15297 15298 private void setEnabledSetting(final String packageName, String className, int newState, 15299 final int flags, int userId, String callingPackage) { 15300 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15301 || newState == COMPONENT_ENABLED_STATE_ENABLED 15302 || newState == COMPONENT_ENABLED_STATE_DISABLED 15303 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15304 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15305 throw new IllegalArgumentException("Invalid new component state: " 15306 + newState); 15307 } 15308 PackageSetting pkgSetting; 15309 final int uid = Binder.getCallingUid(); 15310 final int permission = mContext.checkCallingOrSelfPermission( 15311 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15312 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15313 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15314 boolean sendNow = false; 15315 boolean isApp = (className == null); 15316 String componentName = isApp ? packageName : className; 15317 int packageUid = -1; 15318 ArrayList<String> components; 15319 15320 // writer 15321 synchronized (mPackages) { 15322 pkgSetting = mSettings.mPackages.get(packageName); 15323 if (pkgSetting == null) { 15324 if (className == null) { 15325 throw new IllegalArgumentException("Unknown package: " + packageName); 15326 } 15327 throw new IllegalArgumentException( 15328 "Unknown component: " + packageName + "/" + className); 15329 } 15330 // Allow root and verify that userId is not being specified by a different user 15331 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15332 throw new SecurityException( 15333 "Permission Denial: attempt to change component state from pid=" 15334 + Binder.getCallingPid() 15335 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15336 } 15337 if (className == null) { 15338 // We're dealing with an application/package level state change 15339 if (pkgSetting.getEnabled(userId) == newState) { 15340 // Nothing to do 15341 return; 15342 } 15343 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15344 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15345 // Don't care about who enables an app. 15346 callingPackage = null; 15347 } 15348 pkgSetting.setEnabled(newState, userId, callingPackage); 15349 // pkgSetting.pkg.mSetEnabled = newState; 15350 } else { 15351 // We're dealing with a component level state change 15352 // First, verify that this is a valid class name. 15353 PackageParser.Package pkg = pkgSetting.pkg; 15354 if (pkg == null || !pkg.hasComponentClassName(className)) { 15355 if (pkg != null && 15356 pkg.applicationInfo.targetSdkVersion >= 15357 Build.VERSION_CODES.JELLY_BEAN) { 15358 throw new IllegalArgumentException("Component class " + className 15359 + " does not exist in " + packageName); 15360 } else { 15361 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15362 + className + " does not exist in " + packageName); 15363 } 15364 } 15365 switch (newState) { 15366 case COMPONENT_ENABLED_STATE_ENABLED: 15367 if (!pkgSetting.enableComponentLPw(className, userId)) { 15368 return; 15369 } 15370 break; 15371 case COMPONENT_ENABLED_STATE_DISABLED: 15372 if (!pkgSetting.disableComponentLPw(className, userId)) { 15373 return; 15374 } 15375 break; 15376 case COMPONENT_ENABLED_STATE_DEFAULT: 15377 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15378 return; 15379 } 15380 break; 15381 default: 15382 Slog.e(TAG, "Invalid new component state: " + newState); 15383 return; 15384 } 15385 } 15386 scheduleWritePackageRestrictionsLocked(userId); 15387 components = mPendingBroadcasts.get(userId, packageName); 15388 final boolean newPackage = components == null; 15389 if (newPackage) { 15390 components = new ArrayList<String>(); 15391 } 15392 if (!components.contains(componentName)) { 15393 components.add(componentName); 15394 } 15395 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15396 sendNow = true; 15397 // Purge entry from pending broadcast list if another one exists already 15398 // since we are sending one right away. 15399 mPendingBroadcasts.remove(userId, packageName); 15400 } else { 15401 if (newPackage) { 15402 mPendingBroadcasts.put(userId, packageName, components); 15403 } 15404 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15405 // Schedule a message 15406 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15407 } 15408 } 15409 } 15410 15411 long callingId = Binder.clearCallingIdentity(); 15412 try { 15413 if (sendNow) { 15414 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15415 sendPackageChangedBroadcast(packageName, 15416 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15417 } 15418 } finally { 15419 Binder.restoreCallingIdentity(callingId); 15420 } 15421 } 15422 15423 private void sendPackageChangedBroadcast(String packageName, 15424 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15425 if (DEBUG_INSTALL) 15426 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15427 + componentNames); 15428 Bundle extras = new Bundle(4); 15429 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15430 String nameList[] = new String[componentNames.size()]; 15431 componentNames.toArray(nameList); 15432 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15433 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15434 extras.putInt(Intent.EXTRA_UID, packageUid); 15435 // If this is not reporting a change of the overall package, then only send it 15436 // to registered receivers. We don't want to launch a swath of apps for every 15437 // little component state change. 15438 final int flags = !componentNames.contains(packageName) 15439 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15440 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15441 new int[] {UserHandle.getUserId(packageUid)}); 15442 } 15443 15444 @Override 15445 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15446 if (!sUserManager.exists(userId)) return; 15447 final int uid = Binder.getCallingUid(); 15448 final int permission = mContext.checkCallingOrSelfPermission( 15449 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15450 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15451 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15452 // writer 15453 synchronized (mPackages) { 15454 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15455 allowedByPermission, uid, userId)) { 15456 scheduleWritePackageRestrictionsLocked(userId); 15457 } 15458 } 15459 } 15460 15461 @Override 15462 public String getInstallerPackageName(String packageName) { 15463 // reader 15464 synchronized (mPackages) { 15465 return mSettings.getInstallerPackageNameLPr(packageName); 15466 } 15467 } 15468 15469 @Override 15470 public int getApplicationEnabledSetting(String packageName, int userId) { 15471 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15472 int uid = Binder.getCallingUid(); 15473 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15474 // reader 15475 synchronized (mPackages) { 15476 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15477 } 15478 } 15479 15480 @Override 15481 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15482 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15483 int uid = Binder.getCallingUid(); 15484 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15485 // reader 15486 synchronized (mPackages) { 15487 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15488 } 15489 } 15490 15491 @Override 15492 public void enterSafeMode() { 15493 enforceSystemOrRoot("Only the system can request entering safe mode"); 15494 15495 if (!mSystemReady) { 15496 mSafeMode = true; 15497 } 15498 } 15499 15500 @Override 15501 public void systemReady() { 15502 mSystemReady = true; 15503 15504 // Read the compatibilty setting when the system is ready. 15505 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15506 mContext.getContentResolver(), 15507 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15508 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15509 if (DEBUG_SETTINGS) { 15510 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15511 } 15512 15513 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15514 15515 synchronized (mPackages) { 15516 // Verify that all of the preferred activity components actually 15517 // exist. It is possible for applications to be updated and at 15518 // that point remove a previously declared activity component that 15519 // had been set as a preferred activity. We try to clean this up 15520 // the next time we encounter that preferred activity, but it is 15521 // possible for the user flow to never be able to return to that 15522 // situation so here we do a sanity check to make sure we haven't 15523 // left any junk around. 15524 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15525 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15526 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15527 removed.clear(); 15528 for (PreferredActivity pa : pir.filterSet()) { 15529 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15530 removed.add(pa); 15531 } 15532 } 15533 if (removed.size() > 0) { 15534 for (int r=0; r<removed.size(); r++) { 15535 PreferredActivity pa = removed.get(r); 15536 Slog.w(TAG, "Removing dangling preferred activity: " 15537 + pa.mPref.mComponent); 15538 pir.removeFilter(pa); 15539 } 15540 mSettings.writePackageRestrictionsLPr( 15541 mSettings.mPreferredActivities.keyAt(i)); 15542 } 15543 } 15544 15545 for (int userId : UserManagerService.getInstance().getUserIds()) { 15546 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15547 grantPermissionsUserIds = ArrayUtils.appendInt( 15548 grantPermissionsUserIds, userId); 15549 } 15550 } 15551 } 15552 sUserManager.systemReady(); 15553 15554 // If we upgraded grant all default permissions before kicking off. 15555 for (int userId : grantPermissionsUserIds) { 15556 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15557 } 15558 15559 // Kick off any messages waiting for system ready 15560 if (mPostSystemReadyMessages != null) { 15561 for (Message msg : mPostSystemReadyMessages) { 15562 msg.sendToTarget(); 15563 } 15564 mPostSystemReadyMessages = null; 15565 } 15566 15567 // Watch for external volumes that come and go over time 15568 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15569 storage.registerListener(mStorageListener); 15570 15571 mInstallerService.systemReady(); 15572 mPackageDexOptimizer.systemReady(); 15573 15574 MountServiceInternal mountServiceInternal = LocalServices.getService( 15575 MountServiceInternal.class); 15576 mountServiceInternal.addExternalStoragePolicy( 15577 new MountServiceInternal.ExternalStorageMountPolicy() { 15578 @Override 15579 public int getMountMode(int uid, String packageName) { 15580 if (Process.isIsolated(uid)) { 15581 return Zygote.MOUNT_EXTERNAL_NONE; 15582 } 15583 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15584 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15585 } 15586 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15587 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15588 } 15589 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15590 return Zygote.MOUNT_EXTERNAL_READ; 15591 } 15592 return Zygote.MOUNT_EXTERNAL_WRITE; 15593 } 15594 15595 @Override 15596 public boolean hasExternalStorage(int uid, String packageName) { 15597 return true; 15598 } 15599 }); 15600 } 15601 15602 @Override 15603 public boolean isSafeMode() { 15604 return mSafeMode; 15605 } 15606 15607 @Override 15608 public boolean hasSystemUidErrors() { 15609 return mHasSystemUidErrors; 15610 } 15611 15612 static String arrayToString(int[] array) { 15613 StringBuffer buf = new StringBuffer(128); 15614 buf.append('['); 15615 if (array != null) { 15616 for (int i=0; i<array.length; i++) { 15617 if (i > 0) buf.append(", "); 15618 buf.append(array[i]); 15619 } 15620 } 15621 buf.append(']'); 15622 return buf.toString(); 15623 } 15624 15625 static class DumpState { 15626 public static final int DUMP_LIBS = 1 << 0; 15627 public static final int DUMP_FEATURES = 1 << 1; 15628 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15629 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15630 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15631 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15632 public static final int DUMP_PERMISSIONS = 1 << 6; 15633 public static final int DUMP_PACKAGES = 1 << 7; 15634 public static final int DUMP_SHARED_USERS = 1 << 8; 15635 public static final int DUMP_MESSAGES = 1 << 9; 15636 public static final int DUMP_PROVIDERS = 1 << 10; 15637 public static final int DUMP_VERIFIERS = 1 << 11; 15638 public static final int DUMP_PREFERRED = 1 << 12; 15639 public static final int DUMP_PREFERRED_XML = 1 << 13; 15640 public static final int DUMP_KEYSETS = 1 << 14; 15641 public static final int DUMP_VERSION = 1 << 15; 15642 public static final int DUMP_INSTALLS = 1 << 16; 15643 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15644 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15645 15646 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15647 15648 private int mTypes; 15649 15650 private int mOptions; 15651 15652 private boolean mTitlePrinted; 15653 15654 private SharedUserSetting mSharedUser; 15655 15656 public boolean isDumping(int type) { 15657 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15658 return true; 15659 } 15660 15661 return (mTypes & type) != 0; 15662 } 15663 15664 public void setDump(int type) { 15665 mTypes |= type; 15666 } 15667 15668 public boolean isOptionEnabled(int option) { 15669 return (mOptions & option) != 0; 15670 } 15671 15672 public void setOptionEnabled(int option) { 15673 mOptions |= option; 15674 } 15675 15676 public boolean onTitlePrinted() { 15677 final boolean printed = mTitlePrinted; 15678 mTitlePrinted = true; 15679 return printed; 15680 } 15681 15682 public boolean getTitlePrinted() { 15683 return mTitlePrinted; 15684 } 15685 15686 public void setTitlePrinted(boolean enabled) { 15687 mTitlePrinted = enabled; 15688 } 15689 15690 public SharedUserSetting getSharedUser() { 15691 return mSharedUser; 15692 } 15693 15694 public void setSharedUser(SharedUserSetting user) { 15695 mSharedUser = user; 15696 } 15697 } 15698 15699 @Override 15700 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15701 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15702 (new PackageManagerShellCommand(this)).exec( 15703 this, in, out, err, args, resultReceiver); 15704 } 15705 15706 @Override 15707 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15708 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15709 != PackageManager.PERMISSION_GRANTED) { 15710 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15711 + Binder.getCallingPid() 15712 + ", uid=" + Binder.getCallingUid() 15713 + " without permission " 15714 + android.Manifest.permission.DUMP); 15715 return; 15716 } 15717 15718 DumpState dumpState = new DumpState(); 15719 boolean fullPreferred = false; 15720 boolean checkin = false; 15721 15722 String packageName = null; 15723 ArraySet<String> permissionNames = null; 15724 15725 int opti = 0; 15726 while (opti < args.length) { 15727 String opt = args[opti]; 15728 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15729 break; 15730 } 15731 opti++; 15732 15733 if ("-a".equals(opt)) { 15734 // Right now we only know how to print all. 15735 } else if ("-h".equals(opt)) { 15736 pw.println("Package manager dump options:"); 15737 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15738 pw.println(" --checkin: dump for a checkin"); 15739 pw.println(" -f: print details of intent filters"); 15740 pw.println(" -h: print this help"); 15741 pw.println(" cmd may be one of:"); 15742 pw.println(" l[ibraries]: list known shared libraries"); 15743 pw.println(" f[eatures]: list device features"); 15744 pw.println(" k[eysets]: print known keysets"); 15745 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15746 pw.println(" perm[issions]: dump permissions"); 15747 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15748 pw.println(" pref[erred]: print preferred package settings"); 15749 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15750 pw.println(" prov[iders]: dump content providers"); 15751 pw.println(" p[ackages]: dump installed packages"); 15752 pw.println(" s[hared-users]: dump shared user IDs"); 15753 pw.println(" m[essages]: print collected runtime messages"); 15754 pw.println(" v[erifiers]: print package verifier info"); 15755 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15756 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15757 pw.println(" version: print database version info"); 15758 pw.println(" write: write current settings now"); 15759 pw.println(" installs: details about install sessions"); 15760 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15761 pw.println(" <package.name>: info about given package"); 15762 return; 15763 } else if ("--checkin".equals(opt)) { 15764 checkin = true; 15765 } else if ("-f".equals(opt)) { 15766 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15767 } else { 15768 pw.println("Unknown argument: " + opt + "; use -h for help"); 15769 } 15770 } 15771 15772 // Is the caller requesting to dump a particular piece of data? 15773 if (opti < args.length) { 15774 String cmd = args[opti]; 15775 opti++; 15776 // Is this a package name? 15777 if ("android".equals(cmd) || cmd.contains(".")) { 15778 packageName = cmd; 15779 // When dumping a single package, we always dump all of its 15780 // filter information since the amount of data will be reasonable. 15781 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15782 } else if ("check-permission".equals(cmd)) { 15783 if (opti >= args.length) { 15784 pw.println("Error: check-permission missing permission argument"); 15785 return; 15786 } 15787 String perm = args[opti]; 15788 opti++; 15789 if (opti >= args.length) { 15790 pw.println("Error: check-permission missing package argument"); 15791 return; 15792 } 15793 String pkg = args[opti]; 15794 opti++; 15795 int user = UserHandle.getUserId(Binder.getCallingUid()); 15796 if (opti < args.length) { 15797 try { 15798 user = Integer.parseInt(args[opti]); 15799 } catch (NumberFormatException e) { 15800 pw.println("Error: check-permission user argument is not a number: " 15801 + args[opti]); 15802 return; 15803 } 15804 } 15805 pw.println(checkPermission(perm, pkg, user)); 15806 return; 15807 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15808 dumpState.setDump(DumpState.DUMP_LIBS); 15809 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15810 dumpState.setDump(DumpState.DUMP_FEATURES); 15811 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15812 if (opti >= args.length) { 15813 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15814 | DumpState.DUMP_SERVICE_RESOLVERS 15815 | DumpState.DUMP_RECEIVER_RESOLVERS 15816 | DumpState.DUMP_CONTENT_RESOLVERS); 15817 } else { 15818 while (opti < args.length) { 15819 String name = args[opti]; 15820 if ("a".equals(name) || "activity".equals(name)) { 15821 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15822 } else if ("s".equals(name) || "service".equals(name)) { 15823 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15824 } else if ("r".equals(name) || "receiver".equals(name)) { 15825 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15826 } else if ("c".equals(name) || "content".equals(name)) { 15827 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15828 } else { 15829 pw.println("Error: unknown resolver table type: " + name); 15830 return; 15831 } 15832 opti++; 15833 } 15834 } 15835 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15836 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15837 } else if ("permission".equals(cmd)) { 15838 if (opti >= args.length) { 15839 pw.println("Error: permission requires permission name"); 15840 return; 15841 } 15842 permissionNames = new ArraySet<>(); 15843 while (opti < args.length) { 15844 permissionNames.add(args[opti]); 15845 opti++; 15846 } 15847 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15848 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15849 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15850 dumpState.setDump(DumpState.DUMP_PREFERRED); 15851 } else if ("preferred-xml".equals(cmd)) { 15852 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15853 if (opti < args.length && "--full".equals(args[opti])) { 15854 fullPreferred = true; 15855 opti++; 15856 } 15857 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15858 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15859 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15860 dumpState.setDump(DumpState.DUMP_PACKAGES); 15861 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15862 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15863 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15864 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15865 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15866 dumpState.setDump(DumpState.DUMP_MESSAGES); 15867 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15868 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15869 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15870 || "intent-filter-verifiers".equals(cmd)) { 15871 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15872 } else if ("version".equals(cmd)) { 15873 dumpState.setDump(DumpState.DUMP_VERSION); 15874 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15875 dumpState.setDump(DumpState.DUMP_KEYSETS); 15876 } else if ("installs".equals(cmd)) { 15877 dumpState.setDump(DumpState.DUMP_INSTALLS); 15878 } else if ("write".equals(cmd)) { 15879 synchronized (mPackages) { 15880 mSettings.writeLPr(); 15881 pw.println("Settings written."); 15882 return; 15883 } 15884 } 15885 } 15886 15887 if (checkin) { 15888 pw.println("vers,1"); 15889 } 15890 15891 // reader 15892 synchronized (mPackages) { 15893 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15894 if (!checkin) { 15895 if (dumpState.onTitlePrinted()) 15896 pw.println(); 15897 pw.println("Database versions:"); 15898 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15899 } 15900 } 15901 15902 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15903 if (!checkin) { 15904 if (dumpState.onTitlePrinted()) 15905 pw.println(); 15906 pw.println("Verifiers:"); 15907 pw.print(" Required: "); 15908 pw.print(mRequiredVerifierPackage); 15909 pw.print(" (uid="); 15910 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15911 UserHandle.USER_SYSTEM)); 15912 pw.println(")"); 15913 } else if (mRequiredVerifierPackage != null) { 15914 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15915 pw.print(","); 15916 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15917 UserHandle.USER_SYSTEM)); 15918 } 15919 } 15920 15921 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15922 packageName == null) { 15923 if (mIntentFilterVerifierComponent != null) { 15924 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15925 if (!checkin) { 15926 if (dumpState.onTitlePrinted()) 15927 pw.println(); 15928 pw.println("Intent Filter Verifier:"); 15929 pw.print(" Using: "); 15930 pw.print(verifierPackageName); 15931 pw.print(" (uid="); 15932 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15933 UserHandle.USER_SYSTEM)); 15934 pw.println(")"); 15935 } else if (verifierPackageName != null) { 15936 pw.print("ifv,"); pw.print(verifierPackageName); 15937 pw.print(","); 15938 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15939 UserHandle.USER_SYSTEM)); 15940 } 15941 } else { 15942 pw.println(); 15943 pw.println("No Intent Filter Verifier available!"); 15944 } 15945 } 15946 15947 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15948 boolean printedHeader = false; 15949 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15950 while (it.hasNext()) { 15951 String name = it.next(); 15952 SharedLibraryEntry ent = mSharedLibraries.get(name); 15953 if (!checkin) { 15954 if (!printedHeader) { 15955 if (dumpState.onTitlePrinted()) 15956 pw.println(); 15957 pw.println("Libraries:"); 15958 printedHeader = true; 15959 } 15960 pw.print(" "); 15961 } else { 15962 pw.print("lib,"); 15963 } 15964 pw.print(name); 15965 if (!checkin) { 15966 pw.print(" -> "); 15967 } 15968 if (ent.path != null) { 15969 if (!checkin) { 15970 pw.print("(jar) "); 15971 pw.print(ent.path); 15972 } else { 15973 pw.print(",jar,"); 15974 pw.print(ent.path); 15975 } 15976 } else { 15977 if (!checkin) { 15978 pw.print("(apk) "); 15979 pw.print(ent.apk); 15980 } else { 15981 pw.print(",apk,"); 15982 pw.print(ent.apk); 15983 } 15984 } 15985 pw.println(); 15986 } 15987 } 15988 15989 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15990 if (dumpState.onTitlePrinted()) 15991 pw.println(); 15992 if (!checkin) { 15993 pw.println("Features:"); 15994 } 15995 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15996 while (it.hasNext()) { 15997 String name = it.next(); 15998 if (!checkin) { 15999 pw.print(" "); 16000 } else { 16001 pw.print("feat,"); 16002 } 16003 pw.println(name); 16004 } 16005 } 16006 16007 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 16008 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 16009 : "Activity Resolver Table:", " ", packageName, 16010 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16011 dumpState.setTitlePrinted(true); 16012 } 16013 } 16014 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 16015 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 16016 : "Receiver Resolver Table:", " ", packageName, 16017 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16018 dumpState.setTitlePrinted(true); 16019 } 16020 } 16021 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 16022 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 16023 : "Service Resolver Table:", " ", packageName, 16024 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16025 dumpState.setTitlePrinted(true); 16026 } 16027 } 16028 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 16029 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 16030 : "Provider Resolver Table:", " ", packageName, 16031 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16032 dumpState.setTitlePrinted(true); 16033 } 16034 } 16035 16036 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 16037 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16038 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16039 int user = mSettings.mPreferredActivities.keyAt(i); 16040 if (pir.dump(pw, 16041 dumpState.getTitlePrinted() 16042 ? "\nPreferred Activities User " + user + ":" 16043 : "Preferred Activities User " + user + ":", " ", 16044 packageName, true, false)) { 16045 dumpState.setTitlePrinted(true); 16046 } 16047 } 16048 } 16049 16050 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 16051 pw.flush(); 16052 FileOutputStream fout = new FileOutputStream(fd); 16053 BufferedOutputStream str = new BufferedOutputStream(fout); 16054 XmlSerializer serializer = new FastXmlSerializer(); 16055 try { 16056 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 16057 serializer.startDocument(null, true); 16058 serializer.setFeature( 16059 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 16060 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 16061 serializer.endDocument(); 16062 serializer.flush(); 16063 } catch (IllegalArgumentException e) { 16064 pw.println("Failed writing: " + e); 16065 } catch (IllegalStateException e) { 16066 pw.println("Failed writing: " + e); 16067 } catch (IOException e) { 16068 pw.println("Failed writing: " + e); 16069 } 16070 } 16071 16072 if (!checkin 16073 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 16074 && packageName == null) { 16075 pw.println(); 16076 int count = mSettings.mPackages.size(); 16077 if (count == 0) { 16078 pw.println("No applications!"); 16079 pw.println(); 16080 } else { 16081 final String prefix = " "; 16082 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 16083 if (allPackageSettings.size() == 0) { 16084 pw.println("No domain preferred apps!"); 16085 pw.println(); 16086 } else { 16087 pw.println("App verification status:"); 16088 pw.println(); 16089 count = 0; 16090 for (PackageSetting ps : allPackageSettings) { 16091 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 16092 if (ivi == null || ivi.getPackageName() == null) continue; 16093 pw.println(prefix + "Package: " + ivi.getPackageName()); 16094 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 16095 pw.println(prefix + "Status: " + ivi.getStatusString()); 16096 pw.println(); 16097 count++; 16098 } 16099 if (count == 0) { 16100 pw.println(prefix + "No app verification established."); 16101 pw.println(); 16102 } 16103 for (int userId : sUserManager.getUserIds()) { 16104 pw.println("App linkages for user " + userId + ":"); 16105 pw.println(); 16106 count = 0; 16107 for (PackageSetting ps : allPackageSettings) { 16108 final long status = ps.getDomainVerificationStatusForUser(userId); 16109 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 16110 continue; 16111 } 16112 pw.println(prefix + "Package: " + ps.name); 16113 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 16114 String statusStr = IntentFilterVerificationInfo. 16115 getStatusStringFromValue(status); 16116 pw.println(prefix + "Status: " + statusStr); 16117 pw.println(); 16118 count++; 16119 } 16120 if (count == 0) { 16121 pw.println(prefix + "No configured app linkages."); 16122 pw.println(); 16123 } 16124 } 16125 } 16126 } 16127 } 16128 16129 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 16130 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 16131 if (packageName == null && permissionNames == null) { 16132 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 16133 if (iperm == 0) { 16134 if (dumpState.onTitlePrinted()) 16135 pw.println(); 16136 pw.println("AppOp Permissions:"); 16137 } 16138 pw.print(" AppOp Permission "); 16139 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 16140 pw.println(":"); 16141 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 16142 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 16143 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 16144 } 16145 } 16146 } 16147 } 16148 16149 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 16150 boolean printedSomething = false; 16151 for (PackageParser.Provider p : mProviders.mProviders.values()) { 16152 if (packageName != null && !packageName.equals(p.info.packageName)) { 16153 continue; 16154 } 16155 if (!printedSomething) { 16156 if (dumpState.onTitlePrinted()) 16157 pw.println(); 16158 pw.println("Registered ContentProviders:"); 16159 printedSomething = true; 16160 } 16161 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 16162 pw.print(" "); pw.println(p.toString()); 16163 } 16164 printedSomething = false; 16165 for (Map.Entry<String, PackageParser.Provider> entry : 16166 mProvidersByAuthority.entrySet()) { 16167 PackageParser.Provider p = entry.getValue(); 16168 if (packageName != null && !packageName.equals(p.info.packageName)) { 16169 continue; 16170 } 16171 if (!printedSomething) { 16172 if (dumpState.onTitlePrinted()) 16173 pw.println(); 16174 pw.println("ContentProvider Authorities:"); 16175 printedSomething = true; 16176 } 16177 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 16178 pw.print(" "); pw.println(p.toString()); 16179 if (p.info != null && p.info.applicationInfo != null) { 16180 final String appInfo = p.info.applicationInfo.toString(); 16181 pw.print(" applicationInfo="); pw.println(appInfo); 16182 } 16183 } 16184 } 16185 16186 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 16187 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 16188 } 16189 16190 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 16191 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 16192 } 16193 16194 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 16195 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 16196 } 16197 16198 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 16199 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 16200 } 16201 16202 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 16203 // XXX should handle packageName != null by dumping only install data that 16204 // the given package is involved with. 16205 if (dumpState.onTitlePrinted()) pw.println(); 16206 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 16207 } 16208 16209 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 16210 if (dumpState.onTitlePrinted()) pw.println(); 16211 mSettings.dumpReadMessagesLPr(pw, dumpState); 16212 16213 pw.println(); 16214 pw.println("Package warning messages:"); 16215 BufferedReader in = null; 16216 String line = null; 16217 try { 16218 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16219 while ((line = in.readLine()) != null) { 16220 if (line.contains("ignored: updated version")) continue; 16221 pw.println(line); 16222 } 16223 } catch (IOException ignored) { 16224 } finally { 16225 IoUtils.closeQuietly(in); 16226 } 16227 } 16228 16229 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 16230 BufferedReader in = null; 16231 String line = null; 16232 try { 16233 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16234 while ((line = in.readLine()) != null) { 16235 if (line.contains("ignored: updated version")) continue; 16236 pw.print("msg,"); 16237 pw.println(line); 16238 } 16239 } catch (IOException ignored) { 16240 } finally { 16241 IoUtils.closeQuietly(in); 16242 } 16243 } 16244 } 16245 } 16246 16247 private String dumpDomainString(String packageName) { 16248 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 16249 List<IntentFilter> filters = getAllIntentFilters(packageName); 16250 16251 ArraySet<String> result = new ArraySet<>(); 16252 if (iviList.size() > 0) { 16253 for (IntentFilterVerificationInfo ivi : iviList) { 16254 for (String host : ivi.getDomains()) { 16255 result.add(host); 16256 } 16257 } 16258 } 16259 if (filters != null && filters.size() > 0) { 16260 for (IntentFilter filter : filters) { 16261 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 16262 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 16263 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 16264 result.addAll(filter.getHostsList()); 16265 } 16266 } 16267 } 16268 16269 StringBuilder sb = new StringBuilder(result.size() * 16); 16270 for (String domain : result) { 16271 if (sb.length() > 0) sb.append(" "); 16272 sb.append(domain); 16273 } 16274 return sb.toString(); 16275 } 16276 16277 // ------- apps on sdcard specific code ------- 16278 static final boolean DEBUG_SD_INSTALL = false; 16279 16280 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16281 16282 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16283 16284 private boolean mMediaMounted = false; 16285 16286 static String getEncryptKey() { 16287 try { 16288 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16289 SD_ENCRYPTION_KEYSTORE_NAME); 16290 if (sdEncKey == null) { 16291 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16292 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16293 if (sdEncKey == null) { 16294 Slog.e(TAG, "Failed to create encryption keys"); 16295 return null; 16296 } 16297 } 16298 return sdEncKey; 16299 } catch (NoSuchAlgorithmException nsae) { 16300 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16301 return null; 16302 } catch (IOException ioe) { 16303 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16304 return null; 16305 } 16306 } 16307 16308 /* 16309 * Update media status on PackageManager. 16310 */ 16311 @Override 16312 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16313 int callingUid = Binder.getCallingUid(); 16314 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16315 throw new SecurityException("Media status can only be updated by the system"); 16316 } 16317 // reader; this apparently protects mMediaMounted, but should probably 16318 // be a different lock in that case. 16319 synchronized (mPackages) { 16320 Log.i(TAG, "Updating external media status from " 16321 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16322 + (mediaStatus ? "mounted" : "unmounted")); 16323 if (DEBUG_SD_INSTALL) 16324 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16325 + ", mMediaMounted=" + mMediaMounted); 16326 if (mediaStatus == mMediaMounted) { 16327 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16328 : 0, -1); 16329 mHandler.sendMessage(msg); 16330 return; 16331 } 16332 mMediaMounted = mediaStatus; 16333 } 16334 // Queue up an async operation since the package installation may take a 16335 // little while. 16336 mHandler.post(new Runnable() { 16337 public void run() { 16338 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16339 } 16340 }); 16341 } 16342 16343 /** 16344 * Called by MountService when the initial ASECs to scan are available. 16345 * Should block until all the ASEC containers are finished being scanned. 16346 */ 16347 public void scanAvailableAsecs() { 16348 updateExternalMediaStatusInner(true, false, false); 16349 } 16350 16351 /* 16352 * Collect information of applications on external media, map them against 16353 * existing containers and update information based on current mount status. 16354 * Please note that we always have to report status if reportStatus has been 16355 * set to true especially when unloading packages. 16356 */ 16357 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16358 boolean externalStorage) { 16359 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16360 int[] uidArr = EmptyArray.INT; 16361 16362 final String[] list = PackageHelper.getSecureContainerList(); 16363 if (ArrayUtils.isEmpty(list)) { 16364 Log.i(TAG, "No secure containers found"); 16365 } else { 16366 // Process list of secure containers and categorize them 16367 // as active or stale based on their package internal state. 16368 16369 // reader 16370 synchronized (mPackages) { 16371 for (String cid : list) { 16372 // Leave stages untouched for now; installer service owns them 16373 if (PackageInstallerService.isStageName(cid)) continue; 16374 16375 if (DEBUG_SD_INSTALL) 16376 Log.i(TAG, "Processing container " + cid); 16377 String pkgName = getAsecPackageName(cid); 16378 if (pkgName == null) { 16379 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16380 continue; 16381 } 16382 if (DEBUG_SD_INSTALL) 16383 Log.i(TAG, "Looking for pkg : " + pkgName); 16384 16385 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16386 if (ps == null) { 16387 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16388 continue; 16389 } 16390 16391 /* 16392 * Skip packages that are not external if we're unmounting 16393 * external storage. 16394 */ 16395 if (externalStorage && !isMounted && !isExternal(ps)) { 16396 continue; 16397 } 16398 16399 final AsecInstallArgs args = new AsecInstallArgs(cid, 16400 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16401 // The package status is changed only if the code path 16402 // matches between settings and the container id. 16403 if (ps.codePathString != null 16404 && ps.codePathString.startsWith(args.getCodePath())) { 16405 if (DEBUG_SD_INSTALL) { 16406 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16407 + " at code path: " + ps.codePathString); 16408 } 16409 16410 // We do have a valid package installed on sdcard 16411 processCids.put(args, ps.codePathString); 16412 final int uid = ps.appId; 16413 if (uid != -1) { 16414 uidArr = ArrayUtils.appendInt(uidArr, uid); 16415 } 16416 } else { 16417 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16418 + ps.codePathString); 16419 } 16420 } 16421 } 16422 16423 Arrays.sort(uidArr); 16424 } 16425 16426 // Process packages with valid entries. 16427 if (isMounted) { 16428 if (DEBUG_SD_INSTALL) 16429 Log.i(TAG, "Loading packages"); 16430 loadMediaPackages(processCids, uidArr, externalStorage); 16431 startCleaningPackages(); 16432 mInstallerService.onSecureContainersAvailable(); 16433 } else { 16434 if (DEBUG_SD_INSTALL) 16435 Log.i(TAG, "Unloading packages"); 16436 unloadMediaPackages(processCids, uidArr, reportStatus); 16437 } 16438 } 16439 16440 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16441 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16442 final int size = infos.size(); 16443 final String[] packageNames = new String[size]; 16444 final int[] packageUids = new int[size]; 16445 for (int i = 0; i < size; i++) { 16446 final ApplicationInfo info = infos.get(i); 16447 packageNames[i] = info.packageName; 16448 packageUids[i] = info.uid; 16449 } 16450 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16451 finishedReceiver); 16452 } 16453 16454 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16455 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16456 sendResourcesChangedBroadcast(mediaStatus, replacing, 16457 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16458 } 16459 16460 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16461 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16462 int size = pkgList.length; 16463 if (size > 0) { 16464 // Send broadcasts here 16465 Bundle extras = new Bundle(); 16466 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16467 if (uidArr != null) { 16468 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16469 } 16470 if (replacing) { 16471 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16472 } 16473 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16474 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16475 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16476 } 16477 } 16478 16479 /* 16480 * Look at potentially valid container ids from processCids If package 16481 * information doesn't match the one on record or package scanning fails, 16482 * the cid is added to list of removeCids. We currently don't delete stale 16483 * containers. 16484 */ 16485 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16486 boolean externalStorage) { 16487 ArrayList<String> pkgList = new ArrayList<String>(); 16488 Set<AsecInstallArgs> keys = processCids.keySet(); 16489 16490 for (AsecInstallArgs args : keys) { 16491 String codePath = processCids.get(args); 16492 if (DEBUG_SD_INSTALL) 16493 Log.i(TAG, "Loading container : " + args.cid); 16494 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16495 try { 16496 // Make sure there are no container errors first. 16497 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16498 Slog.e(TAG, "Failed to mount cid : " + args.cid 16499 + " when installing from sdcard"); 16500 continue; 16501 } 16502 // Check code path here. 16503 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16504 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16505 + " does not match one in settings " + codePath); 16506 continue; 16507 } 16508 // Parse package 16509 int parseFlags = mDefParseFlags; 16510 if (args.isExternalAsec()) { 16511 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16512 } 16513 if (args.isFwdLocked()) { 16514 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16515 } 16516 16517 synchronized (mInstallLock) { 16518 PackageParser.Package pkg = null; 16519 try { 16520 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16521 } catch (PackageManagerException e) { 16522 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16523 } 16524 // Scan the package 16525 if (pkg != null) { 16526 /* 16527 * TODO why is the lock being held? doPostInstall is 16528 * called in other places without the lock. This needs 16529 * to be straightened out. 16530 */ 16531 // writer 16532 synchronized (mPackages) { 16533 retCode = PackageManager.INSTALL_SUCCEEDED; 16534 pkgList.add(pkg.packageName); 16535 // Post process args 16536 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16537 pkg.applicationInfo.uid); 16538 } 16539 } else { 16540 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16541 } 16542 } 16543 16544 } finally { 16545 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16546 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16547 } 16548 } 16549 } 16550 // writer 16551 synchronized (mPackages) { 16552 // If the platform SDK has changed since the last time we booted, 16553 // we need to re-grant app permission to catch any new ones that 16554 // appear. This is really a hack, and means that apps can in some 16555 // cases get permissions that the user didn't initially explicitly 16556 // allow... it would be nice to have some better way to handle 16557 // this situation. 16558 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16559 : mSettings.getInternalVersion(); 16560 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16561 : StorageManager.UUID_PRIVATE_INTERNAL; 16562 16563 int updateFlags = UPDATE_PERMISSIONS_ALL; 16564 if (ver.sdkVersion != mSdkVersion) { 16565 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16566 + mSdkVersion + "; regranting permissions for external"); 16567 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16568 } 16569 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16570 16571 // Yay, everything is now upgraded 16572 ver.forceCurrent(); 16573 16574 // can downgrade to reader 16575 // Persist settings 16576 mSettings.writeLPr(); 16577 } 16578 // Send a broadcast to let everyone know we are done processing 16579 if (pkgList.size() > 0) { 16580 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16581 } 16582 } 16583 16584 /* 16585 * Utility method to unload a list of specified containers 16586 */ 16587 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16588 // Just unmount all valid containers. 16589 for (AsecInstallArgs arg : cidArgs) { 16590 synchronized (mInstallLock) { 16591 arg.doPostDeleteLI(false); 16592 } 16593 } 16594 } 16595 16596 /* 16597 * Unload packages mounted on external media. This involves deleting package 16598 * data from internal structures, sending broadcasts about diabled packages, 16599 * gc'ing to free up references, unmounting all secure containers 16600 * corresponding to packages on external media, and posting a 16601 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16602 * that we always have to post this message if status has been requested no 16603 * matter what. 16604 */ 16605 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16606 final boolean reportStatus) { 16607 if (DEBUG_SD_INSTALL) 16608 Log.i(TAG, "unloading media packages"); 16609 ArrayList<String> pkgList = new ArrayList<String>(); 16610 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16611 final Set<AsecInstallArgs> keys = processCids.keySet(); 16612 for (AsecInstallArgs args : keys) { 16613 String pkgName = args.getPackageName(); 16614 if (DEBUG_SD_INSTALL) 16615 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16616 // Delete package internally 16617 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16618 synchronized (mInstallLock) { 16619 boolean res = deletePackageLI(pkgName, null, false, null, null, 16620 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16621 if (res) { 16622 pkgList.add(pkgName); 16623 } else { 16624 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16625 failedList.add(args); 16626 } 16627 } 16628 } 16629 16630 // reader 16631 synchronized (mPackages) { 16632 // We didn't update the settings after removing each package; 16633 // write them now for all packages. 16634 mSettings.writeLPr(); 16635 } 16636 16637 // We have to absolutely send UPDATED_MEDIA_STATUS only 16638 // after confirming that all the receivers processed the ordered 16639 // broadcast when packages get disabled, force a gc to clean things up. 16640 // and unload all the containers. 16641 if (pkgList.size() > 0) { 16642 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16643 new IIntentReceiver.Stub() { 16644 public void performReceive(Intent intent, int resultCode, String data, 16645 Bundle extras, boolean ordered, boolean sticky, 16646 int sendingUser) throws RemoteException { 16647 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16648 reportStatus ? 1 : 0, 1, keys); 16649 mHandler.sendMessage(msg); 16650 } 16651 }); 16652 } else { 16653 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16654 keys); 16655 mHandler.sendMessage(msg); 16656 } 16657 } 16658 16659 private void loadPrivatePackages(final VolumeInfo vol) { 16660 mHandler.post(new Runnable() { 16661 @Override 16662 public void run() { 16663 loadPrivatePackagesInner(vol); 16664 } 16665 }); 16666 } 16667 16668 private void loadPrivatePackagesInner(VolumeInfo vol) { 16669 final String volumeUuid = vol.fsUuid; 16670 if (TextUtils.isEmpty(volumeUuid)) { 16671 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 16672 return; 16673 } 16674 16675 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16676 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16677 16678 final VersionInfo ver; 16679 final List<PackageSetting> packages; 16680 synchronized (mPackages) { 16681 ver = mSettings.findOrCreateVersion(volumeUuid); 16682 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16683 } 16684 16685 // TODO: introduce a new concept similar to "frozen" to prevent these 16686 // apps from being launched until after data has been fully reconciled 16687 for (PackageSetting ps : packages) { 16688 synchronized (mInstallLock) { 16689 final PackageParser.Package pkg; 16690 try { 16691 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16692 loaded.add(pkg.applicationInfo); 16693 16694 } catch (PackageManagerException e) { 16695 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16696 } 16697 16698 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16699 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16700 } 16701 } 16702 } 16703 16704 // Reconcile app data for all started/unlocked users 16705 final UserManager um = mContext.getSystemService(UserManager.class); 16706 for (UserInfo user : um.getUsers()) { 16707 if (um.isUserUnlocked(user.id)) { 16708 reconcileAppsData(volumeUuid, user.id, 16709 Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE); 16710 } else if (um.isUserRunning(user.id)) { 16711 reconcileAppsData(volumeUuid, user.id, Installer.FLAG_DE_STORAGE); 16712 } else { 16713 continue; 16714 } 16715 } 16716 16717 synchronized (mPackages) { 16718 int updateFlags = UPDATE_PERMISSIONS_ALL; 16719 if (ver.sdkVersion != mSdkVersion) { 16720 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16721 + mSdkVersion + "; regranting permissions for " + volumeUuid); 16722 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16723 } 16724 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16725 16726 // Yay, everything is now upgraded 16727 ver.forceCurrent(); 16728 16729 mSettings.writeLPr(); 16730 } 16731 16732 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16733 sendResourcesChangedBroadcast(true, false, loaded, null); 16734 } 16735 16736 private void unloadPrivatePackages(final VolumeInfo vol) { 16737 mHandler.post(new Runnable() { 16738 @Override 16739 public void run() { 16740 unloadPrivatePackagesInner(vol); 16741 } 16742 }); 16743 } 16744 16745 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16746 final String volumeUuid = vol.fsUuid; 16747 if (TextUtils.isEmpty(volumeUuid)) { 16748 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 16749 return; 16750 } 16751 16752 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16753 synchronized (mInstallLock) { 16754 synchronized (mPackages) { 16755 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 16756 for (PackageSetting ps : packages) { 16757 if (ps.pkg == null) continue; 16758 16759 final ApplicationInfo info = ps.pkg.applicationInfo; 16760 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16761 if (deletePackageLI(ps.name, null, false, null, null, 16762 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16763 unloaded.add(info); 16764 } else { 16765 Slog.w(TAG, "Failed to unload " + ps.codePath); 16766 } 16767 } 16768 16769 mSettings.writeLPr(); 16770 } 16771 } 16772 16773 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16774 sendResourcesChangedBroadcast(false, false, unloaded, null); 16775 } 16776 16777 /** 16778 * Examine all users present on given mounted volume, and destroy data 16779 * belonging to users that are no longer valid, or whose user ID has been 16780 * recycled. 16781 */ 16782 private void reconcileUsers(String volumeUuid) { 16783 final File[] files = FileUtils 16784 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16785 for (File file : files) { 16786 if (!file.isDirectory()) continue; 16787 16788 final int userId; 16789 final UserInfo info; 16790 try { 16791 userId = Integer.parseInt(file.getName()); 16792 info = sUserManager.getUserInfo(userId); 16793 } catch (NumberFormatException e) { 16794 Slog.w(TAG, "Invalid user directory " + file); 16795 continue; 16796 } 16797 16798 boolean destroyUser = false; 16799 if (info == null) { 16800 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16801 + " because no matching user was found"); 16802 destroyUser = true; 16803 } else { 16804 try { 16805 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16806 } catch (IOException e) { 16807 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16808 + " because we failed to enforce serial number: " + e); 16809 destroyUser = true; 16810 } 16811 } 16812 16813 if (destroyUser) { 16814 synchronized (mInstallLock) { 16815 try { 16816 mInstaller.removeUserDataDirs(volumeUuid, userId); 16817 } catch (InstallerException e) { 16818 Slog.w(TAG, "Failed to clean up user dirs", e); 16819 } 16820 } 16821 } 16822 } 16823 16824 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16825 final UserManager um = mContext.getSystemService(UserManager.class); 16826 for (UserInfo user : um.getUsers()) { 16827 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16828 if (userDir.exists()) continue; 16829 16830 try { 16831 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral()); 16832 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16833 } catch (IOException e) { 16834 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16835 } 16836 } 16837 } 16838 16839 private void assertPackageKnown(String volumeUuid, String packageName) 16840 throws PackageManagerException { 16841 synchronized (mPackages) { 16842 final PackageSetting ps = mSettings.mPackages.get(packageName); 16843 if (ps == null) { 16844 throw new PackageManagerException("Package " + packageName + " is unknown"); 16845 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16846 throw new PackageManagerException( 16847 "Package " + packageName + " found on unknown volume " + volumeUuid 16848 + "; expected volume " + ps.volumeUuid); 16849 } 16850 } 16851 } 16852 16853 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 16854 throws PackageManagerException { 16855 synchronized (mPackages) { 16856 final PackageSetting ps = mSettings.mPackages.get(packageName); 16857 if (ps == null) { 16858 throw new PackageManagerException("Package " + packageName + " is unknown"); 16859 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16860 throw new PackageManagerException( 16861 "Package " + packageName + " found on unknown volume " + volumeUuid 16862 + "; expected volume " + ps.volumeUuid); 16863 } else if (!ps.getInstalled(userId)) { 16864 throw new PackageManagerException( 16865 "Package " + packageName + " not installed for user " + userId); 16866 } 16867 } 16868 } 16869 16870 /** 16871 * Examine all apps present on given mounted volume, and destroy apps that 16872 * aren't expected, either due to uninstallation or reinstallation on 16873 * another volume. 16874 */ 16875 private void reconcileApps(String volumeUuid) { 16876 final File[] files = FileUtils 16877 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16878 for (File file : files) { 16879 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16880 && !PackageInstallerService.isStageName(file.getName()); 16881 if (!isPackage) { 16882 // Ignore entries which are not packages 16883 continue; 16884 } 16885 16886 try { 16887 final PackageLite pkg = PackageParser.parsePackageLite(file, 16888 PackageParser.PARSE_MUST_BE_APK); 16889 assertPackageKnown(volumeUuid, pkg.packageName); 16890 16891 } catch (PackageParserException | PackageManagerException e) { 16892 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16893 synchronized (mInstallLock) { 16894 removeCodePathLI(file); 16895 } 16896 } 16897 } 16898 } 16899 16900 /** 16901 * Reconcile all app data for the given user. 16902 * <p> 16903 * Verifies that directories exist and that ownership and labeling is 16904 * correct for all installed apps on all mounted volumes. 16905 */ 16906 void reconcileAppsData(int userId, @StorageFlags int flags) { 16907 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16908 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16909 final String volumeUuid = vol.getFsUuid(); 16910 reconcileAppsData(volumeUuid, userId, flags); 16911 } 16912 } 16913 16914 /** 16915 * Reconcile all app data on given mounted volume. 16916 * <p> 16917 * Destroys app data that isn't expected, either due to uninstallation or 16918 * reinstallation on another volume. 16919 * <p> 16920 * Verifies that directories exist and that ownership and labeling is 16921 * correct for all installed apps. 16922 */ 16923 private void reconcileAppsData(String volumeUuid, int userId, @StorageFlags int flags) { 16924 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 16925 + Integer.toHexString(flags)); 16926 16927 final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId); 16928 final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId); 16929 16930 boolean restoreconNeeded = false; 16931 16932 // First look for stale data that doesn't belong, and check if things 16933 // have changed since we did our last restorecon 16934 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 16935 if (!isUserKeyUnlocked(userId)) { 16936 throw new RuntimeException( 16937 "Yikes, someone asked us to reconcile CE storage while " + userId 16938 + " was still locked; this would have caused massive data loss!"); 16939 } 16940 16941 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 16942 16943 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 16944 for (File file : files) { 16945 final String packageName = file.getName(); 16946 try { 16947 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 16948 } catch (PackageManagerException e) { 16949 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16950 synchronized (mInstallLock) { 16951 destroyAppDataLI(volumeUuid, packageName, userId, 16952 Installer.FLAG_CE_STORAGE); 16953 } 16954 } 16955 } 16956 } 16957 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 16958 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 16959 16960 final File[] files = FileUtils.listFilesOrEmpty(deDir); 16961 for (File file : files) { 16962 final String packageName = file.getName(); 16963 try { 16964 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 16965 } catch (PackageManagerException e) { 16966 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16967 synchronized (mInstallLock) { 16968 destroyAppDataLI(volumeUuid, packageName, userId, 16969 Installer.FLAG_DE_STORAGE); 16970 } 16971 } 16972 } 16973 } 16974 16975 // Ensure that data directories are ready to roll for all packages 16976 // installed for this volume and user 16977 final List<PackageSetting> packages; 16978 synchronized (mPackages) { 16979 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16980 } 16981 int preparedCount = 0; 16982 for (PackageSetting ps : packages) { 16983 final String packageName = ps.name; 16984 if (ps.pkg == null) { 16985 Slog.w(TAG, "Odd, missing scanned package " + packageName); 16986 // TODO: might be due to legacy ASEC apps; we should circle back 16987 // and reconcile again once they're scanned 16988 continue; 16989 } 16990 16991 if (ps.getInstalled(userId)) { 16992 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 16993 preparedCount++; 16994 } 16995 } 16996 16997 if (restoreconNeeded) { 16998 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 16999 SELinuxMMAC.setRestoreconDone(ceDir); 17000 } 17001 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 17002 SELinuxMMAC.setRestoreconDone(deDir); 17003 } 17004 } 17005 17006 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 17007 + " packages; restoreconNeeded was " + restoreconNeeded); 17008 } 17009 17010 /** 17011 * Prepare app data for the given app just after it was installed or 17012 * upgraded. This method carefully only touches users that it's installed 17013 * for, and it forces a restorecon to handle any seinfo changes. 17014 * <p> 17015 * Verifies that directories exist and that ownership and labeling is 17016 * correct for all installed apps. If there is an ownership mismatch, it 17017 * will try recovering system apps by wiping data; third-party app data is 17018 * left intact. 17019 */ 17020 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 17021 final PackageSetting ps; 17022 synchronized (mPackages) { 17023 ps = mSettings.mPackages.get(pkg.packageName); 17024 } 17025 17026 final UserManager um = mContext.getSystemService(UserManager.class); 17027 for (UserInfo user : um.getUsers()) { 17028 final int flags; 17029 if (um.isUserUnlocked(user.id)) { 17030 flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE; 17031 } else if (um.isUserRunning(user.id)) { 17032 flags = Installer.FLAG_DE_STORAGE; 17033 } else { 17034 continue; 17035 } 17036 17037 if (ps.getInstalled(user.id)) { 17038 // Whenever an app changes, force a restorecon of its data 17039 // TODO: when user data is locked, mark that we're still dirty 17040 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 17041 } 17042 } 17043 } 17044 17045 /** 17046 * Prepare app data for the given app. 17047 * <p> 17048 * Verifies that directories exist and that ownership and labeling is 17049 * correct for all installed apps. If there is an ownership mismatch, this 17050 * will try recovering system apps by wiping data; third-party app data is 17051 * left intact. 17052 */ 17053 private void prepareAppData(String volumeUuid, int userId, @StorageFlags int flags, 17054 PackageParser.Package pkg, boolean restoreconNeeded) { 17055 if (DEBUG_APP_DATA) { 17056 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 17057 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 17058 } 17059 17060 final String packageName = pkg.packageName; 17061 final ApplicationInfo app = pkg.applicationInfo; 17062 final int appId = UserHandle.getAppId(app.uid); 17063 17064 Preconditions.checkNotNull(app.seinfo); 17065 17066 synchronized (mInstallLock) { 17067 try { 17068 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17069 appId, app.seinfo, app.targetSdkVersion); 17070 } catch (InstallerException e) { 17071 if (app.isSystemApp()) { 17072 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 17073 + ", but trying to recover: " + e); 17074 destroyAppDataLI(volumeUuid, packageName, userId, flags); 17075 try { 17076 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17077 appId, app.seinfo, app.targetSdkVersion); 17078 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 17079 } catch (InstallerException e2) { 17080 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 17081 } 17082 } else { 17083 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 17084 } 17085 } 17086 17087 if (restoreconNeeded) { 17088 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 17089 } 17090 17091 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 17092 // Create a native library symlink only if we have native libraries 17093 // and if the native libraries are 32 bit libraries. We do not provide 17094 // this symlink for 64 bit libraries. 17095 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 17096 final String nativeLibPath = app.nativeLibraryDir; 17097 try { 17098 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 17099 nativeLibPath, userId); 17100 } catch (InstallerException e) { 17101 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 17102 } 17103 } 17104 } 17105 } 17106 } 17107 17108 private void unfreezePackage(String packageName) { 17109 synchronized (mPackages) { 17110 final PackageSetting ps = mSettings.mPackages.get(packageName); 17111 if (ps != null) { 17112 ps.frozen = false; 17113 } 17114 } 17115 } 17116 17117 @Override 17118 public int movePackage(final String packageName, final String volumeUuid) { 17119 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17120 17121 final int moveId = mNextMoveId.getAndIncrement(); 17122 mHandler.post(new Runnable() { 17123 @Override 17124 public void run() { 17125 try { 17126 movePackageInternal(packageName, volumeUuid, moveId); 17127 } catch (PackageManagerException e) { 17128 Slog.w(TAG, "Failed to move " + packageName, e); 17129 mMoveCallbacks.notifyStatusChanged(moveId, 17130 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17131 } 17132 } 17133 }); 17134 return moveId; 17135 } 17136 17137 private void movePackageInternal(final String packageName, final String volumeUuid, 17138 final int moveId) throws PackageManagerException { 17139 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 17140 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17141 final PackageManager pm = mContext.getPackageManager(); 17142 17143 final boolean currentAsec; 17144 final String currentVolumeUuid; 17145 final File codeFile; 17146 final String installerPackageName; 17147 final String packageAbiOverride; 17148 final int appId; 17149 final String seinfo; 17150 final String label; 17151 final int targetSdkVersion; 17152 17153 // reader 17154 synchronized (mPackages) { 17155 final PackageParser.Package pkg = mPackages.get(packageName); 17156 final PackageSetting ps = mSettings.mPackages.get(packageName); 17157 if (pkg == null || ps == null) { 17158 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 17159 } 17160 17161 if (pkg.applicationInfo.isSystemApp()) { 17162 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 17163 "Cannot move system application"); 17164 } 17165 17166 if (pkg.applicationInfo.isExternalAsec()) { 17167 currentAsec = true; 17168 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 17169 } else if (pkg.applicationInfo.isForwardLocked()) { 17170 currentAsec = true; 17171 currentVolumeUuid = "forward_locked"; 17172 } else { 17173 currentAsec = false; 17174 currentVolumeUuid = ps.volumeUuid; 17175 17176 final File probe = new File(pkg.codePath); 17177 final File probeOat = new File(probe, "oat"); 17178 if (!probe.isDirectory() || !probeOat.isDirectory()) { 17179 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17180 "Move only supported for modern cluster style installs"); 17181 } 17182 } 17183 17184 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 17185 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17186 "Package already moved to " + volumeUuid); 17187 } 17188 17189 if (ps.frozen) { 17190 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 17191 "Failed to move already frozen package"); 17192 } 17193 ps.frozen = true; 17194 17195 codeFile = new File(pkg.codePath); 17196 installerPackageName = ps.installerPackageName; 17197 packageAbiOverride = ps.cpuAbiOverrideString; 17198 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17199 seinfo = pkg.applicationInfo.seinfo; 17200 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 17201 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 17202 } 17203 17204 // Now that we're guarded by frozen state, kill app during move 17205 final long token = Binder.clearCallingIdentity(); 17206 try { 17207 killApplication(packageName, appId, "move pkg"); 17208 } finally { 17209 Binder.restoreCallingIdentity(token); 17210 } 17211 17212 final Bundle extras = new Bundle(); 17213 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 17214 extras.putString(Intent.EXTRA_TITLE, label); 17215 mMoveCallbacks.notifyCreated(moveId, extras); 17216 17217 int installFlags; 17218 final boolean moveCompleteApp; 17219 final File measurePath; 17220 17221 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 17222 installFlags = INSTALL_INTERNAL; 17223 moveCompleteApp = !currentAsec; 17224 measurePath = Environment.getDataAppDirectory(volumeUuid); 17225 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 17226 installFlags = INSTALL_EXTERNAL; 17227 moveCompleteApp = false; 17228 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 17229 } else { 17230 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 17231 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 17232 || !volume.isMountedWritable()) { 17233 unfreezePackage(packageName); 17234 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17235 "Move location not mounted private volume"); 17236 } 17237 17238 Preconditions.checkState(!currentAsec); 17239 17240 installFlags = INSTALL_INTERNAL; 17241 moveCompleteApp = true; 17242 measurePath = Environment.getDataAppDirectory(volumeUuid); 17243 } 17244 17245 final PackageStats stats = new PackageStats(null, -1); 17246 synchronized (mInstaller) { 17247 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 17248 unfreezePackage(packageName); 17249 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17250 "Failed to measure package size"); 17251 } 17252 } 17253 17254 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 17255 + stats.dataSize); 17256 17257 final long startFreeBytes = measurePath.getFreeSpace(); 17258 final long sizeBytes; 17259 if (moveCompleteApp) { 17260 sizeBytes = stats.codeSize + stats.dataSize; 17261 } else { 17262 sizeBytes = stats.codeSize; 17263 } 17264 17265 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 17266 unfreezePackage(packageName); 17267 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17268 "Not enough free space to move"); 17269 } 17270 17271 mMoveCallbacks.notifyStatusChanged(moveId, 10); 17272 17273 final CountDownLatch installedLatch = new CountDownLatch(1); 17274 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 17275 @Override 17276 public void onUserActionRequired(Intent intent) throws RemoteException { 17277 throw new IllegalStateException(); 17278 } 17279 17280 @Override 17281 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 17282 Bundle extras) throws RemoteException { 17283 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 17284 + PackageManager.installStatusToString(returnCode, msg)); 17285 17286 installedLatch.countDown(); 17287 17288 // Regardless of success or failure of the move operation, 17289 // always unfreeze the package 17290 unfreezePackage(packageName); 17291 17292 final int status = PackageManager.installStatusToPublicStatus(returnCode); 17293 switch (status) { 17294 case PackageInstaller.STATUS_SUCCESS: 17295 mMoveCallbacks.notifyStatusChanged(moveId, 17296 PackageManager.MOVE_SUCCEEDED); 17297 break; 17298 case PackageInstaller.STATUS_FAILURE_STORAGE: 17299 mMoveCallbacks.notifyStatusChanged(moveId, 17300 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 17301 break; 17302 default: 17303 mMoveCallbacks.notifyStatusChanged(moveId, 17304 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17305 break; 17306 } 17307 } 17308 }; 17309 17310 final MoveInfo move; 17311 if (moveCompleteApp) { 17312 // Kick off a thread to report progress estimates 17313 new Thread() { 17314 @Override 17315 public void run() { 17316 while (true) { 17317 try { 17318 if (installedLatch.await(1, TimeUnit.SECONDS)) { 17319 break; 17320 } 17321 } catch (InterruptedException ignored) { 17322 } 17323 17324 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 17325 final int progress = 10 + (int) MathUtils.constrain( 17326 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 17327 mMoveCallbacks.notifyStatusChanged(moveId, progress); 17328 } 17329 } 17330 }.start(); 17331 17332 final String dataAppName = codeFile.getName(); 17333 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 17334 dataAppName, appId, seinfo, targetSdkVersion); 17335 } else { 17336 move = null; 17337 } 17338 17339 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 17340 17341 final Message msg = mHandler.obtainMessage(INIT_COPY); 17342 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 17343 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 17344 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 17345 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 17346 msg.obj = params; 17347 17348 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 17349 System.identityHashCode(msg.obj)); 17350 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 17351 System.identityHashCode(msg.obj)); 17352 17353 mHandler.sendMessage(msg); 17354 } 17355 17356 @Override 17357 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 17358 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17359 17360 final int realMoveId = mNextMoveId.getAndIncrement(); 17361 final Bundle extras = new Bundle(); 17362 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 17363 mMoveCallbacks.notifyCreated(realMoveId, extras); 17364 17365 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 17366 @Override 17367 public void onCreated(int moveId, Bundle extras) { 17368 // Ignored 17369 } 17370 17371 @Override 17372 public void onStatusChanged(int moveId, int status, long estMillis) { 17373 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 17374 } 17375 }; 17376 17377 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17378 storage.setPrimaryStorageUuid(volumeUuid, callback); 17379 return realMoveId; 17380 } 17381 17382 @Override 17383 public int getMoveStatus(int moveId) { 17384 mContext.enforceCallingOrSelfPermission( 17385 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17386 return mMoveCallbacks.mLastStatus.get(moveId); 17387 } 17388 17389 @Override 17390 public void registerMoveCallback(IPackageMoveObserver callback) { 17391 mContext.enforceCallingOrSelfPermission( 17392 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17393 mMoveCallbacks.register(callback); 17394 } 17395 17396 @Override 17397 public void unregisterMoveCallback(IPackageMoveObserver callback) { 17398 mContext.enforceCallingOrSelfPermission( 17399 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17400 mMoveCallbacks.unregister(callback); 17401 } 17402 17403 @Override 17404 public boolean setInstallLocation(int loc) { 17405 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 17406 null); 17407 if (getInstallLocation() == loc) { 17408 return true; 17409 } 17410 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 17411 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 17412 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 17413 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 17414 return true; 17415 } 17416 return false; 17417 } 17418 17419 @Override 17420 public int getInstallLocation() { 17421 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 17422 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 17423 PackageHelper.APP_INSTALL_AUTO); 17424 } 17425 17426 /** Called by UserManagerService */ 17427 void cleanUpUser(UserManagerService userManager, int userHandle) { 17428 synchronized (mPackages) { 17429 mDirtyUsers.remove(userHandle); 17430 mUserNeedsBadging.delete(userHandle); 17431 mSettings.removeUserLPw(userHandle); 17432 mPendingBroadcasts.remove(userHandle); 17433 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 17434 } 17435 synchronized (mInstallLock) { 17436 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17437 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17438 final String volumeUuid = vol.getFsUuid(); 17439 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 17440 try { 17441 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 17442 } catch (InstallerException e) { 17443 Slog.w(TAG, "Failed to remove user data", e); 17444 } 17445 } 17446 synchronized (mPackages) { 17447 removeUnusedPackagesLILPw(userManager, userHandle); 17448 } 17449 } 17450 } 17451 17452 /** 17453 * We're removing userHandle and would like to remove any downloaded packages 17454 * that are no longer in use by any other user. 17455 * @param userHandle the user being removed 17456 */ 17457 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 17458 final boolean DEBUG_CLEAN_APKS = false; 17459 int [] users = userManager.getUserIds(); 17460 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 17461 while (psit.hasNext()) { 17462 PackageSetting ps = psit.next(); 17463 if (ps.pkg == null) { 17464 continue; 17465 } 17466 final String packageName = ps.pkg.packageName; 17467 // Skip over if system app 17468 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 17469 continue; 17470 } 17471 if (DEBUG_CLEAN_APKS) { 17472 Slog.i(TAG, "Checking package " + packageName); 17473 } 17474 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 17475 if (keep) { 17476 if (DEBUG_CLEAN_APKS) { 17477 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 17478 } 17479 } else { 17480 for (int i = 0; i < users.length; i++) { 17481 if (users[i] != userHandle && ps.getInstalled(users[i])) { 17482 keep = true; 17483 if (DEBUG_CLEAN_APKS) { 17484 Slog.i(TAG, " Keeping package " + packageName + " for user " 17485 + users[i]); 17486 } 17487 break; 17488 } 17489 } 17490 } 17491 if (!keep) { 17492 if (DEBUG_CLEAN_APKS) { 17493 Slog.i(TAG, " Removing package " + packageName); 17494 } 17495 mHandler.post(new Runnable() { 17496 public void run() { 17497 deletePackageX(packageName, userHandle, 0); 17498 } //end run 17499 }); 17500 } 17501 } 17502 } 17503 17504 /** Called by UserManagerService */ 17505 void createNewUser(int userHandle) { 17506 synchronized (mInstallLock) { 17507 try { 17508 mInstaller.createUserConfig(userHandle); 17509 } catch (InstallerException e) { 17510 Slog.w(TAG, "Failed to create user config", e); 17511 } 17512 mSettings.createNewUserLI(this, mInstaller, userHandle); 17513 } 17514 synchronized (mPackages) { 17515 applyFactoryDefaultBrowserLPw(userHandle); 17516 primeDomainVerificationsLPw(userHandle); 17517 } 17518 } 17519 17520 void newUserCreated(final int userHandle) { 17521 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 17522 // If permission review for legacy apps is required, we represent 17523 // dagerous permissions for such apps as always granted runtime 17524 // permissions to keep per user flag state whether review is needed. 17525 // Hence, if a new user is added we have to propagate dangerous 17526 // permission grants for these legacy apps. 17527 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 17528 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 17529 | UPDATE_PERMISSIONS_REPLACE_ALL); 17530 } 17531 } 17532 17533 @Override 17534 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 17535 mContext.enforceCallingOrSelfPermission( 17536 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 17537 "Only package verification agents can read the verifier device identity"); 17538 17539 synchronized (mPackages) { 17540 return mSettings.getVerifierDeviceIdentityLPw(); 17541 } 17542 } 17543 17544 @Override 17545 public void setPermissionEnforced(String permission, boolean enforced) { 17546 // TODO: Now that we no longer change GID for storage, this should to away. 17547 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 17548 "setPermissionEnforced"); 17549 if (READ_EXTERNAL_STORAGE.equals(permission)) { 17550 synchronized (mPackages) { 17551 if (mSettings.mReadExternalStorageEnforced == null 17552 || mSettings.mReadExternalStorageEnforced != enforced) { 17553 mSettings.mReadExternalStorageEnforced = enforced; 17554 mSettings.writeLPr(); 17555 } 17556 } 17557 // kill any non-foreground processes so we restart them and 17558 // grant/revoke the GID. 17559 final IActivityManager am = ActivityManagerNative.getDefault(); 17560 if (am != null) { 17561 final long token = Binder.clearCallingIdentity(); 17562 try { 17563 am.killProcessesBelowForeground("setPermissionEnforcement"); 17564 } catch (RemoteException e) { 17565 } finally { 17566 Binder.restoreCallingIdentity(token); 17567 } 17568 } 17569 } else { 17570 throw new IllegalArgumentException("No selective enforcement for " + permission); 17571 } 17572 } 17573 17574 @Override 17575 @Deprecated 17576 public boolean isPermissionEnforced(String permission) { 17577 return true; 17578 } 17579 17580 @Override 17581 public boolean isStorageLow() { 17582 final long token = Binder.clearCallingIdentity(); 17583 try { 17584 final DeviceStorageMonitorInternal 17585 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 17586 if (dsm != null) { 17587 return dsm.isMemoryLow(); 17588 } else { 17589 return false; 17590 } 17591 } finally { 17592 Binder.restoreCallingIdentity(token); 17593 } 17594 } 17595 17596 @Override 17597 public IPackageInstaller getPackageInstaller() { 17598 return mInstallerService; 17599 } 17600 17601 private boolean userNeedsBadging(int userId) { 17602 int index = mUserNeedsBadging.indexOfKey(userId); 17603 if (index < 0) { 17604 final UserInfo userInfo; 17605 final long token = Binder.clearCallingIdentity(); 17606 try { 17607 userInfo = sUserManager.getUserInfo(userId); 17608 } finally { 17609 Binder.restoreCallingIdentity(token); 17610 } 17611 final boolean b; 17612 if (userInfo != null && userInfo.isManagedProfile()) { 17613 b = true; 17614 } else { 17615 b = false; 17616 } 17617 mUserNeedsBadging.put(userId, b); 17618 return b; 17619 } 17620 return mUserNeedsBadging.valueAt(index); 17621 } 17622 17623 @Override 17624 public KeySet getKeySetByAlias(String packageName, String alias) { 17625 if (packageName == null || alias == null) { 17626 return null; 17627 } 17628 synchronized(mPackages) { 17629 final PackageParser.Package pkg = mPackages.get(packageName); 17630 if (pkg == null) { 17631 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17632 throw new IllegalArgumentException("Unknown package: " + packageName); 17633 } 17634 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17635 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17636 } 17637 } 17638 17639 @Override 17640 public KeySet getSigningKeySet(String packageName) { 17641 if (packageName == null) { 17642 return null; 17643 } 17644 synchronized(mPackages) { 17645 final PackageParser.Package pkg = mPackages.get(packageName); 17646 if (pkg == null) { 17647 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17648 throw new IllegalArgumentException("Unknown package: " + packageName); 17649 } 17650 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17651 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17652 throw new SecurityException("May not access signing KeySet of other apps."); 17653 } 17654 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17655 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17656 } 17657 } 17658 17659 @Override 17660 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17661 if (packageName == null || ks == null) { 17662 return false; 17663 } 17664 synchronized(mPackages) { 17665 final PackageParser.Package pkg = mPackages.get(packageName); 17666 if (pkg == null) { 17667 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17668 throw new IllegalArgumentException("Unknown package: " + packageName); 17669 } 17670 IBinder ksh = ks.getToken(); 17671 if (ksh instanceof KeySetHandle) { 17672 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17673 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17674 } 17675 return false; 17676 } 17677 } 17678 17679 @Override 17680 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17681 if (packageName == null || ks == null) { 17682 return false; 17683 } 17684 synchronized(mPackages) { 17685 final PackageParser.Package pkg = mPackages.get(packageName); 17686 if (pkg == null) { 17687 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17688 throw new IllegalArgumentException("Unknown package: " + packageName); 17689 } 17690 IBinder ksh = ks.getToken(); 17691 if (ksh instanceof KeySetHandle) { 17692 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17693 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17694 } 17695 return false; 17696 } 17697 } 17698 17699 private void deletePackageIfUnusedLPr(final String packageName) { 17700 PackageSetting ps = mSettings.mPackages.get(packageName); 17701 if (ps == null) { 17702 return; 17703 } 17704 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17705 // TODO Implement atomic delete if package is unused 17706 // It is currently possible that the package will be deleted even if it is installed 17707 // after this method returns. 17708 mHandler.post(new Runnable() { 17709 public void run() { 17710 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17711 } 17712 }); 17713 } 17714 } 17715 17716 /** 17717 * Check and throw if the given before/after packages would be considered a 17718 * downgrade. 17719 */ 17720 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17721 throws PackageManagerException { 17722 if (after.versionCode < before.mVersionCode) { 17723 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17724 "Update version code " + after.versionCode + " is older than current " 17725 + before.mVersionCode); 17726 } else if (after.versionCode == before.mVersionCode) { 17727 if (after.baseRevisionCode < before.baseRevisionCode) { 17728 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17729 "Update base revision code " + after.baseRevisionCode 17730 + " is older than current " + before.baseRevisionCode); 17731 } 17732 17733 if (!ArrayUtils.isEmpty(after.splitNames)) { 17734 for (int i = 0; i < after.splitNames.length; i++) { 17735 final String splitName = after.splitNames[i]; 17736 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17737 if (j != -1) { 17738 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17739 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17740 "Update split " + splitName + " revision code " 17741 + after.splitRevisionCodes[i] + " is older than current " 17742 + before.splitRevisionCodes[j]); 17743 } 17744 } 17745 } 17746 } 17747 } 17748 } 17749 17750 private static class MoveCallbacks extends Handler { 17751 private static final int MSG_CREATED = 1; 17752 private static final int MSG_STATUS_CHANGED = 2; 17753 17754 private final RemoteCallbackList<IPackageMoveObserver> 17755 mCallbacks = new RemoteCallbackList<>(); 17756 17757 private final SparseIntArray mLastStatus = new SparseIntArray(); 17758 17759 public MoveCallbacks(Looper looper) { 17760 super(looper); 17761 } 17762 17763 public void register(IPackageMoveObserver callback) { 17764 mCallbacks.register(callback); 17765 } 17766 17767 public void unregister(IPackageMoveObserver callback) { 17768 mCallbacks.unregister(callback); 17769 } 17770 17771 @Override 17772 public void handleMessage(Message msg) { 17773 final SomeArgs args = (SomeArgs) msg.obj; 17774 final int n = mCallbacks.beginBroadcast(); 17775 for (int i = 0; i < n; i++) { 17776 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17777 try { 17778 invokeCallback(callback, msg.what, args); 17779 } catch (RemoteException ignored) { 17780 } 17781 } 17782 mCallbacks.finishBroadcast(); 17783 args.recycle(); 17784 } 17785 17786 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17787 throws RemoteException { 17788 switch (what) { 17789 case MSG_CREATED: { 17790 callback.onCreated(args.argi1, (Bundle) args.arg2); 17791 break; 17792 } 17793 case MSG_STATUS_CHANGED: { 17794 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17795 break; 17796 } 17797 } 17798 } 17799 17800 private void notifyCreated(int moveId, Bundle extras) { 17801 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17802 17803 final SomeArgs args = SomeArgs.obtain(); 17804 args.argi1 = moveId; 17805 args.arg2 = extras; 17806 obtainMessage(MSG_CREATED, args).sendToTarget(); 17807 } 17808 17809 private void notifyStatusChanged(int moveId, int status) { 17810 notifyStatusChanged(moveId, status, -1); 17811 } 17812 17813 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17814 Slog.v(TAG, "Move " + moveId + " status " + status); 17815 17816 final SomeArgs args = SomeArgs.obtain(); 17817 args.argi1 = moveId; 17818 args.argi2 = status; 17819 args.arg3 = estMillis; 17820 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17821 17822 synchronized (mLastStatus) { 17823 mLastStatus.put(moveId, status); 17824 } 17825 } 17826 } 17827 17828 private final static class OnPermissionChangeListeners extends Handler { 17829 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17830 17831 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17832 new RemoteCallbackList<>(); 17833 17834 public OnPermissionChangeListeners(Looper looper) { 17835 super(looper); 17836 } 17837 17838 @Override 17839 public void handleMessage(Message msg) { 17840 switch (msg.what) { 17841 case MSG_ON_PERMISSIONS_CHANGED: { 17842 final int uid = msg.arg1; 17843 handleOnPermissionsChanged(uid); 17844 } break; 17845 } 17846 } 17847 17848 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17849 mPermissionListeners.register(listener); 17850 17851 } 17852 17853 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17854 mPermissionListeners.unregister(listener); 17855 } 17856 17857 public void onPermissionsChanged(int uid) { 17858 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17859 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17860 } 17861 } 17862 17863 private void handleOnPermissionsChanged(int uid) { 17864 final int count = mPermissionListeners.beginBroadcast(); 17865 try { 17866 for (int i = 0; i < count; i++) { 17867 IOnPermissionsChangeListener callback = mPermissionListeners 17868 .getBroadcastItem(i); 17869 try { 17870 callback.onPermissionsChanged(uid); 17871 } catch (RemoteException e) { 17872 Log.e(TAG, "Permission listener is dead", e); 17873 } 17874 } 17875 } finally { 17876 mPermissionListeners.finishBroadcast(); 17877 } 17878 } 17879 } 17880 17881 private class PackageManagerInternalImpl extends PackageManagerInternal { 17882 @Override 17883 public void setLocationPackagesProvider(PackagesProvider provider) { 17884 synchronized (mPackages) { 17885 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17886 } 17887 } 17888 17889 @Override 17890 public void setImePackagesProvider(PackagesProvider provider) { 17891 synchronized (mPackages) { 17892 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17893 } 17894 } 17895 17896 @Override 17897 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17898 synchronized (mPackages) { 17899 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17900 } 17901 } 17902 17903 @Override 17904 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17905 synchronized (mPackages) { 17906 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17907 } 17908 } 17909 17910 @Override 17911 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17912 synchronized (mPackages) { 17913 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17914 } 17915 } 17916 17917 @Override 17918 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17919 synchronized (mPackages) { 17920 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17921 } 17922 } 17923 17924 @Override 17925 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17926 synchronized (mPackages) { 17927 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17928 } 17929 } 17930 17931 @Override 17932 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17933 synchronized (mPackages) { 17934 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17935 packageName, userId); 17936 } 17937 } 17938 17939 @Override 17940 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17941 synchronized (mPackages) { 17942 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17943 packageName, userId); 17944 } 17945 } 17946 17947 @Override 17948 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17949 synchronized (mPackages) { 17950 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17951 packageName, userId); 17952 } 17953 } 17954 17955 @Override 17956 public void setKeepUninstalledPackages(final List<String> packageList) { 17957 Preconditions.checkNotNull(packageList); 17958 List<String> removedFromList = null; 17959 synchronized (mPackages) { 17960 if (mKeepUninstalledPackages != null) { 17961 final int packagesCount = mKeepUninstalledPackages.size(); 17962 for (int i = 0; i < packagesCount; i++) { 17963 String oldPackage = mKeepUninstalledPackages.get(i); 17964 if (packageList != null && packageList.contains(oldPackage)) { 17965 continue; 17966 } 17967 if (removedFromList == null) { 17968 removedFromList = new ArrayList<>(); 17969 } 17970 removedFromList.add(oldPackage); 17971 } 17972 } 17973 mKeepUninstalledPackages = new ArrayList<>(packageList); 17974 if (removedFromList != null) { 17975 final int removedCount = removedFromList.size(); 17976 for (int i = 0; i < removedCount; i++) { 17977 deletePackageIfUnusedLPr(removedFromList.get(i)); 17978 } 17979 } 17980 } 17981 } 17982 17983 @Override 17984 public boolean isPermissionsReviewRequired(String packageName, int userId) { 17985 synchronized (mPackages) { 17986 // If we do not support permission review, done. 17987 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 17988 return false; 17989 } 17990 17991 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 17992 if (packageSetting == null) { 17993 return false; 17994 } 17995 17996 // Permission review applies only to apps not supporting the new permission model. 17997 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 17998 return false; 17999 } 18000 18001 // Legacy apps have the permission and get user consent on launch. 18002 PermissionsState permissionsState = packageSetting.getPermissionsState(); 18003 return permissionsState.isPermissionReviewRequired(userId); 18004 } 18005 } 18006 } 18007 18008 @Override 18009 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 18010 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 18011 synchronized (mPackages) { 18012 final long identity = Binder.clearCallingIdentity(); 18013 try { 18014 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 18015 packageNames, userId); 18016 } finally { 18017 Binder.restoreCallingIdentity(identity); 18018 } 18019 } 18020 } 18021 18022 private static void enforceSystemOrPhoneCaller(String tag) { 18023 int callingUid = Binder.getCallingUid(); 18024 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 18025 throw new SecurityException( 18026 "Cannot call " + tag + " from UID " + callingUid); 18027 } 18028 } 18029} 18030